@yuzhouu/canvas-standard 0.1.2 → 0.1.4

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.
Files changed (39) hide show
  1. package/_vendor/plugin-arrow/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  2. package/_vendor/plugin-arrow/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  3. package/_vendor/plugin-connector/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  4. package/_vendor/plugin-connector/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  5. package/_vendor/plugin-connector/connectorInteractions.d.ts +8 -1
  6. package/_vendor/plugin-connector/index.d.ts +1 -0
  7. package/_vendor/plugin-draw/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  8. package/_vendor/plugin-draw/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  9. package/_vendor/plugin-eraser/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  10. package/_vendor/plugin-eraser/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  11. package/_vendor/plugin-flow/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  12. package/_vendor/plugin-flow/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  13. package/_vendor/plugin-flow/_vendor/plugin-connector/connectorInteractions.d.ts +8 -1
  14. package/_vendor/plugin-flow/_vendor/plugin-connector/index.d.ts +1 -0
  15. package/_vendor/plugin-flow/flowNodeShapeUtil.d.ts +1 -0
  16. package/_vendor/plugin-frame/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  17. package/_vendor/plugin-frame/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  18. package/_vendor/plugin-geo/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  19. package/_vendor/plugin-geo/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  20. package/_vendor/plugin-group/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  21. package/_vendor/plugin-group/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  22. package/_vendor/plugin-html/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  23. package/_vendor/plugin-html/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  24. package/_vendor/plugin-image/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  25. package/_vendor/plugin-image/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  26. package/_vendor/plugin-laser/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  27. package/_vendor/plugin-laser/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  28. package/_vendor/plugin-path/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  29. package/_vendor/plugin-path/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  30. package/_vendor/plugin-runtime-clipboard/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  31. package/_vendor/plugin-runtime-clipboard/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  32. package/_vendor/plugin-runtime-export/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  33. package/_vendor/plugin-runtime-export/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  34. package/_vendor/plugin-text/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  35. package/_vendor/plugin-text/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  36. package/_vendor/plugin-video/_vendor/canvas-core/shapes/shapeUtil.d.ts +1 -0
  37. package/_vendor/plugin-video/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +3 -1
  38. package/index.mjs +77 -82
  39. package/package.json +1 -1
package/index.mjs CHANGED
@@ -1,82 +1,77 @@
1
- import{useEditor as t,useValue as e}from"@yuzhouu/canvas-kit/plugin-runtime";import{SHAPE_HOVER_STROKE as n,SHAPE_HOVER_STROKE_WIDTH as r,ShapeHeadingControl as o,createShapeHeadingDomEventGuard as i,useCanvasRenderers as s}from"@yuzhouu/canvas-kit/plugin-runtime";import{Fragment as a,jsx as l,jsxs as c}from"react/jsx-runtime";import*as d from"react";import u,{createContext as p,createElement as h,forwardRef as f,memo as m,useCallback as g,useContext as y,useDebugValue as x,useEffect as w,useLayoutEffect as b,useMemo as v,useRef as k,useState as S,useSyncExternalStore as P}from"react";import M from"react-dom";import{applyCanvasActionShortcutOverrides as I}from"@yuzhouu/canvas-kit";var T=(t,e)=>()=>(e||(t((e={exports:{}}).exports,e),t=null),e.exports);function C(t){return!!t&&"shape"===t.typeName}function E(t){return!!t&&"asset"===t.typeName}var A=class{},O=class t{x;y;constructor(t,e){this.x=t,this.y=e}add(e){return new t(this.x+e.x,this.y+e.y)}sub(e){return new t(this.x-e.x,this.y-e.y)}mul(e){return new t(this.x*e,this.y*e)}div(e){return new t(this.x/e,this.y/e)}len2(){return this.x*this.x+this.y*this.y}len(){return Math.sqrt(this.len2())}dist2(t){const e=this.x-t.x,n=this.y-t.y;return e*e+n*n}dist(t){return Math.sqrt(this.dist2(t))}rot(e){const n=Math.cos(e),r=Math.sin(e);return new t(this.x*n-this.y*r,this.x*r+this.y*n)}per(){return new t(-this.y,this.x)}normalize(){const e=this.len();return 0===e?new t(0,0):this.div(e)}equals(t){return this.x===t.x&&this.y===t.y}clone(){return new t(this.x,this.y)}static From(e,n){return new t(e,n)}static Zero(){return new t(0,0)}static Med(e,n){return new t((e.x+n.x)/2,(e.y+n.y)/2)}static Lrp(e,n,r){return new t(e.x+(n.x-e.x)*r,e.y+(n.y-e.y)*r)}static Dist(t,e){return t.dist(e)}static Dist2(t,e){return t.dist2(e)}static Angle(t,e){return Math.atan2(e.y-t.y,e.x-t.x)}static Nudge(t,e,n){const r=e.sub(t),o=r.len();return 0===o?t.clone():t.add(r.mul(n/o))}static RotWith(e,n,r){const o=e.x-n.x,i=e.y-n.y,s=Math.cos(r),a=Math.sin(r);return new t(n.x+o*s-i*a,n.y+o*a+i*s)}static IsNaN(t){return isNaN(t.x)||isNaN(t.y)}},N=class t{x;y;w;h;constructor(t,e,n,r){this.x=t,this.y=e,this.w=n,this.h=r}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 O(this.x+this.w/2,this.y+this.h/2)}containsPoint(t){return t.x>=this.minX&&t.x<=this.maxX&&t.y>=this.minY&&t.y<=this.maxY}containsBox(t){return t.minX>=this.minX&&t.maxX<=this.maxX&&t.minY>=this.minY&&t.maxY<=this.maxY}intersects(t){return this.minX<t.maxX&&this.maxX>t.minX&&this.minY<t.maxY&&this.maxY>t.minY}expand(e){return new t(this.x-e,this.y-e,this.w+2*e,this.h+2*e)}clone(){return new t(this.x,this.y,this.w,this.h)}static FromPoints(e){let n=1/0,r=1/0,o=-1/0,i=-1/0;for(const t of e)n=Math.min(n,t.x),r=Math.min(r,t.y),o=Math.max(o,t.x),i=Math.max(i,t.y);return new t(n,r,o-n,i-r)}};function R(t,e,n){const r=e.sub(t),o=n.sub(t),i=r.x*r.x+r.y*r.y;if(0===i)return t;const s=Math.max(0,Math.min(1,(o.x*r.x+o.y*r.y)/i));return new O(t.x+r.x*s,t.y+r.y*s)}function L(t,e,n){return t.dist(R(e,n,t))}function $(t,e,n,r){const o=e.sub(t),i=r.sub(n),s=o.x*i.y-o.y*i.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(t),l=(a.x*i.y-a.y*i.x)/s,c=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&c>=0&&c<=1}function D(t,e,n,r){return $(t,e,n,r)?0:Math.min(L(t,n,r),L(e,n,r),L(n,t,e),L(r,t,e))}function B(t,e){if(!function(t){return t.length>=3&&t.every(t=>Number.isFinite(t.x)&&Number.isFinite(t.y))}(e))return!1;let n=!1;for(let r=0;r<e.length;r+=1){const o=e[r],i=e[(r+e.length-1)%e.length];if(L(t,i,o)<=1e-8)return!0;o.y>t.y!=i.y>t.y&&t.x<(i.x-o.x)*(t.y-o.y)/(i.y-o.y)+o.x&&(n=!n)}return n}var z=["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"],F=Object.fromEntries(z.map(t=>[t,`--land-shape-${t}`])),j={"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"};function W(t){return{kind:"theme",slot:t}}function H(t){return{kind:"custom",value:t}}function _(t){return function(t){return!!t&&"object"==typeof t&&"theme"===t.kind&&z.includes(t.slot)}(t)||function(t){return!!t&&"object"==typeof t&&"custom"===t.kind&&"string"==typeof t.value}(t)}function U(t){return F[t]}function V(t,e){return _(t)?t:e}function K(t){return"custom"===t.kind?t.value:`var(${U(t.slot)}, ${j[t.slot]})`}function q(t,e){if("custom"===t.kind)return t.value;const n=U(t.slot),r=j[t.slot];return e?.(n,r)??r}function X(t){if("custom"!==t.kind)return!1;const e=t.value.trim().toLowerCase();return"transparent"===e||/^#[0-9a-f]{6}00$/.test(e)}function Y(t,e){return t===e||!(!t||!e)&&(t.kind===e.kind&&("theme"===t.kind?t.slot===e.slot:t.value===e.value))}var J=class t{a;b;c;d;e;f;constructor(t,e,n,r,o,i){this.a=t,this.b=e,this.c=n,this.d=r,this.e=o,this.f=i}static Identity(){return new t(1,0,0,1,0,0)}static Translate(e,n){return new t(1,0,0,1,e,n)}static Rotate(e){const n=Math.cos(e),r=Math.sin(e);return new t(n,r,-r,n,0,0)}static Scale(e,n){return new t(e,0,0,n,0,0)}compose(e){return new t(this.a*e.a+this.c*e.b,this.b*e.a+this.d*e.b,this.a*e.c+this.c*e.d,this.b*e.c+this.d*e.d,this.a*e.e+this.c*e.f+this.e,this.b*e.e+this.d*e.f+this.f)}applyToPoint(t){return new O(this.a*t.x+this.c*t.y+this.e,this.b*t.x+this.d*t.y+this.f)}determinant(){return this.a*this.d-this.b*this.c}getMaximumLinearScale(){const t=this.a*this.a+this.b*this.b+this.c*this.c+this.d*this.d,e=this.determinant(),n=Math.max(0,t*t-4*e*e);return Math.sqrt((t+Math.sqrt(n))/2)}tryInvert(e=0){const n=this.determinant(),r=Number.isFinite(e)?Math.max(0,e):0;if(!Number.isFinite(n)||Math.abs(n)<=r)return null;const o=1/n;return new t(this.d*o,-this.b*o,-this.c*o,this.a*o,(this.c*this.f-this.d*this.e)*o,(this.b*this.e-this.a*this.f)*o)}invert(){return this.tryInvert()??t.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(e,n,r,o=1,i=1){const s=t.Translate(e,n),a=0===r?t.Identity():t.Rotate(r),l=1===o&&1===i?t.Identity():t.Scale(o,i);return s.compose(a).compose(l)}};function G(t){return{id:t}}function Z(t){return void 0!==t&&t<0?-1:1}function Q(t,e){if(void 0===e)return t;const n=2*Math.PI;return t+Math.round((e-t)/n)*n}function tt(t,e){const n=2*Math.PI,r=((t-e+Math.PI)%n+n)%n-Math.PI;return Math.abs(r)}function et(t,e,n={}){if(!function(t){return[t.a,t.b,t.c,t.d,t.e,t.f].every(Number.isFinite)}(t)||![e.x,e.y,e.w,e.h].every(Number.isFinite))return null;const r=Number.isFinite(n.epsilon)?Math.max(0,n.epsilon??0):1e-8,o=Math.hypot(t.a,t.b),i=Math.hypot(t.c,t.d),s=t.determinant(),a=({rotation:n,scaleX:r,scaleY:o})=>{const i=e.center,s=t.applyToPoint(i),a={x:s.x-i.x,y:s.y-i.y,rotation:n,scaleX:r,scaleY:o};return Object.values(a).every(Number.isFinite)?a:null},l=r*Math.max(1,o,i),c=o<=l,d=i<=l;if(c||d){if(c&&d)return a({rotation:n.preferredRotation??0,scaleX:0,scaleY:0});if(c){const e=i*Z(n.preferredScaleYSign);return a({rotation:Q(Math.atan2(-t.c/e,t.d/e),n.preferredRotation),scaleX:0,scaleY:e})}const e=o*Z(n.preferredScaleXSign);return a({rotation:Q(Math.atan2(t.b/e,t.a/e),n.preferredRotation),scaleX:e,scaleY:0})}if(Math.abs(t.a*t.c+t.b*t.d)/(o*i)>r)return null;if(Math.abs(s)<=r*o*i)return null;const u=Math.atan2(t.b,t.a),p=o,h=i*(s<0?-1:1),f=[{rotation:Q(u,n.preferredRotation),scaleX:p,scaleY:h},{rotation:Q(u+Math.PI,n.preferredRotation),scaleX:-p,scaleY:-h}],m=Z(n.preferredScaleXSign),g=Z(n.preferredScaleYSign),y=t=>{let e=0;return void 0!==n.preferredScaleXSign&&Z(t.scaleX)===m&&(e+=1),void 0!==n.preferredScaleYSign&&Z(t.scaleY)===g&&(e+=1),{signMatches:e,rotationDistance:void 0===n.preferredRotation?0:tt(t.rotation,n.preferredRotation)}},x=y(f[0]),w=y(f[1]),b=w.signMatches>x.signMatches||w.signMatches===x.signMatches&&w.rotationDistance<x.rotationDistance?f[1]:f[0];return a({rotation:b.rotation,scaleX:b.scaleX,scaleY:b.scaleY})}new O(24,24);function nt(t,e,n){const r=t.shapes.get(e);if(!r)return;const o=t.layers.getContainingParentIdForShape(r);o&&o!==r.parentId&&t.commands.reparentShapes({ids:[e],parentId:o},n)}var rt=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],ot=["top_left","top_right","bottom_right","bottom_left"],it=["free","aspect_ratio_locked"],st=["free"],at=["aspect_ratio_locked"];function lt(t,e){return 0===e.rotation?t.clone():O.RotWith(t,e.rotationCenter,e.rotation)}function ct({axis:t,bounds:e,point:n}){return"horizontal"===t?new O(e.minX+e.maxX-n.x,n.y):new O(n.x,e.minY+e.maxY-n.y)}function dt({localWidth:t,localHeight:e,scaleX:n,scaleY:r}){return{width:Math.abs(n)*t,height:Math.abs(r)*e}}function ut({width:t,height:e,scaleX:n,scaleY:r}){const o=Math.abs(n),i=Math.abs(r);return{width:0===o?t:t/o,height:0===i?e:e/i}}function pt({requestedBounds:t,handleId:e,actualWidth:n,actualHeight:r,scaleX:o,scaleY:i,isResizingFromCenter:s}){return new N(s?t.center.x-n/2:function(t){return"top_left"===t||"left"===t||"bottom_left"===t}(e)?o<0?t.minX:t.maxX-n:function(t){return"top_right"===t||"right"===t||"bottom_right"===t}(e)?o<0?t.maxX-n:t.minX:t.center.x-n/2,s?t.center.y-r/2:function(t){return"top_left"===t||"top"===t||"top_right"===t}(e)?i<0?t.minY:t.maxY-r:function(t){return"bottom_left"===t||"bottom"===t||"bottom_right"===t}(e)?i<0?t.maxY-r:t.minY:t.center.y-r/2,n,r)}function ht({outputBounds:t,cutoutLocalPolygons:e,localToOutput:n}){const r=e.filter(t=>t.length>=3);return 0===r.length?null:[ft((o=t.expand(100),[new O(o.minX,o.minY),new O(o.maxX,o.minY),new O(o.maxX,o.maxY),new O(o.minX,o.maxY)])),...r.map(t=>ft(t,n))].join(" ");var o}function ft(t,e){const n=e?t.map(t=>e.applyToPoint(t)):t,r=n[0];return r?[`M ${mt(r.x)} ${mt(r.y)}`,...n.slice(1).map(t=>`L ${mt(t.x)} ${mt(t.y)}`),"Z"].join(" "):""}function mt(t){return Number.isFinite(t)?Number(t.toFixed(3)).toString():"0"}var gt=[{id:"top",normalizedAnchor:{x:.5,y:0},outwardNormal:{x:0,y:-1}},{id:"right",normalizedAnchor:{x:1,y:.5},outwardNormal:{x:1,y:0}},{id:"bottom",normalizedAnchor:{x:.5,y:1},outwardNormal:{x:0,y:1}},{id:"left",normalizedAnchor:{x:0,y:.5},outwardNormal:{x:-1,y:0}}];function yt(t,e){return t.shapes.getUtil(e).getTerminalBindingPorts(e,{editor:t}).flatMap(n=>{const r=wt(t,e,n);return r?[r]:[]})}function xt(t,e,n){const r=t.shapes.getUtil(e).getTerminalBindingPorts(e,{editor:t}).find(t=>t.id===n);return r?wt(t,e,r):null}function wt(t,e,n){const r=t.shapes.getUtil(e),o=r.getLocalBounds(e),i=t.shapes.computeLocalToPageTransform(e),s=function(t,e){const n=t.determinant();return!Number.isFinite(n)||Math.abs(n)<1e-12?O.Zero():new O((t.d*e.x-t.b*e.y)/n,(-t.c*e.x+t.a*e.y)/n).normalize()}(i,new O(n.outwardNormal.x,n.outwardNormal.y));if(s.len2()<1e-12)return null;const a=new O(o.x+o.w*n.normalizedAnchor.x,o.y+o.h*n.normalizedAnchor.y),l=i.applyToPoint(a),c=Math.max(64,o.w*i.getMaximumLinearScale(),o.h*i.getMaximumLinearScale()),d=r.resolveBindingPoint(e,{editor:t,rawPagePoint:l.add(s.mul(c)),oppositePagePoint:l.sub(s.mul(c))});return{id:n.id,normalizedAnchor:{...n.normalizedAnchor},pagePoint:d,pageOutwardNormal:s}}function bt(t){return[new O(t.minX,t.minY),new O(t.maxX,t.minY),new O(t.maxX,t.maxY),new O(t.minX,t.maxY)]}function vt(t,e,n,r){const o=e.sub(t),i=r.sub(n),s=o.x*i.y-o.y*i.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(t),l=(a.x*i.y-a.y*i.x)/s,c=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&c>=0&&c<=1?l:null}function kt(t,e,n){const r=t[e];return"number"==typeof r&&Number.isFinite(r)?r:n}var St=class{getPositionedBounds(t){const e=this.getLocalBounds(t);return new N(e.x+t.x,e.y+t.y,e.w,e.h)}getRenderBounds(t){return this.getLocalBounds(t)}getPointHitTestBounds(t,e){return this.getPositionedBounds(t)}getExportBounds(t){return this.getRenderBounds(t)}getChildClipLocalBounds(t){return null}getChildClipLocalPolygons(t){const e=this.getChildClipLocalBounds(t);return e?[bt(e)]:null}getChildExportClipLocalBounds(t){return this.getChildClipLocalBounds(t)}getChildExportClipLocalPolygons(t){const e=this.getChildExportClipLocalBounds(t);return e?[bt(e)]:null}getSelectionResizeLocalBounds(t){return this.getLocalBounds(t)}resizeSelectionBounds(t,e){const n=this.getSelectionResizeLocalBounds(t);if(0!==n.x||0!==n.y)throw new Error(`Shape util "${this.type}" must implement resizeSelectionBounds for non-origin local bounds`);const r=ut({width:e.selectionLocalBounds.w,height:e.selectionLocalBounds.h,scaleX:t.scaleX,scaleY:t.scaleY}),o=e.scaleX<0!=e.scaleY<0?2*e.selectionRotation-t.rotation:t.rotation,i=this.validateProps({...t.props,w:r.width,h:r.height}),s=kt(i,"w",r.width),a=kt(i,"h",r.height),l=dt({localWidth:s,localHeight:a,scaleX:t.scaleX,scaleY:t.scaleY}),c=lt(pt({requestedBounds:e.selectionLocalBounds,handleId:e.handleId,actualWidth:l.width,actualHeight:l.height,scaleX:e.scaleX,scaleY:e.scaleY,isResizingFromCenter:e.isResizingFromCenter}).center,{rotation:e.selectionRotation,rotationCenter:e.selectionRotationCenter});return{id:t.id,x:c.x-s/2,y:c.y-a/2,rotation:o,scaleX:e.scaleX<0?-t.scaleX:t.scaleX,scaleY:e.scaleY<0?-t.scaleY:t.scaleY,props:i}}getAllowedSelectionResizeModes(t,e){return it}getSelectionResizeHandleIds(t,e){return rt}flipSelectionBounds(t,e){const n=this.getSelectionPagePoints(t);if(n){const r=n.map(t=>{const n=0===e.selectionRotation?t.clone():O.RotWith(t,e.selectionRotationCenter,-e.selectionRotation),r=ct({axis:e.axis,bounds:e.selectionBounds,point:n});return 0===e.selectionRotation?r:O.RotWith(r,e.selectionRotationCenter,e.selectionRotation)}),o=this.getSelectionPageMiddlePoint(t),i=o?(()=>{const t=0===e.selectionRotation?o.clone():O.RotWith(o,e.selectionRotationCenter,-e.selectionRotation),n=ct({axis:e.axis,bounds:e.selectionBounds,point:t});return 0===e.selectionRotation?n:O.RotWith(n,e.selectionRotationCenter,e.selectionRotation)})():void 0;return this.updateSelectionPagePoints(t,{pagePoints:[r[0],r[1]],pageMiddlePoint:i})}const r=this.getSelectionResizeLocalBounds(t),o=0===e.selectionRotation?e.selectionLocalBounds.center:O.RotWith(e.selectionLocalBounds.center,e.selectionRotationCenter,e.selectionRotation);return{id:t.id,x:o.x-r.center.x,y:o.y-r.center.y,rotation:2*e.selectionRotation-t.rotation,scaleX:"horizontal"===e.axis?-t.scaleX:t.scaleX,scaleY:"vertical"===e.axis?-t.scaleY:t.scaleY}}updateSelectionPagePoints(t,e){throw new Error(`Shape util "${this.type}" must implement updateSelectionPagePoints before selection can transform point-defined geometry`)}getSelectionPagePoints(t){return null}getSelectionPageMiddlePoint(t){return null}contributesToSelectionFrame(t,e){return!0}canParticipateInSelectionResize(t,e){return!0}canParticipateInSelectionFlip(t,e){return this.canParticipateInSelectionResize(t,e)}canParticipateInSelectionRotation(t,e){return!0}canUseSelectionResizeHandles(t,e){return this.canParticipateInSelectionResize(t,e)}canUseSelectionRotateHandle(t,e){return this.canParticipateInSelectionRotation(t,e)}canParticipateInSelectionTranslation(t,e){return!0}getSelectionTargetId(t,e){return t.id}getHoverTargetId(t,e){return t.id}getHoverDecorationTargetId(t,e){return t.id}getTranslateTargetId(t,e){return t.id}isSelectionTransformContainer(t){return!1}shouldRotateDescendants(t){return this.isSelectionTransformContainer(t)}shouldResizeDescendants(t){return!1}getResizeToFitDescendantsProps(t,e){return null}getMinimumChildCount(t){return 0}contributesToExportBounds(t){return!0}canUngroupChildren(t){return!1}getGroupingShapeCreateInput(t){return null}canStartTranslateFromSelectionBounds(t,e){return!0}canSnap(t,e){return!0}canSnapChildrenToSelf(t){return!1}getBoundsSnapGeometry(t){return{}}getHandleSnapGeometry(t){return{outline:bt(this.getLocalBounds(t))}}getPositionedOutlineVertices(t){const e=this.getPositionedBounds(t);return[new O(e.minX,e.minY),new O(e.maxX,e.minY),new O(e.maxX,e.maxY),new O(e.minX,e.maxY)]}getSelectionFramePositionedOutlineVertices(t,e){return null}getSelectionHandleAnchors(t,e){return{terminalHandleAnchors:[],middleHandleAnchors:[]}}getSelectionOverlayInfo(t,e){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,pathStyle:null,bindingSegments:[]}}getLabelPathGeometry(t,e){return null}isWrappedByBrush(t,e){return 0===e.pageOutlineVertices.length?!!e.pageBounds&&e.brushBounds.containsBox(e.pageBounds):e.pageOutlineVertices.every(t=>e.brushBounds.containsPoint(t))}canSelectByBrush(t,e){return!e.isWrapping||this.isWrappedByBrush(t,e)}getLocalTransform(t){const e=this.getLocalBounds(t).center;return J.Translate(t.x+e.x,t.y+e.y).compose(J.Rotate(t.rotation)).compose(J.Scale(t.scaleX,t.scaleY)).compose(J.Translate(-e.x,-e.y))}getPositionedTransform(t){const e=this.getLocalBounds(t).center,n=new O(t.x+e.x,t.y+e.y);return J.Translate(n.x,n.y).compose(J.Rotate(t.rotation)).compose(J.Scale(t.scaleX,t.scaleY)).compose(J.Translate(-n.x,-n.y))}canEdit(t){return!1}canReceiveChildren(t){return!1}getChildTransformPolicy(t){return"isometry"}canReceiveChild(t,e){return this.canReceiveChildren(t)}isChildVisible(t,e,n){return!0}getChildPlacementMeta(t,e,n){return e.meta}canAutomaticallyReceiveChildren(t){return this.canReceiveChildren(t)}canBeDirectlyBrushSelected(t){return!0}canReceiveTerminalBinding(t,e){return!1}getTerminalBindingPorts(t,e){return this.canReceiveTerminalBinding(t,e)?gt:[]}getTerminalBindingOutlines(t,e){return this.canReceiveTerminalBinding(t,e)?[{points:this.getPositionedOutlineVertices(t),closed:!0}]:[]}canCopyToClipboard(t,e){return!0}onEditEnd(t,e){}hitTest(t,e,n){return this.getPositionedBounds(t).containsPoint(e)}hitTestBindingTarget(t,e,n){return this.hitTest(t,e,n)}hitTestLineSegment(t,e){return function(t,e,n){if(n.containsPoint(t)||n.containsPoint(e))return!0;const r=bt(n);for(let o=0;o<r.length;o+=1){const n=r[o],i=r[(o+1)%r.length];if(n&&i&&null!==vt(t,e,n,i))return!0}return!1}(e.positionedStart,e.positionedEnd,this.getPositionedBounds(t).expand(e.positionedMargin))}resolveBindingPoint(t,e){this.getPositionedBounds(t);const n=e.editor.shapes.computePositionedToPageTransform(t),r=n.tryInvert();if(!r)return e.rawPagePoint;const o=function(t,e,n){if(n.length<2)return null;let r=Number.POSITIVE_INFINITY;const o=e.sub(t);for(let i=0;i<n.length;i+=1){const o=n[i],s=n[(i+1)%n.length]??n[0];if(!o||!s)continue;const a=vt(t,e,o,s);null===a||a<=1e-6||a>=r||(r=a)}return Number.isFinite(r)?t.add(o.mul(r)):null}(r.applyToPoint(e.rawPagePoint),r.applyToPoint(e.oppositePagePoint),this.getPositionedOutlineVertices(t));return o?n.applyToPoint(o):e.rawPagePoint}},Pt=class{editor;id;parent;children=new Map;currentChild=null;initial=null;constructor(t,e,n){this.editor=t,this.id=e,this.parent=n}addChild(t){this.children.set(t.id,t)}enter(t){if(this.onEnter(t),!this.initial)return;const e=this.children.get(this.initial);if(!e)throw new Error(`Missing child state "${this.initial}" on "${this.id}"`);this.currentChild=e,e.enter(t)}exit(t){this.currentChild&&(this.currentChild.exit(t),this.currentChild=null),this.onExit(t)}transition(t,e){if(!this.parent){const n=this.children.get(t);if(!n)throw new Error(`Missing root child state "${t}" on tool "${this.id}"`);if(this.currentChild===n)return;return this.currentChild?.exit(e),this.currentChild=n,void n.enter(e)}this.parent.transition(t,e)}isInInitialState(){return!this.currentChild||!!this.initial&&(this.currentChild.id===this.initial&&this.currentChild.isInInitialState())}dispatch(t,e){if(this.currentChild)return this.currentChild.dispatch(t,e);switch(t.type){case"pointer":return this.handlePointerEvent(t,e);case"keyboard":return this.handleKeyboardEvent(t,e);case"wheel":return this.onWheel(t,e);case"tick":return this.onTick(t,e);case"cancel":return this.onCancel(t,e)}}onEnter(t){}onExit(t){}onPointerDown(t,e){}onPointerMove(t,e){}onPointerUp(t,e){}onCancel(t,e){}onKeyDown(t,e){}onKeyUp(t,e){}onWheel(t,e){}onTick(t,e){}handlePointerEvent(t,e){switch(t.name){case"pointer_down":return this.onPointerDown(t,e);case"pointer_move":return this.onPointerMove(t,e);case"pointer_up":return this.onPointerUp(t,e);case"pointer_cancel":return this.onCancel({type:"cancel",reason:"pointer_cancel"},e)}}handleKeyboardEvent(t,e){return"key_down"===t.name?this.onKeyDown(t,e):this.onKeyUp(t,e)}};function Mt(t){return Math.min(1,Math.max(0,(96-t)/96))}function It(t,e,n){if(e.w<=0||e.h<=0||n<=0)return O.Zero();const r=Math.min(n,32),o=Mt(t.x),i=Mt(e.w-t.x),s=Mt(t.y),a=1.25*(i-o)*r,l=1.25*(Mt(e.h-t.y)-s)*r;return 0===a&&0===l?O.Zero():new O(a,l)}Math.PI,Math.PI,Math.PI;function Tt(t,e,n,r={}){let o=!0;return e.graph.effect(t,()=>{e.get(),o&&!1===r.fireImmediately?o=!1:(o=!1,n())})}function Ct(t){return Math.max(0,Math.min(1,t))}function Et(t,e,n){return t.shapes.computePositionedToPageTransform(e).applyToPoint(function(t,e,n){const r=t.shapes.computePositionedBounds(e);return new O(r.minX+r.w*n.x,r.minY+r.h*n.y)}(t,e,n))}function At(t,e,n,r){return function(t,e,n,r){return t.shapes.getUtil(e).resolveBindingPoint(e,{editor:t,rawPagePoint:n,oppositePagePoint:r})}(t,e,Et(t,e,n),r)}var Ot=2*Math.PI;function Nt(t,e){const n="start"===e?t.props.start:t.props.end;return function(t,e){if(0===t.rotation&&1===t.scaleX&&1===t.scaleY)return e;const n=new O(t.x+t.props.w/2,t.y+t.props.h/2),r=e.sub(n),o=new O(r.x*t.scaleX,r.y*t.scaleY);return n.add(o.rot(t.rotation))}(t,new O(t.x+n.x,t.y+n.y))}function Rt(t,e,n){const r="start"===n?e.props.start:e.props.end;return t.shapes.computeLocalToPageTransform(e).applyToPoint(new O(r.x,r.y))}function Lt(t){return"start"===t?"end":"start"}function $t(t,e,n,r){const o=t.shapes.computeLocalToPageTransform(e).tryInvert();if(!o)return null;const i=Bt(o.applyToPoint(n),o.applyToPoint(r)),s=t.shapes.getUtil(e),a={...e,props:{...e.props,w:i.w,h:i.h,start:i.start,end:i.end}},l=et(s.getLocalTransform(e).compose(J.Translate(i.x,i.y)),s.getLocalBounds(a),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY});return l?{...a,...l}:null}function Dt(t,e,n,r){return $t(t,e,"start"===n?r:Rt(t,e,"start"),"end"===n?r:Rt(t,e,"end"))}function Bt(t,e){const n=Vt(t.x,e.x),r=Vt(t.y,e.y);return{x:n.origin,y:r.origin,w:n.size,h:r.size,start:{x:n.startOffset,y:r.startOffset},end:{x:n.endOffset,y:r.endOffset}}}function zt(t){return Xt(new O(t.props.start.x,t.props.start.y).add(new O(t.x,t.y)),new O(t.props.end.x,t.props.end.y).add(new O(t.x,t.y)),t.props.bend)}function Ft(t){return Xt(new O(t.props.start.x,t.props.start.y),new O(t.props.end.x,t.props.end.y),t.props.bend)}function jt(t,e,n){const r=O.Med(t,e),o=e.sub(t);if(o.len()<1e-6)return 0;const i=o.per().normalize();return-ee(n.sub(r),i)}function Wt(t){const e="curved"===t.type&&t.path.includes(" A "),n=e?null:function(t){const e=[];let n=0;for(let r=1;r<t.length;r+=1){const o=t[r-1].dist(t[r]);e.push(o),n+=o}return{length:n,segmentLengths:e}}(t.points),r=e?t.arc.length:n?.length??0,o=n?Ht(t.points,n,t.middle,.5):.5;return{length:r,defaultPosition:.5,getPointAt(r){const i=Ut(r);return e?Zt(t.start.point,t.end.point,t.arc,i):function(t,e,n){const r=t[0]??O.Zero();if(!e||e.length<=1e-6)return r.clone();const o=e.length*n;let i=0;for(let s=0;s<e.segmentLengths.length;s+=1){const n=e.segmentLengths[s];if(o<=i+n||s===e.segmentLengths.length-1){const e=t[s],r=t[s+1],a=n<=1e-6?0:(o-i)/n;return e.add(r.sub(e).mul(Ut(a)))}i+=n}return(t[t.length-1]??r).clone()}(t.points,n,_t(i,o))},getNearestPosition:(r,i)=>e?function(t,e,n=.5){const r=e.sub(t.arc.center);if(r.len2()<=1e-12)return Ut(n);const o=t.arc.center.add(r.normalize().mul(t.arc.radius)),i=Gt(t.start.point,t.end.point,t.arc);if(Math.abs(i)<=1e-6)return Ut(n);const s=Gt(t.start.point,o,t.arc);if(Math.abs(s)<=Math.abs(i)+1e-6)return Ut(s/i);const a=e.dist2(t.start.point),l=e.dist2(t.end.point);return Math.abs(a-l)<=1e-8?n<=.5?0:1:a<l?0:1}(t,r,i?.hintPosition):function(t,e){const n=Ut(t),r=Ut(e);return n<=r?r<=1e-6?.5:n/r*.5:1-r<=1e-6?.5:.5+(n-r)/(1-r)*.5}(Ht(t.points,n,r,_t(i?.hintPosition??.5,o)),o)}}function Ht(t,e,n,r=.5){if(!e||e.length<=1e-6)return Ut(r);let o=0,i=Ut(r),s=1/0;for(let a=0;a<e.segmentLengths.length;a+=1){const l=t[a],c=t[a+1],d=e.segmentLengths[a],u=c.sub(l),p=d<=1e-6?0:Ut(ee(n.sub(l),u)/u.len2()),h=l.add(u.mul(p)),f=(o+d*p)/e.length,m=h.dist2(n),g=m<s-1e-8,y=Math.abs(m-s)<=1e-8&&Math.abs(f-r)<Math.abs(i-r);(g||y)&&(s=m,i=f),o+=d}return Ut(i)}function _t(t,e){const n=Ut(t),r=Ut(e);return n<=.5?r*n*2:r+(1-r)*(n-.5)*2}function Ut(t){return Math.max(0,Math.min(1,t))}function Vt(t,e){const n=Math.min(t,e),r=Math.max(t,e);return Math.abs(r-n)<1e-6?{origin:n-.5,size:1,startOffset:.5,endOffset:.5}:{origin:n,size:r-n,startOffset:t-n,endOffset:e-n}}function Kt(t){return Number.isFinite(t)?Number(t.toFixed(3)).toString():"0"}function qt(t,e=0){return function(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}(t,e)}function Xt(t,e,n){const r=qt(n,0),o=function(t,e,n){const r=O.Med(t,e),o=e.sub(t),i=o.len()?o.per().normalize():new O(0,-1);return r.add(i.mul(-n))}(t,e,r),i=function(t,e,n){const r=function(t,e,n){const r=-2*(t.x*(e.y-n.y)-t.y*(e.x-n.x)+e.x*n.y-n.x*e.y);if(Math.abs(r)<1e-6)return null;const o=((t.x*t.x+t.y*t.y)*(n.y-e.y)+(e.x*e.x+e.y*e.y)*(t.y-n.y)+(n.x*n.x+n.y*n.y)*(e.y-t.y))/r,i=((t.x*t.x+t.y*t.y)*(e.x-n.x)+(e.x*e.x+e.y*e.y)*(n.x-t.x)+(n.x*n.x+n.y*n.y)*(t.x-e.x))/r;return Number.isFinite(o)&&Number.isFinite(i)?new O(o,i):null}(t,e,n);if(!r)return null;const o=r.dist(t);if(o<1e-6)return null;const i=(a=t,l=e,c=n,(c.x-a.x)*(l.y-a.y)-(l.x-a.x)*(c.y-a.y)<0?1:0),s=function(t,e,n){const r=t.dist(n),o=n.dist(e),i=e.dist(t);if(o<1e-6||i<1e-6)return 0;const s=(o*o+i*i-r*r)/(2*o*i);return 2*Math.acos(Math.max(-1,Math.min(1,s)))}(t,e,n);var a,l,c;if(!Number.isFinite(s))return null;const d=Math.PI>s?1:0,u=(Ot-s)*(i?1:-1);return{center:r,radius:o,largeArcFlag:d,sweepFlag:i,size:u,length:Math.abs(u*o)}}(t,o,e),s=Math.abs(r)<1e-6||null===i||0===i.length||!Number.isFinite(i.length)||!Number.isFinite(i.radius),a=s?[t,e]:Jt(t,e,i,24),l=s||null===i?`M ${Kt(t.x)} ${Kt(t.y)} L ${Kt(e.x)} ${Kt(e.y)}`:`M ${Kt(t.x)} ${Kt(t.y)} A ${Kt(i.radius)} ${Kt(i.radius)} 0 ${i.largeArcFlag} ${i.sweepFlag} ${Kt(e.x)} ${Kt(e.y)}`,c={start:{terminal:"start",point:t,handle:t},end:{terminal:"end",point:e,handle:e},middle:o,bend:r,points:a,bounds:N.FromPoints(a),path:l};return s?{type:"straight",...c,arc:null}:{type:"curved",...c,arc:i}}function Yt({start:t,end:e,middle:n,bend:r,arc:o,startHandle:i=t,endHandle:s=e}){const a=Gt(t,e,o);if(Math.abs(a)<1e-6||!Number.isFinite(a)||!Number.isFinite(o.radius)||o.radius<1e-6){const o=Xt(t,e,0);return{...o,start:{...o.start,handle:i},end:{...o.end,handle:s},middle:n,bend:r}}const l={center:o.center,radius:o.radius,largeArcFlag:Math.abs(a)>Math.PI?1:0,sweepFlag:o.sweepFlag,size:a,length:Math.abs(a*o.radius)},c=Jt(t,e,l,24),d=`M ${Kt(t.x)} ${Kt(t.y)} A ${Kt(l.radius)} ${Kt(l.radius)} 0 ${l.largeArcFlag} ${l.sweepFlag} ${Kt(e.x)} ${Kt(e.y)}`;return{type:"curved",start:{terminal:"start",point:t,handle:i},end:{terminal:"end",point:e,handle:s},middle:n,arc:l,bend:r,points:c,bounds:N.FromPoints(c),path:d}}function Jt(t,e,n,r){const o=[],i=O.Angle(n.center,t),s=Gt(t,e,n);for(let a=0;a<=r;a++){const t=a/r;o.push(Qt(n.center,n.radius,i+s*t))}return o}function Gt(t,e,n){return function(t,e,n){const r=e-t;return n?(r%Ot+Ot)%Ot:-((t-e)%Ot+Ot)%Ot}(O.Angle(n.center,t),O.Angle(n.center,e),n.sweepFlag)}function Zt(t,e,n,r){const o=O.Angle(n.center,t),i=Gt(t,e,n);return Qt(n.center,n.radius,o+i*r)}function Qt(t,e,n){return t.add(new O(Math.cos(n)*e,Math.sin(n)*e))}function te(t,e,n){const r=n.sub(e),o=r.x*r.x+r.y*r.y;if(0===o)return t.dist(e);const i=t.sub(e),s=Math.max(0,Math.min(1,ee(i,r)/o)),a=e.add(r.mul(s));return t.dist(a)}function ee(t,e){return t.x*e.x+t.y*e.y}var ne=["solid","dashed","dotted"];function re(t){return"string"==typeof t&&ne.includes(t)}function oe(t){return!!t&&"shape"===t.typeName&&"arrow"===t.type}function ie(t){return!!t&&"binding"===t.typeName&&"arrow"===t.type}function se(t,e,n){return t.bindings.getFromShape(e.id).find(t=>ie(t)&&t.props.terminal===n)??null}function ae(t,e,n){const r=Rt(t,e,n),o=se(t,e,n);if(!o)return{terminal:n,binding:null,target:null,handlePagePoint:r,boundaryPagePoint:r,isArcBoundaryPoint:!0};const i=t.shapes.get(o.toId);return!i||oe(i)?{terminal:n,binding:o,target:null,handlePagePoint:r,boundaryPagePoint:r,isArcBoundaryPoint:!0}:{terminal:n,binding:o,target:i,handlePagePoint:Et(t,i,o.props.normalizedAnchor),boundaryPagePoint:r,isArcBoundaryPoint:!1}}function le(t,e){const n=ae(t,e,"start"),r=ae(t,e,"end"),o=pe(t,e,n.handlePagePoint,r.handlePagePoint);return"curved"===o.type&&(ye(t,n,o,"start"),ye(t,r,o,"end")),{info:he(o,n,r),fullInfo:o,bindingSegments:[xe(n,o),xe(r,o)].filter(t=>null!==t)}}function ce(t,e){if(!se(t,e,"start")&&!se(t,e,"end"))return Ft(e);const n=t.shapes.computeLocalToPageTransform(e).tryInvert();return n?function(t,e,n){const r=ue(e.info,n);if("curved"!==e.info.type)return r;const o=Xt(n.applyToPoint(e.fullInfo.start.point),n.applyToPoint(e.fullInfo.end.point),t.props.bend);if("curved"!==o.type)return r;const i=n.applyToPoint(e.info.start.point),s=n.applyToPoint(e.info.end.point),a=function(t,e,n){const r=e.sub(t);if(r.len2()<1e-12)return null;const o=O.Med(t,e),i=r.per().normalize(),s=n.sub(o),a=s.x*i.x+s.y*i.y;return o.add(i.mul(a))}(i,s,o.arc.center);if(!a)return r;const l={center:a,radius:a.dist(i),sweepFlag:o.arc.sweepFlag},c=Zt(i,s,l,.5);return Yt({start:i,end:s,middle:c,bend:jt(i,s,c),arc:l,startHandle:n.applyToPoint(e.info.start.handle),endHandle:n.applyToPoint(e.info.end.handle)})}(e,le(t,e),n):Xt(new O(e.props.start.x,e.props.start.y),new O(e.props.end.x,e.props.end.y),e.props.bend)}function de(t,e,n){return{...t,start:{...t.start,handle:e},end:{...t.end,handle:n}}}function ue(t,e){const n=t=>e.applyToPoint(t),r=n(t.start.point),o=n(t.end.point),i=n(t.middle),s=t.points.map(n),a=s.map((t,e)=>`${0===e?"M":"L"} ${ge(t.x)} ${ge(t.y)}`).join(" "),l={start:{...t.start,point:r,handle:n(t.start.handle)},end:{...t.end,point:o,handle:n(t.end.handle)},middle:i,bend:jt(r,o,i),points:s,bounds:N.FromPoints(s),path:a};if("straight"===t.type)return{...t,...l};const c=n(t.arc.center),d={...t.arc,center:c,radius:c.dist(r),sweepFlag:e.determinant()<0?1===t.arc.sweepFlag?0:1:t.arc.sweepFlag};return function(t){const e=Math.hypot(t.a,t.b),n=Math.hypot(t.c,t.d),r=Math.max(1,e,n);return Math.abs(e-n)<=1e-8*r&&Math.abs(t.a*t.c+t.b*t.d)<=1e-8*r*r}(e)?Yt({start:r,end:o,middle:i,bend:l.bend,arc:d,startHandle:l.start.handle,endHandle:l.end.handle}):{...t,...l,arc:d}}function pe(t,e,n,r){const o=t.shapes.computeLocalToPageTransform(e),i=o.tryInvert();return i?ue(Xt(i.applyToPoint(n),i.applyToPoint(r),e.props.bend),o):Xt(n,r,e.props.bend)}function he(t,e,n){if(e.boundaryPagePoint.dist2(t.start.point)<1e-10&&n.boundaryPagePoint.dist2(t.end.point)<1e-10)return de(t,e.handlePagePoint,n.handlePagePoint);if("straight"===t.type)return de(Xt(e.boundaryPagePoint,n.boundaryPagePoint,0),e.handlePagePoint,n.handlePagePoint);if(t.path.includes(" A "))return Yt({start:e.boundaryPagePoint,end:n.boundaryPagePoint,middle:Zt(e.boundaryPagePoint,n.boundaryPagePoint,t.arc,.5),bend:t.bend,arc:t.arc,startHandle:e.handlePagePoint,endHandle:n.handlePagePoint});const r=fe(t.points,e.boundaryPagePoint),o=fe(t.points,n.boundaryPagePoint),i=[e.boundaryPagePoint];for(let a=Math.floor(r)+1;a<=Math.floor(o);a+=1){const e=t.points[a];e&&a<o&&i.push(e)}i.push(n.boundaryPagePoint);const s=function(t){if(0===t.length)return O.Zero();const e=[];let n=0;for(let o=0;o<t.length-1;o+=1){const r=t[o].dist(t[o+1]);e.push(r),n+=r}let r=n/2;for(let o=0;o<e.length;o+=1){const n=e[o];if(r<=n){const e=t[o];return e.add(t[o+1].sub(e).mul(0===n?0:r/n))}r-=n}return t[t.length-1]}(i);return{...t,start:{...t.start,point:e.boundaryPagePoint,handle:e.handlePagePoint},end:{...t.end,point:n.boundaryPagePoint,handle:n.handlePagePoint},middle:s,points:i,bounds:N.FromPoints(i),path:me(i),bend:jt(e.boundaryPagePoint,n.boundaryPagePoint,s)}}function fe(t,e){let n=0,r=1/0;for(let o=0;o<t.length-1;o+=1){const i=t[o],s=t[o+1].sub(i),a=s.len2(),l=0===a?0:Math.max(0,Math.min(1,((e.x-i.x)*s.x+(e.y-i.y)*s.y)/a)),c=i.add(s.mul(l)).dist2(e);c<r&&(r=c,n=o+l)}return n}function me(t){return t.map((t,e)=>`${0===e?"M":"L"} ${ge(t.x)} ${ge(t.y)}`).join(" ")}function ge(t){return Number(t.toFixed(3)).toString()}function ye(t,e,n,r){if(!e.target)return void(e.isArcBoundaryPoint=!0);const o=ve(t.shapes.getPageOutlineVertices(e.target.id),n,r);o?(e.boundaryPagePoint=o,e.isArcBoundaryPoint=!0):e.isArcBoundaryPoint=!1}function xe(t,e){if(!t.binding)return null;const n=function(t,e){return{terminal:t.terminal,anchorPagePoint:t.handlePagePoint,boundaryPagePoint:t.boundaryPagePoint,guidePath:"curved"===e.type&&t.isArcBoundaryPoint?be(t.terminal,t.handlePagePoint,t.boundaryPagePoint,e):null}}(t,e);return{terminal:n.terminal,anchorPagePoint:n.anchorPagePoint,boundaryPagePoint:n.boundaryPagePoint,guidePath:n.guidePath}}function we(t,{arrow:e,terminal:n,target:r,anchorPagePoint:o,fallbackBoundaryPagePoint:i}){const s=function(t,e,n){return ae(t,e,n).handlePagePoint}(t,e,Lt(n)),a=pe(t,e,"start"===n?o:s,"end"===n?o:s);if("curved"!==a.type)return{terminal:n,anchorPagePoint:o,boundaryPagePoint:i,guidePath:null};const l=ve(t.shapes.getPageOutlineVertices(r.id),a,n);return l?{terminal:n,anchorPagePoint:o,boundaryPagePoint:l,guidePath:be(n,o,l,a)}:{terminal:n,anchorPagePoint:o,boundaryPagePoint:i,guidePath:null}}function be(t,e,n,r){if(r.path.includes(" A "))return function({terminal:t,handlePagePoint:e,boundaryPagePoint:n,fullInfo:r}){if(e.dist(n)<1e-6)return null;const o="start"===t?r.arc.sweepFlag:function(t){return t?0:1}(r.arc.sweepFlag),i={center:r.arc.center,radius:r.arc.radius,sweepFlag:o};return Yt({start:e,end:n,middle:Zt(e,n,i,.5),bend:r.bend,arc:i}).path}({terminal:t,handlePagePoint:e,boundaryPagePoint:n,fullInfo:r});const o=fe(r.points,n),i=[e];if("start"===t)for(let s=1;s<=Math.floor(o);s+=1){const t=r.points[s];t&&s<o&&i.push(t)}else for(let s=r.points.length-2;s>=Math.ceil(o);s-=1){const t=r.points[s];t&&s>o&&i.push(t)}return i.push(n),me(i)}function ve(t,e,n){const r=[];for(let o=0;o<e.points.length-1;o+=1){const n=e.points[o],i=e.points[o+1];for(let e=0;e<t.length;e+=1){const s=t[e],a=t[(e+1)%t.length];if(!s||!a)continue;const l=ke(n,i,s,a);l&&r.push({point:l.point,position:o+l.t})}}return 0===r.length?null:(r.sort((t,e)=>t.position-e.position),"start"===n?r[0].point:r[r.length-1].point)}function ke(t,e,n,r){const o=e.sub(t),i=r.sub(n),s=o.x*i.y-o.y*i.x;if(Math.abs(s)<1e-9)return null;const a=n.sub(t),l=(a.x*i.y-a.y*i.x)/s,c=(a.x*o.y-a.y*o.x)/s;return l<-1e-9||l>1.000000001||c<-1e-9||c>1.000000001?null:{point:t.add(o.mul(Math.max(0,Math.min(1,l)))),t:Math.max(0,Math.min(1,l))}}function Se(t,e){const n=t.shapes.getPageBounds(e.id)??t.shapes.computePageBounds(e);return n.w*n.h}function Pe(t,e){return t.shapes.getUtil(e).canReceiveChildren(e)}function Me(t,e){return!(!e||oe(e))&&t.shapes.getUtil(e).canReceiveTerminalBinding(e,{editor:t})}function Ie(t,e,n){const r=Pe(t,e),o=Pe(t,n);if(r!==o)return r?1:-1;if(r&&o){const r=Se(t,e)-Se(t,n);if(Math.abs(r)>1e-6)return r}return 0}function Te(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function Ce(t){if(t)return{shapes:[t]}}var Ee=class extends A{type="arrow";getDefaultProps(){return{terminal:"start",normalizedAnchor:{x:.5,y:.5}}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps(),r=e.normalizedAnchor&&"object"==typeof e.normalizedAnchor?e.normalizedAnchor:n.normalizedAnchor;return{terminal:"end"===e.terminal?"end":n.terminal,normalizedAnchor:{x:Math.min(1,Math.max(0,Te(r.x,n.normalizedAnchor.x))),y:Math.min(1,Math.max(0,Te(r.y,n.normalizedAnchor.y)))}}}canBind(t,e,n){return oe(n.fromShape)&&Me(t,n.toShape)}getExclusiveBindingKey(t){return`${t.fromId}:${t.props.terminal}`}onBindingCreate(t,e){return Ce(this.syncArrowTerminal(t,e))}onBindingUpdate(t,e,n){return Ce(this.syncArrowTerminal(t,n))}onBindingLoad(t,e){return Ce(this.syncArrowTerminal(t,e))}getGeometryDependentShapeIds(t,e,n){return"to"===n.role?[e.fromId]:[]}onAfterShapeChange(t,e,n){return Ce(this.syncArrowTerminal(t,e))}onBeforeDeleteShape(t,e,n){if("from"===n.role)return{deleteBindingIds:[e.id]};const r=t.shapes.get(e.fromId);if(!oe(r))return{deleteBindingIds:[e.id]};const o=this.resolveTerminalPagePoint(t,e);return{shapes:[o?Dt(t,r,e.props.terminal,o)??r:r],deleteBindingIds:[e.id]}}onBeforeDeleteBinding(t,e){const n=t.shapes.get(e.fromId);if(!oe(n))return{deleteBindingIds:[e.id]};const r=this.resolveTerminalPagePoint(t,e);return{shapes:[r?Dt(t,n,e.props.terminal,r)??n:n],deleteBindingIds:[e.id]}}syncArrowTerminal(t,e){if(!ie(e))return null;const n=t.shapes.get(e.fromId);if(!oe(n))return null;const r=this.resolveTerminalPagePoint(t,e);return r?Rt(t,n,e.props.terminal).dist(r)<1e-6?null:Dt(t,n,e.props.terminal,r):null}resolveTerminalPagePoint(t,e){if(!ie(e))return null;const n=t.shapes.get(e.fromId),r=t.shapes.get(e.toId);if(!oe(n)||!r||oe(r))return null;const o=Rt(t,n,Lt(e.props.terminal)),i=At(t,r,e.props.normalizedAnchor,o);return we(t,{arrow:n,terminal:e.props.terminal,target:r,anchorPagePoint:Et(t,r,e.props.normalizedAnchor),fallbackBoundaryPagePoint:i}).boundaryPagePoint}};function Ae(t){return Object.freeze({id:t,kind:"api"})}function Oe(t,e,n="user"){if(e.parentId?.startsWith("shape:")){const n=t.shapes.get(e.parentId);if(!n||!t.shapes.computeLocalToPageTransform(n).tryInvert())throw new Error("Cannot create an arrow inside a singular parent transform")}const[r]=t.commands.createShapes([{type:"arrow",x:e.startPagePoint.x,y:e.startPagePoint.y,parentId:e.parentId,props:e.props,meta:e.meta}],{source:n,autoReparent:!1});if(!oe(r))throw new Error("Failed to create arrow shape");const o=$t(t,r,e.startPagePoint,e.endPagePoint);if(!o)throw new Error("Cannot create an arrow inside a singular parent transform");t.commands.updateShapes([{id:r.id,x:o.x,y:o.y,rotation:o.rotation,scaleX:o.scaleX,scaleY:o.scaleY,props:{...o.props}}],{source:n}),e.startBinding&&t.commands.createBinding({type:"arrow",fromId:o.id,toId:e.startBinding.targetShapeId,props:{terminal:"start",normalizedAnchor:e.startBinding.normalizedAnchor}},{source:n}),e.endBinding&&t.commands.createBinding({type:"arrow",fromId:o.id,toId:e.endBinding.targetShapeId,props:{terminal:"end",normalizedAnchor:e.endBinding.normalizedAnchor}},{source:n});const i=t.shapes.get(o.id);if(!oe(i))throw new Error("Failed to create arrow shape");return i}function Ne(t,e,n,r,o="user"){if(!e)return t.interaction.setBindingPreview(r.preview),null;let i=null;return i=function(t,e,n){const r=t.shapes.get(e.shapeId);if(!oe(r))return null;const o=Dt(t,r,e.terminal,e.pagePoint);if(!o)return null;t.commands.updateShapes([{id:r.id,x:o.x,y:o.y,rotation:o.rotation,scaleX:o.scaleX,scaleY:o.scaleY,props:{...o.props}}],{source:n});const i=t.bindings.getFromShape(r.id).find(t=>ie(t)&&t.props.terminal===e.terminal)??null;e.binding?ie(i)?t.commands.updateBinding({id:i.id,toId:e.binding.targetShapeId,props:{terminal:e.terminal,normalizedAnchor:e.binding.normalizedAnchor}},{source:n}):(i&&t.commands.deleteBinding(i.id,{source:n}),t.commands.createBinding({type:"arrow",fromId:r.id,toId:e.binding.targetShapeId,props:{terminal:e.terminal,normalizedAnchor:e.binding.normalizedAnchor}},{source:n})):i&&(t.commands.deleteBinding(i.id,{source:n}),t.commands.updateShapes([{id:r.id,x:o.x,y:o.y,rotation:o.rotation,scaleX:o.scaleX,scaleY:o.scaleY,props:{...o.props}}],{source:n}));const s=t.shapes.get(r.id);return oe(s)?s:o}(t,{shapeId:e,terminal:n,pagePoint:r.pagePoint,binding:r.binding},o),t.interaction.setBindingPreview(r.preview),i}var Re=Ae("plugin-arrow.api");function Le({editor:t}){return function({editor:t}){return{create(e){const n=t.shapes.getDefaultProps("arrow"),r=Oe(t,{startPagePoint:new O(e.start.x,e.start.y),endPagePoint:new O(e.end.x,e.end.y),startBinding:e.startBinding?{targetShapeId:e.startBinding.targetShapeId,normalizedAnchor:e.startBinding.normalizedAnchor}:null,endBinding:e.endBinding?{targetShapeId:e.endBinding.targetShapeId,normalizedAnchor:e.endBinding.normalizedAnchor}:null,meta:e.meta?{...e.meta}:void 0,props:{...n,bend:e.bend??n.bend,stroke:e.stroke??n.stroke,strokeStyle:e.strokeStyle??n.strokeStyle,strokeWidth:e.strokeWidth??n.strokeWidth,headStart:e.headStart??n.headStart,headEnd:e.headEnd??n.headEnd}});return{id:r.id,type:r.type}},getSelectionStyle(){const e=t.state.selectedShapes.get().filter(oe);return 0===e.length?null:{stroke:$e(e.map(t=>t.props.stroke)),strokeStyle:$e(e.map(t=>t.props.strokeStyle)),strokeWidth:$e(e.map(t=>t.props.strokeWidth)),headStart:$e(e.map(t=>t.props.headStart)),headEnd:$e(e.map(t=>t.props.headEnd))}},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(oe).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)},getToolDefaults:()=>t.shapes.getDefaultProps("arrow"),setToolDefaults:e=>(t.shapes.updateDefaultProps("arrow",e),t.shapes.getDefaultProps("arrow"))}}({editor:t})}function $e(t){const[e,...n]=t;return void 0!==e&&n.every(t=>t===e)?e:null}function De(t,e){const n=[];return"arrow"===e.headStart&&n.push(ze(t,"start",e.strokeWidth)),"arrow"===e.headEnd&&n.push(ze(t,"end",e.strokeWidth)),{path:n.length>0?n.map(Be).join(" "):null,points:n.flat()}}function Be([t,e,n]){return[`M ${Fe(t.x)} ${Fe(t.y)}`,`L ${Fe(e.x)} ${Fe(e.y)}`,`L ${Fe(n.x)} ${Fe(n.y)}`].join(" ")}function ze(t,e,n){const r=t[e].point,o=function(t,e){if("curved"===t.type){const n=t[e].point.sub(t.arc.center).per().mul(1===t.arc.sweepFlag?1:-1).normalize();if(n.len2()>0)return n}const n=t.end.point.sub(t.start.point).normalize();return n.len2()>0?n:new O(1,0)}(t,e),i=3.45*n*("start"===e?1:-1),s=o.per().mul(2*n),a=r.add(o.mul(i));return[a.sub(s),r,a.add(s)]}function Fe(t){return Number.isFinite(t)?Number(t.toFixed(3)).toString():"0"}function je(t,e){switch(t){case"dashed":return`${4*e} ${2*e}`;case"dotted":return"0 "+2*e;default:return}}function We(t,e){const n=t&&"object"==typeof t?t:void 0;return{x:He(n?.x,e.x),y:He(n?.y,e.y)}}function He(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function _e(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist(e);const i=t.sub(e),s=Math.max(0,Math.min(1,(i.x*r.x+i.y*r.y)/o));return t.dist(e.add(r.mul(s)))}function Ue(t,e,n,r){return function(t,e,n,r){const o=e.sub(t),i=r.sub(n),s=o.x*i.y-o.y*i.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(t),l=(a.x*i.y-a.y*i.x)/s,c=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&c>=0&&c<=1}(t,e,n,r)?0:Math.min(_e(t,n,r),_e(e,n,r),_e(n,t,e),_e(r,t,e))}var Ve=class extends St{type="arrow";getDefaultProps(){return{w:160,h:48,start:{x:8,y:24},end:{x:152,y:24},bend:0,stroke:W("stroke-slate"),strokeStyle:"solid",strokeWidth:2,headStart:"none",headEnd:"arrow"}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Math.max(1,He(e.w,n.w)),h:Math.max(1,He(e.h,n.h)),start:We(e.start,n.start),end:We(e.end,n.end),bend:He(e.bend,n.bend),stroke:V(e.stroke,n.stroke),strokeStyle:re(e.strokeStyle)?e.strokeStyle:n.strokeStyle,strokeWidth:Math.max(1,He(e.strokeWidth,n.strokeWidth)),headStart:"arrow"===e.headStart?"arrow":"none",headEnd:"none"===e.headEnd?"none":"arrow"}}getPositionedBounds(t){const e=zt(t),n=Math.max(6,.5*t.props.strokeWidth+4);return e.bounds.expand(n)}getPointHitTestBounds(t,e){const n=Math.max(8,t.props.strokeWidth+4);if(!e?.editor)return zt(t).bounds.expand(n);const r=le(e.editor,t).info,o=e.editor.shapes.computePositionedToPageTransform(t).tryInvert();if(!o||0===r.points.length)return zt(t).bounds.expand(n);const i=n*Math.sqrt(o.a*o.a+o.b*o.b+o.c*o.c+o.d*o.d);return N.FromPoints(r.points.map(t=>o.applyToPoint(t))).expand(i)}getLocalBounds(t){return new N(0,0,t.props.w,t.props.h)}getExportBounds(t){const e=Ft(t),n=Math.max(6,.5*t.props.strokeWidth+4);return e.bounds.expand(n)}updateSelectionPagePoints(t,e){const n=this.getSelectionPageMiddlePoint(t);if(e.pageMiddlePoint&&n){const r=this.getSelectionPagePoints(t),o=function(t,e){const n=t[1].sub(t[0]),r=t[2].sub(t[0]),o=n.x*r.y-n.y*r.x;if(Math.abs(o)<1e-9)return null;const i=new J(r.y/o,-n.y/o,-r.x/o,n.x/o,0,0),s=e[1].sub(e[0]),a=e[2].sub(e[0]),l=new J(s.x,s.y,a.x,a.y,0,0).compose(i);return new J(l.a,l.b,l.c,l.d,e[0].x-l.a*t[0].x-l.c*t[0].y,e[0].y-l.b*t[0].x-l.d*t[0].y)}([r[0],r[1],n],[e.pagePoints[0],e.pagePoints[1],e.pageMiddlePoint]);if(o){const e=et(o.compose(this.getLocalTransform(t)),this.getLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});if(e)return{id:t.id,...e}}}const r=function(t,e,n){const r=Bt(e,n);return{...t,x:r.x,y:r.y,rotation:0,scaleX:1,scaleY:1,props:{...t.props,w:r.w,h:r.h,start:r.start,end:r.end,bend:t.props.bend}}}(t,e.pagePoints[0],e.pagePoints[1]);return{id:t.id,x:r.x,y:r.y,rotation:r.rotation,scaleX:r.scaleX,scaleY:r.scaleY,props:{w:r.props.w,h:r.props.h,start:r.props.start,end:r.props.end,bend:e.pageMiddlePoint?jt(e.pagePoints[0],e.pagePoints[1],e.pageMiddlePoint):r.props.bend}}}isWrappedByBrush(t,e){return e.pageOutlineVertices.every(t=>e.brushBounds.containsPoint(t))}getSelectionPagePoints(t){return[Nt(t,"start"),Nt(t,"end")]}getSelectionPageMiddlePoint(t){return this.getLocalTransform(t).applyToPoint(Ft(t).middle)}contributesToSelectionFrame(t,e){return e.editor.selection.getIds().length>1}canUseSelectionResizeHandles(t,e){return e.editor.selection.getIds().length>1}canUseSelectionRotateHandle(t,e){return e.editor.selection.getIds().length>1}canStartTranslateFromSelectionBounds(t,e){return e.editor.selection.getIds().length>1}getSelectionHandleAnchors(t,e){if(!e.isOnlySelected)return{terminalHandleAnchors:[],middleHandleAnchors:[]};const n=le(e.editor,t).info;return{terminalHandleAnchors:[{kind:"binding_terminal",terminal:"start",point:n.start.handle},{kind:"binding_terminal",terminal:"end",point:n.end.handle}],middleHandleAnchors:n.middle?[{kind:"binding_middle",point:n.middle}]:[]}}getSelectionOverlayInfo(t,e){const n=le(e.editor,t),r=n.info,o=ce(e.editor,t),i=De(o,t.props),s=e.editor.shapes.computeLocalToPageTransform(t);return{usesSelectionPathOverlay:!0,startPagePoint:r.start.point,endPagePoint:r.end.point,middlePagePoint:r.middle,path:r.path,pathStyle:{localPath:o.path,localDecorationPaths:i.path?[i.path]:[],localBounds:N.FromPoints([...o.points,...i.points]),localToPage:s,strokeWidth:t.props.strokeWidth,strokeDasharray:je(t.props.strokeStyle,t.props.strokeWidth)},pageClipPath:ht({outputBounds:r.bounds,cutoutLocalPolygons:e.editor.shapes.getContentCutoutLocalPolygonsSignal(t.id).get(),localToOutput:s}),bindingSegments:n.bindingSegments}}getLabelPathGeometry(t,e){return Wt(le(e.editor,t).info)}hitTest(t,e,n){return function(t,e){let n=1/0;for(let r=0;r<t.points.length-1;r++)n=Math.min(n,te(e,t.points[r],t.points[r+1]));return Number.isFinite(n)?n:e.dist(t.start.point)}(n?.editor?le(n.editor,t).info:zt(t),n?.pagePoint??e)<=Math.max(8,t.props.strokeWidth+4)}hitTestLineSegment(t,e){const n=e.editor?le(e.editor,t).info:zt(t),r=Math.max(8,t.props.strokeWidth+4,e.editor?e.pageMargin:e.positionedMargin),o=e.editor?e.pageStart:e.positionedStart,i=e.editor?e.pageEnd:e.positionedEnd;if(1===n.points.length)return _e(n.points[0],o,i)<=r;for(let s=0;s<n.points.length-1;s+=1){const t=n.points[s],e=n.points[s+1];if(t&&e&&Ue(o,i,t,e)<=r)return!0}return!1}};function Ke(t,e,n,r){const o=function(t,e){let n=null;for(const r of e)(!n||Ie(t,r,n)<0)&&(n=r);return n}(t,t.shapes.hitTestPoint(e,{hitTest:"bindingTarget",filter:e=>e.id!==r?.excludeShapeId&&Me(t,e)}));if(!o)return null;const i=function(t,e,n){const r=t.shapes.computePositionedToPageTransform(e).tryInvert(),o=t.shapes.computePositionedBounds(e);if(!r)return{x:.5,y:.5};const i=r.applyToPoint(n),s=o.w<=1e-6?.5:(i.x-o.minX)/o.w,a=o.h<=1e-6?.5:(i.y-o.minY)/o.h;return{x:Ct(s),y:Ct(a)}}(t,o,e);return{targetShape:o,normalizedAnchor:i,resolvedPagePoint:At(t,o,i,n),rawPagePoint:e.clone()}}function qe(t,{terminal:e,rawPagePoint:n,oppositePagePoint:r,excludeShapeId:o,ignoreTargets:i=!1}){if(i)return{pagePoint:n.clone(),binding:null,preview:null};const s=Ke(t,n,r,{excludeShapeId:o});return{pagePoint:s?.resolvedPagePoint??n.clone(),binding:Je(s),preview:Ge(e,s)}}function Xe(t,{terminal:e,rawPagePoint:n,ignoreTargets:r=!1}){return qe(t,{terminal:e,rawPagePoint:n,oppositePagePoint:n.add(new O(1,0)),ignoreTargets:r})}function Ye(t,{arrow:e,terminal:n,rawPagePoint:r,ignoreTargets:o=!1}){const i=qe(t,{terminal:n,rawPagePoint:r,oppositePagePoint:Rt(t,e,Lt(n)),excludeShapeId:e.id,ignoreTargets:o});if(!i.preview)return i;const s=function(t,{arrow:e,terminal:n,rawPagePoint:r,preview:o}){const i=t.shapes.get(o.targetShapeId);if(!i||oe(i))return o;const s=we(t,{arrow:e,terminal:n,target:i,anchorPagePoint:r,fallbackBoundaryPagePoint:o.resolvedPagePoint});return{...o,resolvedPagePoint:s.boundaryPagePoint,guidePath:s.guidePath}}(t,{arrow:e,terminal:n,rawPagePoint:r,preview:i.preview});return{...i,pagePoint:s.resolvedPagePoint,preview:s}}function Je(t){return t?{targetShapeId:t.targetShape.id,normalizedAnchor:t.normalizedAnchor}:null}function Ge(t,e){return e?{terminal:t,targetShapeId:e.targetShape.id,rawPagePoint:e.rawPagePoint,resolvedPagePoint:e.resolvedPagePoint}:null}var Ze=class extends Pt{constructor(t){super(t,"arrow"),this.initial="idle",this.addChild(new Qe(t,this)),this.addChild(new tn(t,this))}},Qe=class extends Pt{constructor(t,e){super(t,"idle",e)}onEnter(){this.editor.interaction.clearSelection()}onPointerDown(t){const e=this.editor.shapes.getDefaultProps("arrow"),n=Xe(this.editor,{terminal:"start",rawPagePoint:t.pagePoint,ignoreTargets:t.accelKey});this.transition("creating",{startPagePoint:n.pagePoint,startScreenPoint:t.screenPoint.clone(),currentPagePoint:n.pagePoint.clone(),shapeId:null,startBinding:n.binding,props:e})}},tn=class extends Pt{info=null;operation=null;isClickCreating=!1;constructor(t,e){super(t,"creating",e)}onEnter(t){if(this.info=t,this.isClickCreating=!1,!this.info)return;this.operation=this.editor.operations.begin({kind:"arrow.create",label:"shape.create",source:"user",history:"record"});const e=Oe(this.editor,{startPagePoint:this.info.startPagePoint,endPagePoint:this.info.startPagePoint,startBinding:this.info.startBinding,props:{stroke:this.info.props.stroke,strokeStyle:this.info.props.strokeStyle,strokeWidth:this.info.props.strokeWidth,headStart:this.info.props.headStart,headEnd:this.info.props.headEnd}},"user");this.info.shapeId=e.id,this.editor.commands.setSelectedShapeIds([e.id],{source:"system"}),this.editor.interaction.setBindingPreview(null),this.updateCreationBindingGuides(e)}onPointerDown(t){this.isClickCreating&&this.updateShape(t.pagePoint)}onPointerMove(t){this.updateShape(t.pagePoint)}onTick(t){if(!this.info)return;const e=this.editor.inputs.state.get();if("dragging"!==e.dragPhase||!e.currentPagePoint||!e.currentScreenPoint)return;const n=It(e.currentScreenPoint,this.editor.state.viewportScreenSize.get(),t.elapsed);0===n.x&&0===n.y||(this.editor.viewport.pan(n),this.updateShape(this.editor.viewport.screenToPage(e.currentScreenPoint)))}onPointerUp(t){if(this.info)return this.updateShape(t.pagePoint),this.info.shapeId?this.info.startScreenPoint.dist(t.screenPoint)<10?this.isClickCreating?(this.cancelOperation(),this.transition("idle"),{clickSequence:"break"}):void(this.isClickCreating=!0):(nt(this.editor,this.info.shapeId,{source:"user"}),this.commitOperation(),this.editor.state.tool.get().isToolLocked?(this.transition("idle"),{clickSequence:"break"}):(this.editor.commands.setActiveTool("select",{source:"system"}),{clickSequence:"break"})):(this.cancelOperation(),void this.transition("idle"));this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.cancelOperation(),this.editor.interaction.setTerminalBindingGuides(null),this.info=null,this.isClickCreating=!1}commitOperation(){const t=this.operation;this.operation=null,t?.commit()}cancelOperation(){const t=this.operation;this.operation=null,t?.isActive&&t.cancel()}updateShape(t){if(!this.info)return;this.info.currentPagePoint=t.clone();const e=this.info.shapeId,n=e?this.editor.shapes.get(e):null,r=oe(n)?Ye(this.editor,{arrow:n,terminal:"end",rawPagePoint:t,ignoreTargets:this.editor.inputs.state.get().accelKey}):qe(this.editor,{terminal:"end",rawPagePoint:t,oppositePagePoint:this.info.startPagePoint,ignoreTargets:this.editor.inputs.state.get().accelKey}),o=this.info.startBinding&&r.binding?.targetShapeId===this.info.startBinding.targetShapeId?{pagePoint:t,binding:null,preview:null}:r,i=Ne(this.editor,e,"end",o,"user")??(e?this.editor.shapes.get(e):null);this.updateCreationBindingGuides(oe(i)?i:null)}updateCreationBindingGuides(t){if(!t)return void this.editor.interaction.setTerminalBindingGuides(null);const e=new Map(this.editor.bindings.getFromShape(t.id).filter(ie).map(t=>[t.props.terminal,t.toId])),n=le(this.editor,t).bindingSegments.map(n=>({...n,ownerShapeId:t.id,targetShapeId:e.get(n.terminal)??null}));this.editor.interaction.setTerminalBindingGuides(n)}};function en({shapeId:t}){return{shapeId:t,operationKind:"select.binding_middle_drag",update({editor:e,pagePoint:n,accelKey:r,source:o}){const i=e.shapes.get(t);if(!oe(i))return"stop";const s=function(t,e){return{start:ae(t,e,"start").handlePagePoint,end:ae(t,e,"end").handlePagePoint}}(e,i),a=jt(s.start,s.end,n),l=e.shapes.computeLocalToPageTransform(i).tryInvert();if(!l)return"stop";const c=jt(l.applyToPoint(s.start),l.applyToPoint(s.end),l.applyToPoint(n)),d=0===function({bend:t,bypassSnap:e,zoom:n}){return e?t:Math.abs(t)*n<=6?0:t}({bend:a,bypassSnap:r,zoom:e.state.cameraZoom.get()})?0:c;return e.commands.updateShapes([{id:i.id,props:{bend:d}}],{source:o}),"continue"}}}function nn(){return{createSession:(t,{handle:e,shape:n})=>oe(n)?"binding_terminal"===e.kind?function({handle:t,shapeId:e,terminal:n}){return{shapeId:e,operationKind:"select.binding_terminal_drag",handleSnapMode:"point",handleSnapContext:{shapeId:e,handle:t},shouldClearBindingPreviewOnExit:!0,update({editor:t,pagePoint:r,accelKey:o,source:i}){const s=t.shapes.get(e);if(!oe(s))return{status:"stop",finalPagePoint:null};const a=Ye(t,{arrow:s,terminal:n,rawPagePoint:r,ignoreTargets:o}),l=Ne(t,s.id,n,a,i);return{status:"continue",finalPagePoint:l?Rt(t,l,n):a.pagePoint}}}}({handle:e,shapeId:n.id,terminal:e.terminal}):"binding_middle"===e.kind?en({shapeId:n.id}):null:null}}function rn(){return{id:"land.arrow.interactions",selectionHandle:nn()}}var on=class{type="arrow";toSvg(t,e){const n=e.resolveColor(t.props.stroke),r=ce(e.editor,t),o=ht({outputBounds:r.bounds,cutoutLocalPolygons:e.editor.shapes.getContentCutoutLocalPolygonsSignal(t.id).get()}),i=o?e.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"path",attrs:{d:o,"clip-rule":"evenodd","fill-rule":"evenodd"}}]}):void 0,s="arrow"===t.props.headStart?`url(#${e.addDef(an("start",n))})`:void 0,a="arrow"===t.props.headEnd?`url(#${e.addDef(an("end",n))})`:void 0;return{tag:"path",attrs:{d:r.path,fill:"none",stroke:n,"stroke-width":t.props.strokeWidth,"stroke-dasharray":je(t.props.strokeStyle,t.props.strokeWidth),"stroke-linecap":"round","stroke-linejoin":"round","marker-start":s,"marker-end":a,"clip-path":i?`url(#${i})`:void 0}}}};function sn(){return{id:"land.arrow",shapeUtils:[new Ve],shapeSvgExporters:[new on],bindingUtils:[new Ee],interactionHandlers:[rn()],setup(t){t.bindings.setTerminalResolver(qe),t.tools.register("arrow",t=>new Ze(t))}}}function an(t,e){return{tag:"marker",attrs:{markerWidth:12,markerHeight:12,viewBox:"0 0 24 24",refX:"start"===t?2:22,refY:12,orient:"auto",markerUnits:"strokeWidth"},children:[{tag:"path",attrs:{d:"start"===t?"M8.9,8 L2,12 L8.9,16":"M15.1,8 L22,12 L15.1,16",fill:"none",stroke:e,"stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"}}]}}function ln(){return{id:"land.arrow.react",shapeRenderers:[{type:"arrow",component:cn,hoverComponent:dn}]}}function cn({shape:t,editor:e}){
2
- return l(un,{shape:t,editor:e,idPrefix:"arrow",stroke:K(t.props.stroke),strokeWidth:t.props.strokeWidth})}function dn({shape:t,editor:e,strokeWidth:r}){
3
- return l(un,{dataUi:"arrow-hover-outline",shape:t,editor:e,idPrefix:"arrow-hover",stroke:n,strokeWidth:r,vectorEffect:"non-scaling-stroke"})}function un({dataUi:t,editor:n,idPrefix:r,shape:o,stroke:i,strokeWidth:s,vectorEffect:a}){const d=`${r}-content-clip-${o.id.replace(/[^a-zA-Z0-9_-]/g,"-")}`,u=ce(n,o),p=De(u,o.props),h=e(n.shapes.getContentCutoutLocalPolygonsSignal(o.id)),f=ht({outputBounds:u.bounds,cutoutLocalPolygons:h});
4
- return c("svg",{"data-ui":t,width:"100%",height:"100%",viewBox:`0 0 ${o.props.w} ${o.props.h}`,overflow:"visible",children:[f?l("defs",{children:l("clipPath",{id:d,clipPathUnits:"userSpaceOnUse",children:l("path",{d:f,clipRule:"evenodd",fillRule:"evenodd"})})}):null,c("g",{clipPath:f?`url(#${d})`:void 0,children:[l("path",{"data-arrow-path":"body",d:u.path,fill:"none",stroke:i,strokeWidth:s,strokeDasharray:je(o.props.strokeStyle,s),strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:a}),p.path?l("path",{"data-arrow-path":"heads",d:p.path,fill:"none",stroke:i,strokeWidth:s,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:a}):null]})]})}var pn={id:"arrow",editor:sn(),render:ln(),api:Re,setup:({editor:t})=>({api:Le({editor:t})})},hn={outline:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},filled:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none"}},fn=(t,e,n,r)=>{const o=f(({color:n="currentColor",size:o=24,stroke:i=2,title:s,className:a,children:l,...c},d)=>h("svg",{ref:d,...hn[t],width:o,height:o,className:["tabler-icon",`tabler-icon-${e}`,a].join(" "),..."filled"===t?{fill:n}:{strokeWidth:i,stroke:n},...c},[s&&h("title",{key:"svg-title"},s),...r.map(([t,e])=>h(t,e)),...Array.isArray(l)?l:[l]]));return o.displayName=`${n}`,o},mn=fn("outline","arrow-right","ArrowRight",[["path",{d:"M5 12l14 0",key:"svg-0"}],["path",{d:"M13 18l6 -6",key:"svg-1"}],["path",{d:"M13 6l6 6",key:"svg-2"}]]),gn=fn("outline","photo-scan","PhotoScan",[["path",{d:"M15 8h.01",key:"svg-0"}],["path",{d:"M6 13l2.644 -2.644a1.21 1.21 0 0 1 1.712 0l3.644 3.644",key:"svg-1"}],["path",{d:"M13 13l1.644 -1.644a1.21 1.21 0 0 1 1.712 0l1.644 1.644",key:"svg-2"}],["path",{d:"M3 7v-2a2 2 0 0 1 2 -2h2",key:"svg-3"}],["path",{d:"M3 17v2a2 2 0 0 0 2 2h2",key:"svg-4"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"svg-5"}],["path",{d:"M17 21h2a2 2 0 0 0 2 -2v-2",key:"svg-6"}]]),yn=fn("outline","photo","Photo",[["path",{d:"M15 8h.01",key:"svg-0"}],["path",{d:"M3 6a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v12a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3v-12",key:"svg-1"}],["path",{d:"M3 16l5 -5c.928 -.893 2.072 -.893 3 0l5 5",key:"svg-2"}],["path",{d:"M14 14l1 -1c.928 -.893 2.072 -.893 3 0l3 3",key:"svg-3"}]]),xn=fn("outline","plus","Plus",[["path",{d:"M12 5l0 14",key:"svg-0"}],["path",{d:"M5 12l14 0",key:"svg-1"}]]),wn=fn("outline","text-scan-ai","TextScanAi",[["path",{d:"M8 12h4.5",key:"svg-0"}],["path",{d:"M8 8h6",key:"svg-1"}],["path",{d:"M8 16h2",key:"svg-2"}],["path",{d:"M3 7v-2a2 2 0 0 1 2 -2h2",key:"svg-3"}],["path",{d:"M3 17v2a2 2 0 0 0 2 2h2",key:"svg-4"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"svg-5"}],["path",{d:"M14 21v-4a2 2 0 1 1 4 0v4",key:"svg-6"}],["path",{d:"M14 19h4",key:"svg-7"}],["path",{d:"M21 15v6",key:"svg-8"}]]),bn=fn("outline","typography","Typography",[["path",{d:"M4 20l3 0",key:"svg-0"}],["path",{d:"M14 20l7 0",key:"svg-1"}],["path",{d:"M6.9 15l6.9 0",key:"svg-2"}],["path",{d:"M10.2 6.3l5.8 13.7",key:"svg-3"}],["path",{d:"M5 20l6 -16l2 0l7 16",key:"svg-4"}]]),vn=36,kn=36,Sn=4,Pn=12,Mn=8,In=15,Tn=12,Cn=20,En=12,An=10,On=8,Nn=8,Rn=320,Ln=160,$n=96,Dn=48,Bn="8 6";function zn(t){return C(t)&&"connector"===t.type}function Fn(t){return function(t){return!!t&&"binding"===t.typeName}(t)&&"connector"===t.type}function jn(t,e){let n=null,r=null;for(const o of t.bindings.getFromShape(e))Fn(o)&&("start"===o.props.terminal?n=o:r=o);return{start:n,end:r}}function Wn(t,e){return t.bindings.getFromShape(e).filter(Fn)}var Hn=.001;function _n(t,e){const n=Un(t),r=Un(e);let o;if(n&&(n.needsWinding=er(n,e.point)),r&&(r.needsWinding=er(r,t.point)),n||r)if(n&&r){if(void 0!==t.obstacleId&&t.obstacleId===e.obstacleId)return o=function(t,e,n,r){const o=dr(t.bounds,e.bounds),i=Math.max(36,36),s=new N(o.minX-i,o.minY-i,o.w+2*i,o.h+2*i),a=Vn(t,s),l=Vn(e,s);return function(t,e){const n=t.filter(t=>!function(t,e){for(let n=1;n<t.length;n+=1){const r=t[n-1],o=t[n];if(Math.abs(r.y-o.y)<Hn){if(r.y>e.minY+Hn&&r.y<e.maxY-Hn&&Math.max(r.x,o.x)>e.minX+Hn&&Math.min(r.x,o.x)<e.maxX-Hn)return!0}else if(r.x>e.minX+Hn&&r.x<e.maxX-Hn&&Math.max(r.y,o.y)>e.minY+Hn&&Math.min(r.y,o.y)<e.maxY-Hn)return!0}return!1}(t,e)&&!function(t){for(let e=1;e<t.length;e+=1)for(let n=e+2;n<t.length;n+=1)if(tr(t[e-1],t[e],t[n-1],t[n]))return!0;return!1}(t));return[...n.length>0?n:t].sort(Yn)[0]}([ur([n,...Kn(a,t.side,l,e.side,s),r]),ur([n,...Kn(l,e.side,a,t.side,s).reverse(),r])],o)}(n,r,t.point,e.point),ur(o);o=n.needsWinding&&r.needsWinding?rr(n,r,t.point,e.point):n.needsWinding?nr(n,r,t.point,e.point):r.needsWinding?nr(r,n,e.point,t.point).reverse():function(t,e,n,r){if(ir(n,r))return[n,r];if(t.axis===e.axis){if("horizontal"===t.axis){const o=(t.point.x+e.point.x)/2;return[n,new O(o,n.y),new O(o,r.y),r]}const o=(t.point.y+e.point.y)/2;return[n,new O(n.x,o),new O(r.x,o),r]}return"horizontal"===t.axis?[n,new O(r.x,n.y),r]:[n,new O(n.x,r.y),r]}(n,r,t.point,e.point)}else{const i=n??r,s=n?t.point:e.point,a=n?e.point:t.point;o=i.needsWinding?function(t,e,n){const{bounds:r,neighborPoint:o}=t;if("horizontal"===t.axis){if(n.y<r.minY||n.y>r.maxY)return[e,o,new O(o.x,n.y),n];const t=n.y+e.y>r.minY+r.maxY?r.maxY+36:r.minY-36;return[e,o,new O(o.x,t),new O(n.x,t),n]}if(n.x<r.minX||n.x>r.maxX)return[e,o,new O(n.x,o.y),n];const i=n.x+e.x>r.minX+r.maxX?r.maxX+36:r.minX-36;return[e,o,new O(i,o.y),new O(i,n.y),n]}(i,s,a):function(t,e,n){if(ir(e,n))return[e,n];const r=n.sub(e);if("horizontal"===t.axis){if(Math.abs(r.x)<=Math.abs(r.y))return[e,new O(n.x,e.y),n];const t=e.x+r.x/2;return[e,new O(t,e.y),new O(t,n.y),n]}if(Math.abs(r.x)>Math.abs(r.y))return[e,new O(e.x,n.y),n];const o=e.y+r.y/2;return[e,new O(e.x,o),new O(n.x,o),n]}(i,s,a),n||o.reverse()}else o=function(t,e){if(ir(t,e))return[t,e];const n=e.sub(t);if(Math.abs(n.x)>Math.abs(n.y)){const r=t.x+n.x/2;return[t,new O(r,t.y),new O(r,e.y),e]}const r=t.y+n.y/2;return[t,new O(t.x,r),new O(e.x,r),e]}(t.point,e.point);return ur(o)}function Un(t){if(!t.obstacleBounds)return null;const e=function(t){return Math.abs(t.x)>=Math.abs(t.y)?"horizontal":"vertical"}(t.direction),n=function(t,e){return"horizontal"===e?new O(t.x>=0?1:-1,0):new O(0,t.y>=0?1:-1)}(t.direction,e);return{point:t.point,neighborPoint:t.point.add(n.mul(36)),bounds:t.obstacleBounds,axis:e,side:or(n,e),needsWinding:!1}}function Vn(t,e){switch(t.side){case"top":return new O(t.point.x,e.minY);case"right":return new O(e.maxX,t.point.y);case"bottom":return new O(t.point.x,e.maxY);case"left":return new O(e.minX,t.point.y)}}function Kn(t,e,n,r,o){const i=2*(o.w+o.h);if(i<=Hn)return[t,n];const s=qn(t,e,o),a=Xn(qn(n,r,o)-s,i),l=[t],c=[{position:0,point:new O(o.minX,o.minY)},{position:o.w,point:new O(o.maxX,o.minY)},{position:o.w+o.h,point:new O(o.maxX,o.maxY)},{position:2*o.w+o.h,point:new O(o.minX,o.maxY)}].map(t=>({...t,travel:Xn(t.position-s,i)})).filter(t=>t.travel>Hn&&t.travel<a-Hn).sort((t,e)=>t.travel-e.travel);return l.push(...c.map(t=>t.point)),l.push(n),l}function qn(t,e,n){switch(e){case"top":return t.x-n.minX;case"right":return n.w+t.y-n.minY;case"bottom":return n.w+n.h+n.maxX-t.x;case"left":return 2*n.w+n.h+n.maxY-t.y}}function Xn(t,e){return(t%e+e)%e}function Yn(t,e){const n=Jn(t)-Jn(e);if(0!==n)return n;const r=Gn(t)-Gn(e);return Math.abs(r)>Hn?r:Qn(Zn(t),Zn(e))}function Jn(t){let e=0;for(let n=1;n<t.length-1;n+=1){const r=t[n].sub(t[n-1]),o=t[n+1].sub(t[n]);Math.abs(r.x*o.y-r.y*o.x)>Hn&&(e+=1)}return e}function Gn(t){let e=0;for(let n=1;n<t.length;n+=1){const r=t[n-1],o=t[n];e+=Math.abs(o.x-r.x)+Math.abs(o.y-r.y)}return e}function Zn(t){const e=t.flatMap(t=>[t.x,t.y]),n=[...t].reverse().flatMap(t=>[t.x,t.y]);return Qn(e,n)<=0?e:n}function Qn(t,e){const n=Math.min(t.length,e.length);for(let r=0;r<n;r+=1){const n=t[r]-e[r];if(Math.abs(n)>Hn)return n}return t.length-e.length}function tr(t,e,n,r){const o=Math.abs(t.y-e.y)<Hn,i=Math.abs(n.y-r.y)<Hn;if(o&&i)return Math.abs(t.y-n.y)<Hn&&Math.max(Math.min(t.x,e.x),Math.min(n.x,r.x))<=Math.min(Math.max(t.x,e.x),Math.max(n.x,r.x))+Hn;if(!o&&!i)return Math.abs(t.x-n.x)<Hn&&Math.max(Math.min(t.y,e.y),Math.min(n.y,r.y))<=Math.min(Math.max(t.y,e.y),Math.max(n.y,r.y))+Hn;const s=o?t:n,a=o?e:r,l=o?n:t,c=o?r:e;return l.x>=Math.min(s.x,a.x)-Hn&&l.x<=Math.max(s.x,a.x)+Hn&&s.y>=Math.min(l.y,c.y)-Hn&&s.y<=Math.max(l.y,c.y)+Hn}function er(t,e){return!function(t,e){return t.x>=e.minX&&t.x<=e.maxX&&t.y>=e.minY&&t.y<=e.maxY}(e,t.bounds)&&(n=t.neighborPoint.sub(t.point),r=e.sub(t.point),n.x*r.x+n.y*r.y<=0);var n,r}function nr(t,e,n,r){const o=t.neighborPoint,i=dr(t.bounds,e.bounds);if("horizontal"===t.axis){if("horizontal"===e.axis&&function(t,e){return t.y<e.minY||t.y>e.maxY}(r,t.bounds))return[n,o,new O(o.x,r.y),r];if("horizontal"===e.axis){const i=r.y+n.y>t.bounds.minY+t.bounds.maxY?t.bounds.maxY+36:t.bounds.minY-36,s=lr(t.bounds,e.bounds);return[n,o,new O(o.x,i),new O(s,i),new O(s,r.y),r]}if(ar(t.bounds,e.bounds)){const i=cr(t.bounds,e.bounds);return[n,o,new O(o.x,i),new O(r.x,i),r]}const s=e.neighborPoint.y>r.y?i.maxY+36:i.minY-36;return[n,o,new O(o.x,s),new O(r.x,s),r]}if("horizontal"===e.axis&&function(t,e){return t.x<e.minX||t.x>e.maxX}(r,t.bounds))return[n,o,new O(r.x,o.y),r];if("vertical"===e.axis){if(sr(t.bounds,e.bounds)){const i=lr(t.bounds,e.bounds);return[n,o,new O(i,o.y),new O(i,r.y),r]}const s=e.neighborPoint.x>r.x?i.maxX+36:i.minX-36;return[n,o,new O(s,o.y),new O(s,r.y),r]}const s=r.x+n.x>t.bounds.minX+t.bounds.maxX?t.bounds.maxX+36:t.bounds.minX-36,a=cr(t.bounds,e.bounds);return[n,o,new O(s,o.y),new O(s,a),new O(r.x,a),r]}function rr(t,e,n,r){const o=t.neighborPoint,i=e.neighborPoint,s=dr(t.bounds,e.bounds);if("horizontal"===t.axis&&"horizontal"===e.axis){if(Math.abs(n.x-r.x)<Hn&&Math.abs(o.x-i.x)<Hn)return[n,o,i,r];let a,l,c;return ar(t.bounds,e.bounds)?(a=o.x,l=i.x,c=cr(t.bounds,e.bounds)):o.x>n.x?(a=s.maxX+36,l=s.minX-36,c=s.minY-36):(a=s.minX-36,l=s.maxX+36,c=s.maxY+36),[n,new O(a,n.y),new O(a,c),new O(l,c),new O(l,r.y),r]}if(t.axis!==e.axis){if("horizontal"===t.axis){const t=o.x>n.x?s.maxX+36:s.minX-36,e=i.y>r.y?s.maxY+36:s.minY-36;return[n,new O(t,n.y),new O(t,e),new O(r.x,e),r]}return rr(e,t,r,n).reverse()}if(Math.abs(n.y-r.y)<Hn&&Math.abs(o.y-i.y)<Hn)return[n,o,i,r];let a,l,c;return sr(t.bounds,e.bounds)?(a=o.y,l=i.y,c=lr(t.bounds,e.bounds)):o.y>n.y?(a=s.maxY+36,l=s.minY-36,c=s.maxX+36):(a=s.minY-36,l=s.maxY+36,c=s.minX-36),[n,new O(n.x,a),new O(c,a),new O(c,l),new O(r.x,l),r]}function or(t,e){return"horizontal"===e?t.x>=0?"right":"left":t.y>=0?"bottom":"top"}function ir(t,e){return Math.abs(t.x-e.x)<Hn||Math.abs(t.y-e.y)<Hn}function sr(t,e){return t.maxX<=e.minX||e.maxX<=t.minX}function ar(t,e){return t.maxY<=e.minY||e.maxY<=t.minY}function lr(t,e){return e.minX>=t.maxX?t.maxX+(e.minX-t.maxX)/2:e.maxX+(t.minX-e.maxX)/2}function cr(t,e){return e.minY>=t.maxY?t.maxY+(e.minY-t.maxY)/2:e.maxY+(t.minY-e.maxY)/2}function dr(t,e){const n=Math.min(t.minX,e.minX),r=Math.min(t.minY,e.minY),o=Math.max(t.maxX,e.maxX),i=Math.max(t.maxY,e.maxY);return new N(n,r,o-n,i-r)}function ur(t){const e=[];for(const n of t){const t=e[e.length-1];if(t&&t.dist(n)<Hn)continue;const r=e[e.length-2];r&&t&&(Math.abs(r.x-t.x)<Hn&&Math.abs(t.x-n.x)<Hn||Math.abs(r.y-t.y)<Hn&&Math.abs(t.y-n.y)<Hn)?e[e.length-1]=n:e.push(n)}return e}var pr="border:";function hr(t,e){const n=t.shapes.computePositionedToPageTransform(e);return t.shapes.getUtil(e).getTerminalBindingOutlines(e,{editor:t}).map(t=>({points:t.points.map(t=>n.applyToPoint(t)),closed:t.closed})).filter(t=>t.points.length>0)}function fr(t,e,n,r){const o=xr(t,e,n);if(!o)return null;const i=function(t,e){return[...t].sort((t,n)=>t.pagePoint.dist(e)-n.pagePoint.dist(e)||t.id.localeCompare(n.id))[0]??null}(yt(t,e),o.point),s=i?xr(t,e,i.pagePoint):null;if(i&&s&&s.distance<=1e-4&&i.pagePoint.dist(o.point)<=r)return{port:i,borderDistance:o.distance};const a=function(t,e,n){const r=t.shapes.computePositionedToPageTransform(e).tryInvert(),o=t.shapes.computePositionedBounds(e);if(!r)return{x:.5,y:.5};const i=r.applyToPoint(n);return{x:br(o.w<=1e-6?.5:(i.x-o.minX)/o.w),y:br(o.h<=1e-6?.5:(i.y-o.minY)/o.h)}}(t,e,o.point);return{port:{id:wr(a),normalizedAnchor:a,pagePoint:o.point,pageOutwardNormal:o.outwardNormal},borderDistance:o.distance}}function mr(t,e,n){if(!n.normalizedAnchor||!n.portId.startsWith(pr))return xt(t,e,n.portId);const r=xr(t,e,function(t,e,n){const r=t.shapes.computePositionedBounds(e);return t.shapes.computePositionedToPageTransform(e).applyToPoint(new O(r.minX+r.w*n.x,r.minY+r.h*n.y))}(t,e,n.normalizedAnchor));return r?{id:n.portId,normalizedAnchor:{...n.normalizedAnchor},pagePoint:r.point,pageOutwardNormal:r.outwardNormal}:null}function gr(t){return t.id.startsWith(pr)?{kind:"border",normalizedAnchor:{...t.normalizedAnchor}}:{kind:"port",portId:t.id}}function yr(t,e){return{terminal:t,portId:e.id,...e.id.startsWith(pr)?{normalizedAnchor:{...e.normalizedAnchor}}:{}}}function xr(t,e,n){const r=hr(t,e);if(0===r.length)return null;const o=t.shapes.getPageCenter(e.id)??n;let i=null,s=0;for(const a of r){if(1===a.points.length){const t=a.points[0],e=t.sub(o).normalize(),r={point:t.clone(),outwardNormal:e.len2()>0?e:new O(1,0),distance:t.dist(n),index:s};(!i||r.distance<i.distance)&&(i=r),s+=1;continue}const t=a.closed?a.points.length:a.points.length-1;for(let e=0;e<t;e+=1){const t=a.points[e],r=a.points[(e+1)%a.points.length];if(!t||!r)continue;const l=R(t,r,n),c=l.dist(n),d=r.sub(t);if(d.len2()<=1e-12)continue;let u=new O(-d.y,d.x).normalize();const p=l.sub(o);u.x*p.x+u.y*p.y<0&&(u=u.mul(-1)),(!i||c<i.distance||c===i.distance&&s<i.index)&&(i={point:l,outwardNormal:u,distance:c,index:s}),s+=1}}return i}function wr(t){return`${pr}${t.x.toFixed(6)}:${t.y.toFixed(6)}`}function br(t){return Math.max(0,Math.min(1,t))}var vr=3;function kr(t){return 3.5+(Math.max(0,t)<=1?2:0)}function Sr(t){const e=Math.max(0,t);return e*kr(e)}function Pr(t){const e=Math.max(0,t);return e*(kr(e)-.5)}function Mr(t,e,n=1){return("start"===t?2:22)+2*("start"===t?1:-1)*kr(e)*Math.max(0,n)}function Ir(t,e,n=1){const r="start"===t?2:22,o="start"===t?1:-1,i=2*(kr(e)-.5)*Math.max(0,n),s=r+o*i;return`M${s},${12-i} L${r},12 L${s},${12+i} M${Mr(t,e,n)},12 L${r},12`}function Tr(t,e){const n=Math.max(0,Math.min(1,e)),r=1-n;return"line"===t.type?t.start.add(t.end.sub(t.start).mul(n)):"quadratic"===t.type?t.start.mul(r*r).add(t.control.mul(2*r*n)).add(t.end.mul(n*n)):t.start.mul(r*r*r).add(t.control1.mul(3*r*r*n)).add(t.control2.mul(3*r*n*n)).add(t.end.mul(n*n*n))}function Cr(t){const e=function(t){const e=[];let n=null,r=0;return t.forEach((t,o)=>{const i="cubic"===t.type?32:"quadratic"===t.type?16:1;for(let s=0;s<=i;s+=1){const a=s/i,l=Tr(t,a);n&&(r+=n.dist(l)),e.push({point:l,distance:r,segmentIndex:o,segmentPosition:a}),n=l}}),e}(t.segments),n=e[e.length-1]?.distance??0;return{length:n,defaultPosition:.5,getPointAt:r=>function(t,e,n,r){const o=e[0];if(!o)return t.startPagePoint.clone();if(n<=$r)return o.point.clone();const i=n*r;for(let s=1;s<e.length;s+=1){const n=e[s-1],r=e[s];if(r.distance<i)continue;const o=r.distance-n.distance;if(o<=$r)continue;const a=Math.max(0,Math.min(1,(i-n.distance)/o));if(n.segmentIndex!==r.segmentIndex)return n.point.add(r.point.sub(n.point).mul(a));const l=t.segments[n.segmentIndex];return l?Tr(l,n.segmentPosition+(r.segmentPosition-n.segmentPosition)*a):n.point.add(r.point.sub(n.point).mul(a))}return e[e.length-1].point.clone()}(t,e,n,Nr(r)),getNearestPosition:(r,o)=>function(t,e,n,r,o){const i=Nr(o);if(n<=$r)return i;let s=i,a=1/0;for(let l=1;l<e.length;l+=1){const o=e[l-1],c=e[l],d=c.point.sub(o.point),u=d.len2();if(u<=$r*$r)continue;const p=Math.max(0,Math.min(1,io(r.sub(o.point),d)/u)),h=o.segmentIndex===c.segmentIndex?t.segments[o.segmentIndex]:null,f=h?Er(h,r,o.segmentPosition,c.segmentPosition,p):0,m=h?(f-o.segmentPosition)/Math.max($r,c.segmentPosition-o.segmentPosition):p,g=h?Tr(h,f):o.point.add(d.mul(p)),y=(o.distance+(c.distance-o.distance)*m)/n,x=g.dist2(r),w=x<a-1e-8,b=Math.abs(x-a)<=1e-8&&Math.abs(y-i)<Math.abs(s-i);(w||b)&&(a=x,s=y)}return Nr(s)}(t,e,n,r,o?.hintPosition??.5)}}function Er(t,e,n,r,o){if("line"===t.type)return n+(r-n)*o;let i=n+(r-n)*o;for(let s=0;s<8;s+=1){const o=Tr(t,i),s=Ar(t,i),a=o.sub(e),l=s.len2()+io(a,Or(t,i));if(Math.abs(l)<=$r)break;const c=Math.max(n,Math.min(r,i-io(a,s)/l));if(Math.abs(c-i)<=1e-10){i=c;break}i=c}return[n,i,r].reduce((n,r)=>Tr(t,r).dist2(e)<Tr(t,n).dist2(e)?r:n,i)}function Ar(t,e){const n=1-e;return"quadratic"===t.type?t.control.sub(t.start).mul(2*n).add(t.end.sub(t.control).mul(2*e)):t.control1.sub(t.start).mul(3*n*n).add(t.control2.sub(t.control1).mul(6*n*e)).add(t.end.sub(t.control2).mul(3*e*e))}function Or(t,e){if("quadratic"===t.type)return t.end.sub(t.control.mul(2)).add(t.start).mul(2);const n=1-e;return t.control2.sub(t.control1.mul(2)).add(t.start).mul(6*n).add(t.end.sub(t.control2.mul(2)).add(t.control1).mul(6*e))}function Nr(t){return Math.max(0,Math.min(1,t))}var Rr=new WeakMap,Lr=.4,$r=1e-6;function Dr(t){const e=t.tryInvert();return e?({point:n,direction:r,along:o,perpendicular:i})=>{const s=e.applyToPoint(n),a=co(e,n,r);if(a.len()<=$r)return Gr({point:n,direction:r,along:o,perpendicular:i});const l=new O(-a.y,a.x),c=a.mul(o).add(l.mul(i));return t.applyToPoint(s.add(c)).sub(n)}:Gr}function Br(t,e){const n=jn(t,e.id),r=n.start?t.shapes.get(n.start.toId):null,o=n.end?t.shapes.get(n.end.toId):null,i=r&&n.start?mr(t,r,n.start.props):null,s=o&&n.end?mr(t,o,n.end.props):null,a=t.shapes.computeLocalToPageTransform(e),l=r?t.shapes.getPageBounds(r.id)??void 0:void 0,c=o?t.shapes.getPageBounds(o.id)??void 0:void 0,d=i&&n.start?n.start.toId:void 0,u=s&&n.end?n.end.toId:void 0,p=function({transform:t,startPoint:e,startNormal:n,startObstacleId:r,startObstacleBounds:o,endPoint:i,endNormal:s,endObstacleId:a,endObstacleBounds:l}){return[t.a,t.b,t.c,t.d,t.e,t.f,...zr(e),...zr(n),r??"",...Fr(o),...zr(i),...zr(s),a??"",...Fr(l)]}({transform:a,startPoint:i?.pagePoint,startNormal:i?.pageOutwardNormal,startObstacleId:d,startObstacleBounds:l,endPoint:s?.pagePoint,endNormal:s?.pageOutwardNormal,endObstacleId:u,endObstacleBounds:c}),h=Rr.get(e);if(h&&function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return!1;return!0}(h.signature,p))return h.info;const f=e.props.curveWaypoints.map(t=>a.applyToPoint(new O(t.x,t.y))),m=e.props.orthogonalBends.map(t=>a.applyToPoint(new O(t.x,t.y))),g=a.applyToPoint(new O(e.props.start.x,e.props.start.y)),y=a.applyToPoint(new O(e.props.end.x,e.props.end.y)),x=i?.pagePoint??g,w=s?.pagePoint??y,b=w.sub(x).normalize(),v=x.sub(w).normalize(),k=Wr({start:i?{point:i.pagePoint,outwardNormal:i.pageOutwardNormal,obstacleId:d,obstacleBounds:l}:{point:x,outwardNormal:b.len()>$r?b:new O(1,0)},end:s?{point:s.pagePoint,outwardNormal:s.pageOutwardNormal,obstacleId:u,obstacleBounds:c}:{point:w,outwardNormal:v.len()>$r?v:new O(-1,0)},routing:e.props.routing,cornerRadius:e.props.cornerRadius,headStart:e.props.headStart,headEnd:e.props.headEnd,strokeWidth:e.props.strokeWidth,terminalOffsetMapper:Dr(a),curveWaypoints:f,orthogonalBends:m});return Rr.set(e,{signature:p,info:k}),k}function zr(t){return t?[1,t.x,t.y]:[0,0,0]}function Fr(t){return t?[1,t.x,t.y,t.w,t.h]:[0,0,0,0,0]}function jr(t,e){const n=Br(t,e),r=t.shapes.computeLocalToPageTransform(e).tryInvert();return r?ao(n,r):n}function Wr({start:t,end:e,routing:n,cornerRadius:r,headStart:o="none",headEnd:i="none",strokeWidth:s=2,terminalOffsetMapper:a=Gr,curveWaypoints:l=[],orthogonalBends:c=[]}){return"curved"===n?function(t,e,n,r){const o=[t.point,...n.map(t=>t.clone()),e.point],i=function(t,e,n){const r=function(t,e,n){if(t.length<2)return[];const r=t.map(t=>({point:t,incoming:O.Zero(),outgoing:O.Zero()}));if(r[0].outgoing=eo(e,t[1]),r[r.length-1].incoming=eo(n,t[t.length-2]),t.length>2){const e=function(t){const e=[];for(let n=0;n<t.length-1;n+=1){let r=t[n],o=t[n+1];r<o?o=r+(o-r)/2:r=o+(r-o)/2,e.push([r*Lr,o*Lr])}return e}(t.slice(1).map((e,n)=>e.dist(t[n])));for(let t=1;t<r.length-1;t+=1){const n=r[t],o=no(n.point,r[t-1].point,r[t+1].point),i=r[t-1].point.sub(n.point),s=so(o.bisector,i)*so(o.bisector,o.normal)>0?1:-1,[a,l]=e[t-1];n.incoming=o.normal.mul(s*a),n.outgoing=o.normal.mul(-s*l)}for(let t=1;t<r.length-1;t+=1){const n=r[t-1],o=r[t],i=r[t+1],s=no(o.point,n.point.add(n.outgoing),i.point.add(i.incoming)),a=o.point.add(s.normal),l=o.point.sub(s.normal),c=a.dist(n.point)+l.dist(i.point)<a.dist(i.point)+l.dist(n.point)?1:-1,[d,u]=e[t-1];o.incoming=s.normal.mul(c*d),o.outgoing=s.normal.mul(-c*u)}}return r.slice(1).map((t,e)=>{const n=r[e];return{type:"cubic",start:n.point,control1:n.point.add(n.outgoing),control2:t.point.add(t.incoming),end:t.point}})}(t,e,n);if(2!==t.length||1!==r.length)return r;const o=r[0],i=o.end.sub(o.start),s=i.len();if(s<=$r)return r;const a=i.normalize(),l=Math.abs(so(a,o.control1.sub(o.start))),c=Math.abs(so(a,o.control2.sub(o.start)));if(l>$r||c>$r)return r;const d=(Math.abs(i.x)>Math.abs(i.y)?new O(Math.sign(i.x),0):new O(0,Math.sign(i.y))).mul(s*Lr);return[{...o,control1:o.start.add(d),control2:o.end.sub(d)}]}(o,t,e),s=i[0],a=i[i.length-1],l=(u=i,p=Ur(t,s?Qr(s):Zr(t,e.point),r.headStart,r),h=Ur(e,a?to(a).mul(-1):Zr(e,t.point),r.headEnd,r),u.length<=1?Hr(u[0]?Vr(u[0]):0,p,h):{start:_r(Vr(u[0]),p),end:_r(Vr(u[u.length-1]),h)}),c=Xr(t,s?Qr(s):Zr(t,e.point),r.headStart,r.strokeWidth,r.terminalOffsetMapper,l.start),d=Xr(e,a?to(a).mul(-1):Zr(e,t.point),r.headEnd,r.strokeWidth,r.terminalOffsetMapper,l.end);var u,p,h;return Yr({start:t,end:e,segments:i.map((n,r,o)=>{const i=0===r?c.routePoint.sub(t.point):O.Zero(),s=r===o.length-1?d.routePoint.sub(e.point):O.Zero();return{...n,start:n.start.add(i),control1:n.control1.add(i),control2:n.control2.add(s),end:n.end.add(s)}}),markerSegments:[...c.markerSegments,...d.markerSegments],startArrowScale:l.start,endArrowScale:l.end,routePoints:o})}(t,e,l,{headStart:o,headEnd:i,strokeWidth:s,terminalOffsetMapper:a}):"orthogonal"===n?function(t,e,n,r,o){const i=mo(t.outwardNormal),s=mo(e.outwardNormal),a=function(t,e,n,r,o){return qr([...qr(t,e,n)].reverse(),r,o).reverse()}(function(t,e,n,r,o){if(0===o.length)return null;const i=o.map(t=>t.clone()),s=i[0],a=i[i.length-1];if(!s||!a)return null;0!==n.x?s.y=t.y:s.x=t.x;0!==r.x?a.y=e.y:a.x=e.x;const l=fo([t,...i,e]);if(l.length<2)return null;for(let c=1;c<l.length;c+=1){const t=l[c-1],e=l[c];if(t.x!==e.x&&t.y!==e.y)return null}return l}(t.point,e.point,i,s,r)??_n({...t,direction:i},{...e,direction:s}),t,i,e,s),l=Kr(a,t,"start",i),c=Kr(a,e,"end",s),d=(f=a,m=Ur(t,l,o.headStart,o),g=Ur(e,c,o.headEnd,o),f.length<=2?Hr(f[0]?.dist(f[f.length-1])??0,m,g):{start:_r(f[0].dist(f[1]),m),end:_r(f[f.length-2].dist(f[f.length-1]),g)}),u=Xr(t,l,o.headStart,o.strokeWidth,o.terminalOffsetMapper,d.start),p=Xr(e,c,o.headEnd,o.strokeWidth,o.terminalOffsetMapper,d.end),h=a.map(t=>t.clone());var f,m,g;h.length>0&&(h[0]=u.routePoint,h[h.length-1]=p.routePoint);return Yr({start:t,end:e,segments:ho(h,n).segments,markerSegments:[...u.markerSegments,...p.markerSegments],startArrowScale:d.start,endArrowScale:d.end,routePoints:a,startTangent:l,endTangent:c.mul(-1)})}(t,e,r,c,{headStart:o,headEnd:i,strokeWidth:s,terminalOffsetMapper:a}):function(t,e,n){const r=e.point.sub(t.point).normalize(),o=r.len()>$r?r:Zr(t,e.point),i=r.len()>$r?r.mul(-1):Zr(e,t.point),s=Hr(t.point.dist(e.point),Ur(t,o,n.headStart,n),Ur(e,i,n.headEnd,n)),a=Xr(t,o,n.headStart,n.strokeWidth,n.terminalOffsetMapper,s.start),l=Xr(e,i,n.headEnd,n.strokeWidth,n.terminalOffsetMapper,s.end);return Yr({start:t,end:e,segments:[{type:"line",start:a.routePoint,end:l.routePoint}],markerSegments:[...a.markerSegments,...l.markerSegments],startArrowScale:s.start,endArrowScale:s.end,routePoints:[t.point,e.point]})}(t,e,{headStart:o,headEnd:i,strokeWidth:s,terminalOffsetMapper:a})}function Hr(t,e,n){const r=e+n;if(r<=$r)return{start:0,end:0};const o=Math.min(1,Math.max(0,t-.01)/r);return{start:e>0?o:0,end:n>0?o:0}}function _r(t,e){return e<=$r?0:Math.min(1,Math.max(0,t-.01)/e)}function Ur(t,e,n,r){return"arrow"!==n?0:r.terminalOffsetMapper({point:t.point,direction:e,along:3+Sr(r.strokeWidth),perpendicular:0}).len()}function Vr(t){const e=Jr(t,"cubic"===t.type?16:"quadratic"===t.type?8:1);return e.slice(1).reduce((t,n,r)=>t+n.dist(e[r]),0)}function Kr(t,e,n,r){if(e.obstacleBounds||t.length<2)return r;const o="start"===n?t[1].sub(t[0]):t[t.length-2].sub(t[t.length-1]);return o.len()>$r?mo(o):r}function qr(t,e,n){if(!e.obstacleBounds||t.length<2)return[...t];const r=t[0],o=t[1],i=o.sub(r);if(i.len()<=$r)return[...t];if(Math.abs(so(i,n))<=$r&&i.x*n.x+i.y*n.y>0)return[...t];const s=e.point.add(n.mul(36)),a=0!==n.x?new O(s.x,o.y):new O(o.x,s.y);return fo([e.point,s,a,...t.slice(1)])}function Xr(t,e,n,r,o,i){if("arrow"!==n||i<=0)return{tipPoint:t.point,routePoint:t.point,markerSegments:[]};const s=e.normalize().len()>$r?e.normalize():Zr(t,t.point),a=(e,n=0)=>o({point:t.point,direction:s,along:e,perpendicular:n}),l=t.point.add(a(3*i)),c=t.point.add(a((3+Sr(r))*i)),d=Pr(r)*i,u=3*i;return{tipPoint:l,routePoint:c,markerSegments:[{type:"line",start:t.point.add(a(u+d,d)),end:l},{type:"line",start:l,end:t.point.add(a(u+d,-d))},{type:"line",start:c,end:l}]}}function Yr({start:t,end:e,segments:n,markerSegments:r,startArrowScale:o,endArrowScale:i,routePoints:s,startTangent:a,endTangent:l}){const c=[];n.forEach((t,e)=>{const n="cubic"===t.type?function(t,e,n,r,o){const i=[];for(let s=0;s<=o;s+=1){const a=s/o,l=1-a;i.push(t.mul(l*l*l).add(e.mul(3*l*l*a)).add(n.mul(3*l*a*a)).add(r.mul(a*a*a)))}return i}(t.start,t.control1,t.control2,t.end,16):"quadratic"===t.type?Jr(t,8):[t.start,t.end];c.push(...0===e?n:n.slice(1))});const d=n[0],u=n[n.length-1],p=[...lo(n),...r.flatMap(t=>[t.start,t.end]),t.point,e.point];return{path:uo(n),startPagePoint:t.point,endPagePoint:e.point,startTangent:a??(d?Qr(d):e.point.sub(t.point).normalize()),endTangent:l??(u?to(u):e.point.sub(t.point).normalize()),startArrowScale:o,endArrowScale:i,pageBounds:N.FromPoints(p),segments:n,markerSegments:r,points:c,routePoints:s}}function Jr(t,e){return Array.from({length:e+1},(n,r)=>Tr(t,r/e))}function Gr({direction:t,along:e,perpendicular:n}){const r=t.normalize(),o=new O(-r.y,r.x);return r.mul(e).add(o.mul(n))}function Zr(t,e){const n=t.outwardNormal.normalize();return n.len()>$r?n:e.sub(t.point).normalize()}function Qr(t){return"line"===t.type?t.end.sub(t.start).normalize():("cubic"===t.type?t.control1:t.control).sub(t.start).normalize()}function to(t){return"line"===t.type?t.end.sub(t.start).normalize():t.end.sub("cubic"===t.type?t.control2:t.control).normalize()}function eo(t,e){const n=e.sub(t.point).normalize(),r=t.outwardNormal.normalize(),o=r.len()>$r?r:n,i=e.sub(t.point),s=Math.abs(io(i,o)),a=i.len();if(a<$r)return O.Zero();const l=s<.001?Math.min(150,a):Math.min(Math.max(s,100),a);return o.mul(l*Lr)}function no(t,e,n){const r=e.dist(t),o=t.dist(n);if(r<$r||o<$r)return{normal:O.Zero(),bisector:O.Zero()};const i=r/(r+o),s=e.add(n.sub(e).mul(i)),a=t.sub(s),l=a.len();if(l<$r)return{normal:O.Zero(),bisector:O.Zero()};const c=a.div(l);return{normal:new O(-c.y,c.x),bisector:a}}function ro(t){const e=[];for(const n of t){const t=new Set([0,1]);for(const e of oo(n.start.x,n.control1.x,n.control2.x,n.end.x))t.add(e);for(const e of oo(n.start.y,n.control1.y,n.control2.y,n.end.y))t.add(e);for(const r of t)e.push(Tr(n,r))}return e}function oo(t,e,n,r){const o=3*(3*e-t-3*n+r),i=2*(3*t-6*e+3*n),s=-3*t+3*e;if(Math.abs(o)<$r){if(Math.abs(i)<$r)return[];const t=-s/i;return t>0&&t<1?[t]:[]}const a=i*i-4*o*s;if(a<0)return[];const l=Math.sqrt(a);return[(-i+l)/(2*o),(-i-l)/(2*o)].filter(t=>t>0&&t<1)}function io(t,e){return t.x*e.x+t.y*e.y}function so(t,e){return t.x*e.y-t.y*e.x}function ao(t,e){const n=t=>e.applyToPoint(t),r=t.segments.map(t=>"line"===t.type?{type:"line",start:n(t.start),end:n(t.end)}:"quadratic"===t.type?{type:"quadratic",start:n(t.start),control:n(t.control),end:n(t.end)}:{type:"cubic",start:n(t.start),control1:n(t.control1),control2:n(t.control2),end:n(t.end)}),o=t.markerSegments.map(t=>({type:"line",start:n(t.start),end:n(t.end)})),i=t.points.map(n),s=n(t.startPagePoint),a=n(t.endPagePoint),l=[...lo(r),...o.flatMap(t=>[t.start,t.end]),s,a];return{...t,path:uo(r),startPagePoint:s,endPagePoint:a,startTangent:co(e,t.startPagePoint,t.startTangent),endTangent:co(e,t.endPagePoint,t.endTangent),pageBounds:N.FromPoints(l.length>0?l:i),segments:r,markerSegments:o,points:i,routePoints:t.routePoints.map(n)}}function lo(t){const e=[];for(const n of t)"cubic"===n.type?e.push(...ro([n])):"quadratic"===n.type?e.push(n.start,n.control,n.end):e.push(n.start,n.end);return e}function co(t,e,n){return t.applyToPoint(e.add(n)).sub(t.applyToPoint(e)).normalize()}function uo(t){const e=t[0];if(!e)return"";const n=[`M ${go(e.start)}`];for(const r of t)n.push("line"===r.type?`L ${go(r.end)}`:"quadratic"===r.type?`Q ${go(r.control)} ${go(r.end)}`:`C ${go(r.control1)} ${go(r.control2)} ${go(r.end)}`);return n.join(" ")}function po(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],o=t[n+1];o&&r.end.equals(o.start)?(e.push(`M ${go(r.start)} L ${go(r.end)} L ${go(o.end)}`),n+=1):e.push(`M ${go(r.start)} L ${go(r.end)}`)}return e.join(" ")}function ho(t,e){if(t.length<2)return{path:"",segments:[],points:[...t]};if(2===t.length||e<=0){const e=t.slice(1).map((e,n)=>({type:"line",start:t[n],end:e}));return{path:uo(e),segments:e,points:[...t]}}const n=[],r=[t[0]];let o=t[0];for(let s=1;s<t.length-1;s+=1){const i=t[s-1],a=t[s],l=t[s+1],c=Math.min(Math.max(0,e),i.dist(a)/2,a.dist(l)/2),d=O.Nudge(a,i,c),u=O.Nudge(a,l,c);o.equals(d)||(n.push({type:"line",start:o,end:d}),r.push(d)),n.push({type:"quadratic",start:d,control:a,end:u}),r.push(a,u),o=u}const i=t[t.length-1];return o.equals(i)||(n.push({type:"line",start:o,end:i}),r.push(i)),{path:uo(n),segments:n,points:r}}function fo(t){const e=function(t){const e=[];for(const n of t)e[e.length-1]?.equals(n)||e.push(n);return e}(t);if(e.length<=2)return e;const n=[e[0]];for(let r=1;r<e.length-1;r+=1){const t=n[n.length-1],o=e[r],i=e[r+1];t.x===o.x&&o.x===i.x||t.y===o.y&&o.y===i.y||n.push(o)}return n.push(e[e.length-1]),n}function mo(t){return Math.abs(t.x)>=Math.abs(t.y)?new O(t.x>=0?1:-1,0):new O(0,t.y>=0?1:-1)}function go(t){return`${yo(t.x)} ${yo(t.y)}`}function yo(t){return Number(t.toFixed(3)).toString()}var xo="connector.curve-waypoint",wo="connector.curve-insert",bo="connector.orthogonal-segment";function vo(t){return`waypoint:${t}`}function ko(t){return`segment:${t}`}function So(t,e){return`segment:${t}:${e}`}function Po(t,e){const n=new RegExp(`^${e}:(\\d+)$`).exec(t);if(!n)return null;const r=Number(n[1]);return Number.isSafeInteger(r)?r:null}function Mo(t){const e=/^segment:(\d+):(horizontal|vertical)$/.exec(t);if(!e)return null;const n=Number(e[1]);return Number.isSafeInteger(n)?{index:n,axis:e[2]}:null}var Io=G("plugin.connector.runtime");function To(t){return t.runtime.require(Io)}function Co(t,e){return{kind:"bound",shapeId:t,attachment:gr(e)}}function Eo(t,e){if("free"===e.kind)return{draft:e,pagePoint:e.pagePoint.clone(),shape:null,port:null};const n=t.shapes.get(e.shapeId);if(!n||zn(n)||t.shapes.isHidden(n.id)||null===t.shapes.getClippedPageBounds(n.id)||!t.shapes.getUtil(n).canReceiveTerminalBinding(n,{editor:t}))return null;const r=function(t,e,n){return"port"===n.kind?xt(t,e,n.portId):mr(t,e,{portId:wr(n.normalizedAnchor),normalizedAnchor:n.normalizedAnchor})}(t,n,e.attachment);return r?{draft:e,pagePoint:r.pagePoint.clone(),shape:n,port:r,obstacleBounds:t.shapes.getPageBounds(n.id)??void 0}:null}function Ao(t,e,n,r){const o=Eo(t,e),i=Eo(t,n);if(!o||!i)return"missing_endpoint";if(o.shape&&t.layers.isOrAncestorLocked(o.shape.id))return"locked_source";const s=t.pages.getCurrentId(),a=o.shape?t.layers.getPageId(o.shape.id):s,l=i.shape?t.layers.getPageId(i.shape.id):s;if(!a||a!==l||a!==s)return"cross_page";if(o.shape&&o.port&&i.shape&&i.port){if(Wo(o.shape.id,o.port.id,i.shape.id,i.port.id))return"same_attachment";if(jo(t,o.shape.id,o.port.id,i.shape.id,i.port.id,r))return"duplicate"}return _o(t,o,i)?null:"invalid_parent"}function Oo(t,e,n="user"){if(Ao(t,e.start,e.end))return null;const r=Eo(t,e.start),o=Eo(t,e.end);if(!r||!o)return null;const i=_o(t,r,o);if(!i)return null;const s={...t.shapes.getDefaultProps("connector"),...e.props},a=Vo({editor:t,parentId:i,start:zo(r,o,"start"),end:zo(o,r,"end"),props:s}),l=t.operations.begin({kind:"connector.commit",label:"shape.create",source:n,history:"user"===n?"record":"ignore"});try{const i=t.commands.createShapes([a],{source:n,autoReparent:!1})[0];if(!zn(i))return l.cancel(),null;if(r.shape&&r.port&&Fo(t,i.id,"start",{shape:r.shape,port:r.port},n),o.shape&&o.port&&Fo(t,i.id,"end",{shape:o.shape,port:o.port},n),"none"!==e.selectionAfter){const r=Array.isArray(e.selectionAfter)?[...e.selectionAfter]:[i.id];t.commands.setSelectedShapeIds(r,{source:n})}const s=t.shapes.get(i.id);return zn(s)?(l.commit(),s):(l.cancel(),null)}catch(c){throw l.isActive&&l.cancel(),c}}function No(t,e){return Lo(t,e)}function Ro(t,e,n,r){return Lo(t,e,{[n]:r})}function Lo(t,e,n={}){const r=jn(t,e.id),o=t.shapes.computeLocalToPageTransform(e),i=o.applyToPoint(new O(e.props.start.x,e.props.start.y)),s=o.applyToPoint(new O(e.props.end.x,e.props.end.y)),a=$o(t,r.start),l=$o(t,r.end),c=n.start??a?.port.pagePoint??i,d=n.end??l?.port.pagePoint??s,u=!n.start&&a?Do(t,a):Bo(c,d,"start"),p=!n.end&&l?Do(t,l):Bo(d,c,"end"),h=a&&l?Ho(t,a.shape,l.shape):e.parentId;if(!h||!t.layers.canReceiveChildren(h))return null;const f=Vo({editor:t,parentId:h,start:u,end:p,props:e.props,manualPageGeometry:{curveWaypoints:e.props.curveWaypoints.map(t=>o.applyToPoint(new O(t.x,t.y))),orthogonalBends:e.props.orthogonalBends.map(t=>o.applyToPoint(new O(t.x,t.y)))}});return{...e,parentId:h,x:f.x,y:f.y,rotation:0,scaleX:1,scaleY:1,props:{...e.props,...f.props}}}function $o(t,e){if(!e)return null;const n=t.shapes.get(e.toId);if(!n)return null;const r=mr(t,n,e.props);return r?{shape:n,port:r}:null}function Do(t,e){return{point:e.port.pagePoint,outwardNormal:e.port.pageOutwardNormal,obstacleId:e.shape.id,obstacleBounds:t.shapes.getPageBounds(e.shape.id)??void 0}}function Bo(t,e,n){const r=e.sub(t).normalize();return{point:t,outwardNormal:r.len()>0?r:new O("start"===n?1:-1,0)}}function zo(t,e,n){return t.shape&&t.port?{point:t.pagePoint,outwardNormal:t.port.pageOutwardNormal,obstacleId:t.shape.id,obstacleBounds:t.obstacleBounds}:Bo(t.pagePoint,e.pagePoint,n)}function Fo(t,e,n,r,o){t.commands.createBinding({type:"connector",fromId:e,toId:r.shape.id,props:yr(n,r.port)},{source:o})}function jo(t,e,n,r,o,i){for(const s of t.state.currentPageShapeIds.get()){if(s===i)continue;const a=t.shapes.get(s);if(!zn(a))continue;const l=jn(t,a.id);if(l.start?.toId===e&&l.start.props.portId===n&&l.end?.toId===r&&l.end.props.portId===o)return!0}return!1}function Wo(t,e,n,r){return t===n&&e===r}function Ho(t,e,n){const r=t.layers.getPageId(e.id);if(!r||r!==t.layers.getPageId(n.id))return null;const o=new Set(Ko(t,n));for(const i of Ko(t,e))if(o.has(i)&&t.layers.canReceiveChildren(i))return i;return r}function _o(t,e,n){if(e.shape&&n.shape)return Ho(t,e.shape,n.shape);const r=t.pages.getCurrentId(),o=e.shape??n.shape,i=e.shape?n.pagePoint:e.pagePoint;if(o){for(const e of Ko(t,o)){if(!e.startsWith("shape:"))return e;const n=t.shapes.get(e);if(n&&Uo(t,n,[i]))return n.id}return t.layers.getPageId(o.id)??r}let s=null;const a=new Map(t.state.currentPageShapeIds.get().map((t,e)=>[t,e]));for(const l of t.state.currentPageShapeIds.get()){const r=t.shapes.get(l);if(!r||zn(r)||!Uo(t,r,[e.pagePoint,n.pagePoint]))continue;const o=t.shapes.getPageBounds(r.id);if(!o)continue;const i={shape:r,area:o.w*o.h,order:a.get(r.id)??-1};(!s||i.area<s.area||i.area===s.area&&i.order>s.order)&&(s=i)}return s?.shape.id??r}function Uo(t,e,n){if(t.shapes.isHidden(e.id)||t.layers.isOrAncestorLocked(e.id)||null===t.shapes.getClippedPageBounds(e.id))return!1;const r=t.shapes.getUtil(e);if(!r.canReceiveChildren(e)||!r.canAutomaticallyReceiveChildren(e))return!1;const o=t.shapes.computeLocalToPageTransform(e).tryInvert();if(!o)return!1;const i=r.getChildClipLocalPolygons(e),s=r.getLocalBounds(e);return n.every(n=>{if(!t.shapes.isPagePointInClip(e.id,n))return!1;const r=o.applyToPoint(n);return i?function(t,e){return e.some(e=>B(t,e))}(r,i):s.containsPoint(r)})}function Vo({editor:t,parentId:e,start:n,end:r,props:o,manualPageGeometry:i}){const s=i?.curveWaypoints??[],a=i?.orthogonalBends??[],l=e.startsWith("shape:")?t.shapes.get(e):null,c=l?t.shapes.computeLocalToPageTransform(l):J.Identity(),d=Wr({start:n,end:r,routing:o.routing,cornerRadius:o.cornerRadius,headStart:o.headStart,headEnd:o.headEnd,strokeWidth:o.strokeWidth,terminalOffsetMapper:Dr(c),curveWaypoints:s,orthogonalBends:a}),u=function(t,e,n){const r=e.startsWith("shape:")?t.shapes.get(e):null,o=(r?t.shapes.computeLocalToPageTransform(r):J.Identity()).tryInvert();return o?{bounds:N.FromPoints(n.map(t=>o.applyToPoint(t))),pageToParent:o}:null}(t,e,[n.point,...d.points,r.point]),p=u?.pageToParent??J.Identity(),h=u?.bounds??d.pageBounds,f=p.applyToPoint(n.point),m=p.applyToPoint(r.point);return{type:"connector",parentId:e,x:h.x,y:h.y,props:{...o,w:Math.max(1,h.w),h:Math.max(1,h.h),start:{x:f.x-h.x,y:f.y-h.y},end:{x:m.x-h.x,y:m.y-h.y},curveWaypoints:s.map(t=>{const e=p.applyToPoint(t);return{x:e.x-h.x,y:e.y-h.y}}),orthogonalBends:a.map(t=>{const e=p.applyToPoint(t);return{x:e.x-h.x,y:e.y-h.y}})}}}function Ko(t,e){const n=[],r=new Set;let o=e.parentId;for(;o.startsWith("shape:");){const e=o;if(r.has(e))break;r.add(e),n.push(e);const i=t.shapes.get(e);if(!i)break;o=i.parentId}return n.push(o),n}var qo=["rectangle","ellipse","message-circle","summary","summary-left","burst","rhombus","triangle","pentagon","hexagon","star","trapezoid","arrow-left","arrow-right"],Xo=["solid","dashed","dotted","none"];function Yo(t){return C(t)&&"geo"===t.type}function Jo(t){return"string"==typeof t&&qo.includes(t)}function Go(t){return"string"==typeof t&&Xo.includes(t)}var Zo=G("plugin.geo.creation-runtime");function Qo(t){return t.runtime.require(Zo)}function ti(t,e){return new N(t.x,t.y,e.w,e.h)}var ei=class extends Pt{kind;constructor(t,e,n){super(t,e),this.kind=n,this.initial="idle",this.addChild(new ni(t,this)),this.addChild(new ri(t,this))}getDefaultProps(){return{...this.editor.shapes.getDefaultProps("geo"),kind:this.kind}}onEnter(){this.editor.shapes.updateDefaultProps("geo",{kind:this.kind})}},ni=class extends Pt{tool;constructor(t,e){super(t,"idle",e),this.tool=e}onEnter(){this.editor.interaction.clearSelection()}onExit(){Qo(this.editor).clearHover()}onPointerMove(t){const e=Qo(this.editor);"touch"!==t.pointerType&&0===t.buttons?e.setHover({pagePoint:t.pagePoint,timestamp:t.timestamp}):e.clearHover()}onPointerDown(t){this.transition("creating",{originPagePoint:t.pagePoint.clone(),originScreenPoint:t.screenPoint.clone(),shapeId:null,props:this.tool.getDefaultProps(),isDragCreating:!1})}},ri=class extends Pt{info=null;operation=null;constructor(t,e){super(t,"creating",e)}onEnter(t){if(this.info=t,this.info){this.operation=this.editor.operations.begin({kind:"geo.create",label:"shape.create",source:"user",history:"record"});try{const t=this.createShape(ti(this.info.originPagePoint,this.info.props),this.info.props);this.info.shapeId=t.id}catch(e){throw this.cancelOperation(),e}}}onPointerMove(t){this.updateShape(t.pagePoint,t.screenPoint,t.shiftKey)}onPointerUp(t){this.info?(this.updateShape(t.pagePoint,t.screenPoint,t.shiftKey),this.info.shapeId&&nt(this.editor,this.info.shapeId,{source:"user"}),this.commitOperation(),this.editor.state.tool.get().isToolLocked?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.cancelOperation(),this.info=null}commitOperation(){const t=this.operation;this.operation=null,t?.commit()}cancelOperation(){const t=this.operation;this.operation=null,t?.isActive&&t.cancel()}updateShape(t,e,n){if(!this.info)return;const r=this.info.originScreenPoint.dist(e);if(!this.info.isDragCreating){if(r<4)return;this.info.isDragCreating=!0}const o=function(t,e,n){let r=e.x-t.x,o=e.y-t.y;if(n){const t=Math.max(Math.abs(r),Math.abs(o));r=(r<0?-1:1)*t,o=(o<0?-1:1)*t}const i=new O(t.x+r,t.y+o);return new N(Math.min(t.x,i.x),Math.min(t.y,i.y),Math.max(Math.abs(i.x-t.x),1),Math.max(Math.abs(i.y-t.y),1))}(this.info.originPagePoint,t,n),i=this.info.shapeId;i&&this.editor.commands.updateShapes([{id:i,x:o.x,y:o.y,props:{w:o.w,h:o.h}}],{source:"user"})}createShape(t,e){const[n]=this.editor.commands.createShapes([{type:"geo",x:t.x,y:t.y,props:{...e,w:t.w,h:t.h}}],{source:"user",autoReparent:!1});if(!n)throw new Error("Failed to create geo shape");return this.editor.commands.setSelectedShapeIds([n.id],{source:"system"}),n}},oi=class extends ei{constructor(t){super(t,"rectangle","rectangle")}},ii=class extends ei{constructor(t){super(t,"ellipse","ellipse")}},si=class extends ei{constructor(t){super(t,"message-circle","message-circle")}},ai=class extends ei{constructor(t){super(t,"summary","summary")}},li=class extends ei{constructor(t){super(t,"summary-left","summary-left")}},ci=class extends ei{constructor(t){super(t,"burst","burst")}},di=class extends ei{constructor(t){super(t,"rhombus","rhombus")}},ui=class extends ei{constructor(t){super(t,"triangle","triangle")}},pi=class extends ei{constructor(t){super(t,"pentagon","pentagon")}},hi=class extends ei{constructor(t){super(t,"hexagon","hexagon")}},fi=class extends ei{constructor(t){super(t,"star","star")}},mi=class extends ei{constructor(t){super(t,"trapezoid","trapezoid")}},gi=class extends ei{constructor(t){super(t,"arrow-left","arrow-left")}},yi=class extends ei{constructor(t){super(t,"arrow-right","arrow-right")}},xi=Ae("plugin-geo.api");function wi({editor:t}){return function({editor:t}){return{create:e=>function(t,e){const n=t.shapes.getDefaultProps("geo"),[r]=t.commands.createShapes([{type:"geo",x:e.x,y:e.y,meta:e.meta?{...e.meta}:void 0,props:{...n,kind:e.kind,w:e.w??n.w,h:e.h??n.h,fill:e.fill??n.fill,stroke:e.stroke??n.stroke,strokeStyle:e.strokeStyle??n.strokeStyle,strokeWidth:e.strokeWidth??n.strokeWidth,cornerRadiusPercent:e.cornerRadiusPercent??n.cornerRadiusPercent}}],{source:"user"});return"geo"===r?.type?{id:r.id,type:r.type}:null}(t,e),getSelectionStyle:()=>function(t){const e=t.state.selectedShapes.get().filter(Yo);return 0===e.length?null:{kind:bi(e.map(t=>t.props.kind)),fill:bi(e.map(t=>t.props.fill)),stroke:bi(e.map(t=>t.props.stroke)),strokeStyle:bi(e.map(t=>t.props.strokeStyle)),strokeWidth:bi(e.map(t=>t.props.strokeWidth)),cornerRadiusPercent:bi(e.map(t=>t.props.cornerRadiusPercent))}}(t),setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(Yo).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)},getToolDefaults:()=>t.shapes.getDefaultProps("geo"),setToolDefaults:e=>(t.shapes.updateDefaultProps("geo",{...e}),t.shapes.getDefaultProps("geo"))}}({editor:t})}function bi(t){const[e,...n]=t;return void 0!==e&&n.every(t=>t===e)?e:null}var vi=/[AaCcHhLlMmVvZz]|[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?/g,ki=/^[AaCcHhLlMmVvZz]$/,Si=Math.PI/6,Pi=1e-8;function Mi(t){const e=t.match(vi)??[],n=t.replace(vi,"").replace(/[\s,]/g,"");if(n.length>0)throw new Error(`Unsupported SVG path content: ${n}`);const r=[];let o=null,i=null,s=new O(0,0),a=0;for(;a<e.length;){const t=e[a];if(t&&ki.test(t)&&(i=t,a+=1,"z"===i.toLowerCase())){if(!o)throw new Error("SVG path closes before starting a subpath.");o.closed=!0,s=o.start.clone(),i=null;continue}if(!i)throw new Error("SVG path data is missing a command.");const n=i,l=Ii(n),c=Ti(e,a,l);a+=l;const d=n===n.toLowerCase();switch(n.toLowerCase()){case"m":s=Ei(s,c[0],c[1],d),o={start:s.clone(),segments:[],closed:!1},r.push(o),i=d?"l":"L";break;case"l":{const t=Ei(s,c[0],c[1],d);Ai(o,{type:"line",start:s,end:t}),s=t;break}case"h":{const t=new O(d?s.x+c[0]:c[0],s.y);Ai(o,{type:"line",start:s,end:t}),s=t;break}case"v":{const t=new O(s.x,d?s.y+c[0]:c[0]);Ai(o,{type:"line",start:s,end:t}),s=t;break}case"c":{const t=Ei(s,c[0],c[1],d),e=Ei(s,c[2],c[3],d),n=Ei(s,c[4],c[5],d);Ai(o,{type:"cubic",start:s,control1:t,control2:e,end:n}),s=n;break}case"a":{const t=Ci(c[3]),e=Ci(c[4]),n=Ei(s,c[5],c[6],d);Ai(o,{type:"arc",start:s,end:n,radiusX:Math.abs(c[0]),radiusY:Math.abs(c[1]),rotation:c[2],largeArc:t,sweep:e}),s=n;break}}}return r}function Ii(t){switch(t.toLowerCase()){case"m":case"l":return 2;case"h":case"v":return 1;case"c":return 6;case"a":return 7;default:throw new Error(`Unsupported SVG path command: ${t}`)}}function Ti(t,e,n){const r=[];for(let o=0;o<n;o+=1){const n=t[e+o];if(!n||ki.test(n))throw new Error("SVG path command has incomplete numeric values.");const i=Number(n);if(!Number.isFinite(i))throw new Error(`Invalid SVG path number: ${n}`);r.push(i)}return r}function Ci(t){if(0!==t&&1!==t)throw new Error(`SVG arc flag must be 0 or 1, received ${t}.`);return 1===t}function Ei(t,e,n,r){return r?new O(t.x+e,t.y+n):new O(e,n)}function Ai(t,e){if(!t)throw new Error("SVG path draws before starting a subpath.");t.segments.push(e)}function Oi(t){const e=[t.start.clone()];for(const n of t.segments)switch(n.type){case"line":Wi(e,n.end);break;case"cubic":{const t=[...Array.from({length:8},(t,e)=>(e+1)/8),...Ri(n)].sort((t,e)=>t-e).filter((t,e,n)=>0===e||Math.abs(t-(n[e-1]??t))>Pi);for(const r of t)Wi(e,Ni(n,r));break}case"arc":for(const t of $i(n))Wi(e,t)}return t.closed&&e.length>1&&Hi(e[0],e[e.length-1])&&e.pop(),e}function Ni(t,e){const n=1-e,r=n*n*n,o=3*n*n*e,i=3*n*e*e,s=e*e*e;return new O(t.start.x*r+t.control1.x*o+t.control2.x*i+t.end.x*s,t.start.y*r+t.control1.y*o+t.control2.y*i+t.end.y*s)}function Ri(t){return[...Li(t.start.x,t.control1.x,t.control2.x,t.end.x),...Li(t.start.y,t.control1.y,t.control2.y,t.end.y)].filter(t=>t>0&&t<1).sort((t,e)=>t-e).filter((t,e,n)=>0===e||Math.abs(t-(n[e-1]??t))>Pi)}function Li(t,e,n,r){const o=3*e-t-3*n+r,i=2*(t-2*e+n),s=e-t;if(Math.abs(o)<=Pi)return Math.abs(i)<=Pi?[]:[-s/i];const a=i*i-4*o*s;if(a<-1e-8)return[];const l=Math.sqrt(Math.max(0,a));return[(-i-l)/(2*o),(-i+l)/(2*o)]}function $i(t){const e=Di(t);if(!e)return[t.end.clone()];const n=Math.max(1,Math.ceil(Math.abs(e.deltaAngle)/Si)),r=[...Array.from({length:n},(t,e)=>(e+1)/n),...Bi(e).map(t=>function(t,e){return zi(t,e)/Math.abs(t.deltaAngle)}(e,t))].filter(t=>t>0&&t<=1).sort((t,e)=>t-e).filter((t,e,n)=>0===e||Math.abs(t-(n[e-1]??t))>Pi),o=[];for(const i of r){const t=e.startAngle+e.deltaAngle*i;o.push(ji(e,t))}return o[o.length-1]=t.end.clone(),o}function Di(t){if(0===t.radiusX||0===t.radiusY||Hi(t.start,t.end))return null;const e=t.rotation*Math.PI/180,n=Math.cos(e),r=Math.sin(e),o=(t.start.x-t.end.x)/2,i=(t.start.y-t.end.y)/2,s=n*o+r*i,a=-r*o+n*i;let l=t.radiusX,c=t.radiusY;const d=s*s/(l*l)+a*a/(c*c);if(d>1){const t=Math.sqrt(d);l*=t,c*=t}const u=l*l,p=c*c,h=s*s,f=a*a,m=u*f+p*h,g=Math.max(0,u*p-u*f-p*h),y=t.largeArc===t.sweep?-1:1,x=0===m?0:y*Math.sqrt(g/m),w=x*(l*a/c),b=x*(-c*s/l),v=n*w-r*b+(t.start.x+t.end.x)/2,k=r*w+n*b+(t.start.y+t.end.y)/2,S=(s-w)/l,P=(a-b)/c,M=(-s-w)/l,I=(-a-b)/c,T=Math.atan2(P,S);let C=(E=S,A=P,O=M,N=I,Math.atan2(E*N-A*O,E*O+A*N));var E,A,O,N;return!t.sweep&&C>0?C-=2*Math.PI:t.sweep&&C<0&&(C+=2*Math.PI),{centerX:v,centerY:k,radiusX:l,radiusY:c,cosRotation:n,sinRotation:r,startAngle:T,deltaAngle:C}}function Bi(t){const{radiusX:e,radiusY:n,cosRotation:r,sinRotation:o}=t,i=Math.atan2(-n*o,e*r),s=Math.atan2(n*r,e*o);return[i,i+Math.PI,s,s+Math.PI].filter(e=>function(t,e){return zi(t,e)<=Math.abs(t.deltaAngle)+Pi}(t,e))}function zi(t,e){return t.deltaAngle>=0?Fi(e-t.startAngle):Fi(t.startAngle-e)}function Fi(t){const e=2*Math.PI;return(t%e+e)%e}function ji(t,e){const n=t.radiusX*Math.cos(e),r=t.radiusY*Math.sin(e);return new O(t.centerX+t.cosRotation*n-t.sinRotation*r,t.centerY+t.sinRotation*n+t.cosRotation*r)}function Wi(t,e){const n=t[t.length-1];n&&Hi(n,e)||t.push(e.clone())}function Hi(t,e){return Math.abs(t.x-e.x)<=Pi&&Math.abs(t.y-e.y)<=Pi}var _i=24,Ui=3.222,Vi=12.443999999999999+Math.max(3.191,3.19)+1,Ki="m19.8415 12.945 1.827 1.428h-2.26a1 1 0 0 0-.972 1.232l.676 2.828-2.462-2.204a1 1 0 0 0-1.66.624l-.386 3.152-1.548-2.838c-.417-.765-1.545-.668-1.825.158l-1.064 3.138-.215-2.358a1 1 0 0 0-1.535-.751l-1.482.95.437-1.803a1 1 0 0 0-1.099-1.228l-2.962.38 1.446-1.17a1 1 0 0 0 .036-1.525L2.1425 10.6l3.088-.791a1 1 0 0 0 .534-1.592l-2-2.513L7.7425 7.879a1 1 0 0 0 1.434-.578l.775-2.464 1.377 2.067a1 1 0 0 0 1.635.042l2.539-3.41-.115 2.574a1 1 0 0 0 1.16 1.031l2.59-.42-.804 1.34a1 1 0 0 0 .67 1.496l2.853.544-1.93 1.207a1 1 0 0 0-.085 1.636Z",qi=function(t){const e=function(t){return Mi(t).map(t=>({closed:t.closed,points:Oi(t)}))}(t),[n]=e;if(1!==e.length||!n||!n.closed)throw new Error("Geo path must contain exactly one closed subpath.");return n.points}(Ki),Xi=function(t){const e=[];for(const n of Mi(t)){e.push(n.start.clone());for(const t of n.segments)switch(e.push(t.end.clone()),t.type){case"line":break;case"cubic":for(const n of Ri(t))e.push(Ni(t,n));break;case"arc":{const n=Di(t);if(!n)break;for(const t of Bi(n))e.push(ji(n,t));break}}}if(0===e.length)throw new Error("SVG path does not contain any points.");return N.FromPoints(e)}(Ki),Yi=[[3.383,17.776],[4.46,19.1],[19.54,19.1],[20.617,17.776],[18.117,5.776],[17.04,4.9],[6.96,4.9],[5.883,5.776]],Ji=[[12.444,3.002],[12.444,7.316],[20.709,7.316],[20.809,7.416],[20.809,15.871],[20.709,15.971],[12.444,15.971],[12.444,20.285],[12.275,20.357],[3.222,11.716],[3.222,11.571],[12.275,2.93]],Gi=[[11.556,3.002],[11.556,7.316],[3.29,7.316],[3.19,7.416],[3.19,15.87],[3.29,15.97],[11.556,15.97],[11.556,20.285],[11.725,20.357],[20.778,11.716],[20.778,11.571],[11.725,2.93]];function Zi(t,e,n={}){switch(e){case"ellipse":return function(t,e=32){const n=[];for(let r=0;r<e;r+=1){const o=r/e*Math.PI*2;n.push(new O(t.center.x+t.w/2*Math.cos(o),t.center.y+t.h/2*Math.sin(o)))}return n}(t);case"message-circle":return function(t){const e=[ws(t,rs),ws(t,is)];let n=is;for(const r of ss){for(let o=1;o<=ns;o+=1)e.push(ws(t,xs(n,r.control1,r.control2,r.end,o/ns)));n=r.end}return e}(t);case"summary":case"summary-left":return Ms(t);case"burst":return function(t){return qi.map(e=>ks(t,(e.x-Xi.minX)/Xi.w,(e.y-Xi.minY)/Xi.h))}(t);case"rhombus":return[new O(t.center.x,t.minY),new O(t.maxX,t.center.y),new O(t.center.x,t.maxY),new O(t.minX,t.center.y)];case"triangle":return[new O(t.center.x,t.minY),new O(t.maxX,t.maxY),new O(t.minX,t.maxY)];case"pentagon":return function(t,e){const n=[];for(let r=0;r<e;r+=1){const t=-Math.PI/2+r*Math.PI*2/e;n.push(new O(Math.cos(t),Math.sin(t)))}return Ss(n,t)}(t,5);case"hexagon":return[new O(t.minX+.25*t.w,t.minY),new O(t.maxX-.25*t.w,t.minY),new O(t.maxX,t.center.y),new O(t.maxX-.25*t.w,t.maxY),new O(t.minX+.25*t.w,t.maxY),new O(t.minX,t.center.y)];case"star":return function(t){const e=[];for(let n=0;n<10;n+=1){const t=-Math.PI/2+n*Math.PI/5,r=n%2==0?1:.48;e.push(new O(Math.cos(t)*r,Math.sin(t)*r))}return Ss(e,t)}(t);case"trapezoid":return function(t){return Yi.map(([e,n])=>ks(t,e/_i,n/_i))}(t);case"arrow-left":return ps(t,"left").outline;case"arrow-right":return ps(t,"right").outline;case"rectangle":return function(t,e=ts(t),n=4){const r=Math.min(Math.max(0,e),Math.max(0,t.w)/2,Math.max(0,t.h)/2);if(0===r)return Ms(t);const o=[];return Ps(o,{centerX:t.maxX-r,centerY:t.minY+r,radius:r,startAngle:-Math.PI/2,endAngle:0,segments:n}),Ps(o,{centerX:t.maxX-r,centerY:t.maxY-r,radius:r,startAngle:0,endAngle:Math.PI/2,segments:n}),Ps(o,{centerX:t.minX+r,centerY:t.maxY-r,radius:r,startAngle:Math.PI/2,endAngle:Math.PI,segments:n}),Ps(o,{centerX:t.minX+r,centerY:t.minY+r,radius:r,startAngle:Math.PI,endAngle:3*Math.PI/2,segments:n}),o}(t,ts({cornerRadiusPercent:n.cornerRadiusPercent,w:t.w,h:t.h}))}return Ts(e)}function Qi(t,e=12){return Math.min(50,Math.max(0,"number"==typeof t&&Number.isFinite(t)?t:e))}function ts({cornerRadiusPercent:t=12,h:e,w:n}){return Math.min(Math.max(0,n),Math.max(0,e))*Qi(t)/100}var es=24,ns=8,rs=new O(3,20),is=new O(4.3,16.1),ss=[{control1:new O(1.976,12.663),control2:new O(2.874,8.228),end:new O(6.4,5.726)},{control1:new O(9.926,3.225),control2:new O(14.99,3.43),end:new O(18.245,6.206)},{control1:new O(21.5,8.983),control2:new O(21.94,13.472),end:new O(19.274,16.707)},{control1:new O(16.608,19.942),control2:new O(11.659,20.922),end:new O(7.7,19)}];function as(t){const e=ws(t,rs),n=ws(t,is),r=[`M${bs(e)}`,`L${bs(n)}`];for(const o of ss)r.push(`C${bs(ws(t,o.control1))} ${bs(ws(t,o.control2))} ${bs(ws(t,o.end))}`);return r.push(`L${bs(e)}`),r.join(" ")}function ls(t){const e=t.w/_i,n=t.h/_i;return`translate(${vs(t.x)} ${vs(t.y)}) scale(${vs(e)} ${vs(n)})`}function cs(t){const e=t.w/Xi.w,n=t.h/Xi.h,r=t.minX-Xi.minX*e,o=t.minY-Xi.minY*n;return`translate(${vs(r)} ${vs(o)}) scale(${vs(e)} ${vs(n)})`}function ds(t,e){const n=Math.min(t.w/_i,t.h/18),r=t.h/18,o="left"===e?t.minX-3*n:t.maxX-20*n,i=t.minY-3*r;return`translate(${vs(o)} ${vs(i)}) scale(${vs(n)} ${vs(r)})`}function us(t,e,n={}){switch(e){case"ellipse":return{tag:"ellipse",cx:t.center.x,cy:t.center.y,rx:t.w/2,ry:t.h/2};case"message-circle":return{tag:"path",d:as(t)};case"summary":return{tag:"path",d:"M16 15a3.2 3.2 0 0 0-1.618-2.783L14 12l.382-.217C15.382 11.213 16 10.15 16 9V7a4 4 0 0 1 4-4M16 15v2a4 4 0 0 0 4 4",fill:"none",transform:ds(t,"right"),vectorEffect:"non-scaling-stroke"};case"summary-left":return{tag:"path",d:"M7 15c0-1.151.618-2.214 1.618-2.783L9 12l-.382-.217A3.2 3.2 0 0 1 7 9V7a4 4 0 0 0-4-4M7 15v2a4 4 0 0 1-4 4",fill:"none",transform:ds(t,"left"),vectorEffect:"non-scaling-stroke"};case"burst":return{tag:"path",d:Ki,transform:cs(t),vectorEffect:"non-scaling-stroke"};case"trapezoid":return{tag:"path",d:"M3.383 17.776A1.1 1.1 0 0 0 4.46 19.1h15.08a1.1 1.1 0 0 0 1.077-1.324l-2.5-12A1.1 1.1 0 0 0 17.04 4.9H6.96a1.1 1.1 0 0 0-1.077.876z",transform:ls(t),vectorEffect:"non-scaling-stroke"};case"arrow-left":return{tag:"path",d:ps(t,"left").path};case"arrow-right":return{tag:"path",d:ps(t,"right").path};case"rectangle":{const e=ts({cornerRadiusPercent:n.cornerRadiusPercent,w:t.w,h:t.h});return{tag:"rect",x:t.x,y:t.y,width:t.w,height:t.h,rx:e,ry:e}}case"rhombus":case"triangle":case"pentagon":case"hexagon":case"star":return{tag:"polygon",points:Zi(t,e,n)}}return Ts(e)}function ps(t,e){const n=Math.min(t.h/_i,t.w/Vi),r=t.center.y-12*n,o="left"===e?t.minX+Ui*n:t.maxX-Ui*n,i="left"===e?o+9.222*n:o-9.222*n;return{outline:("left"===e?Ji:Gi).map(([o,s])=>function(t,e,n){const{neckX:r,originY:o,scale:i,x:s,y:a}=n;let l;l="left"===e?s<=12.444?r+(s-12.444)*i:s>=20.709?t.maxX-(_i-s)*i:ms(s,12.444,20.709,r,t.maxX-3.2910000000000004*i):s>=11.556?r+(s-11.556)*i:s<=3.29?t.minX+s*i:ms(s,3.29,11.556,t.minX+3.29*i,r);return new O(l,o+a*i)}(t,e,{neckX:i,originY:r,scale:n,x:o,y:s})),path:"left"===e?hs(t,{neckX:i,originY:r,scale:n}):fs(t,{neckX:i,originY:r,scale:n})}}function hs(t,e){if(ys(t))return"M12.444 6.416v.9h8.265a.1.1 0 0 1 .1.1v8.455a.1.1 0 0 1-.1.1h-8.265v4.314c0 .034-.008.048-.014.056a.1.1 0 0 1-.047.036.1.1 0 0 1-.058.009c-.01-.002-.025-.005-.05-.029l-9.053-8.641a.1.1 0 0 1 0-.145l9.053-8.641c.025-.024.04-.028.05-.03a.1.1 0 0 1 .058.01.1.1 0 0 1 .047.036c.006.008.014.022.014.056z";const{neckX:n,originY:r,scale:o}=e,i=t.maxX-3.2910000000000004*o;return[`M${bs(new O(n,r+6.416*o))}`,`v${vs(.9*o)}`,`H${vs(i)}`,`a${gs(o,[.1,.1,0,0,1,.1,.1])}`,`v${vs(8.455*o)}`,`a${gs(o,[.1,.1,0,0,1,-.1,.1])}`,`H${vs(n)}`,`v${vs(4.314*o)}`,`c${gs(o,[0,.034,-.008,.048,-.014,.056])}`,`a${gs(o,[.1,.1,0,0,1,-.047,.036])}`,`a${gs(o,[.1,.1,0,0,1,-.058,.009])}`,`c${gs(o,[-.01,-.002,-.025,-.005,-.05,-.029])}`,`l${gs(o,[-9.053,-8.641])}`,`a${gs(o,[.1,.1,0,0,1,0,-.145])}`,`l${gs(o,[9.053,-8.641])}`,`c${gs(o,[.025,-.024,.04,-.028,.05,-.03])}`,`a${gs(o,[.1,.1,0,0,1,.058,.01])}`,`a${gs(o,[.1,.1,0,0,1,.047,.036])}`,`c${gs(o,[.006,.008,.014,.022,.014,.056])}`,"z"].join(" ")}function fs(t,e){if(ys(t))return"M10.656 7.316h.9V3.002c0-.034.008-.048.014-.056a.1.1 0 0 1 .046-.036.1.1 0 0 1 .059-.01c.01.002.025.006.05.03l9.053 8.641a.1.1 0 0 1 0 .145l-9.053 8.641c-.025.024-.04.027-.05.029a.1.1 0 0 1-.059-.01.1.1 0 0 1-.046-.035c-.006-.008-.014-.022-.014-.056V15.97H3.29a.1.1 0 0 1-.1-.1V7.416a.1.1 0 0 1 .1-.1z";const{neckX:n,originY:r,scale:o}=e,i=t.minX+3.29*o;return[`M${bs(new O(n-.9*o,r+7.316*o))}`,`H${vs(n)}`,`V${vs(r+3.002*o)}`,`c${gs(o,[0,-.034,.008,-.048,.014,-.056])}`,`a${gs(o,[.1,.1,0,0,1,.046,-.036])}`,`a${gs(o,[.1,.1,0,0,1,.059,-.01])}`,`c${gs(o,[.01,.002,.025,.006,.05,.03])}`,`l${gs(o,[9.053,8.641])}`,`a${gs(o,[.1,.1,0,0,1,0,.145])}`,`l${gs(o,[-9.053,8.641])}`,`c${gs(o,[-.025,.024,-.04,.027,-.05,.029])}`,`a${gs(o,[.1,.1,0,0,1,-.059,-.01])}`,`a${gs(o,[.1,.1,0,0,1,-.046,-.035])}`,`c${gs(o,[-.006,-.008,-.014,-.022,-.014,-.056])}`,`V${vs(r+15.97*o)}`,`H${vs(i)}`,`a${gs(o,[.1,.1,0,0,1,-.1,-.1])}`,`V${vs(r+7.416*o)}`,`a${gs(o,[.1,.1,0,0,1,.1,-.1])}`,"z"].join(" ")}function ms(t,e,n,r,o){const i=n-e;return 0===i?r:r+(t-e)/i*(o-r)}function gs(t,e){const n=7===e.length;return e.map((e,r)=>vs(n&&r>=2&&r<=4?e:e*t)).join(" ")}function ys(t){return 0===t.x&&0===t.y&&t.w===_i&&t.h===_i}function xs(t,e,n,r,o){const i=1-o,s=i*i*i,a=3*i*i*o,l=3*i*o*o,c=o*o*o;return new O(t.x*s+e.x*a+n.x*l+r.x*c,t.y*s+e.y*a+n.y*l+r.y*c)}function ws(t,e){return ks(t,e.x/es,e.y/es)}function bs(t){return`${vs(t.x)} ${vs(t.y)}`}function vs(t){return Number.isFinite(t)?Number(t.toFixed(4)).toString():"0"}function ks(t,e,n){return new O(t.minX+t.w*e,t.minY+t.h*n)}function Ss(t,e){const n=N.FromPoints([...t]);return 0===n.w||0===n.h?[e.center]:t.map(t=>new O(e.minX+(t.x-n.minX)/n.w*e.w,e.minY+(t.y-n.minY)/n.h*e.h))}function Ps(t,{centerX:e,centerY:n,endAngle:r,radius:o,segments:i,startAngle:s}){const a=Math.max(1,Math.floor(i));for(let l=0;l<=a;l+=1){const i=s+(r-s)*(l/a);t.push(new O(e+Math.cos(i)*o,n+Math.sin(i)*o))}}function Ms(t){return[new O(t.minX,t.minY),new O(t.maxX,t.minY),new O(t.maxX,t.maxY),new O(t.minX,t.maxY)]}function Is(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist(e);const i=t.sub(e),s=Math.max(0,Math.min(1,(i.x*r.x+i.y*r.y)/o));return t.dist(e.add(r.mul(s)))}function Ts(t){throw new Error(`Unsupported geo shape kind: ${String(t)}`)}function Cs(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function Es(t,e){return t.x*e.y-t.y*e.x}function As(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist(e);const i=t.sub(e),s=Math.max(0,Math.min(1,(i.x*r.x+i.y*r.y)/o));return t.dist(e.add(r.mul(s)))}function Os(t,e,n,r){return Ns(t,e,n,r)?0:Math.min(As(t,n,r),As(e,n,r),As(n,t,e),As(r,t,e))}function Ns(t,e,n,r){const o=e.sub(t),i=r.sub(n),s=Es(o,i);if(Math.abs(s)<1e-8)return null;const a=n.sub(t),l=Es(a,i)/s,c=Es(a,o)/s;return l<0||l>1||c<0||c>1?null:{point:t.add(o.mul(l)),t:l}}function Rs(t,e,n){const r=new N(t.x,t.y,t.props.w,t.props.h);return"ellipse"===t.props.kind?function(t,e,n){const r=t.center,o=t.w/2,i=t.h/2;if(o<=0||i<=0)return null;const s=e.sub(r),a=n.sub(e),l=a.x/o,c=a.y/i,d=s.x/o,u=s.y/i,p=l*l+c*c,h=2*(d*l+u*c),f=h*h-4*p*(d*d+u*u-1);if(0===p||f<0)return null;const m=Math.sqrt(f),g=[(-h-m)/(2*p),(-h+m)/(2*p)].filter(t=>t>1e-6&&t<=1).sort((t,e)=>t-e)[0];return void 0===g?null:e.add(a.mul(g))}(r,e,n):function(t,e,n){let r=null;for(let o=0;o<n.length;o+=1){const i=n[o],s=n[(o+1)%n.length]??n[0];if(!i||!s)continue;const a=Ns(t,e,i,s);!a||a.t<=1e-6||(!r||a.t<r.t)&&(r=a)}return r?.point??null}(e,n,Zi(r,t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent}))}function Ls(t){return Zi(new N(0,0,t.props.w,t.props.h),t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent})}var $s=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"];function Ds(t){const e=new N(0,0,t.props.w,t.props.h);return[new O(e.minX,e.minY),new O(e.center.x,e.minY),new O(e.maxX,e.minY),new O(e.minX,e.center.y),e.center,new O(e.maxX,e.center.y),new O(e.minX,e.maxY),new O(e.center.x,e.maxY),new O(e.maxX,e.maxY)].map((t,e)=>({point:t,kind:$s[e]??"custom"}))}function Bs(t){return"arrow-left"===t.props.kind||"arrow-right"===t.props.kind}function zs(t){return N.FromPoints(Zi(new N(0,0,t.w,t.h),t.kind,{cornerRadiusPercent:t.cornerRadiusPercent}))}var Fs=class extends St{type="geo";getDefaultProps(){return{w:160,h:108,kind:"rectangle",fill:W("fill-slate"),stroke:W("stroke-slate"),strokeStyle:"solid",strokeWidth:2,cornerRadiusPercent:12}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Math.max(24,Cs(e.w,n.w)),h:Math.max(24,Cs(e.h,n.h)),kind:Jo(e.kind)?e.kind:n.kind,fill:V(e.fill,n.fill),stroke:V(e.stroke,n.stroke),strokeStyle:Go(e.strokeStyle)?e.strokeStyle:n.strokeStyle,strokeWidth:Math.max(1,Cs(e.strokeWidth,n.strokeWidth)),cornerRadiusPercent:Qi(e.cornerRadiusPercent,n.cornerRadiusPercent)}}getLocalBounds(t){return new N(0,0,t.props.w,t.props.h)}canReceiveTerminalBinding(t){return!0}getPositionedOutlineVertices(t){return Zi(this.getPositionedBounds(t),t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent})}getSelectionResizeLocalBounds(t){return Bs(t)?zs(t.props):this.getLocalBounds(t)}resizeSelectionBounds(t,e){if(!Bs(t))return super.resizeSelectionBounds(t,e);const n=zs(t.props).w*Math.abs(e.scaleX),r=Math.max(24,t.props.h*Math.abs(e.scaleY)),o=function({direction:t,height:e,selectionWidth:n}){const r=Ui+("left"===t?3.191:3.19),o=e/_i,i=n+r*o;return i>=Vi*o?i:n/(1-r/Vi)}({direction:"arrow-left"===t.props.kind?"left":"right",height:r,selectionWidth:n}),i=this.validateProps({...t.props,w:o,h:r}),s=zs(i),a=dt({localWidth:s.w,localHeight:s.h,scaleX:t.scaleX,scaleY:t.scaleY}),l=lt(pt({requestedBounds:e.selectionLocalBounds,handleId:e.handleId,actualWidth:a.width,actualHeight:a.height,scaleX:e.scaleX,scaleY:e.scaleY,isResizingFromCenter:e.isResizingFromCenter}).center,{rotation:e.selectionRotation,rotationCenter:e.selectionRotationCenter}),c=e.scaleX<0!=e.scaleY<0?2*e.selectionRotation-t.rotation:t.rotation,d=e.scaleX<0?-t.scaleX:t.scaleX,u=e.scaleY<0?-t.scaleY:t.scaleY,p=new N(0,0,i.w,i.h).center,h=s.center.sub(p),f=new O(h.x*d,h.y*u).rot(c);return{id:t.id,x:l.x-p.x-f.x,y:l.y-p.y-f.y,rotation:c,scaleX:d,scaleY:u,props:i}}getHandleSnapGeometry(t){return{points:Ds(t),outline:Ls(t)}}hitTest(t,e){const n=this.getPositionedBounds(t);if("ellipse"===t.props.kind){const t=n.w/2,r=n.h/2;if(t<=0||r<=0)return!1;const o=e.x-n.center.x,i=e.y-n.center.y;return o*o/(t*t)+i*i/(r*r)<=1}return function(t,e){if(e.length<3)return!1;let n=!1;for(let r=0,o=e.length-1;r<e.length;o=r,r+=1){const i=e[r],s=e[o];if(!i||!s)continue;if(Is(t,i,s)<=1e-6)return!0;if(i.y>t.y==s.y>t.y)continue;const a=(s.x-i.x)*(t.y-i.y)/(s.y-i.y)+i.x;t.x<a&&(n=!n)}return n}(e,Zi(n,t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent}))}hitTestLineSegment(t,e){const n=this.getPositionedBounds(t);if("ellipse"===t.props.kind)return function(t,e,n,r){const o=t.center,i=t.w/2+r,s=t.h/2+r;if(i<=0||s<=0)return!1;const a=n.sub(e),l=e.sub(o),c=a.x/i,d=a.y/s,u=l.x/i,p=l.y/s,h=c*c+d*d,f=2*(u*c+p*d),m=u*u+p*p-1;if(m<=0)return!0;const g=f*f-4*h*m;if(0===h||g<0)return!1;const y=Math.sqrt(g),x=(-f-y)/(2*h),w=(-f+y)/(2*h);return x>=0&&x<=1||w>=0&&w<=1}(n,e.positionedStart,e.positionedEnd,e.positionedMargin);{const r=Zi(n,t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent});return this.hitTest(t,e.positionedStart)||this.hitTest(t,e.positionedEnd)||function(t,e,n,r){if(n.length<3)return!1;for(let o=0;o<n.length;o+=1){const i=n[o],s=n[(o+1)%n.length];if(i&&s&&Os(t,e,i,s)<=r)return!0}return!1}(e.positionedStart,e.positionedEnd,r,e.positionedMargin)}}resolveBindingPoint(t,e){const n=e.editor.shapes.computePositionedToPageTransform(t),r=n.tryInvert();if(!r)return e.rawPagePoint;const o=Rs(t,r.applyToPoint(e.rawPagePoint),r.applyToPoint(e.oppositePagePoint));return o?n.applyToPoint(o):e.rawPagePoint}};function js(t,e){switch(t){case"dashed":return`${4*e} ${2*e}`;case"dotted":return"0 "+2*e;default:return}}var Ws=class{type="geo";toSvg(t,e){const{kind:n,fill:r,stroke:o,strokeStyle:i,strokeWidth:s,w:a,h:l}=t.props,c="none"===i?0:s,d=c/2,u=Math.max(a-c,0),p=Math.max(l-c,0),h={fill:e.resolveColor(r),stroke:"none"===i?"none":e.resolveColor(o),"stroke-width":c,"stroke-dasharray":js(i,s),"stroke-linejoin":"round","stroke-linecap":"round"};return function(t,e){switch(t.tag){case"ellipse":return{tag:"ellipse",attrs:{...e,cx:t.cx,cy:t.cy,rx:t.rx,ry:t.ry}};case"path":return{tag:"path",attrs:{...e,fill:t.fill??e.fill,d:t.d,transform:t.transform,"vector-effect":t.vectorEffect}};case"polygon":return{tag:"polygon",attrs:{...e,points:t.points.map(t=>`${_s(t.x)},${_s(t.y)}`).join(" ")}};case"rect":return{tag:"rect",attrs:{...e,x:t.x,y:t.y,width:t.width,height:t.height,rx:t.rx,ry:t.ry}}}}(us(new N(d,d,u,p),n,{cornerRadiusPercent:t.props.cornerRadiusPercent}),h)}};function Hs(){return{id:"land.geo",shapeUtils:[new Fs],shapeSvgExporters:[new Ws],setup(t){t.runtime.provide(Zo,function(t){const e=t.signals.atom("geo.creation-hover",null,{isEqual:(t,e)=>t===e||null!==t&&null!==e&&t.timestamp===e.timestamp&&t.pagePoint.equals(e.pagePoint)});return{preview:t.signals.computed("geo.creation-preview",()=>{const n=e.get(),r=t.inputs.state.get(),o=t.state.tool.get();if(!n||t.state.readonly.get()||t.inputs.isSpacePressed.get()||r.isPointing||r.currentTimestamp!==n.timestamp||!r.currentPagePoint?.equals(n.pagePoint)||!Jo(o.activeToolId))return null;const i={...t.shapes.getDefaultProps("geo"),kind:o.activeToolId};return{bounds:ti(n.pagePoint,i),props:i}}),setHover(t){e.set({pagePoint:t.pagePoint.clone(),timestamp:t.timestamp})},clearHover(){null!==e.get()&&e.set(null)}}}(t)),t.tools.register("rectangle",t=>new oi(t)),t.tools.register("ellipse",t=>new ii(t)),t.tools.register("message-circle",t=>new si(t)),t.tools.register("summary",t=>new ai(t)),t.tools.register("summary-left",t=>new li(t)),t.tools.register("burst",t=>new ci(t)),t.tools.register("rhombus",t=>new di(t)),t.tools.register("triangle",t=>new ui(t)),t.tools.register("pentagon",t=>new pi(t)),t.tools.register("hexagon",t=>new hi(t)),t.tools.register("star",t=>new fi(t)),t.tools.register("trapezoid",t=>new mi(t)),t.tools.register("arrow-left",t=>new gi(t)),t.tools.register("arrow-right",t=>new yi(t))}}}function _s(t){return Number.isFinite(t)?Number(t.toFixed(4)).toString():"0"}function Us(){return{id:"land.geo.react",canvasOverlays:[{id:"land.geo.creation-preview",component:Xs,order:10}],shapeRenderers:[{type:"geo",component:Vs,hoverComponent:Ys}]}}function Vs({shape:t}){
5
- return l(qs,{props:t.props})}function Ks({geometry:t,fill:e,stroke:n,strokeWidth:r,strokeDasharray:o,vectorEffect:i}){const s={fill:"path"===t.tag&&"none"===t.fill?"none":e,stroke:n,strokeWidth:r,strokeDasharray:o,strokeLinejoin:"round",strokeLinecap:"round",vectorEffect:"path"===t.tag&&t.vectorEffect?t.vectorEffect:i};switch(t.tag){case"ellipse":return l("ellipse",{...s,cx:t.cx,cy:t.cy,rx:t.rx,ry:t.ry});case"path":return l("path",{...s,d:t.d,transform:t.transform});case"polygon":return l("polygon",{...s,points:t.points.map(t=>`${t.x},${t.y}`).join(" ")});case"rect":return l("rect",{...s,x:t.x,y:t.y,width:t.width,height:t.height,rx:t.rx,ry:t.ry})}}function qs({props:t,fill:e=t.fill,stroke:n=t.stroke,strokeStyle:r=t.strokeStyle,strokeWidth:o=t.strokeWidth,width:i="100%",height:s="100%"}){const a="none"===r?0:o,c=a/2,d=us(new N(c,c,Math.max(t.w-a,0),Math.max(t.h-a,0)),t.kind,{cornerRadiusPercent:t.cornerRadiusPercent});
6
- return l("svg",{width:i,height:s,viewBox:`0 0 ${t.w} ${t.h}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:l(Ks,{geometry:d,fill:K(e),stroke:"none"===r?"none":K(n),strokeWidth:a,strokeDasharray:js(r,o)})})}var Xs=m(function(){const n=e(Qo(t()).preview);return n?l("g",{"data-ui":"geo-creation-preview",transform:`translate(${n.bounds.x} ${n.bounds.y})`,opacity:.48,pointerEvents:"none",children:l(qs,{props:n.props,width:n.bounds.w,height:n.bounds.h})}):null});function Ys({shape:t,strokeWidth:e}){const{h:r,w:o}=t.props,i=us(new N(0,0,o,r),t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent});
7
- return l("svg",{"data-ui":"geo-hover-outline",width:"100%",height:"100%",viewBox:`0 0 ${o} ${r}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:l(Ks,{geometry:i,fill:"none",stroke:n,strokeWidth:e,strokeDasharray:void 0,vectorEffect:"non-scaling-stroke"})})}var Js={id:"geo",editor:Hs(),render:Us(),api:xi,setup:({editor:t})=>({api:wi({editor:t})})};function Gs(t,e){return t.pagePoint.add(t.pageOutwardNormal.mul(20/Math.max(e,1e-4)))}function Zs(t,e,n){return e.dist(Gs(t,n))}function Qs(t,e,n={}){const r=t.state.cameraZoom.get(),o=12/Math.max(r,1e-4),i=o+("target"===n.mode?0:20/Math.max(r,1e-4)),s=t.shapes.getInBounds(new N(e.x-i,e.y-i,2*i,2*i),n.pageId?{pageId:n.pageId}:void 0);let a=null,l=null,c=o,d=Number.POSITIVE_INFINITY;for(const u of s){if(n.excludeShapeIds?.has(u.id)||zn(u)||t.shapes.isHidden(u.id)||null===t.shapes.getClippedPageBounds(u.id))continue;const i=yt(t,u);if("target"===n.mode){if(0===i.length)continue;const r=fr(t,u,e,o);if(!r)continue;const{borderDistance:s,port:p}=r,h=u.id===n.allowInteriorShapeId&&t.shapes.hitTestPoint(e,{hitTest:"bindingTarget",pageId:n.pageId??void 0,filter:t=>t.id===u.id}).length>0;if(s>o&&h){l={shape:u,port:p};continue}if(s>c||s>o)continue;const f=p.pagePoint.dist(e),m=`${u.index}:${u.id}:${p.id}`,g=`${a?.shape.index}:${a?.shape.id}:${a?.port.id}`;(s<c||s===c&&f<d||s===c&&f===d&&m<g)&&(a={shape:u,port:p},c=s,d=f);continue}for(const t of i){const n=Zs(t,e,r);(n<c||n===c&&`${u.index}:${u.id}:${t.id}`<`${a?.shape.index}:${a?.shape.id}:${a?.port.id}`)&&(a={shape:u,port:t},c=n)}}return a??l}function ta(t,e,n,r){const o=ea(t,e,n);return!!o&&("connect"===o.kind?!!Oo(t,{start:Co(e.shape.id,e.port),end:Co(o.target.shape.id,o.target.port),props:r,selectionAfter:[o.target.shape.id]}):function(t,e,n,r){const o=t.commands.createShapes([n.nodeInput],{source:"user",autoReparent:!1})[0];if(!o)return!1;const i=ia(t,o,e.port);if(!i)return t.commands.deleteShapes([o.id],{source:"user"}),!1;if(!Oo(t,{start:Co(e.shape.id,e.port),end:Co(o.id,i),props:r,selectionAfter:[o.id]}))return t.commands.deleteShapes([o.id],{source:"user"}),!1;return!0}(t,e,o,r))}function ea(t,e,n){const r=aa(t,e),o=new Set(r.map(t=>t.id)),i=ra(t,e);for(const c of i)if(!o.has(c.shape.id)&&!jo(t,e.shape.id,e.port.id,c.shape.id,c.port.id))return{kind:"connect",target:c};const s=function(t,e,n,r){const o=e.shape.parentId,i=ua(t,e.shape),s=o.startsWith("shape:")?t.shapes.get(o):null,a=s?t.shapes.computeLocalToPageTransform(s):J.Identity(),l=e.port.pageOutwardNormal.normalize(),c=new O(i.w/2,i.h/2),d=a.applyToPoint(c),u=a.applyToPoint(c.add(new O(i.w/2,0))),p=a.applyToPoint(c.add(new O(0,i.h/2))),h=Math.abs(pa(u.sub(d),l))+Math.abs(pa(p.sub(d),l)),f=e.port.pagePoint.add(l.mul(96+h)),m=n.createNode({editor:t,sourceShape:e.shape,sourcePortId:e.port.id,pageCenter:f,parentId:o});return 0===r.length?m:la({branchTargets:r,editor:t,input:m,source:e})}(t,e,n,r),a=da(t,s),l=ia(t,a,e.port);return l?{kind:"create",nodeInput:s,previewShape:a,targetPort:l}:null}function na(t,e,n){const r=aa(t,e);return 0===r.length?n:la({branchTargets:r,editor:t,input:n,source:e})}function ra(t,e){const n=e.port.pageOutwardNormal.normalize(),r=e.port.pagePoint.add(n.mul(320)),o=N.FromPoints([e.port.pagePoint,r]).expand(160),i=t.layers.getPageId(e.shape.id);if(!i)return[];const s=new Map(t.state.currentPageShapeIds.get().map((t,e)=>[t,e])),a=t.shapes.getInBounds(o,{pageId:i}).filter(n=>n.id!==e.shape.id&&!zn(n)&&!t.shapes.isHidden(n.id)&&null!==t.shapes.getClippedPageBounds(n.id)&&t.shapes.getUtil(n).canReceiveTerminalBinding(n,{editor:t})).flatMap(r=>{const o=t.shapes.getPageCenter(r.id);if(!o)return[];const i=o.sub(e.port.pagePoint),a=pa(i,n),l=Math.abs((d=n,(c=i).x*d.y-c.y*d.x));var c,d;const u=i.len();if(a<=0||a>320||l>160)return[];const p=oa(t,r,e.port.pagePoint);return p?[{shape:r,port:p,distance:u,forward:a,cross:l,order:s.get(r.id)??1/0}]:[]});return a.sort((t,e)=>t.distance-e.distance||t.cross-e.cross||t.forward-e.forward||t.order-e.order||t.shape.id.localeCompare(e.shape.id)||t.port.id.localeCompare(e.port.id)),a.map(({shape:t,port:e})=>({shape:t,port:e}))}function oa(t,e,n){return[...yt(t,e)].sort((t,e)=>{const r=n.sub(t.pagePoint).normalize(),o=n.sub(e.pagePoint).normalize(),i=pa(t.pageOutwardNormal,r);return pa(e.pageOutwardNormal,o)-i||t.pagePoint.dist(n)-e.pagePoint.dist(n)||t.id.localeCompare(e.id)})[0]??null}function ia(t,e,n){const r=n.pageOutwardNormal.normalize();return[...yt(t,e)].sort((t,e)=>pa(t.pageOutwardNormal.normalize(),r)-pa(e.pageOutwardNormal.normalize(),r)||t.pagePoint.dist(n.pagePoint)-e.pagePoint.dist(n.pagePoint)||t.id.localeCompare(e.id))[0]??null}function sa(){return{createNode({editor:t,sourceShape:e,pageCenter:n,parentId:r}){const o=ua(t,e),i=r.startsWith("shape:")?t.shapes.get(r):null,s=(i?t.shapes.computeLocalToPageTransform(i):J.Identity()).tryInvert()?.applyToPoint(n)??n;return{type:"geo",parentId:r,x:s.x-o.w/2,y:s.y-o.h/2,rotation:0,props:{...o}}}}}function aa(t,e){const n=[],r=new Set;for(const o of t.state.currentPageShapeIds.get()){const i=t.shapes.get(o);if(!zn(i))continue;const s=jn(t,i.id),a=s.start?.toId===e.shape.id&&s.start.props.portId===e.port.id?s.end:s.end?.toId===e.shape.id&&s.end.props.portId===e.port.id?s.start:null;if(!a)continue;const l=t.shapes.get(a.toId);!l||r.has(l.id)||zn(l)||t.shapes.isHidden(l.id)||null===t.shapes.getClippedPageBounds(l.id)||(r.add(l.id),n.push(l))}return n}function la({branchTargets:t,editor:e,input:n,source:r}){const o=da(e,n),i=e.shapes.computePageCenter(o),s=new O(-r.port.pageOutwardNormal.y,r.port.pageOutwardNormal.x).normalize();if(0===s.len2())return n;const a=pa(r.port.pagePoint,s),l=ca(e,o,s,a),c=(l.max-l.min)/2,d=function(t,e){const n=t.map(({min:t,max:n})=>({min:t-48-e,max:n+48+e})).sort((t,e)=>t.min-e.min||t.max-e.max),r=[];for(const s of n){const t=r[r.length-1];!t||s.min>t.max+1e-6?r.push({...s}):t.max=Math.max(t.max,s.max)}const o=r.find(({min:t,max:e})=>t<-1e-6&&e>1e-6);if(!o)return 0;const i=t.reduce((t,e)=>t+(e.min+e.max)/2,0);return[o.min,o.max].sort((t,e)=>Math.abs(i+t)-Math.abs(i+e)||Math.abs(t)-Math.abs(e)||e-t)[0]}(t.map(t=>ca(e,t,s,a)),c)-(pa(i,s)-a);if(Math.abs(d)<=1e-6)return n;const u=n.parentId??r.shape.parentId,p=u.startsWith("shape:")?e.shapes.get(u):null,h=(p?e.shapes.computeLocalToPageTransform(p):J.Identity()).tryInvert();if(!h)return n;const f=i.add(s.mul(d)),m=h.applyToPoint(i),g=h.applyToPoint(f).sub(m);return{...n,x:n.x+g.x,y:n.y+g.y}}function ca(t,e,n,r){const o=t.shapes.computePageCorners(e).map(t=>pa(t,n)-r);return{min:Math.min(...o),max:Math.max(...o)}}function da(t,e){const n={id:"shape:connector-quick-create-preview",typeName:"shape",scope:"document",type:e.type,parentId:e.parentId??t.pages.getCurrentId(),index:e.index??"preview",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:{...t.shapes.getDefaultProps(e.type),...e.props},meta:e.meta??{}};return{...n,props:t.shapes.getUtil(n).validateProps(n.props)}}function ua(t,e){return Yo(e)?{w:e.props.w,h:e.props.h,kind:e.props.kind,fill:e.props.fill,stroke:e.props.stroke,strokeStyle:e.props.strokeStyle,strokeWidth:e.props.strokeWidth,cornerRadiusPercent:e.props.cornerRadiusPercent}:t.shapes.getDefaultProps("geo")}function pa(t,e){return t.x*e.x+t.y*e.y}function ha(t){const e={visibleShapes:[],sourceShapeIds:new Set,targetShapeId:null,highlightedPortId:null};if(t.state.readonly.get()||t.state.shapeEditingSession.get()||t.inputs.isSpacePressed.get())return e;const n=To(t).previewSignal.get();if(n){const e=new Map;for(const o of[n.start,n.end]){if(!o.shapeId)continue;const n=t.shapes.get(o.shapeId);n&&ma(t,n,"target")&&e.set(n.id,n)}const r=n[n.movingTerminal];return{visibleShapes:[...e.values()],sourceShapeIds:new Set,targetShapeId:r.shapeId,highlightedPortId:r.portId}}const r=t.state.tool.get().activeToolId;let o=null;if("select"===r){const e=t.state.selectedShapes.get();o=1===e.length?e[0]??null:null}else if("connector"===r){const e=t.render.interaction.hoveredShapeId.get();o=e?t.shapes.get(e)??null:null}return o&&ma(t,o,"source")?{visibleShapes:[o],sourceShapeIds:new Set([o.id]),targetShapeId:null,highlightedPortId:null}:e}function fa(t,e){const n=ha(t),r=To(t),o=Math.max(t.state.cameraZoom.get(),1e-4),i=12/o;let s=null;for(const a of n.visibleShapes)if(n.sourceShapeIds.has(a.id))for(const n of yt(t,a)){if(!r.isPortVisible(n.id))continue;const t=Zs(n,e,o);t<=i+1e-6&&(!s||t<s.distance||t===s.distance&&`${a.index}:${a.id}:${n.id}`<`${s.shape.index}:${s.shape.id}:${s.port.id}`)&&(s={shape:a,port:n,distance:t})}return s?{shape:s.shape,port:s.port}:null}function ma(t,e,n){const r=yt(t,e);return!zn(e)&&!t.shapes.isHidden(e.id)&&null!==t.shapes.getClippedPageBounds(e.id)&&("target"===n||!t.layers.isOrAncestorLocked(e.id))&&t.shapes.getUtil(e).canReceiveTerminalBinding(e,{editor:t})&&("target"===n?r.length>0:r.some(e=>To(t).isPortVisible(e.id)))}function ga(){return{id:"land.connector.react",shapeRenderers:[{type:"connector",component:ba,hoverComponent:va}],selectionCustomHandleRenderers:[{type:xo,component:ya},{type:wo,component:xa},{type:bo,component:wa}],canvasOverlays:[{id:"land.connector.ports-overlay",order:100,component:Sa}]}}function ya({handle:t,strokeWidth:e}){
8
- return l("circle",{"data-selection-custom-handle":t.id,"data-selection-custom-handle-type":t.type,"data-selection-custom-handle-id":t.id,cx:t.point.x,cy:t.point.y,r:Math.max(t.bounds.w,t.bounds.h)/2,fill:"rgba(255,255,255,0.98)",stroke:"var(--land-selection, #2563eb)",strokeWidth:e,style:{cursor:t.cursor??"move",pointerEvents:"auto"}})}function xa({handle:t}){const e=.75*Math.max(t.bounds.w,t.bounds.h),n=.36*Math.max(t.bounds.w,t.bounds.h);
9
- return c("g",{children:[l("circle",{"data-selection-custom-handle":t.id,"data-selection-custom-handle-type":t.type,"data-selection-custom-handle-id":t.id,cx:t.point.x,cy:t.point.y,r:e,fill:"transparent",style:{cursor:t.cursor??"move",pointerEvents:"all"}}),l("circle",{cx:t.point.x,cy:t.point.y,r:n,fill:"rgba(96, 165, 250, 0.72)",pointerEvents:"none"})]})}function wa({handle:t,strokeWidth:e}){const n=Mo(t.id);if(!n)return null;const r=Math.max(t.bounds.w,t.bounds.h),o="horizontal"===n.axis,i=1.35*r+2*e,s=.4*r,a=o?i:s,d=o?s:i,u=1.8*r;
10
- return c("g",{children:[l("rect",{"data-selection-custom-handle":t.id,"data-selection-custom-handle-type":t.type,"data-selection-custom-handle-id":t.id,x:t.point.x-u/2,y:t.point.y-u/2,width:u,height:u,fill:"transparent",style:{cursor:t.cursor??"grab",pointerEvents:"all"}}),l("rect",{x:t.point.x-a/2,y:t.point.y-d/2,width:a,height:d,rx:Math.min(a,d)/2,ry:Math.min(a,d)/2,fill:"rgba(255,255,255,0.98)",stroke:"var(--land-selection, #2563eb)",strokeWidth:e,pointerEvents:"none"})]})}function ba({shape:t,editor:e}){
11
- return l(ka,{shape:t,editor:e,idPrefix:"connector",stroke:K(t.props.stroke),strokeWidth:t.props.strokeWidth})}function va({shape:t,editor:e,strokeWidth:r}){
12
- return l(ka,{dataUi:"connector-hover-outline",shape:t,editor:e,idPrefix:"connector-hover",stroke:n,strokeWidth:r,vectorEffect:"non-scaling-stroke"})}function ka({dataUi:t,editor:n,idPrefix:r,shape:o,stroke:i,strokeWidth:s,vectorEffect:a}){const d=`${r}-content-clip-${o.id.replace(/[^a-zA-Z0-9_-]/g,"-")}`,u=jr(n,o),p=po(u.markerSegments),h=n.shapes.computeRenderBounds(o),f=e(n.shapes.getContentCutoutLocalPolygonsSignal(o.id)),m=ht({outputBounds:u.pageBounds,cutoutLocalPolygons:f});
13
- return c("svg",{"data-ui":t,width:"100%",height:"100%",viewBox:`${h.x} ${h.y} ${h.w} ${h.h}`,overflow:"visible",children:[m?l("defs",{children:l("clipPath",{id:d,clipPathUnits:"userSpaceOnUse",children:l("path",{d:m,clipRule:"evenodd",fillRule:"evenodd"})})}):null,c("g",{clipPath:m?`url(#${d})`:void 0,children:[l("path",{"data-connector-path":"body",d:u.path,fill:"none",stroke:i,strokeWidth:s,strokeDasharray:"dashed"===o.props.strokeStyle?"8 6":void 0,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:a}),p?l("path",{"data-connector-path":"markers",d:p,fill:"none",stroke:i,strokeWidth:s,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:a}):null]})]})}var Sa=m(function(){const o=t(),i=e(o.state.readonly),s=e(o.state.tool).activeToolId;e(o.state.selectedShapes),e(o.render.interaction.hoveredShapeId);const a=e(o.state.shapeEditingSession),d=e(o.inputs.isSpacePressed),u=e(o.render.interaction.selectionTranslationActive),p=e(o.state.cameraZoom),h=To(o),f=e(h.previewSignal);if(i||a||d||u)return null;const m=ha(o),g=new Map(m.visibleShapes.map(t=>[t.id,t])),y=m.targetShapeId?o.shapes.get(m.targetShapeId)??null:null,x=f?y:"connector"===s?m.visibleShapes[0]:null,w=x&&!zn(x)?x:null;if(0===g.size&&!f)return null;const b=Math.max(p,1e-4),v=m.targetShapeId&&m.highlightedPortId?`${m.targetShapeId}:${m.highlightedPortId}`:null,k=f?{point:f.start.pagePoint,outwardNormal:f.start.pageOutwardNormal,obstacleId:f.start.shapeId??void 0,obstacleBounds:f.start.obstacleBounds}:null,S=f?{point:f.end.pagePoint,outwardNormal:f.end.pageOutwardNormal,obstacleId:f.end.shapeId??void 0,obstacleBounds:f.end.obstacleBounds}:null,P=f?Wr({start:k,end:S,routing:f.geometry.routing,cornerRadius:f.geometry.cornerRadius,headStart:f.geometry.headStart,headEnd:f.geometry.headEnd,strokeWidth:f.geometry.strokeWidth,curveWaypoints:f.geometry.curveWaypoints,orthogonalBends:f.geometry.orthogonalBends,terminalOffsetMapper:Dr(f.geometry.localToPageTransform)}):null,M=f&&P?function(t,e){const n=t.geometry.localToPageTransform,r=n.tryInvert();if(!r)return{info:e,localToPageTransform:J.Identity()};const o=ao(e,r);if("rebind"===t.kind)return{info:o,localToPageTransform:n};const i=N.FromPoints([o.startPagePoint,...o.points,o.endPagePoint]);return{info:ao(o,J.Translate(-i.x,-i.y)),localToPageTransform:n.compose(J.Translate(i.x,i.y))}}(f,P):null,I=f?f.start.pagePoint:null,T=f?f.end.pagePoint:null,C=f?K(f.geometry.stroke):"var(--land-selection, #2563eb)",E=f?.geometry.strokeWidth??2,A=f?.geometry.strokeStyle??"solid",O=w?Oa(o,w):null,R=f?f[f.movingTerminal]:null;
14
- return c("g",{"data-ui":"connector-ports-overlay",children:[
15
- l("style",{children:"\n [data-connector-port-idle],\n [data-connector-port-hover-preview] {\n transition: opacity 100ms ease;\n }\n [data-connector-port-hover-preview] {\n opacity: 0;\n }\n [data-connector-port]:hover [data-connector-port-idle] {\n opacity: 0;\n }\n [data-connector-port]:hover [data-connector-port-hover-preview] {\n opacity: 1;\n }\n "}),O?l("path",{"data-ui":"connector-target-border-highlight",d:O,fill:"none",stroke:n,strokeWidth:r/b,strokeLinecap:"round",strokeLinejoin:"round",pointerEvents:"none"}):null,M?l("g",{"data-ui":"connector-creation-preview",pointerEvents:"none",opacity:.78,children:c("g",{"data-ui":"connector-creation-preview-geometry",transform:M.localToPageTransform.toSvgString(),children:[l("path",{"data-ui":"connector-creation-preview-path",d:M.info.path,fill:"none",stroke:C,strokeWidth:E,strokeDasharray:"dashed"===A?"8 6":void 0,strokeLinecap:"round",strokeLinejoin:"round"}),M.info.markerSegments.length>0?l("path",{"data-ui":"connector-creation-preview-markers",d:M.info.markerSegments.map(t=>`M ${t.start.x} ${t.start.y} L ${t.end.x} ${t.end.y}`).join(" "),fill:"none",stroke:C,strokeWidth:E,strokeLinecap:"round",strokeLinejoin:"round"}):null]})}):null,[...g.values()].flatMap(t=>yt(o,t).map(e=>h.isPortVisible(e.id)?l(Ta,{editor:o,shape:t,port:e,zoom:b,highlighted:v===`${t.id}:${e.id}`,targetMode:w?.id===t.id,quickCreateNodeFactory:h.quickCreateNodeFactory},`${t.id}:${e.id}`):null)),R?.shapeId?l(Ma,{point:R.pagePoint,zoom:b}):!f&&"connector"===s&&w?l(Pa,{shape:w,zoom:b}):null,I&&T?l(Ia,{start:I,end:T,zoom:b}):null]})});function Pa({shape:n,zoom:r}){const o=t(),i=e(o.inputs.state);if(!i.currentPagePoint||i.accelKey)return null;const s=12/r,a=fr(o,n,i.currentPagePoint,s);return!a||a.borderDistance>s?null:l(Ma,{point:a.port.pagePoint,zoom:r})}function Ma({point:t,zoom:e}){
16
- return l("circle",{"data-ui":"connector-border-snap-preview",cx:t.x,cy:t.y,r:5/e,fill:"var(--land-selection, #2563eb)",stroke:"#ffffff",strokeWidth:1.5/e,pointerEvents:"none"})}function Ia({start:t,end:e,zoom:n}){const r=4/n,o=1/n;
17
- return l("g",{"data-ui":"connector-creation-terminal-handles",pointerEvents:"none",children:[{terminal:"start",point:t},{terminal:"end",point:e}].map(({terminal:t,point:e})=>l("circle",{"data-connector-creation-terminal":t,cx:e.x,cy:e.y,r:r,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:o},t))})}function Ta({editor:t,shape:e,port:n,zoom:r,highlighted:o,targetMode:i,quickCreateNodeFactory:s}){const[a,d]=S(!1),u=i?n.pagePoint:Gs(n,r),p=4/r,h=12/r,f=15/r,m=12/r,g=180*Math.atan2(n.pageOutwardNormal.y,n.pageOutwardNormal.x)/Math.PI;
18
- return c("g",{"data-ui":"connector-port","data-connector-port":"true","data-connector-port-shape-id":e.id,"data-connector-port-id":n.id,"data-connector-port-target":i?"true":void 0,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:[a&&!i?l(Ca,{editor:t,source:{shape:e,port:n},quickCreateNodeFactory:s,zoom:r}):null,
19
- l("circle",{"data-connector-port-hit-area":"true",cx:u.x,cy:u.y,r:m,fill:"transparent",pointerEvents:"all",cursor:"crosshair"}),
20
- l("circle",{"data-connector-port-idle":"true",cx:u.x,cy:u.y,r:o?1.2*p:p,fill:o?"var(--land-selection, #2563eb)":"rgba(37, 99, 235, 0.28)",pointerEvents:"none"}),i?null:c("g",{"data-connector-port-hover-preview":"true",pointerEvents:"none",children:[l("circle",{cx:u.x,cy:u.y,r:h,fill:"var(--land-selection, #2563eb)"}),l(mn,{"data-connector-port-hover-arrow":"true",x:u.x-f/2,y:u.y-f/2,width:f,height:f,color:"#ffffff",strokeWidth:2.4,transform:`rotate(${g} ${u.x} ${u.y})`})]})]})}function Ca({editor:t,source:e,quickCreateNodeFactory:n,zoom:r}){const o=ea(t,e,n);if(!o)return null;const i=t.shapes.getDefaultProps("connector"),s=function(t){return"connect"===t.kind?t.target:{shape:t.previewShape,port:t.targetPort}}(o),a="create"===o.kind?e.shape.parentId:Ho(t,e.shape,s.shape);if(!a)return null;const d=a.startsWith("shape:")?t.shapes.get(a):null,u=d?t.shapes.computeLocalToPageTransform(d):J.Identity(),p=Wr({start:{point:e.port.pagePoint,outwardNormal:e.port.pageOutwardNormal,obstacleId:e.shape.id,obstacleBounds:t.shapes.getPageBounds(e.shape.id)??void 0},end:{point:s.port.pagePoint,outwardNormal:s.port.pageOutwardNormal,obstacleId:s.shape.id,obstacleBounds:"create"===o.kind?t.shapes.computePageBounds(s.shape):t.shapes.getPageBounds(s.shape.id)??void 0},routing:i.routing,cornerRadius:i.cornerRadius,headStart:i.headStart,headEnd:i.headEnd,strokeWidth:i.strokeWidth,terminalOffsetMapper:Dr(u),curveWaypoints:[],orthogonalBends:[]}),h=K(i.stroke);
21
- return c("g",{"data-ui":"connector-port-quick-connect-preview","data-connector-port-quick-connect-kind":o.kind,pointerEvents:"none",children:[c("g",{opacity:.58,children:[l("path",{"data-ui":"connector-port-quick-connect-path",d:p.path,fill:"none",stroke:h,strokeWidth:i.strokeWidth,strokeDasharray:"dashed"===i.strokeStyle?"8 6":void 0,strokeLinecap:"round",strokeLinejoin:"round"}),p.markerSegments.length>0?l("path",{"data-ui":"connector-port-quick-connect-markers",d:p.markerSegments.map(t=>`M ${t.start.x} ${t.start.y} L ${t.end.x} ${t.end.y}`).join(" "),fill:"none",stroke:h,strokeWidth:i.strokeWidth,strokeLinecap:"round",strokeLinejoin:"round"}):null]}),"create"===o.kind?l(Ea,{editor:t,shape:o.previewShape,zoom:r}):null]})}function Ea({editor:t,shape:e,zoom:n}){const r=s().getShapeRenderer(e.type)?.component,o=t.shapes.computeRenderBounds(e),i=t.shapes.computeLocalToPageTransform(e).compose(J.Translate(o.x,o.y)),a=Oa(t,e);
22
- return c("g",{"data-ui":"connector-port-quick-create-shape",children:[r?l("foreignObject",{"data-ui":"connector-port-quick-create-shape-content",width:o.w,height:o.h,overflow:"visible",opacity:.52,transform:i.toSvgString(),children:l("div",{style:{height:"100%",overflow:"visible",pointerEvents:"none",width:"100%"},children:l(Aa,{Renderer:r,editor:t,shape:e})})}):a?l("path",{"data-ui":"connector-port-quick-create-shape-fallback",d:a,fill:"rgba(37, 99, 235, 0.1)",stroke:"none"}):null,a?l("path",{"data-ui":"connector-port-quick-create-shape-outline",d:a,fill:"none",stroke:"var(--land-selection, #2563eb)",strokeWidth:1.5/n,strokeDasharray:`${5/n} ${4/n}`,strokeLinecap:"round",strokeLinejoin:"round"}):null]})}function Aa({Renderer:t,editor:e,shape:n}){
23
- return l(t,{editor:e,isSelected:!1,shape:n,shapeEditingSession:null})}function Oa(t,e){const n=[];for(const r of hr(t,e)){const[t,...e]=r.points;if(t){n.push(`M ${t.x} ${t.y}`);for(const t of e)n.push(`L ${t.x} ${t.y}`);r.closed&&r.points.length>2&&n.push("Z")}}return n.length>0?n.join(" "):null}var Na=class extends A{type="connector";getDefaultProps(){return{terminal:"start",portId:"top"}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=e.normalizedAnchor&&"object"==typeof e.normalizedAnchor?e.normalizedAnchor:null;return{terminal:"end"===e.terminal?"end":"start",portId:"string"==typeof e.portId&&e.portId.length>0?e.portId:"top",...n?{normalizedAnchor:{x:Ra(n.x),y:Ra(n.y)}}:{}}}canBind(t,e,n){return zn(n.fromShape)&&!zn(n.toShape)&&t.layers.getPageId(n.fromShape.id)===t.layers.getPageId(n.toShape.id)&&null!==mr(t,n.toShape,e.props)}getExclusiveBindingKey(t){return`${t.fromId}:${t.props.terminal}`}onBindingCreate(t,e){return this.getSyncEffect(t,e.fromId)}onBindingUpdate(t,e,n){return this.getSyncEffect(t,n.fromId)}onBindingLoad(t,e){return this.getSyncEffect(t,e.fromId)}onAfterShapeChange(t,e,n){if("from"!==n.role||"start"===e.props.terminal)return this.getSyncEffect(t,e.fromId)}onBeforeDeleteShape(t,e,n){return"from"===n.role?{deleteBindingIds:Wn(t,e.fromId).map(t=>t.id)}:t.shapes.get(e.fromId)?{deleteShapeIds:[e.fromId]}:{}}onBeforeDeleteBinding(t,e){return this.getDetachEffect(t,e)}getExportShapeIds(t,e){return[e.fromId]}getGeometryDependentShapeIds(t,e,n){return"to"===n.role?[e.fromId]:[]}getSyncEffect(t,e){const n=t.shapes.get(e);if(!zn(n))return;const r=No(t,n);var o,i;return r&&(i=r,(o=n).parentId!==i.parentId||o.x!==i.x||o.y!==i.y||o.rotation!==i.rotation||o.scaleX!==i.scaleX||o.scaleY!==i.scaleY||JSON.stringify(o.props)!==JSON.stringify(i.props))?{shapes:[r],suppressBindingIds:Wn(t,e).map(t=>t.id)}:void 0}getDetachEffect(t,e){const n=t.shapes.get(e.fromId);if(!zn(n))return{deleteBindingIds:[e.id]};const r=Br(t,n),o="start"===e.props.terminal?r.startPagePoint:r.endPagePoint,i=Ro(t,n,e.props.terminal,o);return{shapes:i?[i]:void 0,deleteBindingIds:[e.id],suppressBindingIds:Wn(t,e.fromId).map(t=>t.id)}}};function Ra(t){return"number"==typeof t&&Number.isFinite(t)?Math.max(0,Math.min(1,t)):.5}var La="connector.rebind",$a={propagation:"stop"},Da={propagation:"stop",clickSequence:"break"},Ba=class{editor;origin;quickCreateNodeFactory;pointerId;originScreenPoint;preview;initialSelectedShapeIds;props;didClearSelection=!1;operation;constructor(t,e,n,r,o){this.editor=t,this.origin=e,this.quickCreateNodeFactory=o,this.pointerId=r,this.originScreenPoint=n.clone(),this.initialSelectedShapeIds=t.selection.getIds(),this.props=t.shapes.getDefaultProps("connector");const i=Eo(t,e.start);if(!i)throw new Error("Connector creation requires a resolvable start endpoint");const s=Eo(t,{kind:"free",pagePoint:i.pagePoint.clone()});this.preview={kind:"create",origin:e.kind,start:ja(i,s,"start"),end:ja(s,i,"end"),invalidReason:null,isDragging:!1,movingTerminal:"end",geometry:Ka(this.props,Ha(t,i,s))},this.operation=t.operations.begin({kind:"connector.create",label:"shape.create",source:"user",history:"record"}),To(t).setPreview(this.preview)}update(t,e,n){const r=this.originScreenPoint.dist(t)>10;r&&!this.didClearSelection&&(this.initialSelectedShapeIds.length>0&&this.editor.commands.setSelectedShapeIds([],{source:"user"}),this.didClearSelection=!0);const o=r&&!n?Qs(this.editor,e,{allowInteriorShapeId:"bound"===this.origin.start.kind?this.origin.start.shapeId:void 0,mode:"target",pageId:this.editor.pages.getCurrentId()}):null,i=Eo(this.editor,this.origin.start);if(!i)return void this.cancel("command");const s=Wa(this.editor,i,e,this.props.routing,n),a=o?Co(o.shape.id,o.port):{kind:"free",pagePoint:s},l=Eo(this.editor,a);if(!l)return void this.cancel("command");const c=Ao(this.editor,this.origin.start,a);Object.assign(this.preview,{start:ja(i,l,"start"),end:ja(l,i,"end"),invalidReason:c,isDragging:r,geometry:{...this.preview.geometry,localToPageTransform:Ha(this.editor,i,l)}}),To(this.editor).setPreview({...this.preview})}complete(t,e,n){if(this.update(t,e,n),To(this.editor).pointerSession!==this)return!1;let r=!1;if(this.preview.isDragging)this.preview.invalidReason||(r=!!Oo(this.editor,{start:this.preview.start.draft,end:this.preview.end.draft,props:this.props,selectionAfter:"connector"}));else{if("canvas"===this.origin.kind)return!1;const t=Eo(this.editor,this.origin.start);r=!!(t?.shape&&t.port&&ta(this.editor,{shape:t.shape,port:t.port},this.quickCreateNodeFactory,this.props))}return this.clear(),r?(this.operation.commit(),"canvas"!==this.origin.kind||this.editor.state.tool.get().isToolLocked||this.editor.commands.setActiveTool("select",{source:"system"})):(this.operation.cancel(),this.restoreInitialSelection()),r}cancel(t){this.clear(),this.operation.isActive&&this.operation.cancel(),this.restoreInitialSelection()}clear(){const t=To(this.editor);t.setPreview(null),t.setPointerSession(null),this.editor.interaction.setHoveredShapeId(null)}restoreInitialSelection(){this.didClearSelection&&this.editor.commands.setSelectedShapeIds(this.initialSelectedShapeIds,{source:"system"})}};function za(t){return{id:"land.connector.interactions",editorEvent:{handleEvent(e,n){const r=To(e),o=r.pointerSession;if("cancel"===n.type)return o?.cancel(n.reason),e.interaction.setHoveredShapeId(null),o?$a:void 0;if(e.state.readonly.get())return;if(o){if("tick"===n.type){const t=e.inputs.state.get();if(o.preview.isDragging&&t.pointerId===o.pointerId&&t.currentScreenPoint){const r=It(t.currentScreenPoint,e.state.viewportScreenSize.get(),n.elapsed);0===r.x&&0===r.y||(e.viewport.pan(r),o.update(t.currentScreenPoint,e.viewport.screenToPage(t.currentScreenPoint),t.accelKey))}return $a}if("pointer"!==n.type)return $a;if(n.pointerId!==o.pointerId)return $a;if("pointer_move"===n.name)o.update(n.screenPoint,n.pagePoint,n.accelKey);else{if("pointer_up"===n.name)return o.complete(n.screenPoint,n.pagePoint,n.accelKey)?Da:$a;"pointer_cancel"===n.name&&o.cancel("pointer_cancel")}return $a}if("pointer"!==n.type)return;if("pointer_move"===n.name&&"connector"===e.state.tool.get().activeToolId)return void e.interaction.setHoveredShapeId(function(t,e){if(t.state.readonly.get())return null;const n=t.shapes.hitTest(e),r=n?t.shapes.getUtil(n).getHoverTargetId(n,{editor:t}):null,o=r?t.shapes.get(r)??null:null;return o&&ma(t,o,"source")?o:null}(e,n.pagePoint)?.id??null);if("pointer_down"!==n.name||0!==n.button||e.inputs.isSpacePressed.get()||e.state.shapeEditingSession.get())return;const i=e.state.tool.get().activeToolId;let s=null;if("select"===i){const t=fa(e,n.pagePoint);t&&(s={kind:"port",start:Co(t.shape.id,t.port)})}else"connector"===i&&(s={kind:"canvas",start:Fa(e,n)});if(!s)return;const a=new Ba(e,s,n.screenPoint,n.pointerId,t);return r.setPointerSession(a),$a}},selectionHandle:{createSession:(t,{handle:e,shape:n})=>t.state.readonly.get()?null:zn(n)?"binding_terminal"===e.kind?function(t,e,n){if(!zn(t.shapes.get(e)))return null;const r=n.terminal,o="start"===r?"end":"start";let i=null;return{shapeId:e,operationKind:La,shouldClearBindingPreviewOnExit:!0,onDragStart(){To(t).setSelectionHandlesHidden(!0)},update({pagePoint:n,accelKey:s,source:a}){const l=jn(t,e)[o],c=s?null:Qs(t,n,{allowInteriorShapeId:l?.toId,mode:"target",pageId:l?t.layers.getPageId(l.toId):t.pages.getCurrentId()});if(c&&l&&Wo(c.shape.id,c.port.id,l.toId,l.props.portId))return{status:"continue",finalPagePoint:c?.port.pagePoint};const d=c,u=!!d&&(l&&"start"===r?jo(t,d.shape.id,d.port.id,l.toId,l.props.portId,e):!!l&&jo(t,l.toId,l.props.portId,d.shape.id,d.port.id,e));i=d&&!u?d:null;let p=jn(t,e)[r];!i&&p&&(t.commands.deleteBinding(p.id,{source:a}),p=null);const h=t.shapes.get(e);if(!zn(h))return{status:"stop"};const f=l?t.shapes.get(l.toId):null,m=f&&l?mr(t,f,l.props):null,g=f&&m?Eo(t,Co(f.id,m)):null,y=i?.port.pagePoint??(!c&&g?Wa(t,g,n,h.props.routing,s):n),x=Ro(t,h,r,y);x&&function(t,e,n){const r=new Set(Wn(t,e.id).map(t=>t.id));t.commands.updateShapes([{id:e.id,parentId:e.parentId,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,props:e.props}],{source:n,suppressBindingIds:r})}(t,x,a),i&&(p=jn(t,e)[r],p?p.toId===i.shape.id&&p.props.portId===i.port.id||t.commands.updateBinding({id:p.id,toId:i.shape.id,props:yr(r,i.port)},{source:a}):t.commands.createBinding({type:"connector",fromId:e,toId:i.shape.id,props:yr(r,i.port)},{source:a}));const w=jn(t,e)[o],b=w?t.shapes.get(w.toId):null,v=b&&w?mr(t,b,w.props):null;if(b&&v){const n=t.shapes.get(e);zn(n)&&function(t,e,n,r,o,i,s){const a=t.shapes.get(e.id),l=zn(a)?a:e,c=t.shapes.computeLocalToPageTransform(l),d=Co(r,o),u=i?Co(i.shape.id,i.port):{kind:"free",pagePoint:s.clone()},p=Eo(t,d),h=Eo(t,u);if(!p||!h)return void To(t).setPreview(null);const f="start"===n?h:p,m="end"===n?h:p;To(t).setPreview({kind:"rebind",start:ja(f,m,"start"),end:ja(m,f,"end"),isDragging:!0,movingTerminal:n,geometry:Ka(l.props,c,{curveWaypoints:l.props.curveWaypoints.map(t=>c.applyToPoint(new O(t.x,t.y))),orthogonalBends:l.props.orthogonalBends.map(t=>c.applyToPoint(new O(t.x,t.y)))})})}(t,n,r,b.id,v,i,y)}else To(t).setPreview(null);return{status:"continue",finalPagePoint:y}},onCancel(){const e=To(t);e.setPreview(null),e.setSelectionHandlesHidden(!1)},onComplete(){const e=To(t);e.setPreview(null),e.setSelectionHandlesHidden(!1)}}}(t,n.id,e):"custom"===e.kind?function(t,e,n){const r=Br(t,e);if("connector.curve-waypoint"===n.type&&"curved"===e.props.routing){const o=Po(n.id,"waypoint"),i=r.routePoints.slice(1,-1).map(t=>t.clone());return null!==o&&i[o]?_a(t,e.id,(n,r)=>{const s=i.map(t=>t.clone());s[o]=n.clone(),Ua(t,e.id,"curveWaypoints",s,r)},n=>{Ua(t,e.id,"curveWaypoints",i.filter((t,e)=>e!==o),n)}):null}if("connector.curve-insert"===n.type&&"curved"===e.props.routing){const o=Po(n.id,"segment"),i=r.routePoints.slice(1,-1).map(t=>t.clone());return null===o||o>i.length?null:_a(t,e.id,(n,r)=>{const s=i.map(t=>t.clone());s.splice(o,0,n.clone()),Ua(t,e.id,"curveWaypoints",s,r)})}if("connector.orthogonal-segment"===n.type&&"orthogonal"===e.props.routing){const o=Mo(n.id);if(!o||!r.routePoints[o.index+1])return null;const i=r.routePoints.map(t=>t.clone()),s=t.shapes.computeLocalToPageTransform(e),a=e.props.orthogonalBends.map(t=>s.applyToPoint(new O(t.x,t.y)));return _a(t,e.id,(n,r)=>{const s=function(t,e,n,r,o){const i=t[e];if(!i)return r;const s="horizontal"===n?r.y:r.x,a=["horizontal"===n?i.y:i.x],l=t[e-1];e>=2&&l&&a.push("horizontal"===n?l.y:l.x);const c=t[e+2];e<=t.length-4&&c&&a.push("horizontal"===n?c.y:c.x);const d=a.reduce((t,e)=>Math.abs(e-s)<Math.abs(t-s)?e:t);return Math.abs(d-s)>o?r:"horizontal"===n?new O(r.x,d):new O(d,r.y)}(i,o.index,o.axis,n,8/Math.max(t.state.cameraZoom.get(),1e-4)),l=i[o.index],c=("horizontal"===o.axis?s.y===l.y:s.x===l.x)?a:fo(function(t,e,n,r){const o=t[e],i=t[e+1];if(!o||!i)return t.map(t=>t.clone());const s="horizontal"===n?o.y:o.x;if(("horizontal"===n?r.y:r.x)===s)return t.map(t=>t.clone());const a=t=>"horizontal"===n?new O(t.x,r.y):new O(r.x,t.y),l=t.length-2;if(0===e){const e=Va(o,i);return[o.clone(),e,a(e),a(i),...t.slice(2).map(t=>t.clone())]}if(e===l){const e=Va(i,o);return[...t.slice(0,-2).map(t=>t.clone()),a(o),a(e),e,i.clone()]}const c=t.map(t=>t.clone());return c[e]=a(o),c[e+1]=a(i),c}(i,o.index,o.axis,s)).slice(1,-1);Ua(t,e.id,"orthogonalBends",c,r)})}return null}(t,n,e):null:null}}}function Fa(t,e){if(e.accelKey)return{kind:"free",pagePoint:e.pagePoint.clone()};const n=Qs(t,e.pagePoint,{mode:"target",pageId:t.pages.getCurrentId()})??Qs(t,e.pagePoint,{pageId:t.pages.getCurrentId()});return!n||t.layers.isOrAncestorLocked(n.shape.id)?{kind:"free",pagePoint:e.pagePoint.clone()}:Co(n.shape.id,n.port)}function ja(t,e,n){const r=zo(t,e,n);return{draft:t.draft,pagePoint:t.pagePoint.clone(),pageOutwardNormal:r.outwardNormal.clone(),shapeId:t.shape?.id??null,portId:t.port?.id??null,obstacleBounds:t.obstacleBounds}}function Wa(t,e,n,r,o){if("orthogonal"!==r||o||!e.port)return n.clone();const i=e.port.pageOutwardNormal,s=n.sub(e.pagePoint);if(s.x*i.x+s.y*i.y<=0)return n.clone();const a=Math.abs(i.x)>=Math.abs(i.y),l=a?s.y:s.x,c=8/Math.max(t.state.cameraZoom.get(),1e-4);return Math.abs(l)>c?n.clone():a?new O(n.x,e.pagePoint.y):new O(e.pagePoint.x,n.y)}function Ha(t,e,n){const r=_o(t,e,n);if(!r?.startsWith("shape:"))return J.Identity();const o=t.shapes.get(r);return o?t.shapes.computeLocalToPageTransform(o):J.Identity()}function _a(t,e,n,r){const o={shapeId:e,operationKind:"connector.adjust",onDragStart(){To(t).setSelectionHandlesHidden(!0)},update:({pagePoint:t,source:e})=>(n(t,e),{status:"continue",finalPagePoint:t}),onCancel(){To(t).setSelectionHandlesHidden(!1)},onComplete(){To(t).setSelectionHandlesHidden(!1)}};return r&&(o.onDoubleClick=({source:t})=>r(t)),o}function Ua(t,e,n,r,o){const i=t.shapes.get(e);if(!zn(i))return;const s=t.shapes.computeLocalToPageTransform(i).tryInvert();if(!s)return;const a={...i.props,[n]:r.map(t=>{const e=s.applyToPoint(t);return{x:e.x,y:e.y}})},l=No(t,{...i,props:a});if(!l)return;const c=jn(t,i.id),d=new Set([c.start?.id,c.end?.id].filter(t=>!!t));t.commands.updateShapes([{id:i.id,parentId:l.parentId,x:l.x,y:l.y,rotation:l.rotation,scaleX:l.scaleX,scaleY:l.scaleY,props:l.props}],{source:o,suppressBindingIds:d})}function Va(t,e){const n=e.sub(t),r=n.len();return 0===r?t.clone():t.add(n.mul(Math.min(24,r/2)/r))}function Ka(t,e,n={curveWaypoints:[],orthogonalBends:[]}){return{routing:t.routing,cornerRadius:t.cornerRadius,headStart:t.headStart,headEnd:t.headEnd,stroke:t.stroke,strokeWidth:t.strokeWidth,strokeStyle:t.strokeStyle,...n,localToPageTransform:e}}var qa=new Set(["straight","orthogonal","curved"]),Xa=new Set(["solid","dashed"]),Ya=new Set(["none","arrow"]);function Ja(t,e,n=-1/0){return"number"==typeof t&&Number.isFinite(t)?Math.max(n,t):e}function Ga(t,e){const n=t&&"object"==typeof t?t:{};return{x:Ja(n.x,e.x),y:Ja(n.y,e.y)}}function Za(t){return Array.isArray(t)?t.flatMap(t=>{if(!t||"object"!=typeof t)return[];const e=t;return"number"==typeof e.x&&Number.isFinite(e.x)&&"number"==typeof e.y&&Number.isFinite(e.y)?[{x:e.x,y:e.y}]:[]}):[]}function Qa(t,e,n){const r=e.sub(t).normalize();return{point:t,outwardNormal:r.len()>0?r:new O("start"===n?1:-1,0)}}var tl=class extends St{type="connector";getDefaultProps(){return{w:1,h:1,start:{x:0,y:.5},end:{x:1,y:.5},routing:"orthogonal",stroke:W("stroke-slate"),strokeWidth:2,strokeStyle:"solid",headStart:"none",headEnd:"arrow",cornerRadius:8,curveWaypoints:[],orthogonalBends:[]}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Ja(e.w,n.w,1),h:Ja(e.h,n.h,1),start:Ga(e.start,n.start),end:Ga(e.end,n.end),routing:qa.has(e.routing)?e.routing:n.routing,stroke:_(e.stroke)?V(e.stroke,n.stroke):n.stroke,strokeWidth:Ja(e.strokeWidth,n.strokeWidth,.5),strokeStyle:Xa.has(e.strokeStyle)?e.strokeStyle:n.strokeStyle,headStart:Ya.has(e.headStart)?e.headStart:n.headStart,headEnd:Ya.has(e.headEnd)?e.headEnd:n.headEnd,cornerRadius:Ja(e.cornerRadius,n.cornerRadius,0),curveWaypoints:Za(e.curveWaypoints),orthogonalBends:Za(e.orthogonalBends)}}getLocalBounds(t){const e="arrow"===t.props.headStart||"arrow"===t.props.headEnd?Pr(t.props.strokeWidth)+t.props.strokeWidth/2:t.props.strokeWidth/2;return new N(0,0,t.props.w,t.props.h).expand(e)}getPointHitTestBounds(t,e){const n=Math.max(8,t.props.strokeWidth+4);if(!e?.editor)return N.FromPoints([new O(t.x+t.props.start.x,t.y+t.props.start.y),new O(t.x+t.props.end.x,t.y+t.props.end.y)]).expand(n);const r=Br(e.editor,t),o=[...r.points,...r.markerSegments.flatMap(t=>[t.start,t.end])],i=e.editor.shapes.computePositionedToPageTransform(t).tryInvert();if(!i||0===o.length)return super.getPointHitTestBounds(t,e).expand(n);const s=el(e.editor,t)*i.getMaximumLinearScale();return N.FromPoints(o.map(t=>i.applyToPoint(t))).expand(s)}canSnap(){return!1}canParticipateInSelectionResize(t,e){return!1===e.isOnlyAffectedShape}resizeSelectionBounds(t,e){const n=this.getLocalTransform(t),r=n.applyToPoint(this.getSelectionResizeLocalBounds(t).center),o=J.Translate(e.pageCenter.x,e.pageCenter.y).compose(J.Rotate(e.selectionRotation)).compose(J.Scale(e.scaleX,e.scaleY)).compose(J.Rotate(-e.selectionRotation)).compose(J.Translate(-r.x,-r.y)).compose(n),i=o.applyToPoint(new O(t.props.start.x,t.props.start.y)),s=o.applyToPoint(new O(t.props.end.x,t.props.end.y)),a=t.props.curveWaypoints.map(t=>o.applyToPoint(new O(t.x,t.y))),l=t.props.orthogonalBends.map(t=>o.applyToPoint(new O(t.x,t.y))),c=Wr({start:Qa(i,s,"start"),end:Qa(s,i,"end"),routing:t.props.routing,cornerRadius:t.props.cornerRadius,headStart:t.props.headStart,headEnd:t.props.headEnd,strokeWidth:t.props.strokeWidth,curveWaypoints:a,orthogonalBends:l}),d=N.FromPoints([i,...c.points,s]),u=t=>({x:t.x-d.x,y:t.y-d.y});return{id:t.id,x:d.x,y:d.y,rotation:0,scaleX:1,scaleY:1,props:{w:Math.max(1,d.w),h:Math.max(1,d.h),start:u(i),end:u(s),curveWaypoints:a.map(u),orthogonalBends:l.map(u)}}}canParticipateInSelectionFlip(){return!0}canParticipateInSelectionRotation(){return!1}canParticipateInSelectionTranslation(){return!1}contributesToSelectionFrame(t,e){return!0}canUseSelectionResizeHandles(t,e){return e.editor.selection.getIds().length>1}canUseSelectionRotateHandle(t,e){return e.editor.selection.getIds().length>1}canStartTranslateFromSelectionBounds(t,e){return e.editor.selection.getIds().length>1}getSelectionHandleAnchors(t,e){if(!e.isOnlySelected)return{terminalHandleAnchors:[],middleHandleAnchors:[]};if(To(e.editor).selectionHandlesHiddenSignal.get())return{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};const n=Br(e.editor,t),r=[];if("curved"===t.props.routing){for(let e=1;e<n.routePoints.length-1;e+=1)r.push({kind:"custom",type:xo,id:vo(e-1),point:n.routePoints[e],cursor:"move"});let t=0;n.segments.forEach(e=>{"cubic"===e.type&&(r.push({kind:"custom",type:wo,id:ko(t),point:Tr(e,.5),cursor:"move"}),t+=1)})}else if("orthogonal"===t.props.routing){const t=Math.max(e.editor.state.cameraZoom.get(),1e-4);for(let e=0;e<n.routePoints.length-1;e+=1){const o=n.routePoints[e],i=n.routePoints[e+1];if(o.dist(i)*t<36)continue;const s=o.y===i.y?"horizontal":"vertical";r.push({kind:"custom",type:bo,id:So(e,s),point:O.Med(o,i),cursor:"horizontal"===s?"ns-resize":"ew-resize"})}}return{terminalHandleAnchors:[{kind:"binding_terminal",terminal:"start",point:n.startPagePoint},{kind:"binding_terminal",terminal:"end",point:n.endPagePoint}],middleHandleAnchors:[],customHandleAnchors:r}}getSelectionOverlayInfo(t,e){const n=Br(e.editor,t),r=jr(e.editor,t),o=po(r.markerSegments),i=e.editor.shapes.computeLocalToPageTransform(t);return{usesSelectionPathOverlay:!0,startPagePoint:n.startPagePoint,endPagePoint:n.endPagePoint,middlePagePoint:null,path:n.path,pathStyle:{localPath:r.path,localDecorationPaths:o?[o]:[],localBounds:r.pageBounds,localToPage:i,strokeWidth:t.props.strokeWidth,strokeDasharray:"dashed"===t.props.strokeStyle?"8 6":void 0},pageClipPath:ht({outputBounds:n.pageBounds,cutoutLocalPolygons:e.editor.shapes.getContentCutoutLocalPolygonsSignal(t.id).get(),localToOutput:i}),bindingSegments:[]}}getLabelPathGeometry(t,e){return Cr(Br(e.editor,t))}canCopyToClipboard(t,e){const n=jn(e.editor,t.id);return(!n.start||e.copiedShapeIds.has(n.start.toId))&&(!n.end||e.copiedShapeIds.has(n.end.toId))}isWrappedByBrush(t,e){return Br(e.editor,t).points.every(t=>e.brushBounds.containsPoint(t))}hitTest(t,e,n){const r=n?.editor?Br(n.editor,t):null,o=r?r.points:[new O(t.x+t.props.start.x,t.y+t.props.start.y),new O(t.x+t.props.end.x,t.y+t.props.end.y)],i=n?.pagePoint??e,s=n?.editor?el(n.editor,t):Math.max(8,t.props.strokeWidth+4);return nl(o,i)<=s||(r?.markerSegments.some(t=>nl([t.start,t.end],i)<=s)??!1)}hitTestLineSegment(t,e){const n=e.editor?Br(e.editor,t):null,r=n?n.points:[new O(t.x+t.props.start.x,t.y+t.props.start.y),new O(t.x+t.props.end.x,t.y+t.props.end.y)],o=e.editor?e.pageStart:e.positionedStart,i=e.editor?e.pageEnd:e.positionedEnd,s=e.editor?Math.max(el(e.editor,t),e.pageMargin):Math.max(t.props.strokeWidth+4,e.positionedMargin);for(let a=1;a<r.length;a+=1)if(ol(r[a-1],r[a],o,i)<=s)return!0;for(const a of n?.markerSegments??[])if(ol(a.start,a.end,o,i)<=s)return!0;return!1}};function el(t,e){const n=Math.max(t.state.cameraZoom.get(),1e-4),r=t.shapes.computePositionedToPageTransform(e).getMaximumLinearScale(),o=e.props.strokeWidth*r/2;return Math.max(12/n,o)}function nl(t,e){let n=1/0;for(let r=1;r<t.length;r+=1)n=Math.min(n,rl(e,t[r-1],t[r]));return n}function rl(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist(e);const i=t.sub(e),s=Math.max(0,Math.min(1,(i.x*r.x+i.y*r.y)/o));return t.dist(e.add(r.mul(s)))}function ol(t,e,n,r){return Math.min(rl(t,n,r),rl(e,n,r),rl(n,t,e),rl(r,t,e))}var il=class extends Pt{constructor(t){super(t,"connector")}},sl=class{type="connector";toSvg(t,e){const n=e.resolveColor(t.props.stroke),r=jr(e.editor,t),o=ht({outputBounds:r.pageBounds,cutoutLocalPolygons:e.editor.shapes.getContentCutoutLocalPolygonsSignal(t.id).get()}),i=o?e.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"path",attrs:{d:o,"clip-rule":"evenodd","fill-rule":"evenodd"}}]}):void 0,s="arrow"===t.props.headStart&&r.startArrowScale>0?`url(#${e.addDef(ll("start",n,t.props.strokeWidth,r.startArrowScale))})`:void 0,a="arrow"===t.props.headEnd&&r.endArrowScale>0?`url(#${e.addDef(ll("end",n,t.props.strokeWidth,r.endArrowScale))})`:void 0;return{tag:"path",attrs:{d:r.path,fill:"none",stroke:n,"stroke-width":t.props.strokeWidth,"stroke-dasharray":"dashed"===t.props.strokeStyle?"8 6":void 0,"stroke-linecap":"round","stroke-linejoin":"round","marker-start":s,"marker-end":a,"clip-path":i?`url(#${i})`:void 0}}}};function al(t,e){return{id:"land.connector",shapeUtils:[new tl],shapeSvgExporters:[new sl],bindingUtils:[new Na],interactionHandlers:[za(t)],setup(n){n.runtime.provide(Io,function(t,e,n){const r=t.signals.atom("connector.preview",null),o=t.signals.atom("connector.selectionHandlesHidden",!1),i=n?new Set(n):null;let s=null;return{previewSignal:r,quickCreateNodeFactory:e,selectionHandlesHiddenSignal:o,get pointerSession(){return s},isPortVisible:t=>i?.has(t)??!0,setPointerSession(t){s=t},setPreview(t){r.set(t)},setSelectionHandlesHidden(t){o.get()!==t&&o.set(t)},dispose(){s?.cancel("dispose"),s=null,r.set(null),o.set(!1)}}}(n,t,e),t=>t.dispose()),n.tools.register("connector",t=>new il(t))}}}function ll(t,e,n,r){return{tag:"marker",attrs:{markerWidth:12,markerHeight:12,viewBox:"0 0 24 24",refX:Mr(t,n,r),refY:12,orient:"auto",markerUnits:"strokeWidth"},children:[{tag:"path",attrs:{d:Ir(t,n,r),fill:"none",stroke:e,"stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"}}]}}var cl=Ae("plugin-connector.api");function dl({editor:t}){return function({editor:t}){return{getSelectionStyle(){const e=t.state.selectedShapes.get().filter(zn);return 0===e.length?null:{routing:ul(e.map(t=>t.props.routing)),stroke:pl(e.map(t=>t.props.stroke)),strokeWidth:ul(e.map(t=>t.props.strokeWidth)),strokeStyle:ul(e.map(t=>t.props.strokeStyle)),headStart:ul(e.map(t=>t.props.headStart)),headEnd:ul(e.map(t=>t.props.headEnd))}},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(zn).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)},getToolDefaults:()=>t.shapes.getDefaultProps("connector"),setToolDefaults:e=>(t.shapes.updateDefaultProps("connector",e),t.shapes.getDefaultProps("connector"))}}({editor:t})}function ul(t){const[e,...n]=t;return void 0!==e&&n.every(t=>t===e)?e:null}function pl(t){const[e,...n]=t;return void 0!==e&&n.every(t=>Y(e,t))?e:null}function hl(t={}){const e=t.quickCreateNodeFactory??sa(),n=t.visiblePortIds?[...t.visiblePortIds]:void 0;return{id:"connector",requires:[Js],editor:al(e,n),render:ga(),api:cl,setup:({editor:t})=>({api:dl({editor:t})})}}var fl=hl();function ml(t){return Number.isInteger(t)?`${t}`:`${Number(t.toFixed(2))}`}function gl(t,e,n){return Math.max(e,Math.min(n,t))}function yl(t){return t?640:480}function xl(t,e){return t.x===e.x&&t.y===e.y&&t.pressure===e.pressure&&t.segment===e.segment}function wl(t){return new O(t.x,t.y)}function bl(t){return{x:t.x,y:t.y,...void 0===t.pressure?null:{pressure:t.pressure},...void 0===t.segment?null:{segment:t.segment}}}function vl(t){const e=[];for(const n of t)e.push(...n.points.map(bl));return e}function kl(t){return[{points:t.map(bl)}]}function Sl(t){if(void 0!==t&&Number.isFinite(t))return gl(t,.05,1)}function Pl(t,e,n,r,o={}){const i=bl(e),s=t[t.length-1];if(!s)return t.push(i),{anchorPoint:bl(i),hasProvisionalPoint:!1};if(xl(s,i))return o.force&&r.hasProvisionalPoint?{anchorPoint:bl(i),hasProvisionalPoint:!1}:r;if(xl(r.anchorPoint,i))return r.hasProvisionalPoint&&t.pop(),{anchorPoint:bl(r.anchorPoint),hasProvisionalPoint:!1};const a=function(t,e){if(t<=e.softMaxPointCount)return e.minPointDistance;const n=gl((t-e.softMaxPointCount)/Math.max(e.hardMaxPointCount-e.softMaxPointCount,1),0,1);return e.minPointDistance*(1+n*e.maxDistanceMultiplier)}(t.length,n),l=i.x-r.anchorPoint.x,c=i.y-r.anchorPoint.y,d=Math.abs((i.pressure??0)-(r.anchorPoint.pressure??0)),u=!0===o.force||l*l+c*c>=a*a||d>=n.pressureDeltaThreshold;return r.hasProvisionalPoint?t[t.length-1]=i:t.push(i),u?{anchorPoint:bl(i),hasProvisionalPoint:!1}:{anchorPoint:bl(r.anchorPoint),hasProvisionalPoint:!0}}function Ml(t,e){const n=Math.max(2,Math.floor(e));if(t.length<=n)return t.map(bl);const r=function(t,e){let n=Il(t,!0);n.length<e&&(n=Il(t,!1));return new Set(n.slice(0,e).map(t=>t.index))}(t,t.length-n);return t.filter((t,e)=>!r.has(e)).map(bl)}function Il(t,e){const n=[];for(let r=1;r<t.length-1;r+=1){if(e&&Tl(t,r))continue;const o=t[r],i=t[r-1],s=t[r+1];o&&i&&s&&n.push({index:r,score:Cl(o,i,s)})}return n.sort((t,e)=>t.score-e.score||t.index-e.index),n}function Tl(t,e){return"straight"===t[e]?.segment||"straight"===t[e+1]?.segment}function Cl(t,e,n){const r=function(t,e,n){const r=n.x-e.x,o=n.y-e.y,i=r*r+o*o;if(0===i){const n=t.x-e.x,r=t.y-e.y;return n*n+r*r}const s=gl(((t.x-e.x)*r+(t.y-e.y)*o)/i,0,1),a=e.x+r*s,l=e.y+o*s,c=t.x-a,d=t.y-l;return c*c+d*d}(t,e,n),o=function(t,e,n){if(void 0===t.pressure)return 0;const r=e.pressure??t.pressure,o=n.pressure??t.pressure;return 8*Math.abs(t.pressure-(r+o)/2)}(t,e,n);return r+o*o}function El(t){if(0===t.length)return null;if(1===t.length){const e=t[0];return`M ${ml(e.x)} ${ml(e.y)}`}if(2===t.length){const e=t[0],n=t[1];return[`M ${ml(e.x)} ${ml(e.y)}`,`L ${ml(n.x)} ${ml(n.y)}`].join(" ")}const e=[],n=t[0];e.push(`M ${ml(n.x)} ${ml(n.y)}`);for(let r=1;r<t.length;r+=1){const n=t[r];if(!n)continue;if("straight"===n.segment){e.push(`L ${ml(n.x)} ${ml(n.y)}`);continue}const o=t[r+1];if(!o||"straight"===o.segment){if(Al(t,r)){const o=t[r-1];e.push(`Q ${ml(o.x)} ${ml(o.y)} ${ml(n.x)} ${ml(n.y)}`)}else e.push(`L ${ml(n.x)} ${ml(n.y)}`);continue}const i=O.Med(wl(n),wl(o));e.push(`Q ${ml(n.x)} ${ml(n.y)} ${ml(i.x)} ${ml(i.y)}`)}return e.join(" ")}function Al(t,e){return e>=2&&"straight"!==t[e-1]?.segment&&"straight"!==t[e-2]?.segment}function Ol(t){if(t.length<3)return function(t){if(0===t.length)return null;const[e,...n]=t;return e?[`M ${ml(e.x)} ${ml(e.y)}`,...n.map(t=>`L ${ml(t.x)} ${ml(t.y)}`),"Z"].join(" "):null}(t);const e=t[0],n=t[t.length-1];if(!e||!n)return null;const r=O.Med(n,e),o=[`M ${ml(r.x)} ${ml(r.y)}`];for(let i=0;i<t.length;i+=1){const e=t[i],n=t[(i+1)%t.length];if(!e||!n)continue;const r=O.Med(e,n);o.push(`Q ${ml(e.x)} ${ml(e.y)} ${ml(r.x)} ${ml(r.y)}`)}return o.push("Z"),o.join(" ")}function Nl(t){return t.map(bl)}function Rl(t){return t.map(Ll)}function Ll(t){return function(t){return{points:t.points.map(bl)}}(t)}function $l(t,e,n){return t.map(t=>({x:t.x+e,y:t.y+n,...void 0===t.pressure?null:{pressure:t.pressure},...void 0===t.segment?null:{segment:t.segment}}))}function Dl(t,e,n){return t.map(t=>({points:$l(t.points,e,n)}))}function Bl(t,e){return t.map((t,n)=>({points:t.points.map((t,r)=>{const o=e(wl(t),n,r);return{x:o.x,y:o.y,...void 0===t.pressure?null:{pressure:t.pressure},...void 0===t.segment?null:{segment:t.segment}}})}))}function zl(t,e,n){const r=0===e.w?1:e.w,o=0===e.h?1:e.h,i=0===n.w?1:n.w,s=0===n.h?1:n.h;return t.map(t=>({x:n.minX+(t.x-e.minX)/r*i,y:n.minY+(t.y-e.minY)/o*s,...void 0===t.pressure?null:{pressure:t.pressure},...void 0===t.segment?null:{segment:t.segment}}))}function Fl(t,e,n){return t.map(t=>({points:zl(t.points,e,n)}))}function jl(t){return{rotation:t.selectionRotation,rotationCenter:t.selectionRotationCenter}}function Wl(t,e){const n=jl(e);return Bl(t,t=>function(t,e){return 0===e.rotation?t.clone():O.RotWith(t,e.rotationCenter,-e.rotation)}(t,n))}function Hl(t,e){const n=jl(e);return Bl(t,t=>lt(t,n))}function _l(t,e){return Bl(t,t=>ct({axis:e.axis,bounds:e.selectionMirrorBounds,point:t}))}var Ul=.08;function Vl(t,e,n){return Math.max(e,Math.min(n,t))}function Kl(t,e,n){return t+(e-t)*n}function ql(t,e,n){if(t.length<=1)return new O(1,0);if(n&&t.length>=3){const n=t[e],r=t[(e-1+t.length)%t.length],o=t[(e+1)%t.length],i=n.sub(r).normalize(),s=o.sub(n).normalize(),a=i.add(s);return a.len2()>1e-6?a.normalize():s.len2()>0?s:i.len2()>0?i:new O(1,0)}const r=t[e],o=t[e-1]??r,i=t[e+1]??r,s=r.sub(o).normalize(),a=i.sub(r).normalize();if(0===e)return a.len2()>0?a:new O(1,0);if(e===t.length-1)return s.len2()>0?s:new O(1,0);const l=s.add(a);return l.len2()>1e-6?l.normalize():a.len2()>0?a:s.len2()>0?s:new O(1,0)}function Xl(t,e){return t.x*e.x+t.y*e.y}function Yl(t,e,n,r,o,i,s,a){if(n.simulatePressure)return function({distanceFromPrevious:t,previousPressure:e,runningLength:n,totalLength:r,strokeWidth:o,isClosed:i}){const s=Vl(t/Math.max(1.5*o,1),0,1),a=Vl(1-s,Ul,1),l=null===e?Kl(.5,a,.275):Kl(e,a,.275*Math.max(s,.36));if(i)return Vl(l,Ul,1);const c=Vl(n/Math.max(1.8*o,1),0,1),d=Vl((r-n)/Math.max(2.6*o,1),0,1);return Vl(l*Kl(.72,1,Math.min(c,d)),Ul,1)}({distanceFromPrevious:o,previousPressure:e,runningLength:i,totalLength:s,strokeWidth:r,isClosed:a});const l="number"==typeof t.pressure&&Number.isFinite(t.pressure)?Vl(t.pressure,.05,1):e??.55;return null===e?l:Kl(e,l,.68)}function Jl(t,e,n,r,o={}){if(0===t.length)return[];const i=function(t,e){const n=Math.max(t+1,1.6);return{baseRadius:n,minRadius:Math.max(.6,.32*n),minRadiusScale:e?.5:.48,maxRadiusScale:e?1.22:1.24,startTaper:Math.max(1.8*t,2.5),endTaper:Math.max(2.3*t,3.5),simulatePressure:!e}}(e,n),s=t.map(wl),a=[0];let l=0;for(let u=1;u<s.length;u+=1)l+=s[u].dist(s[u-1]),a.push(l);let c=null;const d=t.map((t,n)=>{const d=a[n]??0,u=0===n?0:s[n].dist(s[n-1]),p=Yl(t,c,i,e,u,d,l,r);c=p;const h=o.taperStart??!0,f=o.taperEnd??!0,m=r||s.length<=1?1:Math.min(h?Vl(d/i.startTaper,0,1):1,f?Vl((l-d)/i.endTaper,0,1):1),g=Kl(i.minRadiusScale,i.maxRadiusScale,p),y=Math.max(i.minRadius,i.baseRadius*g*Kl(.7,1,m));return{point:s[n],direction:ql(s,n,r),pressure:p,radius:y,runningLength:d}});return l<.5*i.baseRadius?d.map(t=>({...t,radius:Math.max(t.radius,.92*i.baseRadius)})):d}function Gl(t,e){const n=t[t.length-1];n&&n.dist2(e)<.04?t[t.length-1]=e:t.push(e)}function Zl(t,e,n){const r=t.dist(e);if(0===r)return[];const o=O.Angle(t,e),i=[];for(let s=1;s<n;s+=1){const e=o-Math.PI*(s/n);i.push(new O(t.x+Math.cos(e)*r,t.y+Math.sin(e)*r))}return i}function Ql(t,e,n={}){if(0===t.length)return[];if(1===t.length)return function(t,e,n){const r=[];for(let o=0;o<n;o+=1){const i=2*Math.PI*o/n;r.push(new O(t.x+Math.cos(i)*e,t.y+Math.sin(i)*e))}return r}(t[0].point,t[0].radius,16);const r=[],o=[];let i=.12;for(const c of t)i=Math.max(i,.38*c.radius);const s=i**2;let a=null;for(let c=0;c<t.length;c+=1){const e=t[c],n=t[c+1]??e,i=e.direction,l=n.direction,d=Xl(i,l);let u=0===c||c===t.length-1?i.per().normalize():O.Lrp(l,i,d).per().normalize();u.len2()<1e-6&&(u=a??new O(0,1)),a=u,tc(r,e.point.add(u.mul(e.radius)),s,{force:c===t.length-1}),tc(o,e.point.sub(u.mul(e.radius)),s,{force:c===t.length-1})}if(e&&t.length>=3){const t=[];for(const e of r)Gl(t,e);for(let e=o.length-1;e>=0;e-=1){Gl(t,o[e])}return t}const l=[];for(const c of r)Gl(l,c);if(n.capEnd??1){const e=t[t.length-1];for(const t of Zl(e.point,r[r.length-1],8))Gl(l,t)}for(let c=o.length-1;c>=0;c-=1){Gl(l,o[c])}if(n.capStart??1){const e=t[0];for(const t of Zl(e.point,o[0],8))Gl(l,t)}return l}function tc(t,e,n,r={}){const o=t[t.length-1];(!o||!0===r.force||o.dist2(e)>n)&&Gl(t,e)}var ec=new WeakMap;function nc(t){return{...t}}function rc(t,e,n){return t.map(t=>new O(t.x+e,t.y+n))}function oc(t,e,n){return t.map(t=>rc(t,e,n))}function ic({segments:t,outlineVertices:e,outlinePolygons:n,strokeWidth:r,sampling:o,isClosed:i}){const s=vl(t),a=s.map(wl),l=a.length>0?N.FromPoints(a):new N(0,0,1,1),c=e.length>0?N.FromPoints([...e]):l.expand(Math.max(r/2,1)),d=i&&s.length>=3?function(t){if(t.length<3)return null;const e=El(t);return e?`${e} Z`:null}(s):null,u=void 0!==n?function(t){const e=t.map(t=>Ol(t)).filter(t=>null!==t);return e.length>0?e.join(" "):null}(n):Ol(e);return{normalizedSegments:Rl(t),normalizedPoints:Nl(s),pointBounds:l,path:u,selectionPath:d??El(s),fillPath:d,localBounds:c,renderBounds:c.clone(),outlineVertices:e.map(t=>t.clone()),outlinePolygons:n?n.map(t=>t.map(t=>t.clone())):[e.map(t=>t.clone())],sampling:nc(o)}}function sc(t,e,n,r){const o=function({strokeWidth:t,isPen:e}){return[t,e?"pen":"pointer"].join(":")}({strokeWidth:n,isPen:r}),i=ec.get(t),s=i?.get(o);if(s)return{normalizedSegment:Ll(s.normalizedSegment),sampling:nc(s.sampling)};const a=function(t,e){if(t.length<=1)return{points:t.map(bl),rawPointCount:t.length,sampledPointCount:t.length,maxPointCount:e.maxPointCount,reduced:!1,capped:!1};const n=[bl(t[0])],r=e.minPointDistance*e.minPointDistance;let o=wl(t[0]),i=Sl(t[0].pressure);for(let l=1;l<t.length;l+=1){const s=t[l];if(!s)continue;const a=wl(s),c=Sl(s.pressure),d=l===t.length-1,u="straight"===s.segment,p=d||u?a:O.Lrp(o,a,e.positionBlend),h=u?c:void 0===c?void 0:void 0===i?c:i+(c-i)*e.pressureBlend;o=p,i=h;const f=void 0===h?{x:p.x,y:p.y,...void 0===s.segment?null:{segment:s.segment}}:{x:p.x,y:p.y,pressure:h,...void 0===s.segment?null:{segment:s.segment}},m=n[n.length-1];if(!m){n.push(f);continue}const g=f.x-m.x,y=f.y-m.y,x=Math.abs((f.pressure??0)-(m.pressure??0));if(g*g+y*y<r){if(u){if(xl(m,f))continue;n.push(f);continue}(x>.08||d)&&(n[n.length-1]=f)}else n.push(f)}const s=n.length>e.maxPointCount,a=Ml(n,e.maxPointCount);return{points:a,rawPointCount:t.length,sampledPointCount:a.length,maxPointCount:e.maxPointCount,reduced:a.length<t.length,capped:s}}(t.points,e),l={normalizedSegment:{points:Nl(a.points)},sampling:{rawPointCount:a.rawPointCount,sampledPointCount:a.sampledPointCount,sampledPointLimit:a.maxPointCount,reduced:a.reduced,capped:a.capped}},c=i??new Map;return c.set(o,{normalizedSegment:Ll(l.normalizedSegment),sampling:nc(l.sampling)}),i||ec.set(t,c),l}function ac(t,e,n=!1,r=!1){const o=function(t,e){return{minPointDistance:e?Math.max(.35,.18*t):Math.max(.55,.28*t),positionBlend:e?.68:.66,pressureBlend:e?.68:.45,maxPointCount:yl(e)}}(e,n),i=[],s=[],a=t.filter(t=>t.points.length>0);for(let p=0;p<a.length;p+=1){const t=sc(a[p],o,e,n);i.push(Ll(t.normalizedSegment)),s.push(nc(t.sampling))}const l=Ql(Jl(vl(i),e,n,r),r),c=(d=s,u=o.maxPointCount,{rawPointCount:d.reduce((t,e)=>t+e.rawPointCount,0),sampledPointCount:d.reduce((t,e)=>t+e.sampledPointCount,0),sampledPointLimit:u,reduced:d.some(t=>t.reduced),capped:d.some(t=>t.capped)});var d,u;return ic({segments:i,outlineVertices:l,outlinePolygons:l.length>0?[l]:[],strokeWidth:e,sampling:c,isClosed:r})}var lc=new WeakMap,cc=new WeakMap;function dc(t){return t.segments}function uc(t,e,n){return function(t,e){const n=Math.max(0,t.w-e.left-e.right),r=Math.max(0,t.h-e.top-e.bottom);return new N(t.x+e.left,t.y+e.top,n,r)}(n,{left:t.minX-e.minX,right:e.maxX-t.maxX,top:t.minY-e.minY,bottom:e.maxY-t.maxY})}function pc(t){const e=t,n=lc.get(e);if(n)return n;const r=ac(dc(t.props),t.props.strokeWidth,t.props.isPen??!1,t.props.isClosed);return lc.set(e,r),r}function hc(t,e,n=!1,r=!1){const o=ac(t,e,n,r),i=o.pointBounds,s=ac(Bl(o.normalizedSegments,t=>new O(t.x-i.x,t.y-i.y)),e,n,r);return{x:i.x,y:i.y,segments:s.normalizedSegments,pointBounds:s.pointBounds,localBounds:s.localBounds,renderBounds:s.renderBounds,path:s.path,selectionPath:s.selectionPath,fillPath:s.fillPath,outlineVertices:s.outlineVertices,outlinePolygons:s.outlinePolygons,sampling:s.sampling}}function fc(t,e,n=!1,r=!1){return function(t,e,n=!1,r=!1){return hc(kl(t),e,n,r)}(t,e,n,r)}function mc(t,e,n=!1,r=!1){return hc(t,e,n,r)}function gc(t){const e=t,n=cc.get(e);if(n)return n;const r=function(t,e,n,r,o){return ic({segments:Dl(t.normalizedSegments,n,r),outlineVertices:rc(t.outlineVertices,n,r),outlinePolygons:oc(t.outlinePolygons,n,r),strokeWidth:e,sampling:t.sampling,isClosed:o})}(pc(t),t.props.strokeWidth,t.x,t.y,t.props.isClosed);return cc.set(e,r),r}function yc(t){return vl(xc(t))}function xc(t){const e=function(t,e){return new O(t.x+e.localBounds.center.x,t.y+e.localBounds.center.y)}(t,pc(t));return Bl(function(t){return Dl(dc(t.props),t.x,t.y)}(t),n=>function(t,e,n){if(0===t.rotation&&1===t.scaleX&&1===t.scaleY)return e;const r=e.sub(n),o=new O(r.x*t.scaleX,r.y*t.scaleY);return n.add(o.rot(t.rotation))}(t,n,e))}function wc(t,e){let n=function({segments:t,strokeWidth:e,isPen:n,isClosed:r,targetSelectionStrokeBounds:o}){let i=Rl(t);for(let s=0;s<2;s+=1){const t=ac(i,e,n,r),s=uc(t.pointBounds,t.localBounds,o);i=Fl(i,t.pointBounds,s)}return i}({segments:Wl(xc(t),e),strokeWidth:t.props.strokeWidth,isPen:t.props.isPen??!1,isClosed:t.props.isClosed,targetSelectionStrokeBounds:e.targetSelectionStrokeBounds});return e.scaleX<0&&(n=_l(n,{axis:"horizontal",selectionMirrorBounds:e.targetSelectionStrokeBounds,selectionRotation:e.selectionRotation,selectionRotationCenter:e.selectionRotationCenter})),e.scaleY<0&&(n=_l(n,{axis:"vertical",selectionMirrorBounds:e.targetSelectionStrokeBounds,selectionRotation:e.selectionRotation,selectionRotationCenter:e.selectionRotationCenter})),mc(Hl(n,e),t.props.strokeWidth,t.props.isPen??!1,t.props.isClosed)}function bc(t,e){return mc(Hl(_l(Wl(xc(t),e),e),e),t.props.strokeWidth,t.props.isPen??!1,t.props.isClosed)}function vc(t){return Rl(t)}function kc(t){const e=pc(t);return{...e.sampling,hasPath:null!==e.path,hasSelectionPath:null!==e.selectionPath,outlineVertexCount:e.outlineVertices.length}}var Sc=class extends Pt{constructor(t){super(t,"draw"),this.initial="idle",this.addChild(new Pc(t,this)),this.addChild(new Mc(t,this))}getDefaultProps(){return this.editor.shapes.getDefaultProps("draw")}},Pc=class extends Pt{constructor(t,e){super(t,"idle",e)}onEnter(){this.editor.interaction.clearSelection()}onPointerDown(t){const e=this.parent.getDefaultProps(),n=function(t,e){const n=t.pages.getCurrentId();let r=null,o=1/0,i=-1;const s=t.state.currentPageShapeIds.get();for(let a=0;a<s.length;a+=1){const n=t.shapes.get(s[a]);if(!n||t.shapes.isHidden(n.id))continue;const l=t.shapes.getUtil(n);if(!l.canAutomaticallyReceiveChildren(n))continue;if(!t.layers.canReceiveChildren(n.id))continue;if(!t.shapes.isPagePointInClip(n.id,e))continue;const c=l.getChildClipLocalBounds(n)??l.getLocalBounds(n),d=t.shapes.computeLocalToPageTransform(n).invert().applyToPoint(e);if(!c.containsPoint(d))continue;const u=t.shapes.computePageBounds(n),p=u.w*u.h;(!r||p<o||p===o&&a>i)&&(r=n,o=p,i=a)}return r?.id??n}(this.editor,t.pagePoint),r=n.startsWith("shape:")?this.editor.shapes.get(n):null,o=r?this.editor.shapes.computeLocalToPageTransform(r).invert():J.Identity(),i=o.applyToPoint(t.pagePoint),s=Ic(i,i,t.pressure,"pen"===t.pointerType);var a,l;this.transition("drawing",{originPagePoint:t.pagePoint.clone(),originScreenPoint:t.screenPoint.clone(),originParentPoint:i,pageToParent:o,parentId:n,shapeId:null,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,isClosed:e.isClosed,isPen:"pen"===t.pointerType,pointGuard:(a=e.strokeWidth,l="pen"===t.pointerType,l?{minPointDistance:Math.max(.12,.08*a),pressureDeltaThreshold:.035,softMaxPointCount:1600,hardMaxPointCount:3200,maxDistanceMultiplier:2.5}:{minPointDistance:Math.max(.3,.14*a),pressureDeltaThreshold:.08,softMaxPointCount:900,hardMaxPointCount:2200,maxDistanceMultiplier:6}),pointGuardState:{anchorPoint:Tc(s),hasProvisionalPoint:!1},straightSegmentAnchorPoint:null,preserveStraightEndpointOnNextFreePoint:!1,segments:[{points:[s]}]})}},Mc=class extends Pt{tool;info=null;pendingUpdateFrame=null;operation=null;constructor(t,e){super(t,"drawing",e),this.tool=e}onEnter(t){this.info=t,this.editor.interaction.clearSelection(),this.editor.commands.setSelectedShapeIds([],{source:"system"}),this.operation=this.editor.operations.begin({kind:"draw.create",label:"shape.create",source:"user",history:"record"})}onPointerMove(t){this.appendPoint(t,!1)}onPointerUp(t){this.appendPoint(t,!0),this.flushShapeUpdate();const e=this.info?.shapeId??null;if(!e)return this.cancelOperation(),void this.transition("idle");this.info?.parentId.startsWith("shape:")||nt(this.editor,e,{source:"user"}),this.commitOperation(),this.transition("idle")}onCancel(){this.cancelScheduledShapeUpdate(),this.cancelOperation(),this.transition("idle")}onExit(){this.cancelScheduledShapeUpdate(),this.cancelOperation(),this.info=null}commitOperation(){const t=this.operation;this.operation=null,t?.commit()}cancelOperation(){const t=this.operation;this.operation=null,t?.isActive&&t.cancel()}appendPoint(t,e){if(!this.info)return;const n=Ic(this.info.pageToParent.applyToPoint(t.pagePoint),this.info.originParentPoint,t.pressure,this.info.isPen);if(t.shiftKey?this.appendStraightSegmentPoint(n):(this.exitStraightSegmentMode(),this.info.preserveStraightEndpointOnNextFreePoint?this.appendDistinctCurrentPoint(n)&&(this.info.preserveStraightEndpointOnNextFreePoint=!1):this.appendGuardedCurrentPoint(n,{force:e})),this.splitCurrentSegmentAtLimit(),!this.info.shapeId){const n=this.info.originScreenPoint.dist(t.screenPoint);if(!e&&n<2)return;const r=this.createShape();return void(this.info.shapeId=r.id)}this.scheduleShapeUpdate()}scheduleShapeUpdate(){var t;null===this.pendingUpdateFrame&&(this.pendingUpdateFrame=(t=()=>{this.pendingUpdateFrame=null,this.flushShapeUpdate()},"function"==typeof requestAnimationFrame?{type:"animation",id:requestAnimationFrame(t)}:{type:"timeout",id:setTimeout(t,16)}))}cancelScheduledShapeUpdate(){null!==this.pendingUpdateFrame&&(!function(t){if("animation"===t.type)return void cancelAnimationFrame(t.id);clearTimeout(t.id)}(this.pendingUpdateFrame),this.pendingUpdateFrame=null)}flushShapeUpdate(){this.cancelScheduledShapeUpdate(),this.info?.shapeId&&this.editor.commands.updateShapes([{id:this.info.shapeId,props:Ac(this.info.segments)}],{source:"user"})}createShape(){const t=this.tool.getDefaultProps(),e=function(t,e){return e&&t.layers.canReceiveChildren(e)?e:t.pages.getCurrentId()}(this.editor,this.info?.parentId);this.info&&(this.info.parentId=e);const[n]=this.editor.commands.createShapes([{type:"draw",x:this.info?.originParentPoint.x??0,y:this.info?.originParentPoint.y??0,...e.startsWith("shape:")?{parentId:e}:{},props:{...t,stroke:this.info?.stroke??t.stroke,strokeWidth:this.info?.strokeWidth??t.strokeWidth,fill:this.info?.fill??t.fill,isClosed:this.info?.isClosed??t.isClosed,...Ac(this.info?.segments??[]),isPen:this.info?.isPen??!1}}],{source:"user"});if(!n||"draw"!==n.type)throw new Error("Failed to create draw shape");return n}appendStraightSegmentPoint(t){if(!this.info)return;this.info.preserveStraightEndpointOnNextFreePoint=!1;const e=Cc(this.info),n=e[e.length-1];if(!this.info.straightSegmentAnchorPoint){if(!n)return this.replaceCurrentSegmentPoints([{...t,segment:"straight"}]),void this.resetPointGuard(t);this.info.straightSegmentAnchorPoint=Tc(n)}const r={...t,segment:"straight"};if("straight"===n?.segment)return this.replaceCurrentSegmentPoints([...e.slice(0,-1),r]),void this.resetPointGuard(r);this.replaceCurrentSegmentPoints([...e,r]),this.resetPointGuard(r)}exitStraightSegmentMode(){this.info?.straightSegmentAnchorPoint&&(this.info.straightSegmentAnchorPoint=null,this.info.preserveStraightEndpointOnNextFreePoint=!0)}appendDistinctCurrentPoint(t){if(!this.info)return!1;const e=Cc(this.info),n=e[e.length-1];return(!n||(o=t,(r=n).x!==o.x||r.y!==o.y||r.pressure!==o.pressure||r.segment!==o.segment))&&(this.replaceCurrentSegmentPoints([...e,Tc(t)]),this.resetPointGuard(t),!0);var r,o}appendGuardedCurrentPoint(t,e={}){if(!this.info)return;const n=Cc(this.info).map(Tc);this.info.pointGuardState=Pl(n,t,this.info.pointGuard,this.info.pointGuardState,e),this.replaceCurrentSegmentPoints(n)}resetPointGuard(t){this.info&&(this.info.pointGuardState={anchorPoint:Tc(t),hasProvisionalPoint:!1})}replaceCurrentSegmentPoints(t){if(!this.info)return;const e=Ec(this.info.segments);this.info.segments=[...e.slice(0,-1),{points:t.map(Tc)}]}splitCurrentSegmentAtLimit(){if(!this.info)return;const t=yl(this.info.isPen);let e=Ec(this.info.segments),n=e[e.length-1];for(;n.points.length>t;){const r=n.points.slice(0,t).map(Tc),o=r[r.length-1],i=n.points.slice(t).map(Tc);if(!o||0===i.length)break;const s={points:[Tc(o),...i]};e=[...e.slice(0,-1),{points:r},s],n=s}this.info.segments=e}};function Ic(t,e,n,r){return{x:t.x-e.x,y:t.y-e.y,...r&&n>0?{pressure:n}:null}}function Tc(t){return{x:t.x,y:t.y,...void 0===t.pressure?null:{pressure:t.pressure},...void 0===t.segment?null:{segment:t.segment}}}function Cc(t){const e=Ec(t.segments),n=e[e.length-1];return n?n.points.map(Tc):[]}function Ec(t){return t.length>0?[...t]:[{points:[]}]}function Ac(t){return{segments:vc(Ec(t))}}function Oc(t){return C(t)&&"draw"===t.type}var Nc=Ae("plugin-draw.api");function Rc({editor:t}){return function({editor:t}){return{getSelectionStyle(){const e=t.state.selectedShapes.get().filter(Oc);return 0===e.length?null:{fill:Lc(e.map(t=>t.props.fill)),stroke:Lc(e.map(t=>t.props.stroke)),strokeWidth:Lc(e.map(t=>t.props.strokeWidth)),isClosed:Lc(e.map(t=>t.props.isClosed))}},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(Oc).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)},getToolDefaults:()=>t.shapes.getDefaultProps("draw"),setToolDefaults:e=>(t.shapes.updateDefaultProps("draw",e),t.shapes.getDefaultProps("draw"))}}({editor:t})}function Lc(t){const[e,...n]=t;return void 0!==e&&n.every(t=>t===e)?e:void 0}function $c(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist(e);const i=Math.max(0,Math.min(1,((t.x-e.x)*r.x+(t.y-e.y)*r.y)/o)),s=new O(e.x+r.x*i,e.y+r.y*i);return t.dist(s)}function Dc(t,e,n,r){return function(t,e,n,r){const o=e.sub(t),i=r.sub(n),s=o.x*i.y-o.y*i.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(t),l=(a.x*i.y-a.y*i.x)/s,c=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&c>=0&&c<=1}(t,e,n,r)?0:Math.min($c(t,n,r),$c(e,n,r),$c(n,t,e),$c(r,t,e))}function Bc(t,e){let n=!1;for(let r=0,o=e.length-1;r<e.length;o=r,r+=1){const i=e[r],s=e[o];i&&s&&(i.y>t.y!=s.y>t.y&&t.x<(s.x-i.x)*(t.y-i.y)/(s.y-i.y)+i.x&&(n=!n))}return n}function zc(t,e){if(0===e.length)return Number.POSITIVE_INFINITY;let n=Number.POSITIVE_INFINITY;for(let r=0;r<e.length;r+=1){const o=e[r],i=e[(r+1)%e.length];o&&i&&(n=Math.min(n,$c(t,o,i)))}return n}function Fc(t,e,n,r){if(0===n.length)return!1;if(Bc(t,n)||Bc(e,n))return!0;for(let o=0;o<n.length;o+=1){const i=n[o],s=n[(o+1)%n.length];if(i&&s&&Dc(t,e,i,s)<=r)return!0}return!1}function jc(t,e,n,r={}){if(r.isClosed&&void 0!==r.fill&&!X(r.fill)&&t.normalizedPoints.length>=3&&Bc(n,t.normalizedPoints.map(wl)))return!0;if(r.isClosed&&function(t,e,n){if(0===e.length)return Number.POSITIVE_INFINITY;if(1===e.length)return t.dist(wl(e[0]));let r=Number.POSITIVE_INFINITY;for(let o=1;o<e.length;o+=1){const n=e[o-1],i=e[o];n&&i&&(r=Math.min(r,$c(t,wl(n),wl(i))))}return n&&e.length>=3&&(r=Math.min(r,$c(t,wl(e[e.length-1]),wl(e[0])))),r}(n,t.normalizedPoints,!0)<=Math.max(4,.5*e))return!0;if(0===t.outlineVertices.length)return!1;for(const o of t.outlinePolygons){if(Bc(n,o))return!0;if(zc(n,o)<=Math.max(4,.5*e))return!0}return!1}function Wc(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function Hc(t){if(!t||"object"!=typeof t)return null;const e=t,n=Wc(e.x,NaN),r=Wc(e.y,NaN);if(!Number.isFinite(n)||!Number.isFinite(r))return null;const o=Wc(e.pressure,NaN);return e.x!==n||e.y!==r||void 0!==e.pressure&&e.pressure!==o||void 0!==e.segment&&"straight"!==e.segment?{x:n,y:r,...Number.isFinite(o)?{pressure:o}:null,..."straight"===e.segment?{segment:"straight"}:null}:t}function _c(t){if(!t||"object"!=typeof t)return null;const e=t,n=function(t,e){if(!Array.isArray(t))return e;let n=!1;const r=[];for(const o of t){const t=Hc(o);t?(n=n||t!==o,r.push(t)):n=!0}return 0===r.length?e:n?r:t}(e.points,[]);return 0===n.length?null:n===e.points?t:{points:n}}function Uc(t,e){if(!Array.isArray(t))return e;let n=!1;const r=[];for(const o of t){const t=_c(o);t?(n=n||t!==o,r.push(t)):n=!0}return 0===r.length?e:n?r:t}var Vc=class extends St{type="draw";getDefaultProps(){return{segments:kl([{x:0,y:0},{x:24,y:12}]),stroke:W("stroke-slate"),strokeWidth:4,fill:H("transparent"),isClosed:!1,isPen:!1}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{segments:Uc(e.segments,n.segments),stroke:V(e.stroke,n.stroke),strokeWidth:Math.max(4,Wc(e.strokeWidth,n.strokeWidth)),fill:V(e.fill,n.fill),isClosed:"boolean"==typeof e.isClosed?e.isClosed:n.isClosed,isPen:"boolean"==typeof e.isPen?e.isPen:n.isPen}}getPositionedBounds(t){const e=pc(t);return new N(t.x+e.localBounds.x,t.y+e.localBounds.y,e.localBounds.w,e.localBounds.h)}getLocalBounds(t){return pc(t).localBounds}getRenderBounds(t){return pc(t).renderBounds}getExportBounds(t){return this.getRenderBounds(t)}canReceiveTerminalBinding(t){return!0}getSelectionResizeLocalBounds(t){return this.getLocalBounds(t)}resizeSelectionBounds(t,e){const n=wc(t,{targetSelectionStrokeBounds:e.selectionLocalBounds,scaleX:e.scaleX,scaleY:e.scaleY,selectionRotation:e.selectionRotation,selectionRotationCenter:e.selectionRotationCenter});return{id:t.id,x:n.x,y:n.y,rotation:0,scaleX:1,scaleY:1,props:{segments:vc(n.segments)}}}flipSelectionBounds(t,e){const n=bc(t,{axis:e.axis,selectionMirrorBounds:e.selectionBounds,selectionRotation:e.selectionRotation,selectionRotationCenter:e.selectionRotationCenter});return{id:t.id,x:n.x,y:n.y,rotation:0,scaleX:1,scaleY:1,props:{segments:vc(n.segments)}}}getSelectionOverlayInfo(t){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,pathStyle:null}}isWrappedByBrush(t,e){return e.pageOutlineVertices.every(t=>e.brushBounds.containsPoint(t))}canSelectByBrush(t,e){if(this.isWrappedByBrush(t,e))return!0;if(e.isWrapping)return!1;const n=e.pageOutlineVertices;return!!n.some(t=>e.brushBounds.containsPoint(t))||function(t){const e=new O(t.minX,t.minY),n=new O(t.maxX,t.minY),r=new O(t.maxX,t.maxY),o=new O(t.minX,t.maxY);return[[e,n],[n,r],[r,o],[o,e]]}(e.brushBounds).some(([t,e])=>{for(let r=0;r<n.length;r+=1){const o=n[r],i=n[(r+1)%n.length];if(o&&i&&$(t,e,o,i))return!0}return!1})}getPositionedOutlineVertices(t){return gc(t).outlineVertices}hitTest(t,e){return jc(gc(t),t.props.strokeWidth,e,{fill:t.props.fill,isClosed:t.props.isClosed})}hitTestLineSegment(t,e){return function(t,e,n,r,o={}){const i=Math.max(4,.5*e,o.margin??0);return!!(o.isClosed&&void 0!==o.fill&&!X(o.fill)&&t.normalizedPoints.length>=3&&Fc(n,r,t.normalizedPoints.map(wl),i))||0!==t.outlineVertices.length&&t.outlinePolygons.some(t=>Fc(n,r,t,i))}(gc(t),t.props.strokeWidth,e.positionedStart,e.positionedEnd,{fill:t.props.fill,isClosed:t.props.isClosed,margin:e.positionedMargin})}},Kc=class{type="draw";toSvg(t,e){const n=pc(t);if(!n.path&&!n.selectionPath)return null;const r=[];return n.fillPath&&!X(t.props.fill)&&r.push({tag:"path",attrs:{d:n.fillPath,fill:e.resolveColor(t.props.fill),stroke:"none"}}),t.props.isClosed&&n.selectionPath?r.push({tag:"path",attrs:{d:n.selectionPath,fill:"none",stroke:e.resolveColor(t.props.stroke),"stroke-width":t.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round"}}):n.path&&r.push({tag:"path",attrs:{d:n.path,fill:e.resolveColor(t.props.stroke),stroke:"none"}}),{tag:"g",children:r}}};function qc(){return{id:"land.draw",shapeUtils:[new Vc],shapeSvgExporters:[new Kc],setup(t){t.tools.register("draw",t=>new Sc(t))}}}function Xc({shape:t,stroke:e=t.props.stroke,strokeWidth:n=t.props.strokeWidth}){const{fillPath:r,renderBounds:o,path:i,selectionPath:s}=pc({props:{...t.props,strokeWidth:n}});if(!i&&!s)return null;const a=K(e);
24
- return c("svg",{width:"100%",height:"100%",viewBox:`${o.x} ${o.y} ${Math.max(o.w,1)} ${Math.max(o.h,1)}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[r&&!X(t.props.fill)?l("path",{d:r,fill:K(t.props.fill),stroke:"none"}):null,t.props.isClosed&&s?l("path",{d:s,fill:"none",stroke:a,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}):i?l("path",{d:i,fill:a,stroke:"none"}):null]})}function Yc({shape:t,strokeWidth:e}){const{path:r,renderBounds:o,selectionPath:i}=pc(t),s=i??r;return s?l("svg",{"data-ui":"draw-hover-outline",width:"100%",height:"100%",viewBox:`${o.x} ${o.y} ${Math.max(o.w,1)} ${Math.max(o.h,1)}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:l("path",{d:s,fill:"none",stroke:n,strokeWidth:e,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:"non-scaling-stroke"})}):null}function Jc(){return{id:"land.draw.react",shapeRenderers:[{type:"draw",component:Gc,hoverComponent:Zc}]}}function Gc({shape:t}){
25
- return l(Xc,{shape:t})}function Zc({shape:t,strokeWidth:e}){
26
- return l(Yc,{shape:t,strokeWidth:e})}var Qc={id:"draw",editor:qc(),render:Jc(),api:Nc,setup:({editor:t})=>({api:Rc({editor:t})})};function td(t,e,n){return Math.max(e,Math.min(n,t))}function ed(t,e,n){return t+(e-t)*n}function nd(t,e,n){if(void 0!==t||void 0!==e)return ed(t??e??0,e??t??0,n)}function rd(t,e,n){const r=Math.max(2,Math.round(e));if(0===t.length)return[];if(1===t.length)return Array.from({length:r},()=>({point:bl(t[0]),segmentWeight:0}));const o=function(t,e){const n=[];for(let r=1;r<t.length;r+=1){const e=t[r-1],o=t[r];e&&o&&n.push({start:e,end:o,length:wl(e).dist(wl(o)),segmentWeight:"straight"===o.segment?1:0})}if(e&&t.length>=3){const e=t[t.length-1],r=t[0];e&&r&&n.push({start:e,end:r,length:wl(e).dist(wl(r)),segmentWeight:1})}return n}(t,n),i=o.reduce((t,e)=>t+e.length,0);return 0===o.length||i<=1e-6?Array.from({length:r},()=>({point:bl(t[0]),segmentWeight:0})):Array.from({length:r},(t,e)=>{let s=n?e/r*i:e/Math.max(r-1,1)*i,a=o[o.length-1];for(const n of o){if(s<=n.length||n===a){a=n;break}s-=n.length}const l=a.length<=1e-6?0:td(s/a.length,0,1),c=wl(a.start),d=wl(a.end),u=O.Lrp(c,d,l),p=nd(a.start.pressure,a.end.pressure,l);return{point:{x:u.x,y:u.y,...void 0===p?null:{pressure:p}},segmentWeight:a.segmentWeight}})}function od(t,e,n,r={}){if(t.parentId!==e.parentId)throw new Error("Cannot interpolate draw shapes with different parents");const o=td(n,0,1),i=t.props.isClosed&&e.props.isClosed,s=yc(t),a=yc(e),l=(c=s.length,d=a.length,"number"==typeof(u=r.pointCount)&&Number.isFinite(u)?Math.max(2,Math.round(u)):Math.max(2,c,d,12));var c,d,u;const p=rd(s,l,i),h=rd(a,l,i),f=p.map((t,e)=>{const n=h[e]??h[h.length-1]??t,r=O.Lrp(wl(t.point),wl(n.point),o),i=nd(t.point.pressure,n.point.pressure,o),s=ed(t.segmentWeight,n.segmentWeight,o);return{x:r.x,y:r.y,...void 0===i?null:{pressure:i},...e>0&&s>=.5?{segment:"straight"}:null}}),m=o<.5?t.props.isClosed:e.props.isClosed,g=o<.5?t.props.isPen??!1:e.props.isPen??!1,y=Math.max(1,ed(t.props.strokeWidth,e.props.strokeWidth,o)),x=fc(f,y,g,m),w=o<.5?t:e;return{...w,id:t.id,x:x.x,y:x.y,rotation:0,scaleX:1,scaleY:1,opacity:ed(t.opacity,e.opacity,o),props:{...w.props,segments:Rl(x.segments),strokeWidth:y,isClosed:m,isPen:g}}}var id=G("plugin.eraser.runtime");function sd(t,e){if(t.length!==e.length)return!1;const n=new Set(e);return t.every(t=>n.has(t))}function ad(t){return t.runtime.require(id)}function ld(t){return 4/t.state.camera.get().z}function cd(t,e,n,r){const o=[new O(e.minX,e.minY),new O(e.maxX,e.minY),new O(e.maxX,e.maxY),new O(e.minX,e.maxY)].map(t=>n.applyToPoint(t));let i=0,s=Number.POSITIVE_INFINITY;for(let a=0;a<o.length;a+=1){const e=o[a],n=o[(a+1)%o.length].sub(e),r=t.sub(e),l=n.x*r.y-n.y*r.x;if(Math.abs(l)<=1e-8)return!1;const c=Math.sign(l);if(0===i)i=c;else if(c!==i)return!1;const d=n.len2(),u=0===d?0:Math.max(0,Math.min(1,(r.x*n.x+r.y*n.y)/d));s=Math.min(s,t.dist(e.add(n.mul(u))))}return s>r}function dd(t,e){const n=new Set,r=ld(t);for(const o of t.shapes.hitTestPoint(e,{hitTest:"bindingTarget"})){const i=t.shapes.getUtil(o);if(!i.canReceiveChildren(o))continue;const s=i.getChildClipLocalBounds(o);s&&(cd(e,s,t.shapes.computeLocalToPageTransform(o),r)&&n.add(o.id))}return n}function ud(t,e,n){return n.protectedContainerIds.has(e.id)||t.layers.isOrAncestorLocked(e.id)||t.shapes.getUtil(e).canReceiveChildren(e)&&t.layers.hasLockedDescendant(e.id)?null:e.id}function pd(t,e,n,r){const o=r.topMostOnly?n.slice(0,1):n;for(const i of o){const n=ud(t,i,e);n&&e.erasingShapeIds.add(n)}}function hd(t,e,n){pd(t,e,t.shapes.hitTestPoint(n.pagePoint),{topMostOnly:n.accelKey})}function fd(t,e,n){pd(t,e,t.shapes.hitTestLineSegment(e.previousPagePoint,n.pagePoint,{margin:ld(t)}),{topMostOnly:n.accelKey})}function md(t,e){const n=t.trail[t.trail.length-1];n&&n.dist2(e)<=1e-6||t.trail.push(e.clone())}function gd(t,e){ad(t).setPreview(Array.from(e.erasingShapeIds),e.trail)}function yd(t){ad(t).clear()}var xd=class extends Pt{constructor(t){super(t,"eraser"),this.initial="idle",this.addChild(new wd(t,this)),this.addChild(new bd(t,this)),this.addChild(new vd(t,this))}onExit(){yd(this.editor)}},wd=class extends Pt{constructor(t,e){super(t,"idle",e)}onEnter(){yd(this.editor)}onPointerDown(t){0===t.button&&this.transition("pointing",function(t,e){const n={originScreenPoint:e.screenPoint.clone(),previousPagePoint:e.pagePoint.clone(),protectedContainerIds:dd(t,e.pagePoint),erasingShapeIds:new Set,trail:[e.pagePoint.clone()]};return hd(t,n,e),gd(t,n),n}(this.editor,t))}},bd=class extends Pt{info=null;constructor(t,e){super(t,"pointing",e)}onEnter(t){this.info=t}onPointerMove(t){this.info&&function(t,e){return t.dist2(e)>=9}(this.info.originScreenPoint,t.screenPoint)&&(fd(this.editor,this.info,t),md(this.info,t.pagePoint),this.info.previousPagePoint=t.pagePoint.clone(),gd(this.editor,this.info),this.transition("erasing",this.info))}onPointerUp(t){this.info&&(hd(this.editor,this.info,t),gd(this.editor,this.info),kd(this.editor,this.info)),this.transition("idle")}onCancel(){yd(this.editor),this.transition("idle")}onExit(){this.info=null}},vd=class extends Pt{info=null;constructor(t,e){super(t,"erasing",e)}onEnter(t){this.info=t}onPointerMove(t){this.update(t)}onPointerUp(t){this.update(t),this.info&&kd(this.editor,this.info),this.transition("idle")}onCancel(){yd(this.editor),this.transition("idle")}onExit(){this.info=null}update(t){this.info&&(fd(this.editor,this.info,t),md(this.info,t.pagePoint),this.info.previousPagePoint=t.pagePoint.clone(),gd(this.editor,this.info))}};function kd(t,e){const n=Array.from(e.erasingShapeIds);yd(t),0!==n.length&&t.commands.deleteShapes(n,{source:"user"})}function Sd(){return{id:"land.eraser.react",canvasOverlays:[{id:"land.eraser.trail-overlay",component:Pd}],shapeOpacityModifiers:[{id:"land.eraser.preview-opacity",getOpacityValue(t,e){const n=ad(t).erasingShapeIdSetSignal;return{graph:t.signals,get:()=>t.layers.isOrAncestorInSet(e,n.get())?.32:1}}}]}}var Pd=m(function(){return e(ad(t()).trailActiveSignal)?l(Md,{}):null}),Md=m(function(){const n=t(),r=e(ad(n).trailSignal),o=e(n.state.cameraZoom),i=Math.max(o,1e-4),s=function(){const[t,e]=S(()=>zd());return w(()=>{if("undefined"==typeof window)return;let t=0;const n=r=>{e(r),t=window.requestAnimationFrame(n)};return t=window.requestAnimationFrame(n),()=>{window.cancelAnimationFrame(t)}},[]),t}(),a=k({samples:[],sourceLength:0}),c=Math.max(s,zd());!function(t,e,n,r){jd(t,r),e.length<t.sourceLength&&(t.samples=[],t.sourceLength=0);if(e.length===t.sourceLength)return;const o=t.sourceLength,i=e.length-o,s=t.samples[t.samples.length-1]?.time??r-Rd*i;for(let a=o;a<e.length;a++){const l=e[a],c=(a-o+1)/i;Fd(t,{x:l.x,y:l.y},n,Gd(s,r,c))}t.sourceLength=e.length,jd(t,r)}(a.current,r,i,c);const d=function(t,e){const n=Wd(t,e);return function(t,e){if(t.length<=1)return[...t];const n=.15+.85*(1-e),r=[t[0]];for(let o=1;o<t.length;o++)r.push(Jd(r[r.length-1],t[o],n));return r}(n.length>Td?n.slice(-48):n,Ad)}(a.current.samples,c);if(0===d.length)return null;const u=(h=Ed/i,0===(p=d).length||h<=0?null:1===p.length?tu(_d(p[0],h/2,Nd))??"":tu(function(t){if(0===t.length)return[];if(1===t.length)return _d(t[0].point,Math.max(t[0].radius,.01),Nd);const e=[],n=[];for(const a of t){const t=Kd(a.direction);Qd(e,Xd(a.point,Yd(t,a.radius))),Qd(n,qd(a.point,Yd(t,a.radius)))}const r=[];for(const a of e)Qd(r,a);const o=t[t.length-1],i=Kd(o.direction),s=function({center:t,direction:e,normal:n,radius:r}){if(r<=0)return[];const o=[];for(let i=1;i<Od;i++){const s=i/Od;o.push(qd(t,qd(Yd(e,Math.sin(Math.PI*s)*r),Yd(n,-Math.cos(Math.PI*s)*r))))}return o}({center:o.point,direction:o.direction,normal:i,radius:o.radius});for(const a of s)Qd(r,a);for(let a=n.length-1;a>=0;a--)Qd(r,n[a]);return r}(function(t,e){const n=function(t){const e=[0];for(let n=1;n<t.length;n++)e.push(e[n-1]+Ud(t[n-1],t[n]));return e}(t),r=n[n.length-1]??0,o=Math.max(e,r);return t.map((r,i)=>{const s=n[i]??0,a=Zd(s/o,0,1);return{point:r,direction:Hd(t,i),radius:e/2*a,runningLength:s}})}(p,h))));var p,h;return u?l("g",{"data-ui":"eraser-trail-overlay",children:l("path",{"data-ui":"eraser-trail-scribble",d:u,fill:Id})}):null}),Id="rgba(142, 142, 142, 0.16)",Td=48,Cd=1,Ed=12,Ad=.32,Od=8,Nd=13,Rd=16,Ld=8,$d=180,Dd=180,Bd=680;function zd(){return"undefined"==typeof performance?Date.now():performance.now()}function Fd(t,e,n,r){const o=t.samples[t.samples.length-1];if(!o)return void t.samples.push({...e,time:r,velocity:0});const i=Cd/n,s=Ud(o,e);if(s<i)return void(t.samples[t.samples.length-1]={...o,...e,time:r});const a=s*n/Math.max(Ld,r-o.time);t.samples.push({...e,time:r,velocity:Gd(o.velocity,a,.68)})}function jd(t,e){t.samples=Wd(t.samples,e)}function Wd(t,e){const n=t[t.length-1];if(!n)return[];const r=e-Zd($d+n.velocity*Dd,$d,Bd);if(n.time<r)return[];const o=t.findIndex(t=>t.time>=r);if(-1===o)return[];const i=t.slice(o),s=t[o-1],a=i[0];return s&&a.time>r?[(l=s,c=a,d=Zd((r-s.time)/(a.time-s.time),0,1),{...Jd(l,c,d),time:Gd(l.time,c.time,d),velocity:Gd(l.velocity,c.velocity,d)}),...i]:i;var l,c,d}function Hd(t,e){if(t.length<=1)return{x:1,y:0};const n=t[e-1]??t[e],r=t[e+1]??t[e];return function(t){const e=Math.sqrt(t.x*t.x+t.y*t.y);return e<=0?{x:1,y:0}:{x:t.x/e,y:t.y/e}}(0===e?Xd(r,t[e]):e===t.length-1?Xd(t[e],n):Xd(r,n))}function _d(t,e,n){const r=[];for(let o=0;o<n;o++){const i=2*Math.PI*o/n;r.push({x:t.x+Math.cos(i)*e,y:t.y+Math.sin(i)*e})}return r}function Ud(t,e){return Math.sqrt(Vd(t,e))}function Vd(t,e){const n=t.x-e.x,r=t.y-e.y;return n*n+r*r}function Kd(t){return{x:-t.y,y:t.x}}function qd(t,e){return{x:t.x+e.x,y:t.y+e.y}}function Xd(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Yd(t,e){return{x:t.x*e,y:t.y*e}}function Jd(t,e,n){return{x:Gd(t.x,e.x,n),y:Gd(t.y,e.y,n)}}function Gd(t,e,n){return t+(e-t)*n}function Zd(t,e,n){return Math.max(e,Math.min(n,t))}function Qd(t,e){const n=t[t.length-1];!n||Vd(n,e)>.04?t.push(e):t[t.length-1]=e}function tu(t){if(t.length<2)return null;if(2===t.length)return`M ${nu(t[0])} L ${nu(t[1])} Z`;const e=[`M ${nu(eu(t[0],t[1]))}`];for(let n=1;n<t.length;n++){const r=t[n],o=t[(n+1)%t.length];e.push(`Q ${nu(r)} ${nu(eu(r,o))}`)}return e.push("Z"),e.join(" ")}function eu(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}function nu(t){return`${ru(t.x)},${ru(t.y)}`}function ru(t){return Number.isInteger(t)?`${t}`:t.toFixed(3)}function ou(){return{id:"land.eraser",setup(t){t.runtime.provide(id,function(t){const{atom:e,computed:n}=t.signals,r=e("eraser.shapeIds",[],{isEqual:sd}),o=n("eraser.shapeIdSet",()=>new Set(r.get())),i=e("eraser.trail",[]);return{erasingShapeIdsSignal:r,erasingShapeIdSetSignal:o,trailSignal:i,trailActiveSignal:n("eraser.trailActive",()=>i.get().length>1),setPreview(t,e){r.set(Array.from(new Set(t))),i.set(e.map(t=>t.clone()))},clear(){r.set([]),i.get().length>0&&i.set([])}}}(t)),t.tools.register("eraser",t=>new xd(t))}}}var iu={id:"eraser",editor:ou(),render:Sd()};function su(t){return/^\s*$/.test(t)?"Frame":t}function au(t){return new N(0,-34,t.props.w,t.props.h+34)}function lu(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function cu(t){return new N(t.x,t.y-34,t.props.w,34)}function du(t,e,n){const r=n/2;return!!t.expand(r).containsPoint(e)&&(Math.abs(e.x-t.minX)<=r||Math.abs(e.x-t.maxX)<=r||Math.abs(e.y-t.minY)<=r||Math.abs(e.y-t.maxY)<=r)}var uu=class extends St{type="frame";getDefaultProps(){return{w:640,h:360,name:"",fill:H("transparent"),stroke:W("stroke-muted"),strokeWidth:1}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Math.max(1,lu(e.w,n.w)),h:Math.max(1,lu(e.h,n.h)),name:"string"==typeof e.name?e.name:n.name,fill:V(e.fill,n.fill),stroke:V(e.stroke,n.stroke),strokeWidth:Math.max(0,lu(e.strokeWidth,n.strokeWidth))}}getLocalBounds(t){return new N(0,0,t.props.w,t.props.h)}getRenderBounds(t){return au(t)}getPointHitTestBounds(t){const e=this.getPositionedBounds(t).expand(3),n=cu(t);return N.FromPoints([new O(e.minX,e.minY),new O(e.maxX,e.maxY),new O(n.minX,n.minY),new O(n.maxX,n.maxY)])}canEdit(t){return!0}canReceiveChildren(t){return!0}canSnapChildrenToSelf(t){return!0}canReceiveTerminalBinding(t){return!0}getSelectionResizeHandleIds(t,e){return ot}shouldRotateDescendants(t){return!0}getChildClipLocalBounds(t){return this.getLocalBounds(t)}canSelectByBrush(t,e){return super.isWrappedByBrush(t,e)}hitTest(t,e){return cu(t).containsPoint(e)||du(this.getPositionedBounds(t),e,6)}hitTestBindingTarget(t,e){return this.getPositionedBounds(t).containsPoint(e)}hitTestLineSegment(t,e){return function(t,e,n,r){const o=r/2;if(du(t,e,r)||du(t,n,r))return!0;const i=[new O(t.minX,t.minY),new O(t.maxX,t.minY),new O(t.maxX,t.maxY),new O(t.minX,t.maxY)];for(let s=0;s<i.length;s+=1){const t=i[s],r=i[(s+1)%i.length];if(t&&r&&D(e,n,t,r)<=o)return!0}return!1}(this.getPositionedBounds(t),e.positionedStart,e.positionedEnd,Math.max(6,e.positionedMargin))}},pu=Ae("plugin-frame.api");function hu({editor:t}){return function({editor:t}){return{create(e){const n=t.shapes.getDefaultProps("frame"),[r]=t.commands.createShapes([{type:"frame",x:e.x,y:e.y,meta:e.meta?{...e.meta}:void 0,props:{...n,w:e.w??n.w,h:e.h??n.h,name:e.name??n.name,fill:e.fill??n.fill,stroke:e.stroke??n.stroke,strokeWidth:e.strokeWidth??n.strokeWidth}}],{source:"user"});return"frame"===r?.type?{id:r.id,type:r.type}:null},moveShapesToFrame(e,n){const r=t.shapes.get(n);if(!r||"frame"!==r.type)return[];const o=e.filter(e=>{const n=t.shapes.get(e);return!!n&&!n.isLocked});return o.length>0&&t.commands.reparentShapes({ids:[...o],parentId:n},{source:"user"}),o},getSelectionStyle(){const e=t.state.selectedShapes.get().filter(fu);return 0===e.length?null:{name:mu(e.map(t=>t.props.name)),fill:gu(e.map(t=>t.props.fill)),stroke:gu(e.map(t=>t.props.stroke)),strokeWidth:mu(e.map(t=>t.props.strokeWidth))}},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(fu).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)},getToolDefaults:()=>t.shapes.getDefaultProps("frame"),setToolDefaults:e=>(t.shapes.updateDefaultProps("frame",e),t.shapes.getDefaultProps("frame")),getSelectedChildOrderState(){const e=t.layers.getSelectionSiblingOrderState();if(!e||!e.parentId.startsWith("shape:"))return null;const n=t.shapes.get(e.parentId);return n&&"frame"===n.type?{index:e.index,count:e.count,canMoveBackward:t.layers.canMoveSelectionWithinParent("backward"),canMoveForward:t.layers.canMoveSelectionWithinParent("forward")}:null},moveSelectedChild:e=>t.layers.move(t.selection.getIds(),e,"user")}}({editor:t})}function fu(t){return"frame"===t.type}function mu(t){const e=t[0];return void 0!==e&&t.every(t=>t===e)?e:null}function gu(t){const e=t[0];return e&&t.every(t=>Y(t,e))?e:null}var yu=class extends Pt{constructor(t){super(t,"frame"),this.initial="idle",this.addChild(new xu(t,this)),this.addChild(new wu(t,this))}getDefaultProps(){return this.editor.shapes.getDefaultProps("frame")}},xu=class extends Pt{constructor(t,e){super(t,"idle",e)}onEnter(){this.editor.interaction.clearSelection()}onPointerDown(t){this.transition("creating",{originPagePoint:t.pagePoint.clone(),originScreenPoint:t.screenPoint.clone(),currentPagePoint:t.pagePoint.clone(),shapeId:null,shiftKey:t.shiftKey})}},wu=class extends Pt{tool;info=null;operation=null;constructor(t,e){super(t,"creating",e),this.tool=e}onEnter(t){this.info=t,this.operation=this.editor.operations.begin({kind:"frame.create",label:"shape.create",source:"user",history:"record"})}onPointerMove(t){this.updateShape(t.pagePoint,t.screenPoint,t.shiftKey)}onPointerUp(t){this.info?(this.updateShape(t.pagePoint,t.screenPoint,t.shiftKey,!0),this.commitOperation(),this.editor.state.tool.get().isToolLocked?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.cancelOperation(),this.info=null}commitOperation(){const t=this.operation;this.operation=null,t?.commit()}cancelOperation(){const t=this.operation;this.operation=null,t?.isActive&&t.cancel()}updateShape(t,e,n,r=!1){if(!this.info)return;this.info.currentPagePoint=t.clone(),this.info.shiftKey=n;const o=this.info.originScreenPoint.dist(e);if(!this.info.shapeId&&o<4){if(!r)return;const e=function(t,e){return new N(t.x-e.w/2,t.y-e.h/2,e.w,e.h)}(t,this.tool.getDefaultProps()),n=this.createShape(e);return void(this.info.shapeId=n.id)}const i=function(t,e,n,r){let o=e.x-t.x,i=e.y-t.y;if(n){const t=r.w/r.h,e=Math.abs(o),n=Math.abs(i);0===n||e/Math.max(n,1)>=t?i=e/t*(i<0?-1:1):o=n*t*(o<0?-1:1)}const s=new O(t.x+o,t.y+i);return new N(Math.min(t.x,s.x),Math.min(t.y,s.y),Math.max(Math.abs(s.x-t.x),1),Math.max(Math.abs(s.y-t.y),1))}(this.info.originPagePoint,t,n,this.tool.getDefaultProps());if(!this.info.shapeId){const t=this.createShape(i);return void(this.info.shapeId=t.id)}this.editor.commands.updateShapes([{id:this.info.shapeId,x:i.x,y:i.y,props:{w:i.w,h:i.h}}],{source:"user"})}createShape(t){const[e]=this.editor.commands.createShapes([{type:"frame",x:t.x,y:t.y,props:{...this.tool.getDefaultProps(),w:t.w,h:t.h}}],{source:"user",autoReparent:!1});if(!e||"frame"!==e.type)throw new Error("Failed to create frame shape");return this.editor.commands.setSelectedShapeIds([e.id],{source:"system"}),e}};var bu=class{type="frame";toSvg(t,e){const{fill:n,stroke:r,strokeWidth:o,w:i,h:s,name:a}=t.props,l=e.resolveColor(r),c=o/2;return{tag:"g",children:[{tag:"rect",attrs:{x:c,y:c,width:Math.max(i-o,0),height:Math.max(s-o,0),fill:e.resolveColor(n),stroke:l,"stroke-width":o,"stroke-linejoin":"round","stroke-linecap":"round"}},{tag:"text",attrs:{x:0,y:-8,fill:l,"font-family":"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif","font-size":12,"font-weight":400},children:[su(a)]}]}}};function vu(){return{id:"land.frame",shapeUtils:[new uu],shapeSvgExporters:[new bu],setup(t){t.tools.register("frame",t=>new yu(t))}}}var ku=["Inter","ui-sans-serif","system-ui","-apple-system","BlinkMacSystemFont","'Segoe UI'","sans-serif"].join(", "),Su=i({id:"land.frame.name.dom-events",selector:'[data-ui="frame-canvas-name"]'});function Pu(){return{id:"land.frame.react",domEventGuards:[Su],shapeRenderers:[{type:"frame",component:Mu,hoverComponent:Tu}]}}function Mu({editor:t,shape:e,shapeEditingSession:n}){const r=n?.shapeId===e.id;
27
- return c("div",{style:{height:"100%",overflow:"visible",position:"relative",width:"100%"},children:[l(Iu,{shape:e,hideName:!0}),l(Cu,{editor:t,shape:e,isEditing:r})]})}function Iu({shape:t,hideName:e=!1}){const{fill:n,h:r,name:o,stroke:i,strokeWidth:s,w:a}=t.props,d=s/2,u=Math.max(a-s,0),p=Math.max(r-s,0),h=su(o),f=au(t);
28
- return c("svg",{width:"100%",height:"100%",viewBox:`${f.x} ${f.y} ${f.w} ${f.h}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[l("rect",{x:d,y:d,width:u,height:p,fill:K(n),stroke:K(i),strokeWidth:s,strokeLinejoin:"round",strokeLinecap:"round"}),e?null:l("text",{x:0,y:-8,fill:K(i),fontFamily:ku,fontSize:12,fontWeight:400,style:{userSelect:"none"},children:h})]})}function Tu({shape:t,strokeWidth:e}){const{h:r,w:o}=t.props,i=au(t);
29
- return l("svg",{"data-ui":"frame-hover-outline",width:"100%",height:"100%",viewBox:`${i.x} ${i.y} ${i.w} ${i.h}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:l("rect",{x:0,y:0,width:o,height:r,fill:"none",stroke:n,strokeWidth:e,strokeLinejoin:"round",strokeLinecap:"round",vectorEffect:"non-scaling-stroke"})})}function Cu({editor:t,shape:e,isEditing:n}){
30
- return l(o,{editor:t,shape:e,isEditing:n,value:e.props.name,fallback:su(""),bodyWidth:e.props.w,bodyHeight:e.props.h,renderHeight:34,operationKind:"frame.edit",editAriaLabel:"Edit frame name",inputAriaLabel:"Frame name",dataUi:{heading:"frame-canvas-heading",dragHandle:"frame-drag-handle",name:"frame-canvas-name",input:"frame-canvas-name-input"},onValueChange:n=>{t.commands.updateShapes([{id:e.id,props:{name:n}}],{source:"user"})}})}var Eu={id:"frame",editor:vu(),render:Pu(),api:pu,setup:({editor:t})=>({api:hu({editor:t})})},Au=1e-4,Ou=1e-4,Nu="image.crop",Ru=[{label:"1:1",value:"1:1",ratio:1},{label:"4:3",value:"4:3",ratio:4/3},{label:"16:9",value:"16:9",ratio:16/9}],Lu={top_left:"nwse-resize",top:"ns-resize",top_right:"nesw-resize",right:"ew-resize",bottom_right:"nwse-resize",bottom:"ns-resize",bottom_left:"nesw-resize",left:"ew-resize"},$u=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"];function Du(t){return Math.min(1,Math.max(0,t))}function Bu(t,e,n){return Math.min(n,Math.max(e,t))}function zu(t){return!!t&&"object"==typeof t&&"number"==typeof t.x&&Number.isFinite(t.x)&&"number"==typeof t.y&&Number.isFinite(t.y)}function Fu(t,e){const n=Du(t),r=Du(e);let o=Math.min(n,r),i=Math.max(n,r);if(i-o<Au){const t=(o+i)/2;o=Math.max(0,Math.min(.9999,t-5e-5)),i=o+Au}return{min:o,max:i}}function ju(t){if(!t||"object"!=typeof t)return null;const e=t;if(!zu(e.topLeft)||!zu(e.bottomRight))return null;const n=Fu(e.topLeft.x,e.bottomRight.x),r=Fu(e.topLeft.y,e.bottomRight.y);return{topLeft:{x:n.min,y:r.min},bottomRight:{x:n.max,y:r.max}}}function Wu(t){const e=ju(t);if(!e)return null;const n=e.topLeft.x,r=e.topLeft.y,o=e.bottomRight.x,i=e.bottomRight.y;return{left:n,top:r,right:o,bottom:i,width:o-n,height:i-r}}function Hu(t){return Wu(t)??{left:0,top:0,right:1,bottom:1,width:1,height:1}}function _u(t,e){return Math.abs(t.left-e.left)<=Ou&&Math.abs(t.top-e.top)<=Ou&&Math.abs(t.right-e.right)<=Ou&&Math.abs(t.bottom-e.bottom)<=Ou}function Uu(t){return function(t){return Math.abs(t.left)<=Ou&&Math.abs(t.top)<=Ou&&Math.abs(1-t.right)<=Ou&&Math.abs(1-t.bottom)<=Ou}(t)?null:ju({topLeft:{x:t.left,y:t.top},bottomRight:{x:t.right,y:t.bottom}})}function Vu({centerX:t,centerY:e,height:n,width:r}){const o=Bu(r,Au,1),i=Bu(n,Au,1),s=Bu(t-o/2,0,1-o),a=Bu(e-i/2,0,1-i);return{left:s,top:a,right:s+o,bottom:a+i,width:o,height:i}}function Ku(t){return{x:t.left+t.width/2,y:t.top+t.height/2}}function qu({crop:t,shape:e}){const n=Hu(t);return{w:e.props.w/n.width,h:e.props.h/n.height}}function Xu(t){const e=t.props.w/t.props.h;for(const n of Ru)if(Math.abs(e-n.ratio)<=.01)return n.value;return null}function Yu(t,e){return e===Ju(t.id)}function Ju(t){return`image.crop:edit:${t}`}function Gu({localToPage:t,shape:e}){const n=e.props.w,r=e.props.h,o=(0+n)/2,i=(0+r)/2,s={top_left:new O(0,0),top:new O(o,0),top_right:new O(n,0),right:new O(n,i),bottom_right:new O(n,r),bottom:new O(o,r),bottom_left:new O(0,r),left:new O(0,i)};return $u.map(e=>{return{kind:"custom",type:Nu,id:e,point:t.applyToPoint(s[e]),cursor:(n=e,Lu[n])};var n})}function Zu({change:t,crop:e,shape:n}){const r=qu({crop:e,shape:n}),o=e.bottomRight.x-e.topLeft.x,i=e.bottomRight.y-e.topLeft.y,s=Bu(e.topLeft.x-t.x/r.w,0,1-o),a=Bu(e.topLeft.y-t.y/r.h,0,1-i),l=ju({topLeft:{x:s,y:a},bottomRight:{x:s+o,y:a+i}});return l?{id:n.id,props:{crop:l}}:null}function Qu({preset:t,shape:e}){const n=Ku(Hu(e.props.crop)),r=qu({crop:e.props.crop,shape:e}),o=Ru.find(e=>e.value===t)?.ratio??null;if(!o)return null;const i=o*(r.h/r.w);let s=1,a=s/i;return a>1&&(a=1,s=a*i),function({nextRect:t,shape:e}){const n=Hu(e.props.crop);if(_u(n,t))return null;const r=qu({crop:e.props.crop,shape:e}),o=new O((t.left-n.left)*r.w,(t.top-n.top)*r.h).rot(e.rotation);return{id:e.id,x:e.x+o.x,y:e.y+o.y,props:{w:t.width*r.w,h:t.height*r.h,crop:Uu(t)}}}({nextRect:Vu({centerX:n.x,centerY:n.y,width:s,height:a}),shape:e})}function tp(t){return Number.isFinite(t)?Number(t.toFixed(4)).toString():"0"}var ep=new WeakMap;function np(t,e){return ep.get(t)?.get(e)??null}function rp(t,e){const n=ep.get(t);n&&(n.delete(e),0===n.size&&ep.delete(t))}function op(t){return E(t)&&"image"===t.type}function ip(t){return C(t)&&"image"===t.type}var sp={propagation:"stop"};function ap({handleId:t,shapeId:e,startPagePoint:n,startPageToLocal:r,startShape:o,startCrop:i}){return{shapeId:e,operationKind:"image.crop.handle",update({editor:s,pagePoint:a,source:l}){if(!ip(s.shapes.get(e)))return"stop";const c=function({handleId:t,pageToLocal:e,shape:n,startCrop:r,startPagePoint:o,currentPagePoint:i}){const s=ju(r)??{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},a=qu({crop:s,shape:n});if(a.w<8||a.h<8)return null;const l=e.applyToPoint(o),c=e.applyToPoint(i).sub(l);if(0===c.x&&0===c.y)return null;const d={x:s.topLeft.x*a.w,y:s.topLeft.y*a.h,w:(s.bottomRight.x-s.topLeft.x)*a.w,h:(s.bottomRight.y-s.topLeft.y)*a.h},u=d.x+d.w,p=d.y+d.h;let h=d.x,f=d.y,m=d.w,g=d.h;!function(t){return"top_left"===t||"left"===t||"bottom_left"===t}(t)?function(t){return"top_right"===t||"right"===t||"bottom_right"===t}(t)&&(m=Bu(u+c.x,d.x+8,a.w)-h):(h=Bu(h+c.x,0,u-8),m=u-h),function(t){return"top_left"===t||"top"===t||"top_right"===t}(t)?(f=Bu(f+c.y,0,p-8),g=p-f):function(t){return"bottom_left"===t||"bottom"===t||"bottom_right"===t}(t)&&(g=Bu(p+c.y,d.y+8,a.h)-f);const y=ju({topLeft:{x:h/a.w,y:f/a.h},bottomRight:{x:(h+m)/a.w,y:(f+g)/a.h}});if(!y)return null;const x=new O(h-s.topLeft.x*a.w,f-s.topLeft.y*a.h).rot(n.rotation);return{id:n.id,x:n.x+x.x,y:n.y+x.y,props:{w:m,h:g,crop:y}}}({handleId:t,currentPagePoint:a,pageToLocal:r,shape:o,startCrop:i,startPagePoint:n});return c?(s.commands.updateShapes([c],{source:l}),"continue"):"continue"}}}function lp(){return{createSession(t,{handle:e,shape:n,originPagePoint:r}){return ip(n)&&"custom"===e.kind&&"image.crop"===e.type&&(o=e.id,$u.some(t=>t===o))?ap({handleId:e.id,shapeId:n.id,startPagePoint:r,startPageToLocal:t.shapes.computeLocalToPageTransform(n).invert(),startShape:n,startCrop:n.props.crop}):null;var o}}}function cp(){let t=null;const e=()=>{t?.operation?.isActive&&t.operation.cancel(),t=null};return{id:"land.image.crop.interactions",editorEvent:{handleEvent(n,r){if("cancel"!==r.type){if("keyboard"===r.type)return function(t,e){if("key_down"!==e.name)return;const n=dp(t);if(!n)return;if("Escape"===e.key&&!e.altKey&&!e.accelKey)return t.editing.cancel("user")&&rp(t,n.id),sp;if("Enter"===e.key&&!e.altKey&&!e.accelKey)return t.editing.complete("user")&&rp(t,n.id),sp;const r=function(t){if(t.altKey||t.accelKey)return null;const e=t.shiftKey?10:1;switch(t.key){case"ArrowLeft":return new O(e,0);case"ArrowRight":return new O(-e,0);case"ArrowUp":return new O(0,e);case"ArrowDown":return new O(0,-e);default:return null}}(e);if(r){const e=function({pageDelta:t,shape:e,startCrop:n}){const r=ju(n);return!r||t.equals(O.Zero())?null:Zu({change:t.rot(-e.rotation),crop:r,shape:e})}({pageDelta:r,shape:n,startCrop:n.props.crop});return e&&t.commands.updateShapes([e],{source:"user"}),sp}}(n,r);if("pointer"===r.type)if("pointer_cancel"!==r.name){if("pointer_down"===r.name){if(e(),0!==r.button||"select"!==n.state.tool.get().activeToolId||!n.tools.isInInitialState())return;if(n.selection.hitTestHandle(r.pagePoint))return;const o=dp(n);if(!o)return;return function(t,e,n){const r=t.shapes.computeLocalToPageTransform(e).invert().applyToPoint(n.pagePoint);return r.x>=0&&r.y>=0&&r.x<=e.props.w&&r.y<=e.props.h}(n,o,r)?(t={pointerId:r.pointerId,shapeId:o.id,startCrop:o.props.crop,startPagePoint:r.pagePoint.clone(),startScreenPoint:r.screenPoint.clone(),startPageToLocal:n.shapes.computeLocalToPageTransform(o).invert(),startShape:o,hasDragged:!1,operation:null},sp):n.editing.complete("user")?(rp(n,o.id),n.handleEvent(r),sp):void 0}if(t&&r.pointerId===t.pointerId)return"pointer_move"===r.name?(up(n,r,t),sp):"pointer_up"===r.name?(up(n,r,t),t.operation?.isActive&&t.operation.commit(),e(),sp):void 0}else e()}else e()}},selectionHandle:lp()}}function dp(t){const[e]=t.state.selectedShapes.get();if(!ip(e))return null;const n=t.state.shapeEditingSession.get();return n&&n.shapeId===e.id&&Yu(e,n.operationKind)?e:null}function up(t,e,n){if(!n.hasDragged){if(n.startScreenPoint.dist2(e.screenPoint)<9)return;n.operation=t.operations.begin({kind:"image.crop.translate",label:"shape.edit",source:"user",history:"record"}),n.hasDragged=!0}if(!ip(t.shapes.get(n.shapeId)))return;const r=function({currentPagePoint:t,pageToLocal:e,shape:n,startCrop:r,startPagePoint:o,shiftKey:i}){const s=ju(r);if(!s)return null;const a=e.applyToPoint(o);let l=e.applyToPoint(t).sub(a);return i&&(l=Math.abs(l.x)<Math.abs(l.y)?new O(0,l.y):new O(l.x,0)),0===l.x&&0===l.y?null:Zu({change:l,crop:s,shape:n})}({currentPagePoint:e.pagePoint,pageToLocal:n.startPageToLocal,shape:n.startShape,shiftKey:e.shiftKey,startCrop:n.startCrop,startPagePoint:n.startPagePoint});r&&t.commands.updateShapes([r],{source:"user"})}function pp(t,e=0){return Math.max(0,"number"==typeof t&&Number.isFinite(t)?t:e)}function hp({cornerRadius:t,h:e,w:n}){return Math.min(pp(t),Math.max(0,n)/2,Math.max(0,e)/2)}var fp=24,mp="#ffff00",gp=1,yp=128,xp=24,wp=mp,bp=.45,vp=class{editor;confirmHandler=null;deactivateHistoryScope=null;session=null;snapshot=null;subscribers=new Set;constructor(t){this.editor=t,Tt("image.smudgeSession.lifecycle",t.state.shapeEditingSession,()=>{this.clearIfEditingSessionInvalid()},{fireImmediately:!1})}start(t,e){if(t.isLocked)return!1;const n=Mp(t.id),r=this.editor.state.shapeEditingSession.get();if(r&&(r.shapeId!==t.id||r.operationKind!==n))return!1;if(this.session&&r?.shapeId===t.id&&Ip(t,r.operationKind))return this.updateSession({...this.session,brush:Tp({...this.session.brush,...e})}),!0;this.clear();const o=this.editor.editing.start({shapeId:t.id,operationKind:n,entryMode:"focusEnd"},"user");return!(!o||o.shapeId!==t.id||o.operationKind!==n)&&(this.setSession({shapeId:t.id,brush:Tp(e),strokes:[],activeStroke:null,redoStrokes:[],nextStrokeIndex:1}),this.activateHistoryScope(),!0)}cancel(){const t=this.session?.shapeId??null;this.clear();const e=this.editor.state.shapeEditingSession.get();t&&e?.shapeId===t&&e.operationKind===Mp(t)&&this.editor.editing.cancel("user")}complete(){const t=this.session?.shapeId??null;this.clear();const e=this.editor.state.shapeEditingSession.get();t&&e?.shapeId===t&&e.operationKind===Mp(t)&&this.editor.editing.complete("user")}cancelIfActive(){return!!this.getActiveSession()&&(this.cancel(),!0)}clearForShape(t){this.session?.shapeId===t&&this.clear()}updateBrush(t){if(!this.getActiveSession()||!this.session)return!1;const e=Tp({...this.session.brush,...t});return e.size===this.session.brush.size&&e.color===this.session.brush.color&&e.opacity===this.session.brush.opacity||this.updateSession({...this.session,brush:e}),!0}getSnapshot(t){const e=this.getActiveSession();return e&&e.shapeId===t?this.snapshot:null}getActiveSession(){if(!this.session)return null;const t=this.editor.shapes.get(this.session.shapeId),e=this.editor.state.shapeEditingSession.get();return t&&e&&e.shapeId===this.session.shapeId&&e.operationKind===Mp(this.session.shapeId)?this.snapshot:(this.clear(),null)}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}beginStroke(t){if(!this.session)return;const e=kp(this.session),n={id:`${e.shapeId}:smudge:${e.nextStrokeIndex}`,points:[Fp(t)],brush:{...e.brush}};this.updateSession({...e,activeStroke:n,nextStrokeIndex:e.nextStrokeIndex+1})}appendPoint(t){if(!this.session?.activeStroke)return;const e=this.session.activeStroke.points[this.session.activeStroke.points.length-1];e&&Math.hypot(e.x-t.x,e.y-t.y)<.5||this.updateSession({...this.session,activeStroke:{...this.session.activeStroke,points:[...this.session.activeStroke.points,Fp(t)]}})}endStroke(){this.session?.activeStroke&&this.updateSession(kp(this.session))}cancelStroke(){this.session?.activeStroke&&this.updateSession({...this.session,activeStroke:null})}undo(){if(!this.getActiveSession()||!this.session)return!1;if(this.session.activeStroke&&this.updateSession(kp(this.session)),!this.session||0===this.session.strokes.length)return!1;const t=this.session.strokes[this.session.strokes.length-1];return!!t&&(this.updateSession({...this.session,strokes:this.session.strokes.slice(0,-1),redoStrokes:[...this.session.redoStrokes,t]}),!0)}redo(){if(!this.getActiveSession()||!this.session)return!1;if(this.session.activeStroke||0===this.session.redoStrokes.length)return!1;const t=this.session.redoStrokes[this.session.redoStrokes.length-1];return!!t&&(this.updateSession({...this.session,strokes:[...this.session.strokes,t],redoStrokes:this.session.redoStrokes.slice(0,-1)}),!0)}registerConfirmHandler(t){return this.confirmHandler=t,()=>{this.confirmHandler===t&&(this.confirmHandler=null)}}requestConfirm(t){return this.confirmHandler?this.confirmHandler(t):Promise.resolve(null)}clear(){this.session&&(this.session=null,this.snapshot=null,this.deactivateHistoryScope?.(),this.deactivateHistoryScope=null,this.notify())}clearIfEditingSessionInvalid(){if(!this.session)return;const t=this.editor.state.shapeEditingSession.get();t?.shapeId===this.session.shapeId&&t.operationKind===Mp(this.session.shapeId)||this.clear()}activateHistoryScope(){const t={getState:()=>this.getHistoryScopeState(),subscribe:t=>this.subscribe(t),undo:()=>this.undo(),redo:()=>this.redo()};this.deactivateHistoryScope=this.editor.history.activateScope(t)}getHistoryScopeState(){const t=this.session?.activeStroke?1:0,e=this.session?.activeStroke?0:this.session?.redoStrokes.length??0;return{canUndo:(this.session?.strokes.length??0)+t>0,canRedo:e>0}}setSession(t){this.session=t,this.snapshot=function(t){return{shapeId:t.shapeId,brush:t.brush,strokes:t.activeStroke?[...t.strokes,t.activeStroke]:t.strokes,canUndo:t.strokes.length>0||!!t.activeStroke,canRedo:!t.activeStroke&&t.redoStrokes.length>0}}(t),this.notify()}updateSession(t){this.setSession(t)}notify(){for(const t of this.subscribers)t()}};function kp(t){return t.activeStroke?{...t,strokes:[...t.strokes,t.activeStroke],activeStroke:null,redoStrokes:[]}:t}var Sp=new WeakMap;function Pp(t){const e=Sp.get(t);if(e)return e;const n=new vp(t);return Sp.set(t,n),n}function Mp(t){return`image.smudge:edit:${t}`}function Ip(t,e){return e===Mp(t.id)}function Tp(t){const e="number"==typeof t?.size&&Number.isFinite(t.size)?t.size:xp,n="number"==typeof t?.opacity&&Number.isFinite(t.opacity)?t.opacity:bp??.45;return{size:Math.min(128,Math.max(1,e)),color:"string"==typeof t?.color&&t.color.trim().length>0?t.color:wp,opacity:Math.min(1,Math.max(0,n))}}function Cp({brush:t,editor:e,shape:n}){return Pp(e).start(n,t)}function Ep(t){Pp(t).cancel()}function Ap(t){Pp(t).complete()}function Op(t){return Pp(t).cancelIfActive()}function Np(t,e){return Pp(t).updateBrush(e)}function Rp(t){return Pp(t).getActiveSession()}function Lp(t){return Pp(t).undo()}function $p(t){return Pp(t).redo()}function Dp(t,e){return Pp(t).registerConfirmHandler(e)}async function Bp(t,e){return Pp(t).requestConfirm(e)}function zp(t){return t.map(t=>({id:t.id,brush:{...t.brush},points:t.points.map(Fp)}))}function Fp(t){return{x:t.x,y:t.y,...void 0===t.pressure?{}:{pressure:t.pressure}}}function jp(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}var Wp=class extends St{type="image";getDefaultProps(){return{w:240,h:180,assetId:null,crop:null,cornerRadius:0,altText:""}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Math.max(24,jp(e.w,n.w)),h:Math.max(24,jp(e.h,n.h)),assetId:(r=e.assetId,"string"==typeof r&&r.startsWith("asset:")?e.assetId:null),crop:ju(e.crop),cornerRadius:pp(e.cornerRadius,n.cornerRadius),altText:"string"==typeof e.altText?e.altText:n.altText};var r}getLocalBounds(t){return new N(0,0,t.props.w,t.props.h)}canReceiveTerminalBinding(t){return!0}getAllowedSelectionResizeModes(t,e){return at}canEdit(t){return!0}onEditEnd(t,e){var n,r;n=e.editor,r=t.id,Pp(n).clearForShape(r)}getSelectionHandleAnchors(t,e){const n={terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};if(!e.isOnlySelected)return n;const r=e.editor.state.shapeEditingSession.get();return r&&r.shapeId===t.id&&Yu(t,r.operationKind)?{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:Gu({crop:t.props.crop,localToPage:e.editor.shapes.computeLocalToPageTransform(t),shape:t})}:n}},Hp=class{type="image";toSvg(t,e){const{assetId:n,altText:r,crop:o,h:i,w:s}=t.props;if(!n)return null;const a=e.resolveAssetUrl(n);if(!a)return null;const l=Wu(o),c=l?{tag:"svg",attrs:{x:0,y:0,width:s,height:i,viewBox:(d=l,[tp(d.left),tp(d.top),tp(d.width),tp(d.height)].join(" ")),preserveAspectRatio:"none",overflow:"hidden"},children:[{tag:"image",attrs:{href:a,x:0,y:0,width:1,height:1,preserveAspectRatio:"none","aria-label":r||void 0}}]}:{tag:"image",attrs:{href:a,width:s,height:i,preserveAspectRatio:"none","aria-label":r||void 0}};var d;const u=hp({cornerRadius:t.props.cornerRadius,h:i,w:s});return u<=0?c:{tag:"g",attrs:{"clip-path":`url(#${e.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"rect",attrs:{x:0,y:0,width:s,height:i,rx:u,ry:u}}]})})`},children:[c]}}},_p={propagation:"stop"};function Up(){let t=null;const e=e=>{t=null,function(t){Pp(t).endStroke()}(e)},n=e=>{t=null,function(t){Pp(t).cancelStroke()}(e)};return{id:"land.image.smudge.interactions",editorEvent:{handleEvent(r,o){if("keyboard"===o.type)return(Kp(o)||Vp(o))&&qp(r)&&e(r),function(t,e){if("key_down"!==e.name)return;if(!qp(t))return;if("Escape"===e.key&&!e.altKey&&!e.accelKey)return Ep(t),_p;if(Vp(e))return Bp(t,{replace:!0}),_p;if(Kp(e))return e.shiftKey?t.history.redo():t.history.undo(),_p;return _p}(r,o);if("cancel"===o.type)return qp(r)?(n(r),"command"!==o.reason&&Ep(r),_p):void 0;if("pointer"!==o.type)return;const i=qp(r);if(i){if("pointer_down"===o.name){if(e(r),0!==o.button)return 1===o.button?void 0:_p;const n=Yp(r,i,o.pagePoint),s=Jp(n,i);return t={mode:s?"draw":"pan",originCamera:s?null:r.state.camera.get(),originScreenPoint:s?null:o.screenPoint.clone(),pointerId:o.pointerId,acceptsDrawPoints:s},s&&function(t,e){Pp(t).beginStroke(e)}(r,{x:n.x,y:n.y,pressure:o.pressure}),_p}return t&&t.pointerId===o.pointerId?"pointer_move"===o.name?("draw"===t.mode&&1&o.buttons?t.acceptsDrawPoints&&(t.acceptsDrawPoints=Xp(r,i,o)):"pan"===t.mode&&t.originCamera&&t.originScreenPoint&&1&o.buttons?Gp(r,o,t):e(r),_p):"pointer_up"===o.name?("draw"===t.mode&&t.acceptsDrawPoints?Xp(r,i,o):"pan"===t.mode&&Gp(r,o,t),e(r),_p):"pointer_cancel"===o.name?(n(r),_p):_p:_p}n(r)}}}}function Vp(t){return"key_down"===t.name&&"Enter"===t.key&&!t.altKey&&!t.accelKey}function Kp(t){return"key_down"===t.name&&"z"===t.key.toLowerCase()&&t.accelKey&&!t.altKey}function qp(t){const[e]=t.state.selectedShapes.get();if(!ip(e))return null;const n=t.state.shapeEditingSession.get();return n&&n.shapeId===e.id&&Ip(e,n.operationKind)?e:null}function Xp(t,e,n){const r=Yp(t,e,n.pagePoint);return!!Jp(r,e)&&(function(t,e){Pp(t).appendPoint(e)}(t,{x:r.x,y:r.y,pressure:n.pressure}),!0)}function Yp(t,e,n){return t.shapes.computeLocalToPageTransform(e).invert().applyToPoint(n)}function Jp(t,e){return t.x>=0&&t.y>=0&&t.x<=e.props.w&&t.y<=e.props.h}function Gp(t,e,n){if(!n.originCamera||!n.originScreenPoint)return;const r=e.screenPoint.sub(n.originScreenPoint),o=n.originCamera.z;t.viewport.setCamera({x:n.originCamera.x-r.x/o,y:n.originCamera.y-r.y/o},{source:"user"})}function Zp(){return{id:"land.image",shapeUtils:[new Wp],shapeSvgExporters:[new Hp],interactionHandlers:[cp(),Up()],setup:t=>function(t){let e=null;return Tt("image.cropSession.lifecycle",t.state.shapeEditingSession,()=>{const n=t.state.shapeEditingSession.get(),r=n?.shapeId,o=r&&n?.operationKind===Ju(r)?r:null;e&&e!==o&&rp(t,e),e=o})}(t)}}var Qp={id:"land.image.crop.dom-events",handle:()=>"continue",getCursor({clientPoint:t,editor:e,element:n,container:r}){const o=function(t){const[e]=t.state.selectedShapes.get();if(!ip(e))return null;const n=t.state.shapeEditingSession.get();return n&&n.shapeId===e.id&&Yu(e,n.operationKind)?e:null}(e);if(!o)return;if(n?.closest('[data-selection-custom-handle-type="image.crop"]'))return;if(!t)return;const i=r.getBoundingClientRect(),s=new O(t.x-i.left,t.y-i.top);return ch(e,o,e.viewport.screenToPage(s))?0!==e.inputs.state.get().buttons?"grabbing":"grab":void 0}},th={id:"land.image.smudge.dom-events",handle:()=>"continue",getCursor({clientPoint:t,container:e,editor:n}){const r=function(t){const[e]=t.state.selectedShapes.get();if(!ip(e))return null;const n=t.state.shapeEditingSession.get();return n&&n.shapeId===e.id&&Ip(e,n.operationKind)?e:null}(n);if(!r||!t)return;const o=e.getBoundingClientRect(),i=new O(t.x-o.left,t.y-o.top);return ch(n,r,n.viewport.screenToPage(i))?"crosshair":0!==n.inputs.state.get().buttons?"grabbing":"grab"}};function eh(){return{id:"land.image.react",domEventGuards:[Qp,th],selectionCustomHandleRenderers:[{type:Nu,component:sh}],shapeRenderers:[{type:"image",component:nh,hoverComponent:ih}]}}function nh({editor:t,shape:e,shapeEditingSession:n}){const{altText:r,assetId:o,crop:i,h:s,w:a}=e.props,d=o?t.assets.resolveUrl(o):null,u=hp({cornerRadius:e.props.cornerRadius,h:s,w:a}),p=function(t,e){return P(e=>function(t,e){return Pp(t).subscribe(e)}(t,e),()=>function(t,e){return Pp(t).getSnapshot(e)}(t,e),()=>null)}(t,e.id);if(!d)return l("div",{"aria-label":"Empty image","data-ui":"image-shape-missing-asset",role:"img",style:{alignItems:"center",background:"#f8fafc",border:"1px solid #cbd5e1",borderRadius:u,boxSizing:"border-box",color:"#cbd5e1",display:"flex",height:s,justifyContent:"center",overflow:"hidden",width:a},children:c("svg",{"aria-hidden":"true",className:"lucide lucide-sparkles-icon lucide-sparkles",fill:"none",height:"40",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",width:"40",xmlns:"http://www.w3.org/2000/svg",children:[
31
- l("path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}),
32
- l("path",{d:"M20 2v4"}),
33
- l("path",{d:"M22 4h-4"}),
34
- l("circle",{cx:"4",cy:"20",r:"2"})]})});const h=function({crop:t,shapeHeight:e,shapeWidth:n}){const r=Wu(t);if(!r)return null;const o=n/r.width,i=e/r.height;return{imageX:-r.left*o,imageY:-r.top*i,imageWidth:o,imageHeight:i,rect:r}}({crop:i,shapeHeight:s,shapeWidth:a});if(h){const t=n?.shapeId===e.id&&Yu(e,n.operationKind),o={display:"block",height:h.imageHeight,left:h.imageX,maxWidth:"none",objectFit:"fill",pointerEvents:"none",position:"absolute",top:h.imageY,userSelect:"none",width:h.imageWidth};
35
- return c("div",{"data-ui":"image-shape",style:{display:"block",height:s,overflow:t?"visible":"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:a},children:[t?l("img",{alt:"","aria-hidden":"true","data-ui":"image-crop-preview",draggable:!1,src:d,style:{...o,opacity:.1}}):null,c("div",{"data-ui":"image-crop-window",style:{height:s,overflow:"hidden",position:"absolute",borderRadius:u,inset:0,width:a},children:[l("img",{alt:r,draggable:!1,src:d,style:o}),l(rh,{shape:e,session:p})]})]})}
36
- return c("div",{"data-ui":"image-shape",style:{borderRadius:u,display:"block",height:s,overflow:"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:a},children:[l("img",{alt:r,draggable:!1,src:d,style:{display:"block",height:s,objectFit:"fill",width:a}}),l(rh,{shape:e,session:p})]})}function rh({shape:t,session:e}){return e&&e.shapeId===t.id&&0!==e.strokes.length?l("svg",{"aria-hidden":"true","data-ui":"image-smudge-preview",viewBox:`0 0 ${t.props.w} ${t.props.h}`,style:{display:"block",height:t.props.h,inset:0,overflow:"hidden",pointerEvents:"none",position:"absolute",width:t.props.w},children:e.strokes.map(t=>l(oh,{stroke:t},t.id))}):null}function oh({stroke:t}){const e=t.points[0];if(!e)return null;const n=t.brush.color??"#ffff00",r=t.brush.opacity??.45,o=t.brush.size;if(1===t.points.length)return l("circle",{cx:e.x,cy:e.y,r:o/2,fill:n,opacity:r});const i=function(t){const[e,...n]=t.points;return e?[`M ${lh(e.x)} ${lh(e.y)}`,...n.map(t=>`L ${lh(t.x)} ${lh(t.y)}`)].join(" "):null}(t);return i?l("path",{d:i,fill:"none",opacity:r,stroke:n,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:o}):null}function ih({shape:t,strokeWidth:e}){
37
- return l("div",{"data-ui":"image-hover-outline",style:{borderRadius:hp({cornerRadius:t.props.cornerRadius,h:t.props.h,w:t.props.w}),boxShadow:`inset 0 0 0 ${e}px ${n}`,inset:0,position:"absolute"}})}function sh({handle:t,strokeWidth:e}){const{x:n,y:r,w:o,h:i,center:s}=t.bounds,a=1.35*Math.max(o,i),d=Math.max(2.5*e,2),u=d/2,p={fill:"none",stroke:"rgba(37, 99, 235, 0.96)",strokeLinecap:"butt",strokeLinejoin:"miter",strokeWidth:d,pointerEvents:"none"},h=function({id:t,extension:e,outwardOffset:n,centerX:r,centerY:o}){switch(t){case"top_left":return{kind:"corner",points:[ah(r-n,o+e),ah(r-n,o-n),ah(r+e,o-n)].join(" ")};case"top":return{kind:"edge",x1:r-e,y1:o-n,x2:r+e,y2:o-n};case"top_right":return{kind:"corner",points:[ah(r-e,o-n),ah(r+n,o-n),ah(r+n,o+e)].join(" ")};case"right":return{kind:"edge",x1:r+n,y1:o-e,x2:r+n,y2:o+e};case"bottom_right":return{kind:"corner",points:[ah(r+n,o-e),ah(r+n,o+n),ah(r-e,o+n)].join(" ")};case"bottom":return{kind:"edge",x1:r-e,y1:o+n,x2:r+e,y2:o+n};case"bottom_left":return{kind:"corner",points:[ah(r+e,o+n),ah(r-n,o+n),ah(r-n,o-e)].join(" ")};case"left":return{kind:"edge",x1:r-n,y1:o-e,x2:r-n,y2:o+e};default:return{kind:"edge",x1:r,y1:o,x2:r,y2:o}}}({id:t.id,extension:a,outwardOffset:u,centerX:s.x,centerY:s.y});
38
- return c("g",{children:[l("rect",{"data-selection-custom-handle":t.id,"data-selection-custom-handle-type":t.type,"data-selection-custom-handle-id":t.id,x:n-.8*o,y:r-.8*i,width:2.6*o,height:2.6*i,fill:"transparent",style:{cursor:t.cursor??"grab",pointerEvents:"auto"}}),"corner"===h.kind?l("polyline",{points:h.points,...p}):l("line",{x1:h.x1,y1:h.y1,x2:h.x2,y2:h.y2,...p})]})}function ah(t,e){return`${t},${e}`}function lh(t){return Number.isFinite(t)?Number(t.toFixed(2)).toString():"0"}function ch(t,e,n){const r=t.shapes.computeLocalToPageTransform(e).invert().applyToPoint(n);return r.x>=0&&r.y>=0&&r.x<=e.props.w&&r.y<=e.props.h}var dh=Ae("plugin-image.api");function uh({editor:t}){return function({editor:t}){return{getSelectionState(){const e=fh(t);if(!e)return null;const n=t.state.shapeEditingSession.get();return{shapeId:e.id,cornerRadius:pp(e.props.cornerRadius),crop:e.props.crop,cropPreset:Xu(e),isCropping:n?.shapeId===e.id&&Yu(e,n.operationKind),smudge:Rp(t)}},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(ip).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...void 0===e.cornerRadius?{}:{cornerRadius:pp(e.cornerRadius)}}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)},startCrop(e){const n=hh(t,e);return!(!n||n.isLocked)&&(!!t.editing.start({shapeId:n.id,operationKind:Ju(n.id),entryMode:"focusEnd"},"user")&&(function(t,e){const n=ep.get(t)??new Map;ep.set(t,n),n.set(e.id,{...e,props:{...e.props,crop:e.props.crop?{topLeft:{...e.props.crop.topLeft},bottomRight:{...e.props.crop.bottomRight}}:null},meta:{...e.meta}})}(t,n),!0))},finishCrop(){const e=fh(t);if(!e||!mh(t,e))return!1;const n=t.editing.complete("user");return n&&rp(t,e.id),n},cancelCrop(){const e=fh(t);if(!e||!mh(t,e))return!1;const n=t.editing.cancel("user");return n&&rp(t,e.id),n},zoomCrop:e=>ph(t,t=>function({direction:t,shape:e}){const n=Hu(e.props.crop),r=Ku(n),o=Bu("in"===t?.8:1.25,Math.max(Au/n.width,Au/n.height),Math.min(1/n.width,1/n.height)),i=Vu({centerX:r.x,centerY:r.y,width:n.width*o,height:n.height*o});return _u(n,i)?null:{id:e.id,props:{crop:Uu(i)}}}({direction:e,shape:t})),setCropAspectRatio:e=>ph(t,t=>Qu({preset:e,shape:t})),resetCrop:()=>ph(t,e=>function({baselineShape:t,shape:e}){const n=t.x,r=t.y,o=t.props.w,i=t.props.h,s=ju(t.props.crop);return Math.abs(e.x-n)<=Ou&&Math.abs(e.y-r)<=Ou&&Math.abs(e.props.w-o)<=Ou&&Math.abs(e.props.h-i)<=Ou&&(null===e.props.crop&&null===s||null!==e.props.crop&&null!==s&&Math.abs(e.props.crop.topLeft.x-s.topLeft.x)<=Ou&&Math.abs(e.props.crop.topLeft.y-s.topLeft.y)<=Ou&&Math.abs(e.props.crop.bottomRight.x-s.bottomRight.x)<=Ou&&Math.abs(e.props.crop.bottomRight.y-s.bottomRight.y)<=Ou)?null:{id:e.id,x:n,y:r,props:{w:o,h:i,crop:s}}}({baselineShape:np(t,e.id)??e,shape:e})),smudge:{start(e){const n=hh(t,e?.shapeId);return!!n&&!!n.props.assetId&&!n.isLocked&&Cp({brush:e?.brush,editor:t,shape:n})},setBrush:e=>Np(t,e),cancel(){Ep(t)},undo:()=>Lp(t),redo:()=>$p(t),getSnapshot:()=>Rp(t)}}}({editor:t})}function ph(t,e){const n=fh(t);if(!n||n.isLocked||!mh(t,n))return!1;const r=e(n);return!!r&&(t.commands.updateShapes([r],{source:"user"}),!0)}function hh(t,e){const n=e?t.shapes.get(e):t.state.selectedShapes.get()[0];return ip(n)?n:null}function fh(t){return 1===t.selection.getIds().length?hh(t):null}function mh(t,e){const n=t.state.shapeEditingSession.get();return n?.shapeId===e.id&&Yu(e,n.operationKind)}var gh={id:"image",editor:Zp(),render:eh(),api:dh,setup:({editor:t})=>({api:uh({editor:t})})},yh=Ae("image.host-api");async function xh(t){const e=new Uint8Array(await t.arrayBuffer());let n="";for(let r=0;r<e.length;r+=32768)n+=String.fromCharCode(...e.subarray(r,r+32768));return`data:${t.type||"application/octet-stream"};base64,${btoa(n)}`}var wh="blobs",bh=null;function vh(){return"undefined"==typeof indexedDB?Promise.resolve(null):(bh||(bh=new Promise((t,e)=>{const n=indexedDB.open("land.plugin-image",1);n.addEventListener("upgradeneeded",()=>{n.result.objectStoreNames.contains(wh)||n.result.createObjectStore(wh)}),n.addEventListener("success",()=>{const e=n.result;e.addEventListener("versionchange",()=>{e.close(),bh=null}),t(e)}),n.addEventListener("error",()=>{bh=null,e(n.error)})})),bh)}var kh="image-blob:";function Sh(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?`${kh}${crypto.randomUUID()}`:`${kh}${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}async function Ph(t){const e=Sh();if("undefined"==typeof indexedDB)throw new Error("IndexedDB is not available for image storage.");return await async function(t,e){const n=await vh();n&&await new Promise((r,o)=>{const i=n.transaction(wh,"readwrite");i.addEventListener("complete",()=>r()),i.addEventListener("abort",()=>o(i.error)),i.addEventListener("error",()=>o(i.error)),i.objectStore(wh).put(e,t)})}(e,t),{storageKey:e}}async function Mh(t){const e=await async function(t){const e=await vh();return e?new Promise((n,r)=>{const o=e.transaction(wh,"readonly").objectStore(wh).get(t);o.addEventListener("success",()=>{n(o.result??null)}),o.addEventListener("error",()=>r(o.error))}):null}(t);return e instanceof Blob?e:null}async function Ih(t){const e=await Mh(t);return e?xh(e):null}async function Th(t){await async function(t){const e=await vh();e&&await new Promise((n,r)=>{const o=e.transaction(wh,"readwrite");o.addEventListener("complete",()=>n()),o.addEventListener("abort",()=>r(o.error)),o.addEventListener("error",()=>r(o.error)),o.objectStore(wh).delete(t)})}(t)}async function Ch(){return(await async function(){const t=await vh();return t?new Promise((e,n)=>{const r=t.transaction(wh,"readonly").objectStore(wh).getAllKeys();r.addEventListener("success",()=>e([...r.result])),r.addEventListener("error",()=>n(r.error))}):null}())?.map(String)??[]}function Eh(t,e){const n=t.assets.get(e);if(!op(n)||"local"!==n.props.source.kind)return null;const{storageKey:r}=n.props.source;return r.length>0?r:null}function Ah(t,e){const n=t.assets.get(e);return op(n)&&"remote"===n.props.source.kind&&n.props.source.url.length>0?n.props.source.url:null}function Oh(t){const e=new Set;for(const n of t.assets.getAll())op(n)&&"local"===n.props.source.kind&&n.props.source.storageKey.length>0&&e.add(n.props.source.storageKey);return e}async function Nh({editor:t,objectUrls:e}){const n=Oh(t),r=await Ch(),o=[];for(const i of r)n.has(i)||(e?.release(i),await Th(i),o.push(i));return o}function Rh(){const t=new Map,e=new Map;let n=0,r=!1;const o=async(o,i={})=>{if(i.signal?.throwIfAborted(),r)return null;const s=t.get(o);if(s)return s;const a=e.get(o);if(a)return a;const l=n,c=Mh(o).then(e=>{if(i.signal?.throwIfAborted(),!e||r||l!==n)return null;const s=URL.createObjectURL(e);return t.set(o,s),s}).finally(()=>{e.delete(o)});return e.set(o,c),c};return{async preloadForEditor(t,e={}){e.signal?.throwIfAborted(),await Promise.all(Array.from(Oh(t)).map(t=>o(t,e)))},preload:o,resolve:e=>t.get(e)??null,resolveAssetUrl(e,n){const r=Ah(e,n);if(r)return r;const o=Eh(e,n);return o?t.get(o)??null:null},release(n){const r=t.get(n);r&&(URL.revokeObjectURL(r),t.delete(n)),e.delete(n)},releaseAll(){r=!0,n+=1;for(const e of t.values())URL.revokeObjectURL(e);t.clear(),e.clear()}}}function Lh(){const t=Rh(),e={objectUrls:t,async cleanupAfterRestore(e,{signal:n}){n.throwIfAborted(),await Nh({editor:e,objectUrls:t}),n.throwIfAborted()},preloadForEditor:(e,{signal:n})=>t.preloadForEditor(e,{signal:n}),resolveAssetUrl:(e,n)=>t.resolveAssetUrl(e,n)};return{value:e,dispose(){e.objectUrls.releaseAll()}}}function $h(t,{signal:e}={}){return e?.throwIfAborted(),new Promise((n,r)=>{const o=new Image,i=()=>{o.removeEventListener("load",s),o.removeEventListener("error",a),e?.removeEventListener("abort",l)},s=()=>{i(),n({width:o.naturalWidth||o.width,height:o.naturalHeight||o.height})},a=()=>{i(),r(new Error("Could not decode image file."))},l=()=>{i(),r(e?.reason)};o.addEventListener("load",s),o.addEventListener("error",a),e?.addEventListener("abort",l,{once:!0}),o.src=t,e?.aborted&&l()})}async function Dh(t,{signal:e}={}){e?.throwIfAborted();const n=zh(t)?t:t.blob,r=(zh(t),t.name),o=zh(t)?t.type:t.mimeType||t.blob.type,i=URL.createObjectURL(n),s=await $h(i,{signal:e}).finally(()=>{URL.revokeObjectURL(i)});e?.throwIfAborted();const{storageKey:a}=await Ph(n);try{e?.throwIfAborted()}catch(l){try{await Th(a)}catch(c){throw new AggregateError([l,c],"Could not discard an aborted image blob write.")}throw l}return{name:r||"Image",source:{kind:"local",storageKey:a,...!zh(t)&&t.originalUrl?{originalUrl:t.originalUrl}:{}},mimeType:o||"image/png",fileSize:n.size,width:s.width,height:s.height}}async function Bh({name:t,signal:e,url:n}){const r=await $h(n,{signal:e});return{name:t||Fh(n)||"Image",source:{kind:"remote",url:n},mimeType:null,width:r.width,height:r.height}}function zh(t){return"undefined"!=typeof File&&t instanceof File}function Fh(t){try{const e=new URL(t).pathname.split("/").filter(Boolean).at(-1);return e?decodeURIComponent(e):null}catch{return null}}function jh(t){for(const e of t)if(e.type.startsWith("image/"))return e;return null}function Wh({filename:t,url:e}){const n=document.createElement("a");n.href=e,n.download=t,n.click()}async function Hh({blob:t,filename:e}){const n=URL.createObjectURL(t);try{Wh({filename:e,url:n})}finally{window.setTimeout(()=>URL.revokeObjectURL(n),0)}}var _h=1;function Uh(t,e){return t.commands.createAsset({type:"image",props:{w:e.width,h:e.height,name:e.name,source:e.source,mimeType:e.mimeType,fileSize:e.fileSize,isAnimated:"image/gif"===e.mimeType}},{source:"user"})}async function Vh({editor:t,imageObjectUrls:e,pagePoint:n,signal:r,size:o,source:i}){return"file"===i.type?Zh(i.file)?Kh({editor:t,imageObjectUrls:e,input:await Dh(i.file,{signal:r}),pagePoint:n,size:o,signal:r}):null:"blob"===i.type?Zh(i.blob)?Kh({editor:t,imageObjectUrls:e,input:await Dh(i,{signal:r}),pagePoint:n,size:o,signal:r}):null:async function({editor:t,imageObjectUrls:e,pagePoint:n,signal:r,size:o,source:i}){return Kh({editor:t,imageObjectUrls:e,input:await Bh({...i,signal:r}),pagePoint:n,size:o,signal:r,altText:i.altText})}({editor:t,imageObjectUrls:e,source:i,pagePoint:n,size:o,signal:r})}async function Kh({editor:t,imageObjectUrls:e,input:n,pagePoint:r,size:o,signal:i,altText:s}){const a="local"===n.source.kind?n.source.storageKey:null;a&&await e.preload(a,{signal:i}),i.throwIfAborted();let l=null;try{try{const e=Uh(t,n);l=e.id;const i=o??function({height:t,width:e}){const n=Math.min(1,360/Math.max(e,t));return{w:Math.max(24,Math.round(e*n)),h:Math.max(24,Math.round(t*n))}}({width:e.props.w,height:e.props.h}),a=t.state.viewportPageBounds.get(),c=r??a?.center??t.viewport.screenToPage(new O(360,240)),[d]=t.commands.createShapes([{type:"image",x:Math.round(c.x-i.w/2),y:Math.round(c.y-i.h/2),props:{...i,assetId:e.id,crop:null,altText:s??n.name}}],{source:"user"});return d?(t.commands.setSelectedShapeIds([d.id],{source:"user"}),d.id):null}catch(c){throw l&&t.commands.deleteAsset(l,{source:"system"}),c}}catch(c){throw a&&(e.release(a),await Th(a)),c}}async function qh({editor:t,file:e,imageObjectUrls:n,signal:r}){if(!Zh(e))return;const[o]=t.state.selectedShapes.get();if(!ip(o)||o.isLocked)return;const i=await Dh(e,{signal:r});await Yh({editor:t,imageObjectUrls:n,input:i,nextProps:{crop:null,altText:i.name},signal:r,shape:o})}async function Xh({editor:t,imageObjectUrls:e,onError:n}){const[r]=t.state.selectedShapes.get();if(!ip(r)||!r.props.assetId)return;const o=t.assets.get(r.props.assetId);if(!op(o))return;const i="string"==typeof o.props.name&&o.props.name.length>0?o.props.name:"land-image";if("remote"===o.props.source.kind)return void(await async function({filename:t,onError:e,url:n}){try{const e=await fetch(n);if(!e.ok)throw new Error(`Could not download image URL (${e.status}).`);await Hh({blob:await e.blob(),filename:t})}catch(r){e?.(new Error("Could not download remote image; opening URL instead.",{cause:r})),function(t){const e=document.createElement("a");e.href=t,e.rel="noreferrer",e.target="_blank",e.click()}(n)}}({filename:i,onError:n,url:o.props.source.url}));const s=o.props.source.storageKey;if(!s)return;const a=await Mh(s);if(a)return void(await Hh({blob:a,filename:i}));const l=e.resolve(s);l&&Wh({filename:i,url:l})}async function Yh({canCommit:t,editor:e,imageObjectUrls:n,input:r,nextProps:o,shape:i,signal:s}){const a=i.props.assetId,l="local"===r.source.kind?r.source.storageKey:null;try{s.throwIfAborted(),l&&await n.preload(l,{signal:s}),s.throwIfAborted()}catch(c){throw await Jh({imageObjectUrls:n,storageKey:l}),c}try{const s=e.shapes.get(i.id);if(!ip(s)||s.isLocked||s.props.assetId!==a||t&&!t())return await Jh({imageObjectUrls:n,storageKey:l}),null;const d=`image.asset.replace:${i.id}:${_h++}`,u=e.operations.begin({kind:d,label:"image.asset.replace",source:"user",history:"record"});try{const t=Uh(e,r);return e.commands.updateShapes([{id:i.id,props:{assetId:t.id,...o}}],{source:"user"}),a&&!function(t,e){return t.snapshots.getDocument().records.some(t=>"shape"===t.typeName&&t.props.assetId===e)}(e,a)&&e.commands.deleteAsset(a,{source:"user"}),u.commit(),{assetId:t.id,storageKey:l}}catch(c){throw u.isActive&&u.cancel(),c}}catch(c){throw await Jh({imageObjectUrls:n,storageKey:l}),c}}async function Jh({imageObjectUrls:t,storageKey:e}){e&&(t.release(e),await Th(e))}async function Gh(t){try{const e=await fetch(t);if(!e.ok)return null;const n=await e.blob();return Zh(n)?n:null}catch{return null}}function Zh(t){return!t.type||t.type.startsWith("image/")}var Qh=new WeakSet;async function tf({editor:t,imageObjectUrls:e,replace:n=!0,signal:r}){r.throwIfAborted();const o=Rp(t);if(!o)return null;const i=zp(o.strokes);if(0===i.length)return Ap(t),null;if(Qh.has(o))return null;Qh.add(o);try{return await async function({editor:t,imageObjectUrls:e,replace:n,session:r,signal:o,strokes:i}){o.throwIfAborted();const s=t.shapes.get(r.shapeId);if(!ip(s)||s.isLocked||!s.props.assetId)return null;const a=t.assets.get(s.props.assetId);if(!op(a))return null;const l=s.props.assetId,c=await async function({asset:t,imageObjectUrls:e}){if("remote"===t.props.source.kind)return Gh(t.props.source.url);const n=t.props.source.storageKey,r=await Mh(n);if(r)return r;const o=e.resolve(n);return o?Gh(o):null}({asset:a,imageObjectUrls:e});if(o.throwIfAborted(),!c)return null;if(!ef(t,r,l,s)||t.assets.get(l)!==a)return null;const{imageBlob:d,maskBlob:u,height:p,width:h}=await async function({crop:t,shape:e,signal:n,sourceBlob:r,strokes:o}){n.throwIfAborted();const i=await async function(t){if("function"==typeof createImageBitmap){const e=await createImageBitmap(t);return{source:e,width:e.width,height:e.height,dispose(){e.close()}}}const e=URL.createObjectURL(t),n=new Image;n.decoding="async",n.src=e,"function"==typeof n.decode?await n.decode():await new Promise((t,e)=>{n.onload=()=>t(),n.onerror=()=>e(new Error("Could not decode image."))});return{source:n,width:n.naturalWidth||n.width,height:n.naturalHeight||n.height,dispose(){URL.revokeObjectURL(e)}}}(r);try{n.throwIfAborted();const r=i.width,s=i.height,a=nf(r,s);a.context.drawImage(i.source,0,0,r,s),rf({context:a.context,crop:t,imageHeight:s,imageWidth:r,mask:!1,shape:e,strokes:o});const l=nf(r,s);rf({context:l.context,crop:t,imageHeight:s,imageWidth:r,mask:!0,shape:e,strokes:o});const c=await a.toBlob("image/png");n.throwIfAborted();const d=await l.toBlob("image/png");return n.throwIfAborted(),{imageBlob:c,maskBlob:d,width:r,height:s}}finally{i.dispose()}}({crop:s.props.crop,shape:s,signal:o,sourceBlob:c,strokes:i});if(o.throwIfAborted(),!ef(t,r,l,s)||t.assets.get(l)!==a)return null;const f={shapeId:s.id,sourceAssetId:l,imageBlob:d,maskBlob:u,width:h,height:p,crop:s.props.crop?{topLeft:{...s.props.crop.topLeft},bottomRight:{...s.props.crop.bottomRight}}:null,strokes:i};if(n){o.throwIfAborted();const n=await async function({blob:t,canCommit:e,editor:n,imageObjectUrls:r,name:o,shape:i,signal:s}){s.throwIfAborted();const a=await Dh({blob:t,name:o},{signal:s});return s.throwIfAborted(),Yh({editor:n,imageObjectUrls:r,input:a,nextProps:{},shape:i,canCommit:e,signal:s})}({blob:d,canCommit:()=>!o.aborted&&ef(t,r,l,s)&&t.assets.get(l)===a,editor:t,imageObjectUrls:e,name:af(a.props.name),shape:s,signal:o});if(o.throwIfAborted(),!n)return null;if(!ef(t,r,n.assetId,s)){const o=Rp(t),i=t.shapes.get(r.shapeId);return o?.shapeId===r.shapeId&&ip(i)&&i.props.assetId===n.assetId&&Ep(t),await async function({assetId:t,editor:e,imageObjectUrls:n,storageKey:r}){if(!r||t&&e.assets.get(t))return;n.release(r),await Th(r)}({assetId:n.assetId,editor:t,imageObjectUrls:e,storageKey:n.storageKey}),null}return o.throwIfAborted(),Ap(t),f}return o.throwIfAborted(),Ap(t),f}({editor:t,imageObjectUrls:e,replace:n,session:o,signal:r,strokes:i})}finally{Qh.delete(o)}}function ef(t,e,n,r){if(Rp(t)!==e)return!1;const o=t.shapes.get(e.shapeId);return ip(o)&&!o.isLocked&&o.props.assetId===n&&function(t,e){if(t.props.w!==e.props.w||t.props.h!==e.props.h)return!1;const n=t.props.crop,r=e.props.crop;return n&&r?n.topLeft.x===r.topLeft.x&&n.topLeft.y===r.topLeft.y&&n.bottomRight.x===r.bottomRight.x&&n.bottomRight.y===r.bottomRight.y:n===r}(o,r)}function nf(t,e){if("undefined"!=typeof OffscreenCanvas){const n=new OffscreenCanvas(t,e),r=n.getContext("2d");if(!r)throw new Error("Could not create image smudge canvas context.");return{context:r,toBlob:t=>n.convertToBlob({type:t})}}const n=document.createElement("canvas");n.width=t,n.height=e;const r=n.getContext("2d");if(!r)throw new Error("Could not create image smudge canvas context.");return{context:r,toBlob:t=>new Promise((e,r)=>{n.toBlob(t=>{t?e(t):r(new Error("Could not encode image smudge canvas."))},t)})}}function rf({context:t,crop:e,imageHeight:n,imageWidth:r,mask:o,shape:i,strokes:s}){if(0===s.length)return;const a=Hu(e),l={x:a.left*r,y:a.top*n,w:a.width*r,h:a.height*n},c=l.w/i.props.w,d=l.h/i.props.h,u=(Math.abs(c)+Math.abs(d))/2;t.save(),t.beginPath(),t.rect(l.x,l.y,l.w,l.h),t.clip(),t.lineCap="round",t.lineJoin="round";for(const p of s){const e=p.points[0];if(!e)continue;const n=sf(p.brush.opacity),r=Math.max(1,p.brush.size*u),i=p.brush.color??"#ffff00";t.globalAlpha=n,t.strokeStyle=o?"#ffffff":i,t.fillStyle=o?"#ffffff":i,t.lineWidth=r;const s=of({cropPixelRect:l,point:e,scaleX:c,scaleY:d});if(1!==p.points.length){t.beginPath(),t.moveTo(s.x,s.y);for(const e of p.points.slice(1)){const n=of({cropPixelRect:l,point:e,scaleX:c,scaleY:d});t.lineTo(n.x,n.y)}t.stroke()}else t.beginPath(),t.arc(s.x,s.y,r/2,0,2*Math.PI),t.fill()}t.restore()}function of({cropPixelRect:t,point:e,scaleX:n,scaleY:r}){return{x:t.x+e.x*n,y:t.y+e.y*r}}function sf(t){return"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):.45}function af(t){const e=t.trim();if(!e)return"Image smudged.png";const n=e.lastIndexOf(".");return n<=0?`${e} smudged.png`:`${e.slice(0,n)} smudged.png`}function lf({editor:t,imageAssetService:e,imageApi:n,onError:r,tasks:o}){let i,s=!1;const a=cf(t=>i.insert({source:{type:"file",file:t}}),r),l=cf(t=>i.replaceSelection({file:t}),r),c={start:t=>n.smudge.start(t),setBrush:t=>n.smudge.setBrush(t),cancel(){n.smudge.cancel()},confirm:n=>o.run(async r=>{const o=await tf({editor:t,imageObjectUrls:e.objectUrls,replace:n?.replace??!0,signal:r});return r.throwIfAborted(),o}),isActive:()=>null!==n.smudge.getSnapshot()};i={openInsertFilePicker(){a.open()},openReplaceFilePicker(){l.open()},insert:({source:n,pagePoint:r,size:i})=>o.run(async o=>{o.throwIfAborted();const s=await Vh({editor:t,imageObjectUrls:e.objectUrls,source:n,pagePoint:r,size:i,signal:o});return o.throwIfAborted(),s}),replaceSelection:({file:n})=>o.run(async r=>{if(!n.type.startsWith("image/"))return!1;const[o]=t.state.selectedShapes.get();return!(!ip(o)||o.isLocked)&&(await qh({editor:t,file:n,imageObjectUrls:e.objectUrls,signal:r}),r.throwIfAborted(),!0)}),downloadSelectionOriginal:()=>o.run(async n=>{await Xh({editor:t,imageObjectUrls:e.objectUrls,onError:r}),n.throwIfAborted()}),smudge:c};const d=Dp(t,t=>c.confirm(t));return{value:i,dispose(){s||(s=!0,a.dispose(),l.dispose(),d())}}}function cf(t,e){let n=null,r=!1;return{open(){if(!r){if(!globalThis.document)throw new Error("Image file selection requires a browser document.");n??=function(){const n=document.createElement("input");return n.type="file",n.accept="image/*",n.hidden=!0,n.onchange=()=>{const o=n.files?.[0]??null;n.value="",o&&!r&&t(o).catch(t=>{e?.(new Error("Image file selection failed.",{cause:t}))})},n}(),n.click()}},dispose(){r=!0,n&&(n.onchange=null),n=null}}}function df(t){return{kind:"svg-inliner",id:"image.svg-inliner",async prepare({editor:e,requestedShapeIds:n}){const r=uf(e,e.layers.getExportTraversalIds(n).flatMap(t=>{const n=e.shapes.get(t);return n?[n]:[]})),o=new Set;for(const i of r.values()){if("local"!==i.props.source.kind)continue;const{storageKey:e}=i.props.source;if(!o.has(e)&&(o.add(e),0===e.length||!(await t.objectUrls.preload(e))))throw new Error(`Could not load image asset "${i.id}".`)}},async inline({editor:e,exportedShapes:n,svg:r}){let o=r;const i=uf(e,n),s=new Set;for(const a of i.values()){const e=hf(a,t);if(!e)throw new Error(`Could not resolve image asset "${a.id}".`);if(s.has(e))continue;const n=await pf(a,e);if(n.href===n.dataUrl){s.add(e);continue}const r=`href="${ff(n.href)}"`;if(!o.includes(r))throw new Error(`Could not find image asset "${a.id}" in the generated SVG.`);o=o.split(r).join(`href="${n.dataUrl}"`),s.add(e)}return o}}}function uf(t,e){const n=new Map;for(const r of e){if(!ip(r)||!r.props.assetId)continue;const e=t.assets.get(r.props.assetId);if(!op(e))throw new Error(`Image asset "${r.props.assetId}" is unavailable.`);n.set(e.id,e)}return n}async function pf(t,e){const{source:n}=t.props;if("local"===n.kind){const r=await Ih(n.storageKey);if(!r)throw new Error(`Could not embed local image asset "${t.id}".`);return{href:e,dataUrl:r}}if(e.startsWith("data:"))return{href:e,dataUrl:e};let r;try{r=await fetch(e)}catch(i){throw new Error(`Could not download image asset "${t.id}".`,{cause:i})}if(!r.ok)throw new Error(`Could not download image asset "${t.id}" (${r.status}).`);const o=await xh(await r.blob());if(!o)throw new Error(`Could not embed remote image asset "${t.id}".`);return{href:e,dataUrl:o}}function hf(t,e){return"local"===t.props.source.kind?e.objectUrls.resolve(t.props.source.storageKey):t.props.source.url}function ff(t){return t.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function mf(t={}){return{id:"image.host",requires:[gh],api:yh,setup({apis:e,editor:n,tasks:r}){const o=(t.createAssetService??Lh)();let i=null;try{const s=lf({editor:n,imageApi:e.require(dh),imageAssetService:o.value,onError:t.onError,tasks:r});return i=s.dispose,{api:s.value,imports:[{id:"image.host-import",order:100,acceptsPreview:t=>t.fileTypes.some(t=>t.startsWith("image/"))||t.dataTypes.some(t=>{const e=t.toLowerCase();return"files"===e||"text/uri-list"===e}),accepts:t=>null!==jh(t.files)||(t.urls?.some(gf)??!1),async import(t){const e=jh(t.files),n=t.urls?.find(gf);return(e||n)&&await s.value.insert({source:e?{type:"file",file:e}:{type:"url",url:n},pagePoint:t.pagePoint})?"handled":"ignored"}}],assetResolvers:[{id:"image.host.asset-resolver",resolve:t=>o.value.resolveAssetUrl(n,t),preload:({signal:t})=>o.value.preloadForEditor(n,{signal:t}),cleanupAfterRestore:({signal:t})=>o.value.cleanupAfterRestore(n,{signal:t})}],exports:[df(o.value)],dispose(){i?.(),o.dispose()}}}catch(s){throw i?.(),o.dispose(),s}}}}function gf(t){return t.startsWith("data:image/")||/\.(?:avif|bmp|gif|jpe?g|png|svg|webp)(?:[?#].*)?$/i.test(t)}var yf="land:",xf="shape";function wf(t){const e=t.trim();if(!e)return null;const n=function(t){return/^[a-z][a-z0-9+.-]*:/i.test(t)}(e)?e:`https://${e}`;return bf(n)?n:null}function bf(t){return null!==Sf(t)||vf(t)}function vf(t){try{const e=new URL(t);return"http:"===e.protocol||"https:"===e.protocol||"mailto:"===e.protocol}catch{return!1}}function kf(t){return`${yf}//${xf}/${encodeURIComponent(t)}`}function Sf(t){try{const e=new URL(t);if(e.protocol!==yf||e.hostname!==xf||e.username||e.password||e.port||e.search||e.hash||!e.pathname.startsWith("/"))return null;const n=decodeURIComponent(e.pathname.slice(1));return n.startsWith("shape:")&&n.length>6?n:null}catch{return null}}function Pf({href:t,openExternal:e,openInternal:n}){const r=Sf(t);r?n?.(r):vf(t)&&e(t)}var Mf=/[;{}<>\u0000-\u001f\u007f]/u,If=/(?:url|expression)\s*\(|!\s*important|@\s*import|javascript\s*:/iu,Tf=/^((?:\d+(?:\.\d{1,3})?)|(?:\.\d{1,3}))(px|em|rem|%)?$/iu;function Cf(t){return{type:"doc",content:t.split("\n").map(t=>({type:"paragraph",content:t.length>0?[{type:"text",text:t}]:[]}))}}function Ef(t){return t.content.map(t=>$f(t)).join("\n")}function Af(t){if(!t||"object"!=typeof t)return Cf("");const e=t,n=Array.isArray(e.content)?e.content.map(t=>Wf(t,0)).filter(t=>null!==t):[];return{type:"doc",attrs:Yf(e.attrs),content:n}}function Of(t){return"text"===t.type&&"string"==typeof t.text}function Nf(t){if("paragraph"===t.type)return Xf(t.attrs?.textAlign)}function Rf(t,e){const n=t?.some(t=>"code"===t.type)?void 0:e;if(!(t&&0!==t.length||n))return;const r=n?{backgroundColor:n}:{},o=new Set;for(const i of t??[])switch(i.type){case"bold":case"strong":r.fontWeight=700;break;case"italic":case"em":r.fontStyle="italic";break;case"strike":case"s":o.add("line-through");break;case"underline":case"u":o.add("underline");break;case"textStyle":{const t=Uf(i.attrs);void 0!==t?.color&&(r.color=t.color),void 0!==t?.backgroundColor&&(r.backgroundColor=t.backgroundColor),void 0!==t?.fontFamily&&(r.fontFamily=t.fontFamily),void 0!==t?.fontSize&&(r.fontSize=t.fontSize),void 0!==t?.lineHeight&&(r.lineHeight=t.lineHeight);break}}return o.size>0&&(r.textDecorationLine=["line-through","underline"].filter(t=>o.has(t)).join(" ")),Object.keys(r).length>0?r:void 0}function Lf(t){if(t&&0!==t.length)for(const e of t){if("link"!==e.type)continue;const t=e.attrs?.href;return"string"==typeof t?t:void 0}}function $f(t){return Of(t)?t.text:t.content?.map(t=>$f(t)).join("")??""}function Df(t){const e=[];return void 0!==t.color&&e.push(`color:${t.color}`),void 0!==t.backgroundColor&&e.push(`background-color:${t.backgroundColor}`),void 0!==t.fontFamily&&e.push(`font-family:${t.fontFamily}`),void 0!==t.fontSize&&e.push(`font-size:${t.fontSize}`),void 0!==t.fontWeight&&e.push(`font-weight:${String(t.fontWeight)}`),void 0!==t.fontStyle&&e.push(`font-style:${t.fontStyle}`),void 0!==t.lineHeight&&e.push(`line-height:${t.lineHeight}`),void 0!==t.textDecorationLine&&e.push(`text-decoration-line:${t.textDecorationLine}`),e.join(";")}function Bf(t){const e=t.content?.map(t=>function(t){if(Of(t)){const e=Rf(t.marks),n=Lf(t.marks),r=zf(t.text),o=e?`<span style="${Ff(Df(e))}">${r}</span>`:r;return n&&vf(n)?`<a href="${Ff(n)}" target="_blank" rel="noopener noreferrer">${o}</a>`:e?o:r}return"hardBreak"===t.type?"<br>":Bf(t)}(t)).join("")??"";if("bulletList"===t.type)return`<ul style="margin:0;padding-inline-start:1.5em;list-style-type:disc">${e}</ul>`;if("orderedList"===t.type)return`<ol style="margin:0;padding-inline-start:1.5em;list-style-type:decimal">${e}</ol>`;if("listItem"===t.type)return`<li>${e}</li>`;if("blockquote"===t.type)return`<blockquote style="margin:0;padding-inline-start:0.75em;border-inline-start:2px solid currentColor">${e}</blockquote>`;const n=Nf(t);return`<p style="${n?`margin:0;text-align:${n}`:"margin:0"}">${e.length>0?e:"<br>"}</p>`}function zf(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Ff(t){return zf(t).replaceAll('"',"&quot;")}function jf(t,e){if(!t||"object"!=typeof t||e>8)return null;const n=t;if("text"===n.type){const t=function(t){return{type:"text",text:"string"==typeof t.text?t.text:"",marks:Array.isArray(t.marks)?t.marks.map(Hf).filter(t=>null!==t):void 0}}(n);return t.text.length>0?t:null}return Wf(n,e)}function Wf(t,e){if(!t||"object"!=typeof t)return null;const n=t,r="string"==typeof n.type?n.type:"paragraph",o=Array.isArray(n.content)?n.content.map(t=>jf(t,e+1)).filter(t=>null!==t):[];return{type:r,attrs:_f(r,n.attrs),content:o}}function Hf(t){if(!t||"object"!=typeof t)return null;const e=t;if("string"!=typeof e.type)return null;if("link"===e.type){const t=Yf(e.attrs),n=t?.href;return"string"==typeof n&&bf(n)?{type:"link",attrs:{...t,href:n}}:null}if("textStyle"===e.type){const t=Uf(e.attrs);return t?{type:"textStyle",attrs:t}:null}return{type:e.type,attrs:Yf(e.attrs)}}function _f(t,e){const n=Yf(e);if("paragraph"!==t)return n;const r={...n};delete r.textAlign;const o=e&&"object"==typeof e&&!Array.isArray(e)?Xf(e.textAlign):void 0;return void 0!==o&&(r.textAlign=o),Object.keys(r).length>0?r:void 0}function Uf(t){if(!t||"object"!=typeof t||Array.isArray(t))return;const e=t,n={color:Vf(e.color,128),backgroundColor:Vf(e.backgroundColor,128),fontFamily:Vf(e.fontFamily,256),fontSize:Kf(e.fontSize),lineHeight:qf(e.lineHeight)},r=Object.entries(n).filter(t=>void 0!==t[1]);return r.length>0?Object.fromEntries(r):void 0}function Vf(t,e){if("string"!=typeof t)return;const n=t.trim();return 0===n.length||n.length>e||Mf.test(n)||If.test(n)?void 0:n}function Kf(t){const e="string"==typeof t?Tf.exec(t.trim()):null;if(!e||"px"!==e[2]?.toLowerCase())return;const n=Number(e[1]);return n>=1&&n<=512?`${String(n)}px`:void 0}function qf(t){const e="string"==typeof t?Tf.exec(t.trim()):null;if(!e)return;const n=Number(e[1]),r=e[2]?.toLowerCase()??"";return("px"===r?n>=1&&n<=1024:"%"===r?n>=50&&n<=1e3:n>=.5&&n<=10)?`${String(n)}${r}`:void 0}function Xf(t){return"left"===t||"center"===t||"right"===t?t:void 0}function Yf(t){if(!t||"object"!=typeof t)return;const e=Object.entries(t).map(([t,e])=>[t,Jf(e)]).filter(t=>void 0!==t[1]);return e.length>0?Object.fromEntries(e):void 0}function Jf(t,e=0){if(null===t||"string"==typeof t||"number"==typeof t||"boolean"==typeof t)return t;if(!(e>8)){if(Array.isArray(t))return t.map(t=>Jf(t,e+1)).filter(t=>void 0!==t);if(t&&"object"==typeof t){const n=Object.entries(t).map(([t,n])=>[t,Jf(n,e+1)]).filter(t=>void 0!==t[1]);return Object.fromEntries(n)}}}function Gf(t){return C(t)&&"text"===t.type}function Zf(t){return{richText:t.richText,w:t.w,h:t.h,autoSize:t.autoSize,scale:t.scale,font:t.font,size:t.size,color:t.color,backgroundColor:t.backgroundColor,textAlign:t.textAlign}}function Qf(t){return Zf(t.shapes.getDefaultProps("text"))}function tm(t,e,n="user"){const r={...Qf(t),...e.props,richText:e.props?.richText??Cf("")},[o]=t.commands.createShapes([{type:"text",x:e.x,y:e.y,parentId:e.parentId,index:e.index,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,meta:e.meta,props:{richText:r.richText,w:r.w,h:r.h,autoSize:r.autoSize,scale:r.scale,font:r.font,size:r.size,color:r.color,backgroundColor:r.backgroundColor,textAlign:r.textAlign}}],{source:n});if(!Gf(o))throw new Error("Failed to create text shape");return o}function em(t,e,n,r,o="user"){const i=t.shapes.get(e);Gf(i)&&t.commands.updateShapes([{id:i.id,props:{richText:n,..."number"==typeof r?.w?{w:r.w}:null,..."number"==typeof r?.h?{h:r.h}:null}}],{source:o})}var nm="path-label",rm="geo-label",om={[nm]:{selectionTarget:"owner",hoverTarget:"owner",hoverDecorationTarget:"owner",translateTarget:"owner",canSnap:!1,canReceiveTerminalBinding:!1,contributesToSelectionFrame:!0,canUseSelectionResizeHandles:!1,canUseSelectionRotateHandle:!1,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!0},[rm]:{selectionTarget:"owner",hoverTarget:"owner",hoverDecorationTarget:"label",translateTarget:"owner",canSnap:!1,canReceiveTerminalBinding:!1,contributesToSelectionFrame:!1,canUseSelectionResizeHandles:!0,canUseSelectionRotateHandle:!0,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!1}};function im(t,e){return t?Math.min(t.paddingInline,Math.max(0,(e-1)/2)):0}function sm(t,e){return et(t.shapes.computeLocalToPageTransform(e),t.shapes.computeLocalBounds(e),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY})?.rotation??e.rotation}function am(t,e,n,r){const o=t.shapes.getUtil(e),i=et(t.shapes.computeLocalToPageTransform(e),t.shapes.computeLocalBounds(e),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY});if(!i)return null;const s={...e,...i,x:r.x,y:r.y,rotation:r.rotation,props:o.validateProps({...e.props,...r.props})},a=n.startsWith("shape:")?t.shapes.get(n):null;if(n.startsWith("shape:")&&!a)return null;const l=(a?t.shapes.computeLocalToPageTransform(a):J.Identity()).tryInvert();return l?et(l.compose(o.getLocalTransform(s)),o.getLocalBounds(s),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY}):null}function lm(t,e,n){const r=t.bindings.getToShape(e).find(t=>t.type===n);if(!r)return null;const o=t.shapes.get(r.fromId);return Gf(o)?o:null}function cm(t,e){const n={...Qf(t),...e.layout.props,autoSize:!1,textAlign:"middle"},r=am(t,{id:"shape:draft-label",typeName:"shape",scope:"document",type:"text",parentId:e.owner.parentId,index:e.index,x:0,y:0,rotation:0,scaleX:1,scaleY:1,opacity:1,isHidden:!1,isLocked:!1,meta:{},props:n},e.owner.parentId,e.layout);if(!r)return null;const o=t.operations.begin({kind:e.operationKind,label:"shape.create",source:"user",history:"record"});try{const o=tm(t,{x:r.x,y:r.y,parentId:e.owner.parentId,index:e.index,rotation:r.rotation,scaleX:r.scaleX,scaleY:r.scaleY,props:n},"user");return t.commands.createBinding({type:e.bindingType,fromId:o.id,toId:e.owner.id,props:e.bindingProps},{source:"user"}),o}catch(i){throw o.cancel(),i}}function dm(t,e){const n=t.shapes.get(e);if(!Gf(n))return null;const r=t.bindings.getFromShape(e).find(t=>t.type in om);if(!r)return null;const o=r.type;return{label:n,ownerId:r.toId,bindingType:o,behavior:om[o]}}function um(t,e,n,r){if("path-label"===r)return{minWidth:24,maxWidth:120,paddingInline:4.25};const o=Math.max(.01,e.props.scale),i=t.shapes.computeLocalBounds(n),s="geo"===n.type?n.props.kind:null,a="summary"===s||"summary-left"===s?.75:1;return{minWidth:16,maxWidth:Math.max(16,i.w*a/o),paddingInline:16,normalizedCenterX:"summary-left"===s?1-a/2:a/2}}function pm(t,e){const n=dm(t,e.id);if(!n)return null;const r=t.shapes.get(n.ownerId);return r?um(t,e,r,n.bindingType):null}function hm(t,e,n){t.editing.start({shapeId:e.id,entryMode:n.entryMode??"selectAll",operationKind:n.isExisting?n.editOperationKind:n.createOperationKind,reuseActiveOperation:!n.isExisting},"user")}function fm(t,e={}){const n={offset:0};return t.content.map((t,r)=>(r>0&&(n.offset+=1),mm(t,`block:${r}`,n,e)))}function mm(t,e,n,r){const o="codeBlock"===t.type?void 0:r.defaultBackgroundColor,i=function(t,e,n,r){return t.content?.map((t,o)=>function(t,e,n,r){if(Of(t)){const o=n.offset;n.offset+=t.text.length;const i=function(t,e,n){const r=e+t.length,o=n.searchRanges?.filter(t=>t.from<r&&t.to>e);if(!o||0===o.length)return t;const i=[];let s=0;for(const a of o){const o=Math.max(a.from,e)-e,c=Math.min(a.to,r)-e;o>s&&i.push(t.slice(s,o)),i.push(l("mark",{className:"land-text-search-match","data-active":n.activeSearchRange?.from===a.from&&n.activeSearchRange.to===a.to?"true":void 0,children:t.slice(o,c)},`search:${a.from}:${a.to}:${e}`)),s=c}s<t.length&&i.push(t.slice(s));return i}(t.text,o,r),s=Rf(t.marks,r.defaultBackgroundColor),a=Lf(t.marks);return a&&bf(a)?l("span",{"data-rich-text-link":"true","data-rich-text-link-href":a,onPointerEnter:t=>{r.linkHandlers?.onPointerEnter?.({href:a,element:t.currentTarget})},onPointerLeave:()=>{r.linkHandlers?.onPointerLeave?.()},style:{...s,cursor:r.linkHandlers?"pointer":void 0,pointerEvents:r.linkHandlers?"auto":"none",textDecorationLine:gm(s?.textDecorationLine)},children:i},e):l("span",{style:s,children:i},e)}return"hardBreak"===t.type?l("br",{},e):mm(t,e,n,{...r,defaultBackgroundColor:"codeBlock"===t.type?void 0:r.defaultBackgroundColor})}(t,`${e}:${o}`,n,r))??[]}(t,e,n,{...r,defaultBackgroundColor:o});return"bulletList"===t.type?l("ul",{style:{listStyleType:"disc",margin:0,paddingInlineStart:"1.5em"},children:i},e):"orderedList"===t.type?l("ol",{style:{listStyleType:"decimal",margin:0,paddingInlineStart:"1.5em"},children:i},e):"listItem"===t.type?l("li",{children:i},e):"blockquote"===t.type?l("blockquote",{style:{borderInlineStart:"2px solid currentColor",margin:0,paddingInlineStart:"0.75em"},children:i},e):l("p",{style:{margin:0,textAlign:Nf(t)},children:i.length>0?i:l("br",{})},e)}function gm(t){const e=new Set(t?.split(/\s+/u)??[]);return e.add("underline"),["line-through","underline"].filter(t=>e.has(t)).join(" ")}var ym="default",xm={id:"host-default",label:"Host default",cssFamily:"inherit",source:{kind:"system"}};function wm(){return{defaultFont:xm,defaultFontLabel:"Default",fonts:[]}}function bm(){return vm(wm())}function vm(t){const e=new Map;for(const r of t.fonts)km(r.id)&&"default"!==r.id&&e.set(r.id,r);const n={id:ym,label:t.defaultFontLabel,cssFamily:t.defaultFont.cssFamily,source:t.defaultFont.source};return{defaultFont:t.defaultFont,defaultFontLabel:t.defaultFontLabel,fontOptions:[n,...e.values()],fontsById:e}}function km(t){return"string"==typeof t&&t.trim().length>0}function Sm(t,e){return"default"===e?t.defaultFont:t.fontsById.get(e)??t.defaultFont}var Pm=new WeakMap;function Mm(t,e,n){const r=Sm(e,t),o=n??("undefined"==typeof document?void 0:document);if(!o||!Im(r.source))return Promise.resolve();const i=function(t){const{source:e}=t;return e&&"system"!==e.kind?"stylesheet"===e.kind?`${t.id}:stylesheet:${e.cssUrl}`:`${t.id}:font-face:${e.family}:${String(e.src)}`:t.id}(r),s=function(t){const e=Pm.get(t);if(e)return e;const n=new Map;return Pm.set(t,n),n}(o),a=s.get(i);if(a)return a;const l=async function(t,e){const{source:n}=e;if(!Im(n))return;if("stylesheet"===n.kind)return await function(t,e,n){return Array.from(t.querySelectorAll("link[data-land-text-font]")).find(t=>t.dataset.landTextFont===e.id)?Promise.resolve():new Promise(r=>{const o=t.createElement("link");o.rel="stylesheet",o.href=n.cssUrl,o.dataset.landTextFont=e.id;const i=()=>r();o.addEventListener("load",i,{once:!0}),o.addEventListener("error",i,{once:!0}),(t.head??t.documentElement).appendChild(o)})}(t,e,n),void(await Tm(t,n));await async function(t,e){const{fonts:n}=t,r=t.defaultView?.FontFace;if(!n||!r)return;if(Array.from(n).filter(t=>t.family===e.family&&"loaded"===t.status).length>0)return;const o=await new r(e.family,e.src,e.descriptors).load();n.add(o)}(t,n),await Tm(t,n)}(o,r).catch(()=>{s.delete(i)});return s.set(i,l),l}function Im(t){return!!t&&"system"!==t.kind}async function Tm(t,e){const{fonts:n}=t;if(!n)return;const r=function(t){if(t.weights)return t.weights;if("font-face"===t.kind){const e=t.descriptors?.weight;if("string"==typeof e&&/^\d+$/.test(e))return[Number(e)]}return[400]}(e),o=e.sampleText??"Aa";await Promise.all(r.map(t=>n.load(`${t} 16px "${e.family}"`,o)))}var Cm=T((t,e)=>{e.exports={...d}}),Em=T(t=>{var e=Cm();var n="function"==typeof Object.is?Object.is:function(t,e){return t===e&&(0!==t||1/t==1/e)||t!=t&&e!=e},r=e.useState,o=e.useEffect,i=e.useLayoutEffect,s=e.useDebugValue;function a(t){var e=t.getSnapshot;t=t.value;try{var r=e();return!n(t,r)}catch(o){return!0}}var l="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(t,e){return e()}:function(t,e){var n=e(),l=r({inst:{value:n,getSnapshot:e}}),c=l[0].inst,d=l[1];return i(function(){c.value=n,c.getSnapshot=e,a(c)&&d({inst:c})},[t,n,e]),o(function(){return a(c)&&d({inst:c}),t(function(){a(c)&&d({inst:c})})},[t]),s(n),n};t.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:l}),Am=T(t=>{"production"!==process.env.NODE_ENV&&function(){function e(t){var e=t.getSnapshot;t=t.value;try{var n=e();return!r(t,n)}catch(o){return!0}}"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var n=Cm(),r="function"==typeof Object.is?Object.is:function(t,e){return t===e&&(0!==t||1/t==1/e)||t!=t&&e!=e},o=n.useState,i=n.useEffect,s=n.useLayoutEffect,a=n.useDebugValue,l=!1,c=!1,d="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(t,e){return e()}:function(t,d){l||void 0===n.startTransition||(l=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var u=d();if(!c){var p=d();r(u,p)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),c=!0)}var h=(p=o({inst:{value:u,getSnapshot:d}}))[0].inst,f=p[1];return s(function(){h.value=u,h.getSnapshot=d,e(h)&&f({inst:h})},[t,u,d]),i(function(){return e(h)&&f({inst:h}),t(function(){e(h)&&f({inst:h})})},[t]),a(u),u};t.useSyncExternalStore=void 0!==n.useSyncExternalStore?n.useSyncExternalStore:d,"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()}),Om=T((t,e)=>{"production"===process.env.NODE_ENV?e.exports=Em():e.exports=Am()});function Nm(t){this.content=t}function Rm(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let o=t.child(r),i=e.child(r);if(o!=i){if(!o.sameMarkup(i))return n;if(o.isText&&o.text!=i.text){let t=o.text,e=i.text,r=0;for(;t[r]==e[r];r++)n++;return r&&r<t.length&&r<e.length&&Dm(t.charCodeAt(r-1))&&$m(t.charCodeAt(r))&&n--,n}if(o.content.size||i.content.size){let t=Rm(o.content,i.content,n+1);if(null!=t)return t}n+=o.nodeSize}else n+=o.nodeSize}}function Lm(t,e,n,r){for(let o=t.childCount,i=e.childCount;;){if(0==o||0==i)return o==i?null:{a:n,b:r};let s=t.child(--o),a=e.child(--i),l=s.nodeSize;if(s!=a){if(!s.sameMarkup(a))return{a:n,b:r};if(s.isText&&s.text!=a.text){let t=s.text,e=a.text,o=t.length,i=e.length;for(;o>0&&i>0&&t[o-1]==e[i-1];)o--,i--,n--,r--;return o&&i&&o<t.length&&Dm(t.charCodeAt(o-1))&&$m(t.charCodeAt(o))&&(n++,r++),{a:n,b:r}}if(s.content.size||a.content.size){let t=Lm(s.content,a.content,n-1,r-1);if(t)return t}n-=l,r-=l}else n-=l,r-=l}}function $m(t){return t>=56320&&t<57344}function Dm(t){return t>=55296&&t<56320}Nm.prototype={constructor:Nm,find:function(t){for(var e=0;e<this.content.length;e+=2)if(this.content[e]===t)return e;return-1},get:function(t){var e=this.find(t);return-1==e?void 0:this.content[e+1]},update:function(t,e,n){var r=n&&n!=t?this.remove(n):this,o=r.find(t),i=r.content.slice();return-1==o?i.push(n||t,e):(i[o+1]=e,n&&(i[o]=n)),new Nm(i)},remove:function(t){var e=this.find(t);if(-1==e)return this;var n=this.content.slice();return n.splice(e,2),new Nm(n)},addToStart:function(t,e){return new Nm([t,e].concat(this.remove(t).content))},addToEnd:function(t,e){var n=this.remove(t).content.slice();return n.push(t,e),new Nm(n)},addBefore:function(t,e,n){var r=this.remove(e),o=r.content.slice(),i=r.find(t);return o.splice(-1==i?o.length:i,0,e,n),new Nm(o)},forEach:function(t){for(var e=0;e<this.content.length;e+=2)t(this.content[e],this.content[e+1])},prepend:function(t){return(t=Nm.from(t)).size?new Nm(t.content.concat(this.subtract(t).content)):this},append:function(t){return(t=Nm.from(t)).size?new Nm(this.subtract(t).content.concat(t.content)):this},subtract:function(t){var e=this;t=Nm.from(t);for(var n=0;n<t.content.length;n+=2)e=e.remove(t.content[n]);return e},toObject:function(){var t={};return this.forEach(function(e,n){t[e]=n}),t},get size(){return this.content.length>>1}},Nm.from=function(t){if(t instanceof Nm)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Nm(e)};var Bm=class t{constructor(t,e){if(this.content=t,this.size=e||0,null==e)for(let n=0;n<t.length;n++)this.size+=t[n].nodeSize}nodesBetween(t,e,n,r=0,o){for(let i=0,s=0;s<e;i++){let a=this.content[i],l=s+a.nodeSize;if(l>t&&!1!==n(a,r+s,o||null,i)&&a.content.size){let o=s+1;a.nodesBetween(Math.max(0,t-o),Math.min(a.content.size,e-o),n,r+o)}s=l}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,e,n,r){let o="",i=!0;return this.nodesBetween(t,e,(s,a)=>{let l=s.isText?s.text.slice(Math.max(t,a)-a,e-a):s.isLeaf?r?"function"==typeof r?r(s):r:s.type.spec.leafText?s.type.spec.leafText(s):"":"";s.isBlock&&(s.isLeaf&&l||s.isTextblock)&&n&&(i?i=!1:o+=n),o+=l},0),o}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,o=this.content.slice(),i=0;for(n.isText&&n.sameMarkup(r)&&(o[o.length-1]=n.withText(n.text+r.text),i=1);i<e.content.length;i++)o.push(e.content[i]);return new t(o,this.size+e.size)}cut(e,n=this.size){if(0==e&&n==this.size)return this;let r=[],o=0;if(n>e)for(let t=0,i=0;i<n;t++){let s=this.content[t],a=i+s.nodeSize;a>e&&((i<e||a>n)&&(s=s.isText?s.cut(Math.max(0,e-i),Math.min(s.text.length,n-i)):s.cut(Math.max(0,e-i-1),Math.min(s.content.size,n-i-1))),r.push(s),o+=s.nodeSize),i=a}return new t(r,o)}cutByIndex(e,n){return e==n?t.empty:0==e&&n==this.content.length?this:new t(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let o=this.content.slice(),i=this.size+n.nodeSize-r.nodeSize;return o[e]=n,new t(o,i)}addToStart(e){return new t([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new t(this.content.concat(e),this.size+e.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let e=0;e<this.content.length;e++)if(!this.content[e].eq(t.content[e]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(t){let e=this.content[t];if(!e)throw new RangeError("Index "+t+" out of range for "+this);return e}maybeChild(t){return this.content[t]||null}forEach(t){for(let e=0,n=0;e<this.content.length;e++){let r=this.content[e];t(r,n,e),n+=r.nodeSize}}findDiffStart(t,e=0){return Rm(this,t,e)}findDiffEnd(t,e=this.size,n=t.size){return Lm(this,t,e,n)}findIndex(t){if(0==t)return Fm(0,t);if(t==this.size)return Fm(this.content.length,t);if(t>this.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let e=0,n=0;;e++){let r=n+this.child(e).nodeSize;if(r>=t)return r==t?Fm(e+1,r):Fm(e,n);n=r}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(t=>t.toJSON()):null}static fromJSON(e,n){if(!n)return t.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return t.fromArray(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return t.empty;let n,r=0;for(let t=0;t<e.length;t++){let o=e[t];r+=o.nodeSize,t&&o.isText&&e[t-1].sameMarkup(o)?(n||(n=e.slice(0,t)),n[n.length-1]=o.withText(n[n.length-1].text+o.text)):n&&n.push(o)}return new t(n||e,r)}static from(e){if(!e)return t.empty;if(e instanceof t)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new t([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}};Bm.empty=new Bm([],0);var zm={index:0,offset:0};function Fm(t,e){return zm.index=t,zm.offset=e,zm}function jm(t,e){if(t===e)return!0;if(!t||"object"!=typeof t||!e||"object"!=typeof e)return!1;let n=Array.isArray(t);if(Array.isArray(e)!=n)return!1;if(n){if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!jm(t[n],e[n]))return!1}else{for(let n in t)if(!(n in e)||!jm(t[n],e[n]))return!1;for(let n in e)if(!(n in t))return!1}return!0}var Wm=class t{constructor(t,e){this.type=t,this.attrs=e}addToSet(t){let e,n=!1;for(let r=0;r<t.length;r++){let o=t[r];if(this.eq(o))return t;if(this.type.excludes(o.type))e||(e=t.slice(0,r));else{if(o.type.excludes(this.type))return t;!n&&o.type.rank>this.type.rank&&(e||(e=t.slice(0,r)),e.push(this),n=!0),e&&e.push(o)}}return e||(e=t.slice()),n||e.push(this),e}removeFromSet(t){for(let e=0;e<t.length;e++)if(this.eq(t[e]))return t.slice(0,e).concat(t.slice(e+1));return t}isInSet(t){for(let e=0;e<t.length;e++)if(this.eq(t[e]))return!0;return!1}eq(t){return this==t||this.type==t.type&&jm(this.attrs,t.attrs)}toJSON(){let t={type:this.type.name};for(let e in this.attrs){t.attrs=this.attrs;break}return t}static fromJSON(t,e){if(!e)throw new RangeError("Invalid input for Mark.fromJSON");let n=t.marks[e.type];if(!n)throw new RangeError(`There is no mark type ${e.type} in this schema`);let r=n.create(e.attrs);return n.checkAttrs(r.attrs),r}static sameSet(t,e){if(t==e)return!0;if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!t[n].eq(e[n]))return!1;return!0}static setFrom(e){if(!e||Array.isArray(e)&&0==e.length)return t.none;if(e instanceof t)return[e];let n=e.slice();return n.sort((t,e)=>t.type.rank-e.type.rank),n}};Wm.none=[];var Hm=class extends Error{},_m=class t{constructor(t,e,n){this.content=t,this.openStart=e,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let r=Vm(this.content,e+this.openStart,n,this.openStart+1,this.openEnd+1);return r&&new t(r,this.openStart,this.openEnd)}removeBetween(e,n){return new t(Um(this.content,e+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(e,n){if(!n)return t.empty;let r=n.openStart||0,o=n.openEnd||0;if("number"!=typeof r||"number"!=typeof o)throw new RangeError("Invalid input for Slice.fromJSON");return new t(Bm.fromJSON(e,n.content),r,o)}static maxOpen(e,n=!0){let r=0,o=0;for(let t=e.firstChild;t&&!t.isLeaf&&(n||!t.type.spec.isolating);t=t.firstChild)r++;for(let t=e.lastChild;t&&!t.isLeaf&&(n||!t.type.spec.isolating);t=t.lastChild)o++;return new t(e,r,o)}};function Um(t,e,n){let{index:r,offset:o}=t.findIndex(e),i=t.maybeChild(r),{index:s,offset:a}=t.findIndex(n);if(o==e||i.isText){if(a!=n&&!t.child(s).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=s)throw new RangeError("Removing non-flat range");return t.replaceChild(r,i.copy(Um(i.content,e-o-1,n-o-1)))}function Vm(t,e,n,r,o,i){let{index:s,offset:a}=t.findIndex(e),l=t.maybeChild(s);if(a==e||l.isText)return i&&r<=0&&o<=0&&!i.canReplace(s,s,n)?null:t.cut(0,e).append(n).append(t.cut(e));let c=Vm(l.content,e-a-1,n,0==s?r-1:0,s==t.childCount-1?o-1:0,l);return c&&t.replaceChild(s,l.copy(c))}function Km(t,e,n){if(n.openStart>t.depth)throw new Hm("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new Hm("Inconsistent open depths");return qm(t,e,n,0)}function qm(t,e,n,r){let o=t.index(r),i=t.node(r);if(o==e.index(r)&&r<t.depth-n.openStart){let s=qm(t,e,n,r+1);return i.copy(i.content.replaceChild(o,s))}if(n.content.size){if(n.openStart||n.openEnd||t.depth!=r||e.depth!=r){let{start:o,end:s}=function(t,e){let n=e.depth-t.openStart,r=e.node(n).copy(t.content);for(let o=n-1;o>=0;o--)r=e.node(o).copy(Bm.from(r));return{start:r.resolveNoCache(t.openStart+n),end:r.resolveNoCache(r.content.size-t.openEnd-n)}}(n,t);return Zm(i,Qm(t,o,s,e,r))}{let r=t.parent,o=r.content;return Zm(r,o.cut(0,t.parentOffset).append(n.content).append(o.cut(e.parentOffset)))}}return Zm(i,tg(t,e,r))}function Xm(t,e){if(!e.type.compatibleContent(t.type))throw new Hm("Cannot join "+e.type.name+" onto "+t.type.name)}function Ym(t,e,n){let r=t.node(n);return Xm(r,e.node(n)),r}function Jm(t,e){let n=e.length-1;n>=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function Gm(t,e,n,r){let o=(e||t).node(n),i=0,s=e?e.index(n):o.childCount;t&&(i=t.index(n),t.depth>n?i++:t.textOffset&&(Jm(t.nodeAfter,r),i++));for(let a=i;a<s;a++)Jm(o.child(a),r);e&&e.depth==n&&e.textOffset&&Jm(e.nodeBefore,r)}function Zm(t,e){if(!t.type.validContent(e))throw new Hm("Invalid content for node "+t.type.name);return t.copy(e)}function Qm(t,e,n,r,o){let i=t.depth>o&&Ym(t,e,o+1),s=r.depth>o&&Ym(n,r,o+1),a=[];return Gm(null,t,o,a),i&&s&&e.index(o)==n.index(o)?(Xm(i,s),Jm(Zm(i,Qm(t,e,n,r,o+1)),a)):(i&&Jm(Zm(i,tg(t,e,o+1)),a),Gm(e,n,o,a),s&&Jm(Zm(s,tg(n,r,o+1)),a)),Gm(r,null,o,a),new Bm(a)}function tg(t,e,n){let r=[];return Gm(null,t,n,r),t.depth>n&&Jm(Zm(Ym(t,e,n+1),tg(t,e,n+1)),r),Gm(e,null,n,r),new Bm(r)}_m.empty=new _m(Bm.empty,0,0);var eg=class t{constructor(t,e,n){this.pos=t,this.path=e,this.parentOffset=n,this.depth=e.length/3-1}resolveDepth(t){return null==t?this.depth:t<0?this.depth+t:t}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(t){return this.path[3*this.resolveDepth(t)]}index(t){return this.path[3*this.resolveDepth(t)+1]}indexAfter(t){return t=this.resolveDepth(t),this.index(t)+(t!=this.depth||this.textOffset?1:0)}start(t){return 0==(t=this.resolveDepth(t))?0:this.path[3*t-1]+1}end(t){return t=this.resolveDepth(t),this.start(t)+this.node(t).content.size}before(t){if(!(t=this.resolveDepth(t)))throw new RangeError("There is no position before the top-level node");return t==this.depth+1?this.pos:this.path[3*t-1]}after(t){if(!(t=this.resolveDepth(t)))throw new RangeError("There is no position after the top-level node");return t==this.depth+1?this.pos:this.path[3*t-1]+this.path[3*t].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let t=this.parent,e=this.index(this.depth);if(e==t.childCount)return null;let n=this.pos-this.path[this.path.length-1],r=t.child(e);return n?t.child(e).cut(n):r}get nodeBefore(){let t=this.index(this.depth),e=this.pos-this.path[this.path.length-1];return e?this.parent.child(t).cut(0,e):0==t?null:this.parent.child(t-1)}posAtIndex(t,e){e=this.resolveDepth(e);let n=this.path[3*e],r=0==e?0:this.path[3*e-1]+1;for(let o=0;o<t;o++)r+=n.child(o).nodeSize;return r}marks(){let t=this.parent,e=this.index();if(0==t.content.size)return Wm.none;if(this.textOffset)return t.child(e).marks;let n=t.maybeChild(e-1),r=t.maybeChild(e);if(!n){let t=n;n=r,r=t}let o=n.marks;for(var i=0;i<o.length;i++)!1!==o[i].type.spec.inclusive||r&&o[i].isInSet(r.marks)||(o=o[i--].removeFromSet(o));return o}marksAcross(t){let e=this.parent.maybeChild(this.index());if(!e||!e.isInline)return null;let n=e.marks,r=t.parent.maybeChild(t.index());for(var o=0;o<n.length;o++)!1!==n[o].type.spec.inclusive||r&&n[o].isInSet(r.marks)||(n=n[o--].removeFromSet(n));return n}sharedDepth(t){for(let e=this.depth;e>0;e--)if(this.start(e)<=t&&this.end(e)>=t)return e;return 0}blockRange(t=this,e){if(t.pos<this.pos)return t.blockRange(this);for(let n=this.depth-(this.parent.inlineContent||this.pos==t.pos?1:0);n>=0;n--)if(t.pos<=this.end(n)&&(!e||e(this.node(n))))return new ig(this,t,n);return null}sameParent(t){return this.pos-this.parentOffset==t.pos-t.parentOffset}max(t){return t.pos>this.pos?t:this}min(t){return t.pos<this.pos?t:this}toString(){let t="";for(let e=1;e<=this.depth;e++)t+=(t?"/":"")+this.node(e).type.name+"_"+this.index(e-1);return t+":"+this.parentOffset}static resolve(e,n){if(!(n>=0&&n<=e.content.size))throw new RangeError("Position "+n+" out of range");let r=[],o=0,i=n;for(let t=e;;){let{index:e,offset:n}=t.content.findIndex(i),s=i-n;if(r.push(t,e,o+n),!s)break;if(t=t.child(e),t.isText)break;i=s-1,o+=n+1}return new t(n,r,i)}static resolveCached(e,n){let r=og.get(e);if(r)for(let t=0;t<r.elts.length;t++){let e=r.elts[t];if(e.pos==n)return e}else og.set(e,r=new ng);let o=r.elts[r.i]=t.resolve(e,n);return r.i=(r.i+1)%rg,o}},ng=class{constructor(){this.elts=[],this.i=0}},rg=12,og=new WeakMap,ig=class{constructor(t,e,n){this.$from=t,this.$to=e,this.depth=n}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}},sg=Object.create(null),ag=class t{constructor(t,e,n,r=Wm.none){this.type=t,this.attrs=e,this.marks=r,this.content=n||Bm.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(t){return this.content.child(t)}maybeChild(t){return this.content.maybeChild(t)}forEach(t){this.content.forEach(t)}nodesBetween(t,e,n,r=0){this.content.nodesBetween(t,e,n,r,this)}descendants(t){this.nodesBetween(0,this.content.size,t)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,"")}textBetween(t,e,n,r){return this.content.textBetween(t,e,n,r)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(t){return this==t||this.sameMarkup(t)&&this.content.eq(t.content)}sameMarkup(t){return this.hasMarkup(t.type,t.attrs,t.marks)}hasMarkup(t,e,n){return this.type==t&&jm(this.attrs,e||t.defaultAttrs||sg)&&Wm.sameSet(this.marks,n||Wm.none)}copy(e=null){return e==this.content?this:new t(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new t(this.type,this.attrs,this.content,e)}cut(t,e=this.content.size){return 0==t&&e==this.content.size?this:this.copy(this.content.cut(t,e))}slice(t,e=this.content.size,n=!1){if(t==e)return _m.empty;let r=this.resolve(t),o=this.resolve(e),i=n?0:r.sharedDepth(e),s=r.start(i);return new _m(r.node(i).content.cut(r.pos-s,o.pos-s),r.depth-i,o.depth-i)}replace(t,e,n){return Km(this.resolve(t),this.resolve(e),n)}nodeAt(t){for(let e=this;;){let{index:n,offset:r}=e.content.findIndex(t);if(e=e.maybeChild(n),!e)return null;if(r==t||e.isText)return e;t-=r+1}}childAfter(t){let{index:e,offset:n}=this.content.findIndex(t);return{node:this.content.maybeChild(e),index:e,offset:n}}childBefore(t){if(0==t)return{node:null,index:0,offset:0};let{index:e,offset:n}=this.content.findIndex(t);if(n<t)return{node:this.content.child(e),index:e,offset:n};let r=this.content.child(e-1);return{node:r,index:e-1,offset:n-r.nodeSize}}resolve(t){return eg.resolveCached(this,t)}resolveNoCache(t){return eg.resolve(this,t)}rangeHasMark(t,e,n){let r=!1;return e>t&&this.nodesBetween(t,e,t=>(n.isInSet(t.marks)&&(r=!0),!r)),r}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let t=this.type.name;return this.content.size&&(t+="("+this.content.toStringInner()+")"),cg(this.marks,t)}contentMatchAt(t){let e=this.type.contentMatch.matchFragment(this.content,0,t);if(!e)throw new Error("Called contentMatchAt on a node with invalid content");return e}canReplace(t,e,n=Bm.empty,r=0,o=n.childCount){let i=this.contentMatchAt(t).matchFragment(n,r,o),s=i&&i.matchFragment(this.content,e);if(!s||!s.validEnd)return!1;for(let a=r;a<o;a++)if(!this.type.allowsMarks(n.child(a).marks))return!1;return!0}canReplaceWith(t,e,n,r){if(r&&!this.type.allowsMarks(r))return!1;let o=this.contentMatchAt(t).matchType(n),i=o&&o.matchFragment(this.content,e);return!!i&&i.validEnd}canAppend(t){return t.content.size?this.canReplace(this.childCount,this.childCount,t.content):this.type.compatibleContent(t.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let t=Wm.none;for(let e=0;e<this.marks.length;e++){let n=this.marks[e];n.type.checkAttrs(n.attrs),t=n.addToSet(t)}if(!Wm.sameSet(t,this.marks))throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(t=>t.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let t={type:this.type.name};for(let e in this.attrs){t.attrs=this.attrs;break}return this.content.size&&(t.content=this.content.toJSON()),this.marks.length&&(t.marks=this.marks.map(t=>t.toJSON())),t}static fromJSON(t,e){if(!e)throw new RangeError("Invalid input for Node.fromJSON");let n;if(e.marks){if(!Array.isArray(e.marks))throw new RangeError("Invalid mark data for Node.fromJSON");n=e.marks.map(t.markFromJSON)}if("text"==e.type){if("string"!=typeof e.text)throw new RangeError("Invalid text node in JSON");return t.text(e.text,n)}let r=Bm.fromJSON(t,e.content),o=t.nodeType(e.type).create(e.attrs,r,n);return o.type.checkAttrs(o.attrs),o}};ag.prototype.text=void 0;var lg=class t extends ag{constructor(t,e,n,r){if(super(t,e,null,r),!n)throw new RangeError("Empty text nodes are not allowed");this.text=n}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):cg(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(t,e){return this.text.slice(t,e)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new t(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new t(this.type,this.attrs,e,this.marks)}cut(t=0,e=this.text.length){return 0==t&&e==this.text.length?this:this.withText(this.text.slice(t,e))}eq(t){return this.sameMarkup(t)&&this.text==t.text}toJSON(){let t=super.toJSON();return t.text=this.text,t}};function cg(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}var dg=class t{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new ug(e,n);if(null==r.next)return t.empty;let o=pg(r);r.next&&r.err("Unexpected trailing text");let i=wg(function(t){let e=[[]];return o(i(t,0),n()),e;function n(){return e.push([])-1}function r(t,n,r){let o={term:r,to:n};return e[t].push(o),o}function o(t,e){t.forEach(t=>t.to=e)}function i(t,e){if("choice"==t.type)return t.exprs.reduce((t,n)=>t.concat(i(n,e)),[]);if("seq"!=t.type){if("star"==t.type){let s=n();return r(e,s),o(i(t.expr,s),s),[r(s)]}if("plus"==t.type){let s=n();return o(i(t.expr,e),s),o(i(t.expr,s),s),[r(s)]}if("opt"==t.type)return[r(e)].concat(i(t.expr,e));if("range"==t.type){let s=e;for(let e=0;e<t.min;e++){let e=n();o(i(t.expr,s),e),s=e}if(-1==t.max)o(i(t.expr,s),s);else for(let e=t.min;e<t.max;e++){let e=n();r(s,e),o(i(t.expr,s),e),s=e}return[r(s)]}if("name"==t.type)return[r(e,void 0,t.value)];throw new Error("Unknown expr type")}for(let r=0;;r++){let s=i(t.exprs[r],e);if(r==t.exprs.length-1)return s;o(s,e=n())}}}(o));return function(t,e){for(let n=0,r=[t];n<r.length;n++){let t=r[n],o=!t.validEnd,i=[];for(let e=0;e<t.next.length;e++){let{type:n,next:s}=t.next[e];i.push(n.name),!o||n.isText||n.hasRequiredAttrs()||(o=!1),-1==r.indexOf(s)&&r.push(s)}o&&e.err("Only non-generatable nodes ("+i.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}(i,r),i}matchType(t){for(let e=0;e<this.next.length;e++)if(this.next[e].type==t)return this.next[e].next;return null}matchFragment(t,e=0,n=t.childCount){let r=this;for(let o=e;r&&o<n;o++)r=r.matchType(t.child(o).type);return r}get inlineContent(){return 0!=this.next.length&&this.next[0].type.isInline}get defaultType(){for(let t=0;t<this.next.length;t++){let{type:e}=this.next[t];if(!e.isText&&!e.hasRequiredAttrs())return e}return null}compatible(t){for(let e=0;e<this.next.length;e++)for(let n=0;n<t.next.length;n++)if(this.next[e].type==t.next[n].type)return!0;return!1}fillBefore(t,e=!1,n=0){let r=[this];return function o(i,s){let a=i.matchFragment(t,n);if(a&&(!e||a.validEnd))return Bm.from(s.map(t=>t.createAndFill()));for(let t=0;t<i.next.length;t++){let{type:e,next:n}=i.next[t];if(!e.isText&&!e.hasRequiredAttrs()&&-1==r.indexOf(n)){r.push(n);let t=o(n,s.concat(e));if(t)return t}}return null}(this,[])}findWrapping(t){for(let n=0;n<this.wrapCache.length;n+=2)if(this.wrapCache[n]==t)return this.wrapCache[n+1];let e=this.computeWrapping(t);return this.wrapCache.push(t,e),e}computeWrapping(t){let e=Object.create(null),n=[{match:this,type:null,via:null}];for(;n.length;){let r=n.shift(),o=r.match;if(o.matchType(t)){let t=[];for(let e=r;e.type;e=e.via)t.push(e.type);return t.reverse()}for(let t=0;t<o.next.length;t++){let{type:i,next:s}=o.next[t];i.isLeaf||i.hasRequiredAttrs()||i.name in e||r.type&&!s.validEnd||(n.push({match:i.contentMatch,type:i,via:r}),e[i.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(t){if(t>=this.next.length)throw new RangeError(`There's no ${t}th edge in this content match`);return this.next[t]}toString(){let t=[];return function e(n){t.push(n);for(let r=0;r<n.next.length;r++)-1==t.indexOf(n.next[r].next)&&e(n.next[r].next)}(this),t.map((e,n)=>{let r=n+(e.validEnd?"*":" ")+" ";for(let o=0;o<e.next.length;o++)r+=(o?", ":"")+e.next[o].type.name+"->"+t.indexOf(e.next[o].next);return r}).join("\n")}};dg.empty=new dg(!0);var ug=class{constructor(t,e){this.string=t,this.nodeTypes=e,this.inline=null,this.pos=0,this.tokens=t.split(/\s*(?=\b|\W|$)/),""==this.tokens[this.tokens.length-1]&&this.tokens.pop(),""==this.tokens[0]&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(t){return this.next==t&&(this.pos++||!0)}err(t){throw new SyntaxError(t+" (in content expression '"+this.string+"')")}};function pg(t){let e=[];do{e.push(hg(t))}while(t.eat("|"));return 1==e.length?e[0]:{type:"choice",exprs:e}}function hg(t){let e=[];do{e.push(fg(t))}while(t.next&&")"!=t.next&&"|"!=t.next);return 1==e.length?e[0]:{type:"seq",exprs:e}}function fg(t){let e=function(t){if(t.eat("(")){let e=pg(t);return t.eat(")")||t.err("Missing closing paren"),e}if(!/\W/.test(t.next)){let e=function(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let o=[];for(let i in n){let t=n[i];t.isInGroup(e)&&o.push(t)}0==o.length&&t.err("No node type or group '"+e+"' found");return o}(t,t.next).map(e=>(null==t.inline?t.inline=e.isInline:t.inline!=e.isInline&&t.err("Mixing inline and block content"),{type:"name",value:e}));return t.pos++,1==e.length?e[0]:{type:"choice",exprs:e}}t.err("Unexpected token '"+t.next+"'")}(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else{if(!t.eat("{"))break;e=gg(t,e)}return e}function mg(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function gg(t,e){let n=mg(t),r=n;return t.eat(",")&&(r="}"!=t.next?mg(t):-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function yg(t,e){return e-t}function xg(t,e){let n=[];return function e(r){let o=t[r];if(1==o.length&&!o[0].term)return e(o[0].to);n.push(r);for(let t=0;t<o.length;t++){let{term:r,to:i}=o[t];r||-1!=n.indexOf(i)||e(i)}}(e),n.sort(yg)}function wg(t){let e=Object.create(null);return function n(r){let o=[];r.forEach(e=>{t[e].forEach(({term:e,to:n})=>{if(!e)return;let r;for(let t=0;t<o.length;t++)o[t][0]==e&&(r=o[t][1]);xg(t,n).forEach(t=>{r||o.push([e,r=[]]),-1==r.indexOf(t)&&r.push(t)})})});let i=e[r.join(",")]=new dg(r.indexOf(t.length-1)>-1);for(let t=0;t<o.length;t++){let r=o[t][1].sort(yg);i.next.push({type:o[t][0],next:e[r.join(",")]||n(r)})}return i}(xg(t,0))}function bg(t){let e=Object.create(null);for(let n in t){let r=t[n];if(!r.hasDefault)return null;e[n]=r.default}return e}function vg(t,e){let n=Object.create(null);for(let r in t){let o=e&&e[r];if(void 0===o){let e=t[r];if(!e.hasDefault)throw new RangeError("No value supplied for attribute "+r);o=e.default}n[r]=o}return n}function kg(t,e,n,r){for(let o in e)if(!(o in t))throw new RangeError(`Unsupported attribute ${o} for ${n} of type ${r}`);for(let o in t)t[o].validate&&t[o].validate(e[o])}function Sg(t,e){let n=Object.create(null);if(e)for(let r in e)n[r]=new Mg(t,r,e[r]);return n}var Pg=class t{constructor(t,e,n){this.name=t,this.schema=e,this.spec=n,this.markSet=null,this.groups=n.group?n.group.split(" "):[],this.attrs=Sg(t,n.attrs),this.defaultAttrs=bg(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(n.inline||"text"==t),this.isText="text"==t}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==dg.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(t){return this.groups.indexOf(t)>-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let t in this.attrs)if(this.attrs[t].isRequired)return!0;return!1}compatibleContent(t){return this==t||this.contentMatch.compatible(t.contentMatch)}computeAttrs(t){return!t&&this.defaultAttrs?this.defaultAttrs:vg(this.attrs,t)}create(t=null,e,n){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new ag(this,this.computeAttrs(t),Bm.from(e),Wm.setFrom(n))}createChecked(t=null,e,n){return e=Bm.from(e),this.checkContent(e),new ag(this,this.computeAttrs(t),e,Wm.setFrom(n))}createAndFill(t=null,e,n){if(t=this.computeAttrs(t),(e=Bm.from(e)).size){let t=this.contentMatch.fillBefore(e);if(!t)return null;e=t.append(e)}let r=this.contentMatch.matchFragment(e),o=r&&r.fillBefore(Bm.empty,!0);return o?new ag(this,t,e.append(o),Wm.setFrom(n)):null}validContent(t){let e=this.contentMatch.matchFragment(t);if(!e||!e.validEnd)return!1;for(let n=0;n<t.childCount;n++)if(!this.allowsMarks(t.child(n).marks))return!1;return!0}checkContent(t){if(!this.validContent(t))throw new RangeError(`Invalid content for node ${this.name}: ${t.toString().slice(0,50)}`)}checkAttrs(t){kg(this.attrs,t,"node",this.name)}allowsMarkType(t){return null==this.markSet||this.markSet.indexOf(t)>-1}allowsMarks(t){if(null==this.markSet)return!0;for(let e=0;e<t.length;e++)if(!this.allowsMarkType(t[e].type))return!1;return!0}allowedMarks(t){if(null==this.markSet)return t;let e;for(let n=0;n<t.length;n++)this.allowsMarkType(t[n].type)?e&&e.push(t[n]):e||(e=t.slice(0,n));return e?e.length?e:Wm.none:t}static compile(e,n){let r=Object.create(null);e.forEach((e,o)=>r[e]=new t(e,n,o));let o=n.spec.topNode||"doc";if(!r[o])throw new RangeError("Schema is missing its top node type ('"+o+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let t in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};var Mg=class{constructor(t,e,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,"default"),this.default=n.default,this.validate="string"==typeof n.validate?function(t,e,n){let r=n.split("|");return n=>{let o=null===n?"null":typeof n;if(r.indexOf(o)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${o}`)}}(t,e,n.validate):n.validate}get isRequired(){return!this.hasDefault}},Ig=class t{constructor(t,e,n,r){this.name=t,this.rank=e,this.schema=n,this.spec=r,this.attrs=Sg(t,r.attrs),this.excluded=null;let o=bg(this.attrs);this.instance=o?new Wm(this,o):null}create(t=null){return!t&&this.instance?this.instance:new Wm(this,vg(this.attrs,t))}static compile(e,n){let r=Object.create(null),o=0;return e.forEach((e,i)=>r[e]=new t(e,o++,n,i)),r}removeFromSet(t){for(var e=0;e<t.length;e++)t[e].type==this&&(t=t.slice(0,e).concat(t.slice(e+1)),e--);return t}isInSet(t){for(let e=0;e<t.length;e++)if(t[e].type==this)return t[e]}checkAttrs(t){kg(this.attrs,t,"mark",this.name)}excludes(t){return this.excluded.indexOf(t)>-1}},Tg=class{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let e=this.spec={};for(let r in t)e[r]=t[r];e.nodes=Nm.from(t.nodes),e.marks=Nm.from(t.marks||{}),this.nodes=Pg.compile(this.spec.nodes,this),this.marks=Ig.compile(this.spec.marks,this);let n=Object.create(null);for(let r in this.nodes){if(r in this.marks)throw new RangeError(r+" can not be both a node and a mark");let t=this.nodes[r],e=t.spec.content||"",o=t.spec.marks;if(t.contentMatch=n[e]||(n[e]=dg.parse(e,this.nodes)),t.inlineContent=t.contentMatch.inlineContent,t.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!t.isInline||!t.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=t}t.markSet="_"==o?null:o?Cg(this,o.split(" ")):""!=o&&t.inlineContent?null:[]}for(let r in this.marks){let t=this.marks[r],e=t.spec.excludes;t.excluded=null==e?[t]:""==e?[]:Cg(this,e.split(" "))}this.nodeFromJSON=t=>ag.fromJSON(this,t),this.markFromJSON=t=>Wm.fromJSON(this,t),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(t,e=null,n,r){if("string"==typeof t)t=this.nodeType(t);else{if(!(t instanceof Pg))throw new RangeError("Invalid node type: "+t);if(t.schema!=this)throw new RangeError("Node type from different schema used ("+t.name+")")}return t.createChecked(e,n,r)}text(t,e){let n=this.nodes.text;return new lg(n,n.defaultAttrs,t,Wm.setFrom(e))}mark(t,e){return"string"==typeof t&&(t=this.marks[t]),t.create(e)}nodeType(t){let e=this.nodes[t];if(!e)throw new RangeError("Unknown node type: "+t);return e}};function Cg(t,e){let n=[];for(let r=0;r<e.length;r++){let o=e[r],i=t.marks[o],s=i;if(i)n.push(i);else for(let e in t.marks){let r=t.marks[e];("_"==o||r.spec.group&&r.spec.group.split(" ").indexOf(o)>-1)&&n.push(s=r)}if(!s)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}var Eg=class t{constructor(t,e){this.schema=t,this.rules=e,this.tags=[],this.styles=[];let n=this.matchedStyles=[];e.forEach(t=>{if(function(t){return null!=t.tag}(t))this.tags.push(t);else if(function(t){return null!=t.style}(t)){let e=/[^=]*/.exec(t.style)[0];n.indexOf(e)<0&&n.push(e),this.styles.push(t)}}),this.normalizeLists=!this.tags.some(e=>{if(!/^(ul|ol)\b/.test(e.tag)||!e.node)return!1;let n=t.nodes[e.node];return n.contentMatch.matchType(n)})}parse(t,e={}){let n=new $g(this,e,!1);return n.addAll(t,Wm.none,e.from,e.to),n.finish()}parseSlice(t,e={}){let n=new $g(this,e,!0);return n.addAll(t,Wm.none,e.from,e.to),_m.maxOpen(n.finish())}matchTag(t,e,n){for(let r=n?this.tags.indexOf(n)+1:0;r<this.tags.length;r++){let n=this.tags[r];if(Dg(t,n.tag)&&(void 0===n.namespace||t.namespaceURI==n.namespace)&&(!n.context||e.matchesContext(n.context))){if(n.getAttrs){let e=n.getAttrs(t);if(!1===e)continue;n.attrs=e||void 0}return n}}}matchStyle(t,e,n,r){for(let o=r?this.styles.indexOf(r)+1:0;o<this.styles.length;o++){let r=this.styles[o],i=r.style;if(!(0!=i.indexOf(t)||r.context&&!n.matchesContext(r.context)||i.length>t.length&&(61!=i.charCodeAt(t.length)||i.slice(t.length+1)!=e))){if(r.getAttrs){let t=r.getAttrs(e);if(!1===t)continue;r.attrs=t||void 0}return r}}}static schemaRules(t){let e=[];function n(t){let n=null==t.priority?50:t.priority,r=0;for(;r<e.length;r++){let t=e[r];if((null==t.priority?50:t.priority)<n)break}e.splice(r,0,t)}for(let r in t.marks){let e=t.marks[r].spec.parseDOM;e&&e.forEach(t=>{n(t=Bg(t)),t.mark||t.ignore||t.clearMark||(t.mark=r)})}for(let r in t.nodes){let e=t.nodes[r].spec.parseDOM;e&&e.forEach(t=>{n(t=Bg(t)),t.node||t.ignore||t.mark||(t.node=r)})}return e}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new t(e,t.schemaRules(e)))}},Ag={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Og={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Ng={ol:!0,ul:!0};function Rg(t,e,n){return null!=e?(e?1:0)|("full"===e?2:0):t&&"pre"==t.whitespace?3:-5&n}var Lg=class{constructor(t,e,n,r,o,i){this.type=t,this.attrs=e,this.marks=n,this.solid=r,this.options=i,this.content=[],this.activeMarks=Wm.none,this.match=o||(4&i?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let e=this.type.contentMatch.fillBefore(Bm.from(t));if(!e){let e,n=this.type.contentMatch;return(e=n.findWrapping(t.type))?(this.match=n,e):null}this.match=this.type.contentMatch.matchFragment(e)}return this.match.findWrapping(t.type)}finish(t){if(!(1&this.options)){let t,e=this.content[this.content.length-1];if(e&&e.isText&&(t=/[ \t\r\n\u000c]+$/.exec(e.text))){let n=e;e.text.length==t[0].length?this.content.pop():this.content[this.content.length-1]=n.withText(n.text.slice(0,n.text.length-t[0].length))}}let e=Bm.from(this.content);return!t&&this.match&&(e=e.append(this.match.fillBefore(Bm.empty,!0))),this.type?this.type.create(this.attrs,e,this.marks):e}inlineContext(t){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:t.parentNode&&!Ag.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}},$g=class{constructor(t,e,n){this.parser=t,this.options=e,this.isOpen=n,this.open=0,this.localPreserveWS=!1;let r,o=e.topNode,i=Rg(null,e.preserveWhitespace,0)|(n?4:0);r=o?new Lg(o.type,o.attrs,Wm.none,!0,e.topMatch||o.type.contentMatch,i):new Lg(n?null:t.schema.topNodeType,null,Wm.none,!0,null,i),this.nodes=[r],this.find=e.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(t,e){3==t.nodeType?this.addTextNode(t,e):1==t.nodeType&&this.addElement(t,e)}addTextNode(t,e){let n=t.nodeValue,r=this.top,o=2&r.options?"full":this.localPreserveWS||(1&r.options)>0,{schema:i}=this.parser;if("full"===o||r.inlineContext(t)||/[^ \t\r\n\u000c]/.test(n)){if(o)if("full"===o)n=n.replace(/\r\n?/g,"\n");else if(i.linebreakReplacement&&/[\r\n]/.test(n)&&this.top.findWrapping(i.linebreakReplacement.create())){let t=n.split(/\r?\n|\r/);for(let n=0;n<t.length;n++)n&&this.insertNode(i.linebreakReplacement.create(),e,!0),t[n]&&this.insertNode(i.text(t[n]),e,!/\S/.test(t[n]));n=""}else n=n.replace(/\r?\n|\r/g," ");else if(n=n.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(n)&&this.open==this.nodes.length-1){let e=r.content[r.content.length-1],o=t.previousSibling;(!e||o&&"BR"==o.nodeName||e.isText&&/[ \t\r\n\u000c]$/.test(e.text))&&(n=n.slice(1))}n&&this.insertNode(i.text(n),e,!/\S/.test(n)),this.findInText(t)}else this.findInside(t)}addElement(t,e,n){let r=this.localPreserveWS,o=this.top;("PRE"==t.tagName||/pre/.test(t.style&&t.style.whiteSpace))&&(this.localPreserveWS=!0);let i,s=t.nodeName.toLowerCase();Ng.hasOwnProperty(s)&&this.parser.normalizeLists&&function(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let t=1==e.nodeType?e.nodeName.toLowerCase():null;t&&Ng.hasOwnProperty(t)&&n?(n.appendChild(e),e=n):"li"==t?n=e:t&&(n=null)}}(t);let a=this.options.ruleFromNode&&this.options.ruleFromNode(t)||(i=this.parser.matchTag(t,this,n));t:if(a?a.ignore:Og.hasOwnProperty(s))this.findInside(t),this.ignoreFallback(t,e);else if(!a||a.skip||a.closeParent){a&&a.closeParent?this.open=Math.max(0,this.open-1):a&&a.skip.nodeType&&(t=a.skip);let n,r=this.needsBlock;if(Ag.hasOwnProperty(s))o.content.length&&o.content[0].isInline&&this.open&&(this.open--,o=this.top),n=!0,o.type||(this.needsBlock=!0);else if(!t.firstChild){this.leafFallback(t,e);break t}let i=a&&a.skip?e:this.readStyles(t,e);i&&this.addAll(t,i),n&&this.sync(o),this.needsBlock=r}else{let n=this.readStyles(t,e);n&&this.addElementByRule(t,a,n,!1===a.consuming?i:void 0)}this.localPreserveWS=r}leafFallback(t,e){"BR"==t.nodeName&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(t.ownerDocument.createTextNode("\n"),e)}ignoreFallback(t,e){"BR"!=t.nodeName||this.top.type&&this.top.type.inlineContent||this.findPlace(this.parser.schema.text("-"),e,!0)}readStyles(t,e){let n=t.style;if(n&&n.length)for(let r=0;r<this.parser.matchedStyles.length;r++){let t=this.parser.matchedStyles[r],o=n.getPropertyValue(t);if(o)for(let n;;){let r=this.parser.matchStyle(t,o,this,n);if(!r)break;if(r.ignore)return null;if(e=r.clearMark?e.filter(t=>!r.clearMark(t)):e.concat(this.parser.schema.marks[r.mark].create(r.attrs)),!1!==r.consuming)break;n=r}}return e}addElementByRule(t,e,n,r){let o,i;if(e.node)if(i=this.parser.schema.nodes[e.node],i.isLeaf)this.insertNode(i.create(e.attrs),n,"BR"==t.nodeName)||this.leafFallback(t,n);else{let t=this.enter(i,e.attrs||null,n,e.preserveWhitespace);t&&(o=!0,n=t)}else{let t=this.parser.schema.marks[e.mark];n=n.concat(t.create(e.attrs))}let s=this.top;if(i&&i.isLeaf)this.findInside(t);else if(r)this.addElement(t,n,r);else if(e.getContent)this.findInside(t),e.getContent(t,this.parser.schema).forEach(t=>this.insertNode(t,n,!1));else{let r=t;"string"==typeof e.contentElement?r=t.querySelector(e.contentElement):"function"==typeof e.contentElement?r=e.contentElement(t):e.contentElement&&(r=e.contentElement),this.findAround(t,r,!0),this.addAll(r,n),this.findAround(t,r,!1)}o&&this.sync(s)&&this.open--}addAll(t,e,n,r){let o=n||0;for(let i=n?t.childNodes[n]:t.firstChild,s=null==r?null:t.childNodes[r];i!=s;i=i.nextSibling,++o)this.findAtPoint(t,o),this.addDOM(i,e);this.findAtPoint(t,o)}findPlace(t,e,n){let r,o;for(let i=this.open,s=0;i>=0;i--){let e=this.nodes[i],a=e.findWrapping(t);if(a&&(!r||r.length>a.length+s)&&(r=a,o=e,!a.length))break;if(e.solid){if(n)break;s+=2}}if(!r)return null;this.sync(o);for(let i=0;i<r.length;i++)e=this.enterInner(r[i],null,e,!1);return e}insertNode(t,e,n){if(t.isInline&&this.needsBlock&&!this.top.type){let t=this.textblockFromContext();t&&(e=this.enterInner(t,null,e))}let r=this.findPlace(t,e,n);if(r){this.closeExtra();let e=this.top;e.match&&(e.match=e.match.matchType(t.type));let n=Wm.none;for(let o of r.concat(t.marks))(e.type?e.type.allowsMarkType(o.type):zg(o.type,t.type))&&(n=o.addToSet(n));return e.content.push(t.mark(n)),!0}return!1}enter(t,e,n,r){let o=this.findPlace(t.create(e),n,!1);return o&&(o=this.enterInner(t,e,n,!0,r)),o}enterInner(t,e,n,r=!1,o){this.closeExtra();let i=this.top;i.match=i.match&&i.match.matchType(t);let s=Rg(t,o,i.options);4&i.options&&0==i.content.length&&(s|=4);let a=Wm.none;return n=n.filter(e=>!(i.type?i.type.allowsMarkType(e.type):zg(e.type,t))||(a=e.addToSet(a),!1)),this.nodes.push(new Lg(t,e,a,r,null,s)),this.open++,n}closeExtra(t=!1){let e=this.nodes.length-1;if(e>this.open){for(;e>this.open;e--)this.nodes[e-1].content.push(this.nodes[e].finish(t));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!(!this.isOpen&&!this.options.topOpen))}sync(t){for(let e=this.open;e>=0;e--){if(this.nodes[e]==t)return this.open=e,!0;this.localPreserveWS&&(this.nodes[e].options|=1)}return!1}get currentPos(){this.closeExtra();let t=0;for(let e=this.open;e>=0;e--){let n=this.nodes[e].content;for(let e=n.length-1;e>=0;e--)t+=n[e].nodeSize;e&&t++}return t}findAtPoint(t,e){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==t&&this.find[n].offset==e&&(this.find[n].pos=this.currentPos)}findInside(t){if(this.find)for(let e=0;e<this.find.length;e++)null==this.find[e].pos&&1==t.nodeType&&t.contains(this.find[e].node)&&(this.find[e].pos=this.currentPos)}findAround(t,e,n){if(t!=e&&this.find)for(let r=0;r<this.find.length;r++)null==this.find[r].pos&&1==t.nodeType&&t.contains(this.find[r].node)&&e.compareDocumentPosition(this.find[r].node)&(n?2:4)&&(this.find[r].pos=this.currentPos)}findInText(t){if(this.find)for(let e=0;e<this.find.length;e++)this.find[e].node==t&&(this.find[e].pos=this.currentPos-(t.nodeValue.length-this.find[e].offset))}matchesContext(t){if(t.indexOf("|")>-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let e=t.split("/"),n=this.options.context,r=!(this.isOpen||n&&n.parent.type!=this.nodes[0].type),o=-(n?n.depth+1:0)+(r?0:1),i=(t,s)=>{for(;t>=0;t--){let a=e[t];if(""==a){if(t==e.length-1||0==t)continue;for(;s>=o;s--)if(i(t-1,s))return!0;return!1}{let t=s>0||0==s&&r?this.nodes[s].type:n&&s>=o?n.node(s-o).type:null;if(!t||t.name!=a&&!t.isInGroup(a))return!1;s--}}return!0};return i(e.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let e=t.depth;e>=0;e--){let n=t.node(e).contentMatchAt(t.indexAfter(e)).defaultType;if(n&&n.isTextblock&&n.defaultAttrs)return n}for(let e in this.parser.schema.nodes){let t=this.parser.schema.nodes[e];if(t.isTextblock&&t.defaultAttrs)return t}}};function Dg(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function Bg(t){let e={};for(let n in t)e[n]=t[n];return e}function zg(t,e){let n=e.schema.nodes;for(let r in n){let o=n[r];if(!o.allowsMarkType(t))continue;let i=[],s=t=>{i.push(t);for(let n=0;n<t.edgeCount;n++){let{type:r,next:o}=t.edge(n);if(r==e)return!0;if(i.indexOf(o)<0&&s(o))return!0}};if(s(o.contentMatch))return!0}}var Fg=class t{constructor(t,e){this.nodes=t,this.marks=e}serializeFragment(t,e={},n){n||(n=Wg(e).createDocumentFragment());let r=n,o=[];return t.forEach(t=>{if(o.length||t.marks.length){let n=0,i=0;for(;n<o.length&&i<t.marks.length;){let e=t.marks[i];if(this.marks[e.type.name]){if(!e.eq(o[n][0])||!1===e.type.spec.spanning)break;n++,i++}else i++}for(;n<o.length;)r=o.pop()[1];for(;i<t.marks.length;){let n=t.marks[i++],s=this.serializeMark(n,t.isInline,e);s&&(o.push([n,r]),r.appendChild(s.dom),r=s.contentDOM||s.dom)}}r.appendChild(this.serializeNodeInner(t,e))}),n}serializeNodeInner(t,e){if(t.isText)return Wg(e).createTextNode(t.text);let{dom:n,contentDOM:r}=Ug(Wg(e),this.nodes[t.type.name](t),null,t.attrs);if(r){if(t.isLeaf)throw new RangeError("Content hole not allowed in a leaf node spec");this.serializeFragment(t.content,e,r)}return n}serializeNode(t,e={}){let n=this.serializeNodeInner(t,e);for(let r=t.marks.length-1;r>=0;r--){let o=this.serializeMark(t.marks[r],t.isInline,e);o&&((o.contentDOM||o.dom).appendChild(n),n=o.dom)}return n}serializeMark(t,e,n={}){let r=this.marks[t.type.name];return r&&Ug(Wg(n),r(t,e),null,t.attrs)}static renderSpec(t,e,n=null,r){return"string"==typeof e?{dom:t.createTextNode(e)}:Ug(t,e,n,r)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new t(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(t){let e=jg(t.nodes);return e.text||(e.text=t=>t.text),e}static marksFromSchema(t){return jg(t.marks)}};function jg(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function Wg(t){return t.document||window.document}var Hg=new WeakMap;function _g(t){let e=Hg.get(t);return void 0===e&&Hg.set(t,e=function(t){let e=null;function n(t){if(t&&"object"==typeof t)if(Array.isArray(t))if("string"==typeof t[0])e||(e=[]),e.push(t);else for(let e=0;e<t.length;e++)n(t[e]);else for(let e in t)n(t[e])}return n(t),e}(t)),e}function Ug(t,e,n,r){if(1==e.nodeType)return{dom:e};if(e.dom&&1==e.dom.nodeType)return e;let o,i=e[0];if("string"!=typeof i)throw new RangeError("Invalid array passed to renderSpec");if(r&&(o=_g(r))&&o.indexOf(e)>-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let s,a=i.indexOf(" ");a>0&&(n=i.slice(0,a),i=i.slice(a+1));let l=n?t.createElementNS(n,i):t.createElement(i),c=e[1],d=1;if(c&&"object"==typeof c&&null==c.nodeType&&!Array.isArray(c)){d=2;for(let t in c)if(null!=c[t]){let e=t.indexOf(" ");e>0?l.setAttributeNS(t.slice(0,e),t.slice(e+1),c[t]):"style"==t&&l.style?l.style.cssText=c[t]:l.setAttribute(t,c[t])}}for(let u=d;u<e.length;u++){let o=e[u];if(0===o){if(u<e.length-1||u>d)throw new RangeError("Content hole must be the only child of its parent node");return{dom:l,contentDOM:l}}if("string"==typeof o)l.appendChild(t.createTextNode(o));else{let{dom:e,contentDOM:i}=Ug(t,o,n,r);if(l.appendChild(e),i){if(s)throw new RangeError("Multiple content holes");s=i}}}return{dom:l,contentDOM:s}}var Vg=Math.pow(2,16);function Kg(t,e){return t+e*Vg}function qg(t){return 65535&t}var Xg=class{constructor(t,e,n){this.pos=t,this.delInfo=e,this.recover=n}get deleted(){return(8&this.delInfo)>0}get deletedBefore(){return(5&this.delInfo)>0}get deletedAfter(){return(6&this.delInfo)>0}get deletedAcross(){return(4&this.delInfo)>0}},Yg=class t{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&t.empty)return t.empty}recover(t){let e=0,n=qg(t);if(!this.inverted)for(let r=0;r<n;r++)e+=this.ranges[3*r+2]-this.ranges[3*r+1];return this.ranges[3*n]+e+function(t){return(t-(65535&t))/Vg}(t)}mapResult(t,e=1){return this._map(t,e,!1)}map(t,e=1){return this._map(t,e,!0)}_map(t,e,n){let r=0,o=this.inverted?2:1,i=this.inverted?1:2;for(let s=0;s<this.ranges.length;s+=3){let a=this.ranges[s]-(this.inverted?r:0);if(a>t)break;let l=this.ranges[s+o],c=this.ranges[s+i],d=a+l;if(t<=d){let o=a+r+((l?t==a?-1:t==d?1:e:e)<0?0:c);if(n)return o;let i=t==(e<0?a:d)?null:Kg(s/3,t-a),u=t==a?2:t==d?1:4;return(e<0?t!=a:t!=d)&&(u|=8),new Xg(o,u,i)}r+=c-l}return n?t+r:new Xg(t+r,0,null)}touches(t,e){let n=0,r=qg(e),o=this.inverted?2:1,i=this.inverted?1:2;for(let s=0;s<this.ranges.length;s+=3){let e=this.ranges[s]-(this.inverted?n:0);if(e>t)break;let a=this.ranges[s+o];if(t<=e+a&&s==3*r)return!0;n+=this.ranges[s+i]-a}return!1}forEach(t){let e=this.inverted?2:1,n=this.inverted?1:2;for(let r=0,o=0;r<this.ranges.length;r+=3){let i=this.ranges[r],s=i-(this.inverted?o:0),a=i+(this.inverted?0:o),l=this.ranges[r+e],c=this.ranges[r+n];t(s,s+l,a,a+c),o+=c-l}}invert(){return new t(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return 0==e?t.empty:new t(e<0?[0,-e,0]:[0,0,e])}};Yg.empty=new Yg([]);var Jg=class t{constructor(t,e,n=0,r=(t?t.length:0)){this.mirror=e,this.from=n,this.to=r,this._maps=t||[],this.ownData=!(t||e)}get maps(){return this._maps}slice(e=0,n=this.maps.length){return new t(this._maps,this.mirror,e,n)}appendMap(t,e){this.ownData||(this._maps=this._maps.slice(),this.mirror=this.mirror&&this.mirror.slice(),this.ownData=!0),this.to=this._maps.push(t),null!=e&&this.setMirror(this._maps.length-1,e)}appendMapping(t){for(let e=0,n=this._maps.length;e<t._maps.length;e++){let r=t.getMirror(e);this.appendMap(t._maps[e],null!=r&&r<e?n+r:void 0)}}getMirror(t){if(this.mirror)for(let e=0;e<this.mirror.length;e++)if(this.mirror[e]==t)return this.mirror[e+(e%2?-1:1)]}setMirror(t,e){this.mirror||(this.mirror=[]),this.mirror.push(t,e)}appendMappingInverted(t){for(let e=t.maps.length-1,n=this._maps.length+t._maps.length;e>=0;e--){let r=t.getMirror(e);this.appendMap(t._maps[e].invert(),null!=r&&r>e?n-r-1:void 0)}}invert(){let e=new t;return e.appendMappingInverted(this),e}map(t,e=1){if(this.mirror)return this._map(t,e,!0);for(let n=this.from;n<this.to;n++)t=this._maps[n].map(t,e);return t}mapResult(t,e=1){return this._map(t,e,!1)}_map(t,e,n){let r=0;for(let o=this.from;o<this.to;o++){let n=this._maps[o].mapResult(t,e);if(null!=n.recover){let e=this.getMirror(o);if(null!=e&&e>o&&e<this.to){o=e,t=this._maps[e].recover(n.recover);continue}}r|=n.delInfo,t=n.pos}return n?t:new Xg(t,r,null)}},Gg=Object.create(null),Zg=class{getMap(){return Yg.empty}merge(t){return null}static fromJSON(t,e){if(!e||!e.stepType)throw new RangeError("Invalid input for Step.fromJSON");let n=Gg[e.stepType];if(!n)throw new RangeError(`No step type ${e.stepType} defined`);return n.fromJSON(t,e)}static jsonID(t,e){if(t in Gg)throw new RangeError("Duplicate use of step JSON ID "+t);return Gg[t]=e,e.prototype.jsonID=t,e}},Qg=class t{constructor(t,e){this.doc=t,this.failed=e}static ok(e){return new t(e,null)}static fail(e){return new t(null,e)}static fromReplace(e,n,r,o){try{return t.ok(e.replace(n,r,o))}catch(i){if(i instanceof Hm)return t.fail(i.message);throw i}}};function ty(t,e,n){let r=[];for(let o=0;o<t.childCount;o++){let i=t.child(o);i.content.size&&(i=i.copy(ty(i.content,e,i))),i.isInline&&(i=e(i,n,o)),r.push(i)}return Bm.fromArray(r)}var ey=class t extends Zg{constructor(t,e,n){super(),this.from=t,this.to=e,this.mark=n}apply(t){let e=t.slice(this.from,this.to),n=t.resolve(this.from),r=n.node(n.sharedDepth(this.to)),o=new _m(ty(e.content,(t,e)=>t.isAtom&&e.type.allowsMarkType(this.mark.type)?t.mark(this.mark.addToSet(t.marks)):t,r),e.openStart,e.openEnd);return Qg.fromReplace(t,this.from,this.to,o)}invert(){return new ny(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new t(n.pos,r.pos,this.mark)}merge(e){return e instanceof t&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new t(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if("number"!=typeof n.from||"number"!=typeof n.to)throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new t(n.from,n.to,e.markFromJSON(n.mark))}};Zg.jsonID("addMark",ey);var ny=class t extends Zg{constructor(t,e,n){super(),this.from=t,this.to=e,this.mark=n}apply(t){let e=t.slice(this.from,this.to),n=new _m(ty(e.content,t=>t.mark(this.mark.removeFromSet(t.marks)),t),e.openStart,e.openEnd);return Qg.fromReplace(t,this.from,this.to,n)}invert(){return new ey(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new t(n.pos,r.pos,this.mark)}merge(e){return e instanceof t&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new t(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if("number"!=typeof n.from||"number"!=typeof n.to)throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new t(n.from,n.to,e.markFromJSON(n.mark))}};Zg.jsonID("removeMark",ny);var ry=class t extends Zg{constructor(t,e){super(),this.pos=t,this.mark=e}apply(t){let e=t.nodeAt(this.pos);if(!e)return Qg.fail("No node at mark step's position");let n=e.type.create(e.attrs,null,this.mark.addToSet(e.marks));return Qg.fromReplace(t,this.pos,this.pos+1,new _m(Bm.from(n),0,e.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);if(n){let e=this.mark.addToSet(n.marks);if(e.length==n.marks.length){for(let r=0;r<n.marks.length;r++)if(!n.marks[r].isInSet(e))return new t(this.pos,n.marks[r]);return new t(this.pos,this.mark)}}return new oy(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new t(n.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,n){if("number"!=typeof n.pos)throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new t(n.pos,e.markFromJSON(n.mark))}};Zg.jsonID("addNodeMark",ry);var oy=class t extends Zg{constructor(t,e){super(),this.pos=t,this.mark=e}apply(t){let e=t.nodeAt(this.pos);if(!e)return Qg.fail("No node at mark step's position");let n=e.type.create(e.attrs,null,this.mark.removeFromSet(e.marks));return Qg.fromReplace(t,this.pos,this.pos+1,new _m(Bm.from(n),0,e.isLeaf?0:1))}invert(t){let e=t.nodeAt(this.pos);return e&&this.mark.isInSet(e.marks)?new ry(this.pos,this.mark):this}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new t(n.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,n){if("number"!=typeof n.pos)throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new t(n.pos,e.markFromJSON(n.mark))}};Zg.jsonID("removeNodeMark",oy);var iy=class t extends Zg{constructor(t,e,n,r=!1){super(),this.from=t,this.to=e,this.slice=n,this.structure=r}apply(t){return this.structure&&ay(t,this.from,this.to)?Qg.fail("Structure replace would overwrite content"):Qg.fromReplace(t,this.from,this.to,this.slice)}getMap(){return new Yg([this.from,this.to-this.from,this.slice.size])}invert(e){return new t(this.from,this.from+this.slice.size,e.slice(this.from,this.to))}map(e){let n=e.mapResult(this.to,-1),r=this.from==this.to&&t.MAP_BIAS<0?n:e.mapResult(this.from,1);return r.deletedAcross&&n.deletedAcross?null:new t(r.pos,Math.max(r.pos,n.pos),this.slice,this.structure)}merge(e){if(!(e instanceof t)||e.structure||this.structure)return null;if(this.from+this.slice.size!=e.from||this.slice.openEnd||e.slice.openStart){if(e.to!=this.from||this.slice.openStart||e.slice.openEnd)return null;{let n=this.slice.size+e.slice.size==0?_m.empty:new _m(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new t(e.from,this.to,n,this.structure)}}{let n=this.slice.size+e.slice.size==0?_m.empty:new _m(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new t(this.from,this.to+(e.to-e.from),n,this.structure)}}toJSON(){let t={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(e,n){if("number"!=typeof n.from||"number"!=typeof n.to)throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new t(n.from,n.to,_m.fromJSON(e,n.slice),!!n.structure)}};iy.MAP_BIAS=1,Zg.jsonID("replace",iy);var sy=class t extends Zg{constructor(t,e,n,r,o,i,s=!1){super(),this.from=t,this.to=e,this.gapFrom=n,this.gapTo=r,this.slice=o,this.insert=i,this.structure=s}apply(t){if(this.structure&&(ay(t,this.from,this.gapFrom)||ay(t,this.gapTo,this.to)))return Qg.fail("Structure gap-replace would overwrite content");let e=t.slice(this.gapFrom,this.gapTo);if(e.openStart||e.openEnd)return Qg.fail("Gap is not a flat range");let n=this.slice.insertAt(this.insert,e.content);return n?Qg.fromReplace(t,this.from,this.to,n):Qg.fail("Content does not fit in gap")}getMap(){return new Yg([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(e){let n=this.gapTo-this.gapFrom;return new t(this.from,this.from+this.slice.size+n,this.from+this.insert,this.from+this.insert+n,e.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1),o=this.from==this.gapFrom?n.pos:e.map(this.gapFrom,-1),i=this.to==this.gapTo?r.pos:e.map(this.gapTo,1);return n.deletedAcross&&r.deletedAcross||o<n.pos||i>r.pos?null:new t(n.pos,r.pos,o,i,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(e,n){if("number"!=typeof n.from||"number"!=typeof n.to||"number"!=typeof n.gapFrom||"number"!=typeof n.gapTo||"number"!=typeof n.insert)throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new t(n.from,n.to,n.gapFrom,n.gapTo,_m.fromJSON(e,n.slice),n.insert,!!n.structure)}};function ay(t,e,n){let r=t.resolve(e),o=n-e,i=r.depth;for(;o>0&&i>0&&r.indexAfter(i)==r.node(i).childCount;)i--,o--;if(o>0){let t=r.node(i).maybeChild(r.indexAfter(i));for(;o>0;){if(!t||t.isLeaf)return!0;t=t.firstChild,o--}}return!1}function ly(t,e,n,r=n.contentMatch,o=!0){let i=t.doc.nodeAt(e),s=[],a=e+1;for(let l=0;l<i.childCount;l++){let e=i.child(l),c=a+e.nodeSize,d=r.matchType(e.type);if(d){r=d;for(let r=0;r<e.marks.length;r++)n.allowsMarkType(e.marks[r].type)||t.step(new ny(a,c,e.marks[r]));if(o&&e.isText&&"pre"!=n.whitespace){let t,r,o=/\r?\n|\r/g;for(;t=o.exec(e.text);)r||(r=new _m(Bm.from(n.schema.text(" ",n.allowedMarks(e.marks))),0,0)),s.push(new iy(a+t.index,a+t.index+t[0].length,r))}}else s.push(new iy(a,c,_m.empty));a=c}if(!r.validEnd){let e=r.fillBefore(Bm.empty,!0);t.replace(a,a,new _m(e,0,0))}for(let l=s.length-1;l>=0;l--)t.step(s[l])}function cy(t,e,n){return(0==e||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function dy(t){let e=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let n=t.depth,r=0,o=0;;--n){let i=t.$from.node(n),s=t.$from.index(n)+r,a=t.$to.indexAfter(n)-o;if(n<t.depth&&i.canReplace(s,a,e))return n;if(0==n||i.type.spec.isolating||!cy(i,s,a))break;s&&(r=1),a<i.childCount&&(o=1)}return null}function uy(t,e,n=null,r=t){let o=function(t,e){let{parent:n,startIndex:r,endIndex:o}=t,i=n.contentMatchAt(r).findWrapping(e);if(!i)return null;let s=i.length?i[0]:e;return n.canReplaceWith(r,o,s)?i:null}(t,e),i=o&&function(t,e){let{parent:n,startIndex:r,endIndex:o}=t,i=n.child(r),s=e.contentMatch.findWrapping(i.type);if(!s)return null;let a=(s.length?s[s.length-1]:e).contentMatch;for(let l=r;a&&l<o;l++)a=a.matchType(n.child(l).type);return a&&a.validEnd?s:null}(r,e);return i?o.map(py).concat({type:e,attrs:n}).concat(i.map(py)):null}function py(t){return{type:t,attrs:null}}function hy(t,e,n,r){e.forEach((o,i)=>{if(o.isText){let s,a=/\r?\n|\r/g;for(;s=a.exec(o.text);){let o=t.mapping.slice(r).map(n+1+i+s.index);t.replaceWith(o,o+1,e.type.schema.linebreakReplacement.create())}}})}function fy(t,e,n,r){e.forEach((o,i)=>{if(o.type==o.type.schema.linebreakReplacement){let o=t.mapping.slice(r).map(n+1+i);t.replaceWith(o,o+1,e.type.schema.text("\n"))}})}function my(t,e,n=1,r){let o=t.resolve(e),i=o.depth-n,s=r&&r[r.length-1]||o.parent;if(i<0||o.parent.type.spec.isolating||!o.parent.canReplace(o.index(),o.parent.childCount)||!s.type.validContent(o.parent.content.cutByIndex(o.index(),o.parent.childCount)))return!1;for(let c=o.depth-1,d=n-2;c>i;c--,d--){let t=o.node(c),e=o.index(c);if(t.type.spec.isolating)return!1;let n=t.content.cutByIndex(e,t.childCount),i=r&&r[d+1];i&&(n=n.replaceChild(0,i.type.create(i.attrs)));let s=r&&r[d]||t;if(!t.canReplace(e+1,t.childCount)||!s.type.validContent(n))return!1}let a=o.indexAfter(i),l=r&&r[0];return o.node(i).canReplaceWith(a,a,l?l.type:o.node(i+1).type)}function gy(t,e){let n=t.resolve(e),r=n.index();return yy(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function yy(t,e){return!(!t||!e||t.isLeaf||!function(t,e){e.content.size||t.type.compatibleContent(e.type);let n=t.contentMatchAt(t.childCount),{linebreakReplacement:r}=t.type.schema;for(let o=0;o<e.childCount;o++){let i=e.child(o),s=i.type==r?t.type.schema.nodes.text:i.type;if(n=n.matchType(s),!n)return!1;if(!t.type.allowsMarks(i.marks))return!1}return n.validEnd}(t,e))}function xy(t,e,n=-1){let r=t.resolve(e);for(let o=r.depth;;o--){let t,i,s=r.index(o);if(o==r.depth?(t=r.nodeBefore,i=r.nodeAfter):n>0?(t=r.node(o+1),s++,i=r.node(o).maybeChild(s)):(t=r.node(o).maybeChild(s-1),i=r.node(o+1)),t&&!t.isTextblock&&yy(t,i)&&r.node(o).canReplace(s,s+1))return e;if(0==o)break;e=n<0?r.before(o):r.after(o)}}function wy(t,e,n){let r=t.resolve(e);if(!n.content.size)return e;let o=n.content;for(let i=0;i<n.openStart;i++)o=o.firstChild.content;for(let i=1;i<=(0==n.openStart&&n.size?2:1);i++)for(let t=r.depth;t>=0;t--){let e=t==r.depth?0:r.pos<=(r.start(t+1)+r.end(t+1))/2?-1:1,n=r.index(t)+(e>0?1:0),s=r.node(t),a=!1;if(1==i)a=s.canReplace(n,n,o);else{let t=s.contentMatchAt(n).findWrapping(o.firstChild.type);a=t&&s.canReplaceWith(n,n,t[0])}if(a)return 0==e?r.pos:e<0?r.before(t+1):r.after(t+1)}return null}function by(t,e,n=e,r=_m.empty){if(e==n&&!r.size)return null;let o=t.resolve(e),i=t.resolve(n);return vy(o,i,r)?new iy(e,n,r):new ky(o,i,r).fit()}function vy(t,e,n){return!n.openStart&&!n.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),n.content)}Zg.jsonID("replaceAround",sy);var ky=class{constructor(t,e,n){this.$from=t,this.$to=e,this.unplaced=n,this.frontier=[],this.placed=Bm.empty;for(let r=0;r<=t.depth;r++){let e=t.node(r);this.frontier.push({type:e.type,match:e.contentMatchAt(t.indexAfter(r))})}for(let r=t.depth;r>0;r--)this.placed=Bm.from(t.node(r).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let t=this.findFittable();t?this.placeNodes(t):this.openMore()||this.dropNode()}let t=this.mustMoveInline(),e=this.placed.size-this.depth-this.$from.depth,n=this.$from,r=this.close(t<0?this.$to:n.doc.resolve(t));if(!r)return null;let o=this.placed,i=n.depth,s=r.depth;for(;i&&s&&1==o.childCount;)o=o.firstChild.content,i--,s--;let a=new _m(o,i,s);return t>-1?new sy(n.pos,t,this.$to.pos,this.$to.end(),a,e):a.size||n.pos!=this.$to.pos?new iy(n.pos,r.pos,a):null}findFittable(){let t=this.unplaced.openStart;for(let e=this.unplaced.content,n=0,r=this.unplaced.openEnd;n<t;n++){let o=e.firstChild;if(e.childCount>1&&(r=0),o.type.spec.isolating&&r<=n){t=n;break}e=o.content}for(let e=1;e<=2;e++)for(let n=1==e?t:this.unplaced.openStart;n>=0;n--){let t,r=null;n?(r=My(this.unplaced.content,n-1).firstChild,t=r.content):t=this.unplaced.content;let o=t.firstChild;for(let i=this.depth;i>=0;i--){let t,{type:s,match:a}=this.frontier[i],l=null;if(1==e&&(o?a.matchType(o.type)||(l=a.fillBefore(Bm.from(o),!1)):r&&s.compatibleContent(r.type)))return{sliceDepth:n,frontierDepth:i,parent:r,inject:l};if(2==e&&o&&(t=a.findWrapping(o.type)))return{sliceDepth:n,frontierDepth:i,parent:r,wrap:t};if(r&&a.matchType(r.type))break}}}openMore(){let{content:t,openStart:e,openEnd:n}=this.unplaced,r=My(t,e);return!(!r.childCount||r.firstChild.isLeaf)&&(this.unplaced=new _m(t,e+1,Math.max(n,r.size+e>=t.size-n?e+1:0)),!0)}dropNode(){let{content:t,openStart:e,openEnd:n}=this.unplaced,r=My(t,e);if(r.childCount<=1&&e>0){let o=t.size-e<=e+r.size;this.unplaced=new _m(Sy(t,e-1,1),e-1,o?e-1:n)}else this.unplaced=new _m(Sy(t,e,1),e,n)}placeNodes({sliceDepth:t,frontierDepth:e,parent:n,inject:r,wrap:o}){for(;this.depth>e;)this.closeFrontierNode();if(o)for(let f=0;f<o.length;f++)this.openFrontierNode(o[f]);let i=this.unplaced,s=n?n.content:i.content,a=i.openStart-t,l=0,c=[],{match:d,type:u}=this.frontier[e];if(r){for(let t=0;t<r.childCount;t++)c.push(r.child(t));d=d.matchFragment(r)}let p=s.size+t-(i.content.size-i.openEnd);for(;l<s.childCount;){let t=s.child(l),e=d.matchType(t.type);if(!e)break;l++,(l>1||0==a||t.content.size)&&(d=e,c.push(Iy(t.mark(u.allowedMarks(t.marks)),1==l?a:0,l==s.childCount?p:-1)))}let h=l==s.childCount;h||(p=-1),this.placed=Py(this.placed,e,Bm.from(c)),this.frontier[e].match=d,h&&p<0&&n&&n.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let f=0,m=s;f<p;f++){let t=m.lastChild;this.frontier.push({type:t.type,match:t.contentMatchAt(t.childCount)}),m=t.content}this.unplaced=h?0==t?_m.empty:new _m(Sy(i.content,t-1,1),t-1,p<0?i.openEnd:t-1):new _m(Sy(i.content,t,l),i.openStart,i.openEnd)}mustMoveInline(){if(!this.$to.parent.isTextblock)return-1;let t,e=this.frontier[this.depth];if(!e.type.isTextblock||!Ty(this.$to,this.$to.depth,e.type,e.match,!1)||this.$to.depth==this.depth&&(t=this.findCloseLevel(this.$to))&&t.depth==this.depth)return-1;let{depth:n}=this.$to,r=this.$to.after(n);for(;n>1&&r==this.$to.end(--n);)++r;return r}findCloseLevel(t){t:for(let e=Math.min(this.depth,t.depth);e>=0;e--){let{match:n,type:r}=this.frontier[e],o=e<t.depth&&t.end(e+1)==t.pos+(t.depth-(e+1)),i=Ty(t,e,r,n,o);if(i){for(let n=e-1;n>=0;n--){let{match:e,type:r}=this.frontier[n],o=Ty(t,n,r,e,!0);if(!o||o.childCount)continue t}return{depth:e,fit:i,move:o?t.doc.resolve(t.after(e+1)):t}}}}close(t){let e=this.findCloseLevel(t);if(!e)return null;for(;this.depth>e.depth;)this.closeFrontierNode();e.fit.childCount&&(this.placed=Py(this.placed,e.depth,e.fit)),t=e.move;for(let n=e.depth+1;n<=t.depth;n++){let e=t.node(n),r=e.type.contentMatch.fillBefore(e.content,!0,t.index(n));this.openFrontierNode(e.type,e.attrs,r)}return t}openFrontierNode(t,e=null,n){let r=this.frontier[this.depth];r.match=r.match.matchType(t),this.placed=Py(this.placed,this.depth,Bm.from(t.create(e,n))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(Bm.empty,!0);t.childCount&&(this.placed=Py(this.placed,this.frontier.length,t))}};function Sy(t,e,n){return 0==e?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(Sy(t.firstChild.content,e-1,n)))}function Py(t,e,n){return 0==e?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(Py(t.lastChild.content,e-1,n)))}function My(t,e){for(let n=0;n<e;n++)t=t.firstChild.content;return t}function Iy(t,e,n){if(e<=0)return t;let r=t.content;return e>1&&(r=r.replaceChild(0,Iy(r.firstChild,e-1,1==r.childCount?n-1:0))),e>0&&(r=t.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(t.type.contentMatch.matchFragment(r).fillBefore(Bm.empty,!0)))),t.copy(r)}function Ty(t,e,n,r,o){let i=t.node(e),s=o?t.indexAfter(e):t.index(e);if(s==i.childCount&&!n.compatibleContent(i.type))return null;let a=r.fillBefore(i.content,!0,s);return a&&!function(t,e,n){for(let r=n;r<e.childCount;r++)if(!t.allowsMarks(e.child(r).marks))return!0;return!1}(n,i.content,s)?a:null}function Cy(t){return t.spec.defining||t.spec.definingForContent}function Ey(t,e,n,r,o){if(e<n){let o=t.firstChild;t=t.replaceChild(0,o.copy(Ey(o.content,e+1,n,r,o)))}if(e>r){let e=o.contentMatchAt(0),n=e.fillBefore(t).append(t);t=n.append(e.matchFragment(n).fillBefore(Bm.empty,!0))}return t}function Ay(t,e){let n=[];for(let r=Math.min(t.depth,e.depth);r>=0;r--){let o=t.start(r);if(o<t.pos-(t.depth-r)||e.end(r)>e.pos+(e.depth-r)||t.node(r).type.spec.isolating||e.node(r).type.spec.isolating)break;(o==e.start(r)||r==t.depth&&r==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&r&&e.start(r-1)==o-1)&&n.push(r)}return n}var Oy=class t extends Zg{constructor(t,e,n){super(),this.pos=t,this.attr=e,this.value=n}apply(t){let e=t.nodeAt(this.pos);if(!e)return Qg.fail("No node at attribute step's position");let n=Object.create(null);for(let o in e.attrs)n[o]=e.attrs[o];n[this.attr]=this.value;let r=e.type.create(n,null,e.marks);return Qg.fromReplace(t,this.pos,this.pos+1,new _m(Bm.from(r),0,e.isLeaf?0:1))}getMap(){return Yg.empty}invert(e){return new t(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new t(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,n){if("number"!=typeof n.pos||"string"!=typeof n.attr)throw new RangeError("Invalid input for AttrStep.fromJSON");return new t(n.pos,n.attr,n.value)}};Zg.jsonID("attr",Oy);var Ny=class t extends Zg{constructor(t,e){super(),this.attr=t,this.value=e}apply(t){let e=Object.create(null);for(let r in t.attrs)e[r]=t.attrs[r];e[this.attr]=this.value;let n=t.type.create(e,t.content,t.marks);return Qg.ok(n)}getMap(){return Yg.empty}invert(e){return new t(this.attr,e.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,n){if("string"!=typeof n.attr)throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new t(n.attr,n.value)}};Zg.jsonID("docAttr",Ny);var Ry=Error;Ry=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n},(Ry.prototype=Object.create(Error.prototype)).constructor=Ry,Ry.prototype.name="TransformError";var Ly=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new Jg}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let e=this.maybeStep(t);if(e.failed)throw new Ry(e.failed);return this}maybeStep(t){let e=t.apply(this.doc);return e.failed||this.addStep(t,e.doc),e}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,e=-1e9;for(let n=0;n<this.mapping.maps.length;n++){let r=this.mapping.maps[n];n&&(t=r.map(t,1),e=r.map(e,-1)),r.forEach((n,r,o,i)=>{t=Math.min(t,o),e=Math.max(e,i)})}return 1e9==t?null:{from:t,to:e}}addStep(t,e){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=e}replace(t,e=t,n=_m.empty){let r=by(this.doc,t,e,n);return r&&this.step(r),this}replaceWith(t,e,n){return this.replace(t,e,new _m(Bm.from(n),0,0))}delete(t,e){return this.replace(t,e,_m.empty)}insert(t,e){return this.replaceWith(t,t,e)}replaceRange(t,e,n){return function(t,e,n,r){if(!r.size)return t.deleteRange(e,n);let o=t.doc.resolve(e),i=t.doc.resolve(n);if(vy(o,i,r))return t.step(new iy(e,n,r));let s=Ay(o,i);0==s[s.length-1]&&s.pop();let a=-(o.depth+1);s.unshift(a);for(let p=o.depth,h=o.pos-1;p>0;p--,h--){let t=o.node(p).type.spec;if(t.defining||t.definingAsContext||t.isolating)break;s.indexOf(p)>-1?a=p:o.before(p)==h&&s.splice(1,0,-p)}let l=s.indexOf(a),c=[],d=r.openStart;for(let p=r.content,h=0;;h++){let t=p.firstChild;if(c.push(t),h==r.openStart)break;p=t.content}for(let p=d-1;p>=0;p--){let t=c[p],e=Cy(t.type);if(e&&!t.sameMarkup(o.node(Math.abs(a)-1)))d=p;else if(e||!t.type.isTextblock)break}for(let p=r.openStart;p>=0;p--){let e=(p+d+1)%(r.openStart+1),a=c[e];if(a)for(let c=0;c<s.length;c++){let d=s[(c+l)%s.length],u=!0;d<0&&(u=!1,d=-d);let p=o.node(d-1),h=o.index(d-1);if(p.canReplaceWith(h,h,a.type,a.marks))return t.replace(o.before(d),u?i.after(d):n,new _m(Ey(r.content,0,r.openStart,e),e,r.openEnd))}}let u=t.steps.length;for(let p=s.length-1;p>=0&&(t.replace(e,n,r),!(t.steps.length>u));p--){let t=s[p];t<0||(e=o.before(t),n=i.after(t))}}(this,t,e,n),this}replaceRangeWith(t,e,n){return function(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let o=function(t,e,n){let r=t.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),n))return e;if(0==r.parentOffset)for(let o=r.depth-1;o>=0;o--){let t=r.index(o);if(r.node(o).canReplaceWith(t,t,n))return r.before(o+1);if(t>0)return null}if(r.parentOffset==r.parent.content.size)for(let o=r.depth-1;o>=0;o--){let t=r.indexAfter(o);if(r.node(o).canReplaceWith(t,t,n))return r.after(o+1);if(t<r.node(o).childCount)return null}return null}(t.doc,e,r.type);null!=o&&(e=n=o)}t.replaceRange(e,n,new _m(Bm.from(r),0,0))}(this,t,e,n),this}deleteRange(t,e){return function(t,e,n){let r=t.doc.resolve(e),o=t.doc.resolve(n);if(r.parent.isTextblock&&o.parent.isTextblock&&r.start()!=o.start()&&0==r.parentOffset&&0==o.parentOffset){let i=r.sharedDepth(n),s=!1;for(let t=r.depth;t>i;t--)r.node(t).type.spec.isolating&&(s=!0);for(let t=o.depth;t>i;t--)o.node(t).type.spec.isolating&&(s=!0);if(!s){for(let t=r.depth;t>0&&e==r.start(t);t--)e=r.before(t);for(let t=o.depth;t>0&&n==o.start(t);t--)n=o.before(t);r=t.doc.resolve(e),o=t.doc.resolve(n)}}let i=Ay(r,o);for(let s=0;s<i.length;s++){let e=i[s],n=s==i.length-1;if(n&&0==e||r.node(e).type.contentMatch.validEnd)return t.delete(r.start(e),o.end(e));if(e>0&&(n||r.node(e-1).canReplace(r.index(e-1),o.indexAfter(e-1))))return t.delete(r.before(e),o.after(e))}for(let s=1;s<=r.depth&&s<=o.depth;s++)if(e-r.start(s)==r.depth-s&&n>r.end(s)&&o.end(s)-n!=o.depth-s&&r.start(s-1)==o.start(s-1)&&r.node(s-1).canReplace(r.index(s-1),o.index(s-1)))return t.delete(r.before(s),n);t.delete(e,n)}(this,t,e),this}lift(t,e){return function(t,e,n){let{$from:r,$to:o,depth:i}=e,s=r.before(i+1),a=o.after(i+1),l=s,c=a,d=Bm.empty,u=0;for(let f=i,m=!1;f>n;f--)m||r.index(f)>0?(m=!0,d=Bm.from(r.node(f).copy(d)),u++):l--;let p=Bm.empty,h=0;for(let f=i,m=!1;f>n;f--)m||o.after(f+1)<o.end(f)?(m=!0,p=Bm.from(o.node(f).copy(p)),h++):c++;t.step(new sy(l,c,s,a,new _m(d.append(p),u,h),d.size-u,!0))}(this,t,e),this}join(t,e=1){return function(t,e,n){let r=null,{linebreakReplacement:o}=t.doc.type.schema,i=t.doc.resolve(e-n),s=i.node().type;if(o&&s.inlineContent){let t="pre"==s.whitespace,e=!!s.contentMatch.matchType(o);t&&!e?r=!1:!t&&e&&(r=!0)}let a=t.steps.length;if(!1===r){let r=t.doc.resolve(e+n);fy(t,r.node(),r.before(),a)}s.inlineContent&&ly(t,e+n-1,s,i.node().contentMatchAt(i.index()),null==r);let l=t.mapping.slice(a),c=l.map(e-n);if(t.step(new iy(c,l.map(e+n,-1),_m.empty,!0)),!0===r){let e=t.doc.resolve(c);hy(t,e.node(),e.before(),t.steps.length)}}(this,t,e),this}wrap(t,e){return function(t,e,n){let r=Bm.empty;for(let s=n.length-1;s>=0;s--){if(r.size){let t=n[s].type.contentMatch.matchFragment(r);if(!t||!t.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=Bm.from(n[s].type.create(n[s].attrs,r))}let o=e.start,i=e.end;t.step(new sy(o,i,o,i,new _m(r,0,0),n.length,!0))}(this,t,e),this}setBlockType(t,e=t,n,r=null){return function(t,e,n,r,o){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let i=t.steps.length;t.doc.nodesBetween(e,n,(e,n)=>{let s="function"==typeof o?o(e):o;if(e.isTextblock&&!e.hasMarkup(r,s)&&function(t,e,n){let r=t.resolve(e),o=r.index();return r.parent.canReplaceWith(o,o+1,n)}(t.doc,t.mapping.slice(i).map(n),r)){let o=null;if(r.schema.linebreakReplacement){let t="pre"==r.whitespace,e=!!r.contentMatch.matchType(r.schema.linebreakReplacement);t&&!e?o=!1:!t&&e&&(o=!0)}!1===o&&fy(t,e,n,i),ly(t,t.mapping.slice(i).map(n,1),r,void 0,null===o);let a=t.mapping.slice(i),l=a.map(n,1),c=a.map(n+e.nodeSize,1);return t.step(new sy(l,c,l+1,c-1,new _m(Bm.from(r.create(s,null,e.marks)),0,0),1,!0)),!0===o&&hy(t,e,n,i),!1}})}(this,t,e,n,r),this}setNodeMarkup(t,e,n=null,r){return function(t,e,n,r,o){let i=t.doc.nodeAt(e);if(!i)throw new RangeError("No node at given position");n||(n=i.type);let s=n.create(r,null,o||i.marks);if(i.isLeaf)return t.replaceWith(e,e+i.nodeSize,s);if(!n.validContent(i.content))throw new RangeError("Invalid content for node type "+n.name);t.step(new sy(e,e+i.nodeSize,e+1,e+i.nodeSize-1,new _m(Bm.from(s),0,0),1,!0))}(this,t,e,n,r),this}setNodeAttribute(t,e,n){return this.step(new Oy(t,e,n)),this}setDocAttribute(t,e){return this.step(new Ny(t,e)),this}addNodeMark(t,e){return this.step(new ry(t,e)),this}removeNodeMark(t,e){let n=this.doc.nodeAt(t);if(!n)throw new RangeError("No node at position "+t);if(e instanceof Wm)e.isInSet(n.marks)&&this.step(new oy(t,e));else{let r,o=n.marks,i=[];for(;r=e.isInSet(o);)i.push(new oy(t,r)),o=r.removeFromSet(o);for(let t=i.length-1;t>=0;t--)this.step(i[t])}return this}split(t,e=1,n){return function(t,e,n=1,r){let o=t.doc.resolve(e),i=Bm.empty,s=Bm.empty;for(let a=o.depth,l=o.depth-n,c=n-1;a>l;a--,c--){i=Bm.from(o.node(a).copy(i));let t=r&&r[c];s=Bm.from(t?t.type.create(t.attrs,s):o.node(a).copy(s))}t.step(new iy(e,e,new _m(i.append(s),n,n),!0))}(this,t,e,n),this}addMark(t,e,n){return function(t,e,n,r){let o,i,s=[],a=[];t.doc.nodesBetween(e,n,(t,l,c)=>{if(!t.isInline)return;let d=t.marks;if(!r.isInSet(d)&&c.type.allowsMarkType(r.type)){let c=Math.max(l,e),u=Math.min(l+t.nodeSize,n),p=r.addToSet(d);for(let t=0;t<d.length;t++)d[t].isInSet(p)||(o&&o.to==c&&o.mark.eq(d[t])?o.to=u:s.push(o=new ny(c,u,d[t])));i&&i.to==c?i.to=u:a.push(i=new ey(c,u,r))}}),s.forEach(e=>t.step(e)),a.forEach(e=>t.step(e))}(this,t,e,n),this}removeMark(t,e,n){return function(t,e,n,r){let o=[],i=0;t.doc.nodesBetween(e,n,(t,s)=>{if(!t.isInline)return;i++;let a=null;if(r instanceof Ig){let e,n=t.marks;for(;e=r.isInSet(n);)(a||(a=[])).push(e),n=e.removeFromSet(n)}else r?r.isInSet(t.marks)&&(a=[r]):a=t.marks;if(a&&a.length){let r=Math.min(s+t.nodeSize,n);for(let t=0;t<a.length;t++){let n,l=a[t];for(let t=0;t<o.length;t++){let e=o[t];e.step==i-1&&l.eq(o[t].style)&&(n=e)}n?(n.to=r,n.step=i):o.push({style:l,from:Math.max(s,e),to:r,step:i})}}}),o.forEach(e=>t.step(new ny(e.from,e.to,e.style)))}(this,t,e,n),this}clearIncompatible(t,e,n){return ly(this,t,e,n),this}},$y=Object.create(null),Dy=class{constructor(t,e,n){this.$anchor=t,this.$head=e,this.ranges=n||[new By(t.min(e),t.max(e))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let t=this.ranges;for(let e=0;e<t.length;e++)if(t[e].$from.pos!=t[e].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(t,e=_m.empty){let n=e.content.lastChild,r=null;for(let s=0;s<e.openEnd;s++)r=n,n=n.lastChild;let o=t.steps.length,i=this.ranges;for(let s=0;s<i.length;s++){let{$from:a,$to:l}=i[s],c=t.mapping.slice(o);t.replaceRange(c.map(a.pos),c.map(l.pos),s?_m.empty:e),0==s&&qy(t,o,(n?n.isInline:r&&r.isTextblock)?-1:1)}}replaceWith(t,e){let n=t.steps.length,r=this.ranges;for(let o=0;o<r.length;o++){let{$from:i,$to:s}=r[o],a=t.mapping.slice(n),l=a.map(i.pos),c=a.map(s.pos);o?t.deleteRange(l,c):(t.replaceRangeWith(l,c,e),qy(t,n,e.isInline?-1:1))}}static findFrom(t,e,n=!1){let r=t.parent.inlineContent?new jy(t):Ky(t.node(0),t.parent,t.pos,t.index(),e,n);if(r)return r;for(let o=t.depth-1;o>=0;o--){let r=e<0?Ky(t.node(0),t.node(o),t.before(o+1),t.index(o),e,n):Ky(t.node(0),t.node(o),t.after(o+1),t.index(o)+1,e,n);if(r)return r}return null}static near(t,e=1){return this.findFrom(t,e)||this.findFrom(t,-e)||new Uy(t.node(0))}static atStart(t){return Ky(t,t,0,0,1)||new Uy(t)}static atEnd(t){return Ky(t,t,t.content.size,t.childCount,-1)||new Uy(t)}static fromJSON(t,e){if(!e||!e.type)throw new RangeError("Invalid input for Selection.fromJSON");let n=$y[e.type];if(!n)throw new RangeError(`No selection type ${e.type} defined`);return n.fromJSON(t,e)}static jsonID(t,e){if(t in $y)throw new RangeError("Duplicate use of selection JSON ID "+t);return $y[t]=e,e.prototype.jsonID=t,e}getBookmark(){return jy.between(this.$anchor,this.$head).getBookmark()}};Dy.prototype.visible=!0;var By=class{constructor(t,e){this.$from=t,this.$to=e}},zy=!1;function Fy(t){zy||t.parent.inlineContent||(zy=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}var jy=class t extends Dy{constructor(t,e=t){Fy(t),Fy(e),super(t,e)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,n){let r=e.resolve(n.map(this.head));if(!r.parent.inlineContent)return Dy.near(r);let o=e.resolve(n.map(this.anchor));return new t(o.parent.inlineContent?o:r,r)}replace(t,e=_m.empty){if(super.replace(t,e),e==_m.empty){let e=this.$from.marksAcross(this.$to);e&&t.ensureMarks(e)}}eq(e){return e instanceof t&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Wy(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,n){if("number"!=typeof n.anchor||"number"!=typeof n.head)throw new RangeError("Invalid input for TextSelection.fromJSON");return new t(e.resolve(n.anchor),e.resolve(n.head))}static create(t,e,n=e){let r=t.resolve(e);return new this(r,n==e?r:t.resolve(n))}static between(e,n,r){let o=e.pos-n.pos;if(r&&!o||(r=o>=0?1:-1),!n.parent.inlineContent){let t=Dy.findFrom(n,r,!0)||Dy.findFrom(n,-r,!0);if(!t)return Dy.near(n,r);n=t.$head}return e.parent.inlineContent||(0==o||(e=(Dy.findFrom(e,-r,!0)||Dy.findFrom(e,r,!0)).$anchor).pos<n.pos!=o<0)&&(e=n),new t(e,n)}};Dy.jsonID("text",jy);var Wy=class t{constructor(t,e){this.anchor=t,this.head=e}map(e){return new t(e.map(this.anchor),e.map(this.head))}resolve(t){return jy.between(t.resolve(this.anchor),t.resolve(this.head))}},Hy=class t extends Dy{constructor(t){let e=t.nodeAfter,n=t.node(0).resolve(t.pos+e.nodeSize);super(t,n),this.node=e}map(e,n){let{deleted:r,pos:o}=n.mapResult(this.anchor),i=e.resolve(o);return r?Dy.near(i):new t(i)}content(){return new _m(Bm.from(this.node),0,0)}eq(e){return e instanceof t&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new _y(this.anchor)}static fromJSON(e,n){if("number"!=typeof n.anchor)throw new RangeError("Invalid input for NodeSelection.fromJSON");return new t(e.resolve(n.anchor))}static create(e,n){return new t(e.resolve(n))}static isSelectable(t){return!t.isText&&!1!==t.type.spec.selectable}};Hy.prototype.visible=!1,Dy.jsonID("node",Hy);var _y=class t{constructor(t){this.anchor=t}map(e){let{deleted:n,pos:r}=e.mapResult(this.anchor);return n?new Wy(r,r):new t(r)}resolve(t){let e=t.resolve(this.anchor),n=e.nodeAfter;return n&&Hy.isSelectable(n)?new Hy(e):Dy.near(e)}},Uy=class t extends Dy{constructor(t){super(t.resolve(0),t.resolve(t.content.size))}replace(t,e=_m.empty){if(e==_m.empty){t.delete(0,t.doc.content.size);let e=Dy.atStart(t.doc);e.eq(t.selection)||t.setSelection(e)}else super.replace(t,e)}toJSON(){return{type:"all"}}static fromJSON(e){return new t(e)}map(e){return new t(e)}eq(e){return e instanceof t}getBookmark(){return Vy}};Dy.jsonID("all",Uy);var Vy={map(){return this},resolve:t=>new Uy(t)};function Ky(t,e,n,r,o,i=!1){if(e.inlineContent)return jy.create(t,n);for(let s=r-(o>0?0:1);o>0?s<e.childCount:s>=0;s+=o){let r=e.child(s);if(r.isAtom){if(!i&&Hy.isSelectable(r))return Hy.create(t,n-(o<0?r.nodeSize:0))}else{let e=Ky(t,r,n+o,o<0?r.childCount:0,o,i);if(e)return e}n+=r.nodeSize*o}return null}function qy(t,e,n){let r=t.steps.length-1;if(r<e)return;let o,i=t.steps[r];(i instanceof iy||i instanceof sy)&&(t.mapping.maps[r].forEach((t,e,n,r)=>{null==o&&(o=r)}),t.setSelection(Dy.near(t.doc.resolve(o),n)))}var Xy=class extends Ly{constructor(t){super(t.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=t.selection,this.storedMarks=t.storedMarks}get selection(){return this.curSelectionFor<this.steps.length&&(this.curSelection=this.curSelection.map(this.doc,this.mapping.slice(this.curSelectionFor)),this.curSelectionFor=this.steps.length),this.curSelection}setSelection(t){if(t.$from.doc!=this.doc)throw new RangeError("Selection passed to setSelection must point at the current document");return this.curSelection=t,this.curSelectionFor=this.steps.length,this.updated=-3&this.updated|1,this.storedMarks=null,this}get selectionSet(){return(1&this.updated)>0}setStoredMarks(t){return this.storedMarks=t,this.updated|=2,this}ensureMarks(t){return Wm.sameSet(this.storedMarks||this.selection.$from.marks(),t)||this.setStoredMarks(t),this}addStoredMark(t){return this.ensureMarks(t.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(t){return this.ensureMarks(t.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(2&this.updated)>0}addStep(t,e){super.addStep(t,e),this.updated=-3&this.updated,this.storedMarks=null}setTime(t){return this.time=t,this}replaceSelection(t){return this.selection.replace(this,t),this}replaceSelectionWith(t,e=!0){let n=this.selection;return e&&(t=t.mark(this.storedMarks||(n.empty?n.$from.marks():n.$from.marksAcross(n.$to)||Wm.none))),n.replaceWith(this,t),this}deleteSelection(){return this.selection.replace(this),this}insertText(t,e,n){let r=this.doc.type.schema;if(null==e)return t?this.replaceSelectionWith(r.text(t),!0):this.deleteSelection();{if(null==n&&(n=e),!t)return this.deleteRange(e,n);let o=this.storedMarks;if(!o){let t=this.doc.resolve(e);o=n==e?t.marks():t.marksAcross(this.doc.resolve(n))}return this.replaceRangeWith(e,n,r.text(t,o)),this.selection.empty||this.selection.to!=e+t.length||this.setSelection(Dy.near(this.selection.$to)),this}}setMeta(t,e){return this.meta["string"==typeof t?t:t.key]=e,this}getMeta(t){return this.meta["string"==typeof t?t:t.key]}get isGeneric(){for(let t in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=4,this}get scrolledIntoView(){return(4&this.updated)>0}};function Yy(t,e){return e&&t?t.bind(e):t}var Jy=class{constructor(t,e,n){this.name=t,this.init=Yy(e.init,n),this.apply=Yy(e.apply,n)}},Gy=[new Jy("doc",{init:t=>t.doc||t.schema.topNodeType.createAndFill(),apply:t=>t.doc}),new Jy("selection",{init:(t,e)=>t.selection||Dy.atStart(e.doc),apply:t=>t.selection}),new Jy("storedMarks",{init:t=>t.storedMarks||null,apply:(t,e,n,r)=>r.selection.$cursor?t.storedMarks:null}),new Jy("scrollToSelection",{init:()=>0,apply:(t,e)=>t.scrolledIntoView?e+1:e})],Zy=class{constructor(t,e){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=Gy.slice(),e&&e.forEach(t=>{if(this.pluginsByKey[t.key])throw new RangeError("Adding different instances of a keyed plugin ("+t.key+")");this.plugins.push(t),this.pluginsByKey[t.key]=t,t.spec.state&&this.fields.push(new Jy(t.key,t.spec.state,t))})}},Qy=class t{constructor(t){this.config=t}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(t){return this.applyTransaction(t).state}filterTransaction(t,e=-1){for(let n=0;n<this.config.plugins.length;n++)if(n!=e){let e=this.config.plugins[n];if(e.spec.filterTransaction&&!e.spec.filterTransaction.call(e,t,this))return!1}return!0}applyTransaction(t){if(!this.filterTransaction(t))return{state:this,transactions:[]};let e=[t],n=this.applyInner(t),r=null;for(;;){let o=!1;for(let i=0;i<this.config.plugins.length;i++){let s=this.config.plugins[i];if(s.spec.appendTransaction){let a=r?r[i].n:0,l=r?r[i].state:this,c=a<e.length&&s.spec.appendTransaction.call(s,a?e.slice(a):e,l,n);if(c&&n.filterTransaction(c,i)){if(c.setMeta("appendedTransaction",t),!r){r=[];for(let t=0;t<this.config.plugins.length;t++)r.push(t<i?{state:n,n:e.length}:{state:this,n:0})}e.push(c),n=n.applyInner(c),o=!0}r&&(r[i]={state:n,n:e.length})}}if(!o)return{state:n,transactions:e}}}applyInner(e){if(!e.before.eq(this.doc))throw new RangeError("Applying a mismatched transaction");let n=new t(this.config),r=this.config.fields;for(let t=0;t<r.length;t++){let o=r[t];n[o.name]=o.apply(e,this[o.name],this,n)}return n}get tr(){return new Xy(this)}static create(e){let n=new Zy(e.doc?e.doc.type.schema:e.schema,e.plugins),r=new t(n);for(let t=0;t<n.fields.length;t++)r[n.fields[t].name]=n.fields[t].init(e,r);return r}reconfigure(e){let n=new Zy(this.schema,e.plugins),r=n.fields,o=new t(n);for(let t=0;t<r.length;t++){let n=r[t].name;o[n]=this.hasOwnProperty(n)?this[n]:r[t].init(e,o)}return o}toJSON(t){let e={doc:this.doc.toJSON(),selection:this.selection.toJSON()};if(this.storedMarks&&(e.storedMarks=this.storedMarks.map(t=>t.toJSON())),t&&"object"==typeof t)for(let n in t){if("doc"==n||"selection"==n)throw new RangeError("The JSON fields `doc` and `selection` are reserved");let r=t[n],o=r.spec.state;o&&o.toJSON&&(e[n]=o.toJSON.call(r,this[r.key]))}return e}static fromJSON(e,n,r){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let o=new Zy(e.schema,e.plugins),i=new t(o);return o.fields.forEach(t=>{if("doc"==t.name)i.doc=ag.fromJSON(e.schema,n.doc);else if("selection"==t.name)i.selection=Dy.fromJSON(i.doc,n.selection);else if("storedMarks"==t.name)n.storedMarks&&(i.storedMarks=n.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let o in r){let s=r[o],a=s.spec.state;if(s.key==t.name&&a&&a.fromJSON&&Object.prototype.hasOwnProperty.call(n,o))return void(i[t.name]=a.fromJSON.call(s,e,n[o],i))}i[t.name]=t.init(e,i)}}),i}};function tx(t,e,n){for(let r in t){let o=t[r];o instanceof Function?o=o.bind(e):"handleDOMEvents"==r&&(o=tx(o,e,{})),n[r]=o}return n}var ex=class{constructor(t){this.spec=t,this.props={},t.props&&tx(t.props,this,this.props),this.key=t.key?t.key.key:rx("plugin")}getState(t){return t[this.key]}},nx=Object.create(null);function rx(t){return t in nx?t+"$"+ ++nx[t]:(nx[t]=0,t+"$")}var ox=class{constructor(t="key"){this.key=rx(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}},ix=(t,e)=>!t.selection.empty&&(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function sx(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}var ax=(t,e,n)=>{let r=sx(t,n);if(!r)return!1;let o=ux(r);if(!o){let n=r.blockRange(),o=n&&dy(n);return null!=o&&(e&&e(t.tr.lift(n,o).scrollIntoView()),!0)}let i=o.nodeBefore;if(Sx(t,o,e,-1))return!0;if(0==r.parent.content.size&&(cx(i,"end")||Hy.isSelectable(i)))for(let s=r.depth;;s--){let n=by(t.doc,r.before(s),r.after(s),_m.empty);if(n&&n.slice.size<n.to-n.from){if(e){let r=t.tr.step(n);r.setSelection(cx(i,"end")?Dy.findFrom(r.doc.resolve(r.mapping.map(o.pos,-1)),-1):Hy.create(r.doc,o.pos-i.nodeSize)),e(r.scrollIntoView())}return!0}if(1==s||r.node(s-1).childCount>1)break}return!(!i.isAtom||o.depth!=r.depth-1)&&(e&&e(t.tr.delete(o.pos-i.nodeSize,o.pos).scrollIntoView()),!0)};function lx(t,e,n){let r=e.nodeBefore,o=e.pos-1;for(;!r.isTextblock;o--){if(r.type.spec.isolating)return!1;let t=r.lastChild;if(!t)return!1;r=t}let i=e.nodeAfter,s=e.pos+1;for(;!i.isTextblock;s++){if(i.type.spec.isolating)return!1;let t=i.firstChild;if(!t)return!1;i=t}let a=by(t.doc,o,s,_m.empty);if(!a||a.from!=o||a instanceof iy&&a.slice.size>=s-o)return!1;if(n){let e=t.tr.step(a);e.setSelection(jy.create(e.doc,o)),n(e.scrollIntoView())}return!0}function cx(t,e,n=!1){for(let r=t;r;r="start"==e?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&1!=r.childCount)return!1}return!1}var dx=(t,e,n)=>{let{$head:r,empty:o}=t.selection,i=r;if(!o)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;i=ux(r)}let s=i&&i.nodeBefore;return!(!s||!Hy.isSelectable(s))&&(e&&e(t.tr.setSelection(Hy.create(t.doc,i.pos-s.nodeSize)).scrollIntoView()),!0)};function ux(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){if(t.index(e)>0)return t.doc.resolve(t.before(e+1));if(t.node(e).type.spec.isolating)break}return null}function px(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset<n.parent.content.size)?null:n}var hx=(t,e,n)=>{let r=px(t,n);if(!r)return!1;let o=mx(r);if(!o)return!1;let i=o.nodeAfter;if(Sx(t,o,e,1))return!0;if(0==r.parent.content.size&&(cx(i,"start")||Hy.isSelectable(i))){let n=by(t.doc,r.before(),r.after(),_m.empty);if(n&&n.slice.size<n.to-n.from){if(e){let r=t.tr.step(n);r.setSelection(cx(i,"start")?Dy.findFrom(r.doc.resolve(r.mapping.map(o.pos)),1):Hy.create(r.doc,r.mapping.map(o.pos))),e(r.scrollIntoView())}return!0}}return!(!i.isAtom||o.depth!=r.depth-1)&&(e&&e(t.tr.delete(o.pos,o.pos+i.nodeSize).scrollIntoView()),!0)},fx=(t,e,n)=>{let{$head:r,empty:o}=t.selection,i=r;if(!o)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):r.parentOffset<r.parent.content.size)return!1;i=mx(r)}let s=i&&i.nodeAfter;return!(!s||!Hy.isSelectable(s))&&(e&&e(t.tr.setSelection(Hy.create(t.doc,i.pos)).scrollIntoView()),!0)};function mx(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){let n=t.node(e);if(t.index(e)+1<n.childCount)return t.doc.resolve(t.after(e+1));if(n.type.spec.isolating)break}return null}var gx=(t,e)=>{let{$head:n,$anchor:r}=t.selection;return!(!n.parent.type.spec.code||!n.sameParent(r))&&(e&&e(t.tr.insertText("\n").scrollIntoView()),!0)};function yx(t){for(let e=0;e<t.edgeCount;e++){let{type:n}=t.edge(e);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}var xx=(t,e)=>{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let o=n.node(-1),i=n.indexAfter(-1),s=yx(o.contentMatchAt(i));if(!s||!o.canReplaceWith(i,i,s))return!1;if(e){let r=n.after(),o=t.tr.replaceWith(r,r,s.createAndFill());o.setSelection(Dy.near(o.doc.resolve(r),1)),e(o.scrollIntoView())}return!0},wx=(t,e)=>{let n=t.selection,{$from:r,$to:o}=n;if(n instanceof Uy||r.parent.inlineContent||o.parent.inlineContent)return!1;let i=yx(o.parent.contentMatchAt(o.indexAfter()));if(!i||!i.isTextblock)return!1;if(e){let n=(!r.parentOffset&&o.index()<o.parent.childCount?r:o).pos,s=t.tr.insert(n,i.createAndFill());s.setSelection(jy.create(s.doc,n+1)),e(s.scrollIntoView())}return!0},bx=(t,e)=>{let{$cursor:n}=t.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let r=n.before();if(my(t.doc,r))return e&&e(t.tr.split(r).scrollIntoView()),!0}let r=n.blockRange(),o=r&&dy(r);return null!=o&&(e&&e(t.tr.lift(r,o).scrollIntoView()),!0)};var vx,kx=(t,e)=>{let{$from:n,$to:r}=t.selection;if(t.selection instanceof Hy&&t.selection.node.isBlock)return!(!n.parentOffset||!my(t.doc,n.pos)||(e&&e(t.tr.split(n.pos).scrollIntoView()),0));if(!n.depth)return!1;let o,i,s=[],a=!1,l=!1;for(let p=n.depth;;p--){if(n.node(p).isBlock){a=n.end(p)==n.pos+(n.depth-p),l=n.start(p)==n.pos-(n.depth-p),i=yx(n.node(p-1).contentMatchAt(n.indexAfter(p-1)));let t=vx&&vx(r.parent,a,n);s.unshift(t||(a&&i?{type:i}:null)),o=p;break}if(1==p)return!1;s.unshift(null)}let c=t.tr;(t.selection instanceof jy||t.selection instanceof Uy)&&c.deleteSelection();let d=c.mapping.map(n.pos),u=my(c.doc,d,s.length,s);if(u||(s[0]=i?{type:i}:null,u=my(c.doc,d,s.length,s)),!u)return!1;if(c.split(d,s.length,s),!a&&l&&n.node(o).type!=i){let t=c.mapping.map(n.before(o)),e=c.doc.resolve(t);i&&n.node(o-1).canReplaceWith(e.index(),e.index()+1,i)&&c.setNodeMarkup(c.mapping.map(n.before(o)),i)}return e&&e(c.scrollIntoView()),!0};function Sx(t,e,n,r){let o,i,s=e.nodeBefore,a=e.nodeAfter,l=s.type.spec.isolating||a.type.spec.isolating;if(!l&&function(t,e,n){let r=e.nodeBefore,o=e.nodeAfter,i=e.index();return!(!(r&&o&&r.type.compatibleContent(o.type))||(!r.content.size&&e.parent.canReplace(i-1,i)?(n&&n(t.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),0):!e.parent.canReplace(i,i+1)||!o.isTextblock&&!gy(t.doc,e.pos)||(n&&n(t.tr.join(e.pos).scrollIntoView()),0)))}(t,e,n))return!0;let c=!l&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(i=s.contentMatchAt(s.childCount)).findWrapping(a.type))&&i.matchType(o[0]||a.type).validEnd){if(n){let r=e.pos+a.nodeSize,i=Bm.empty;for(let t=o.length-1;t>=0;t--)i=Bm.from(o[t].create(null,i));i=Bm.from(s.copy(i));let l=t.tr.step(new sy(e.pos-1,r,e.pos,r,new _m(i,1,0),o.length,!0)),c=l.doc.resolve(r+2*o.length);c.nodeAfter&&c.nodeAfter.type==s.type&&gy(l.doc,c.pos)&&l.join(c.pos),n(l.scrollIntoView())}return!0}let d=a.type.spec.isolating||r>0&&l?null:Dy.findFrom(e,1),u=d&&d.$from.blockRange(d.$to),p=u&&dy(u);if(null!=p&&p>=e.depth)return n&&n(t.tr.lift(u,p).scrollIntoView()),!0;if(c&&cx(a,"start",!0)&&cx(s,"end")){let r=s,o=[];for(;o.push(r),!r.isTextblock;)r=r.lastChild;let i=a,l=1;for(;!i.isTextblock;i=i.firstChild)l++;if(r.canReplace(r.childCount,r.childCount,i.content)){if(n){let r=Bm.empty;for(let t=o.length-1;t>=0;t--)r=Bm.from(o[t].copy(r));n(t.tr.step(new sy(e.pos-o.length,e.pos+a.nodeSize,e.pos+l,e.pos+a.nodeSize-l,new _m(r,o.length,0),0,!0)).scrollIntoView())}return!0}}return!1}function Px(t){return function(e,n){let r=e.selection,o=t<0?r.$from:r.$to,i=o.depth;for(;o.node(i).isInline;){if(!i)return!1;i--}return!!o.node(i).isTextblock&&(n&&n(e.tr.setSelection(jy.create(e.doc,t<0?o.start(i):o.end(i)))),!0)}}var Mx=Px(-1),Ix=Px(1);function Tx(t,e=null){return function(n,r){let o=!1;for(let i=0;i<n.selection.ranges.length&&!o;i++){let{$from:{pos:r},$to:{pos:s}}=n.selection.ranges[i];n.doc.nodesBetween(r,s,(r,i)=>{if(o)return!1;if(r.isTextblock&&!r.hasMarkup(t,e))if(r.type==t)o=!0;else{let e=n.doc.resolve(i),r=e.index();o=e.parent.canReplaceWith(r,r+1,t)}})}if(!o)return!1;if(r){let o=n.tr;for(let r=0;r<n.selection.ranges.length;r++){let{$from:{pos:i},$to:{pos:s}}=n.selection.ranges[r];o.setBlockType(i,s,t,e)}r(o.scrollIntoView())}return!0}}function Cx(...t){return function(e,n,r){for(let o=0;o<t.length;o++)if(t[o](e,n,r))return!0;return!1}}var Ex=Cx(ix,ax,dx),Ax=Cx(ix,hx,fx),Ox={Enter:Cx(gx,wx,bx,kx),"Mod-Enter":xx,Backspace:Ex,"Mod-Backspace":Ex,"Shift-Backspace":Ex,Delete:Ax,"Mod-Delete":Ax,"Mod-a":(t,e)=>(e&&e(t.tr.setSelection(new Uy(t.doc))),!0)},Nx={"Ctrl-h":Ox.Backspace,"Alt-Backspace":Ox["Mod-Backspace"],"Ctrl-d":Ox.Delete,"Ctrl-Alt-Backspace":Ox["Mod-Delete"],"Alt-Delete":Ox["Mod-Delete"],"Alt-d":Ox["Mod-Delete"],"Ctrl-a":Mx,"Ctrl-e":Ix};for(let os in Ox)Nx[os]=Ox[os];"undefined"!=typeof navigator?/Mac|iP(hone|[oa]d)/.test(navigator.platform):"undefined"!=typeof os&&os.platform&&os.platform();function Rx(t,e=null){return function(n,r){let{$from:o,$to:i}=n.selection,s=o.blockRange(i);if(!s)return!1;let a=r?n.tr:null;return!!function(t,e,n,r=null){let o=!1,i=e,s=e.$from.doc;if(e.depth>=2&&e.$from.node(e.depth-1).type.compatibleContent(n)&&0==e.startIndex){if(0==e.$from.index(e.depth-1))return!1;let t=s.resolve(e.start-2);i=new ig(t,t,e.depth),e.endIndex<e.parent.childCount&&(e=new ig(e.$from,s.resolve(e.$to.end(e.depth)),e.depth)),o=!0}let a=uy(i,n,r,e);if(!a)return!1;t&&function(t,e,n,r,o){let i=Bm.empty;for(let d=n.length-1;d>=0;d--)i=Bm.from(n[d].type.create(n[d].attrs,i));t.step(new sy(e.start-(r?2:0),e.end,e.start,e.end,new _m(i,0,0),n.length,!0));let s=0;for(let d=0;d<n.length;d++)n[d].type==o&&(s=d+1);let a=n.length-s,l=e.start+n.length-(r?2:0),c=e.parent;for(let d=e.startIndex,u=e.endIndex,p=!0;d<u;d++,p=!1)!p&&my(t.doc,l,a)&&(t.split(l,a),l+=2*a),l+=c.child(d).nodeSize}(t,e,a,o,n);return!0}(a,s,t,e)&&(r&&r(a.scrollIntoView()),!0)}}function Lx(t){return function(e,n){let{$from:r,$to:o}=e.selection,i=r.blockRange(o,e=>e.childCount>0&&e.firstChild.type==t);return!!i&&(!n||(r.node(i.depth-1).type==t?function(t,e,n,r){let o=t.tr,i=r.end,s=r.$to.end(r.depth);i<s&&(o.step(new sy(i-1,s,i,s,new _m(Bm.from(n.create(null,r.parent.copy())),1,0),1,!0)),r=new ig(o.doc.resolve(r.$from.pos),o.doc.resolve(s),r.depth));const a=dy(r);if(null==a)return!1;o.lift(r,a);let l=o.doc.resolve(o.mapping.map(i,-1)-1);gy(o.doc,l.pos)&&l.nodeBefore.type==l.nodeAfter.type&&o.join(l.pos);return e(o.scrollIntoView()),!0}(e,n,t,i):function(t,e,n){let r=t.tr,o=n.parent;for(let h=n.end,f=n.endIndex-1,m=n.startIndex;f>m;f--)h-=o.child(f).nodeSize,r.delete(h-1,h+1);let i=r.doc.resolve(n.start),s=i.nodeAfter;if(r.mapping.map(n.end)!=n.start+i.nodeAfter.nodeSize)return!1;let a=0==n.startIndex,l=n.endIndex==o.childCount,c=i.node(-1),d=i.index(-1);if(!c.canReplace(d+(a?0:1),d+1,s.content.append(l?Bm.empty:Bm.from(o))))return!1;let u=i.pos,p=u+s.nodeSize;return r.step(new sy(u-(a?1:0),p+(l?1:0),u+1,p-1,new _m((a?Bm.empty:Bm.from(o.copy(Bm.empty))).append(l?Bm.empty:Bm.from(o.copy(Bm.empty))),a?0:1,l?0:1),a?0:1)),e(r.scrollIntoView()),!0}(e,n,i)))}}var $x=function(t){for(var e=0;;e++)if(!(t=t.previousSibling))return e},Dx=function(t){let e=t.assignedSlot||t.parentNode;return e&&11==e.nodeType?e.host:e},Bx=null,zx=function(t,e,n){let r=Bx||(Bx=document.createRange());return r.setEnd(t,null==n?t.nodeValue.length:n),r.setStart(t,e||0),r},Fx=function(t,e,n,r){return n&&(Wx(t,e,n,r,-1)||Wx(t,e,n,r,1))},jx=/^(img|br|input|textarea|hr)$/i;function Wx(t,e,n,r,o){for(var i;;){if(t==n&&e==r)return!0;if(e==(o<0?0:Hx(t))){let n=t.parentNode;if(!n||1!=n.nodeType||_x(t)||jx.test(t.nodeName)||"false"==t.contentEditable)return!1;e=$x(t)+(o<0?0:1),t=n}else{if(1!=t.nodeType)return!1;{let n=t.childNodes[e+(o<0?-1:0)];if(1==n.nodeType&&"false"==n.contentEditable){if(!(null===(i=n.pmViewDesc)||void 0===i?void 0:i.ignoreForSelection))return!1;e+=o}else t=n,e=o<0?Hx(t):0}}}}function Hx(t){return 3==t.nodeType?t.nodeValue.length:t.childNodes.length}function _x(t){let e;for(let n=t;n&&!(e=n.pmViewDesc);n=n.parentNode);return e&&e.node&&e.node.isBlock&&(e.dom==t||e.contentDOM==t)}var Ux=function(t){return t.focusNode&&Fx(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset)};function Vx(t,e){let n=document.createEvent("Event");return n.initEvent("keydown",!0,!0),n.keyCode=t,n.key=n.code=e,n}var Kx="undefined"!=typeof navigator?navigator:null,qx="undefined"!=typeof document?document:null,Xx=Kx&&Kx.userAgent||"",Yx=/Edge\/(\d+)/.exec(Xx),Jx=/MSIE \d/.exec(Xx),Gx=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(Xx),Zx=!!(Jx||Gx||Yx),Qx=Jx?document.documentMode:Gx?+Gx[1]:Yx?+Yx[1]:0,tw=!Zx&&/gecko\/(\d+)/i.test(Xx);tw&&(/Firefox\/(\d+)/.exec(Xx)||[0,0])[1];var ew=!Zx&&/Chrome\/(\d+)/.exec(Xx),nw=!!ew,rw=ew?+ew[1]:0,ow=!Zx&&!!Kx&&/Apple Computer/.test(Kx.vendor),iw=ow&&(/Mobile\/\w+/.test(Xx)||!!Kx&&Kx.maxTouchPoints>2),sw=iw||!!Kx&&/Mac/.test(Kx.platform),aw=!!Kx&&/Win/.test(Kx.platform),lw=/Android \d/.test(Xx),cw=!!qx&&"webkitFontSmoothing"in qx.documentElement.style,dw=cw?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function uw(t){let e=t.defaultView&&t.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:t.documentElement.clientWidth,top:0,bottom:t.documentElement.clientHeight}}function pw(t,e){return"number"==typeof t?t:t[e]}function hw(t){let e=t.getBoundingClientRect(),n=e.width/t.offsetWidth||1,r=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*n,top:e.top,bottom:e.top+t.clientHeight*r}}function fw(t,e,n){let r=t.someProp("scrollThreshold")||0,o=t.someProp("scrollMargin")||5,i=t.dom.ownerDocument;for(let s=n||t.dom;s;){if(1!=s.nodeType){s=Dx(s);continue}let t=s,n=t==i.body,a=n?uw(i):hw(t),l=0,c=0;if(e.top<a.top+pw(r,"top")?c=-(a.top-e.top+pw(o,"top")):e.bottom>a.bottom-pw(r,"bottom")&&(c=e.bottom-e.top>a.bottom-a.top?e.top+pw(o,"top")-a.top:e.bottom-a.bottom+pw(o,"bottom")),e.left<a.left+pw(r,"left")?l=-(a.left-e.left+pw(o,"left")):e.right>a.right-pw(r,"right")&&(l=e.right-a.right+pw(o,"right")),l||c)if(n)i.defaultView.scrollBy(l,c);else{let n=t.scrollLeft,r=t.scrollTop;c&&(t.scrollTop+=c),l&&(t.scrollLeft+=l);let o=t.scrollLeft-n,i=t.scrollTop-r;e={left:e.left-o,top:e.top-i,right:e.right-o,bottom:e.bottom-i}}let d=n?"fixed":getComputedStyle(s).position;if(/^(fixed|sticky)$/.test(d))break;s="absolute"==d?s.offsetParent:Dx(s)}}function mw(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=Dx(r));return e}function gw(t,e){for(let n=0;n<t.length;n++){let{dom:r,top:o,left:i}=t[n];r.scrollTop!=o+e&&(r.scrollTop=o+e),r.scrollLeft!=i&&(r.scrollLeft=i)}}var yw=null;function xw(t,e){let n,r,o,i,s=2e8,a=0,l=e.top,c=e.top;for(let d=t.firstChild,u=0;d;d=d.nextSibling,u++){let t;if(1==d.nodeType)t=d.getClientRects();else{if(3!=d.nodeType)continue;t=zx(d).getClientRects()}for(let p=0;p<t.length;p++){let h=t[p];if(h.top<=l&&h.bottom>=c){l=Math.max(h.bottom,l),c=Math.min(h.top,c);let t=h.left>e.left?h.left-e.left:h.right<e.left?e.left-h.right:0;if(t<s){n=d,s=t,r=t&&3==n.nodeType?{left:h.right<e.left?h.right:h.left,top:e.top}:e,1==d.nodeType&&t&&(a=u+(e.left>=(h.left+h.right)/2?1:0));continue}}else h.top>e.top&&!o&&h.left<=e.left&&h.right>=e.left&&(o=d,i={left:Math.max(h.left,Math.min(h.right,e.left)),top:h.top});!n&&(e.left>=h.right&&e.top>=h.top||e.left>=h.left&&e.top>=h.bottom)&&(a=u+1)}}return!n&&o&&(n=o,r=i,s=0),n&&3==n.nodeType?function(t,e){let n,r=t.nodeValue.length,o=document.createRange();for(let i=0;i<r;i++){o.setEnd(t,i+1),o.setStart(t,i);let r=Sw(o,1);if(r.top!=r.bottom&&ww(e,r)){n={node:t,offset:i+(e.left>=(r.left+r.right)/2?1:0)};break}}return o.detach(),n||{node:t,offset:0}}(n,r):!n||s&&1==n.nodeType?{node:t,offset:a}:xw(n,r)}function ww(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function bw(t,e,n){let r=t.childNodes.length;if(r&&n.top<n.bottom)for(let o=Math.max(0,Math.min(r-1,Math.floor(r*(e.top-n.top)/(n.bottom-n.top))-2)),i=o;;){let n=t.childNodes[i];if(1==n.nodeType){let t=n.getClientRects();for(let r=0;r<t.length;r++){let o=t[r];if(ww(e,o))return bw(n,e,o)}}if((i=(i+1)%r)==o)break}return t}function vw(t,e){let n,r=t.dom.ownerDocument,o=0,i=function(t,e,n){if(t.caretPositionFromPoint)try{let r=t.caretPositionFromPoint(e,n);if(r)return{node:r.offsetNode,offset:Math.min(Hx(r.offsetNode),r.offset)}}catch(r){}if(t.caretRangeFromPoint){let r=t.caretRangeFromPoint(e,n);if(r)return{node:r.startContainer,offset:Math.min(Hx(r.startContainer),r.startOffset)}}}(r,e.left,e.top);i&&({node:n,offset:o}=i);let s,a=(t.root.elementFromPoint?t.root:r).elementFromPoint(e.left,e.top);if(!a||!t.dom.contains(1!=a.nodeType?a.parentNode:a)){let n=t.dom.getBoundingClientRect();if(!ww(e,n))return null;if(a=bw(t.dom,e,n),!a)return null}if(ow)for(let c=a;n&&c;c=Dx(c))c.draggable&&(n=void 0);if(a=function(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left<t.getBoundingClientRect().left?n:t}(a,e),n){if(tw&&1==n.nodeType&&(o=Math.min(o,n.childNodes.length),o<n.childNodes.length)){let t,r=n.childNodes[o];"IMG"==r.nodeName&&(t=r.getBoundingClientRect()).right<=e.left&&t.bottom>e.top&&o++}let r;cw&&o&&1==n.nodeType&&1==(r=n.childNodes[o-1]).nodeType&&"false"==r.contentEditable&&r.getBoundingClientRect().top>=e.top&&o--,n==t.dom&&o==n.childNodes.length-1&&1==n.lastChild.nodeType&&e.top>n.lastChild.getBoundingClientRect().bottom?s=t.state.doc.content.size:0!=o&&1==n.nodeType&&"BR"==n.childNodes[o-1].nodeName||(s=function(t,e,n,r){let o=-1;for(let i=e,s=!1;i!=t.dom;){let e,n=t.docView.nearestDesc(i,!0);if(!n)return null;if(1==n.dom.nodeType&&(n.node.isBlock&&n.parent||!n.contentDOM)&&((e=n.dom.getBoundingClientRect()).width||e.height)&&(n.node.isBlock&&n.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(n.dom.nodeName)&&(!s&&e.left>r.left||e.top>r.top?o=n.posBefore:(!s&&e.right<r.left||e.bottom<r.top)&&(o=n.posAfter),s=!0),!n.contentDOM&&o<0&&!n.node.isText))return(n.node.isBlock?r.top<(e.top+e.bottom)/2:r.left<(e.left+e.right)/2)?n.posBefore:n.posAfter;i=n.dom.parentNode}return o>-1?o:t.docView.posFromDOM(e,n,-1)}(t,n,o,e))}null==s&&(s=function(t,e,n){let{node:r,offset:o}=xw(e,n),i=-1;if(1==r.nodeType&&!r.firstChild){let t=r.getBoundingClientRect();i=t.left!=t.right&&n.left>(t.left+t.right)/2?1:-1}return t.docView.posFromDOM(r,o,i)}(t,a,e));let l=t.docView.nearestDesc(a,!0);return{pos:s,inside:l?l.posAtStart-l.border:-1}}function kw(t){return t.top<t.bottom||t.left<t.right}function Sw(t,e){let n=t.getClientRects();if(n.length){let t=n[e<0?0:n.length-1];if(kw(t))return t}return Array.prototype.find.call(n,kw)||t.getBoundingClientRect()}var Pw=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function Mw(t,e,n){let{node:r,offset:o,atom:i}=t.docView.domFromPos(e,n<0?-1:1),s=cw||tw;if(3==r.nodeType){if(!s||!Pw.test(r.nodeValue)&&(n<0?o:o!=r.nodeValue.length)){let t=o,e=o,i=n<0?1:-1;return n<0&&!o?(e++,i=-1):n>=0&&o==r.nodeValue.length?(t--,i=1):n<0?t--:e++,Iw(Sw(zx(r,t,e),i),i<0)}{let t=Sw(zx(r,o,o),n);if(tw&&o&&/\s/.test(r.nodeValue[o-1])&&o<r.nodeValue.length){let e=Sw(zx(r,o-1,o-1),-1);if(e.top==t.top){let n=Sw(zx(r,o,o+1),-1);if(n.top!=t.top)return Iw(n,n.left<e.left)}}return t}}if(!t.state.doc.resolve(e-(i||0)).parent.inlineContent){if(null==i&&o&&(n<0||o==Hx(r))){let t=r.childNodes[o-1];if(1==t.nodeType)return Tw(t.getBoundingClientRect(),!1)}if(null==i&&o<Hx(r)){let t=r.childNodes[o];if(1==t.nodeType)return Tw(t.getBoundingClientRect(),!0)}return Tw(r.getBoundingClientRect(),n>=0)}if(null==i&&o&&(n<0||o==Hx(r))){let t=r.childNodes[o-1],e=3==t.nodeType?zx(t,Hx(t)-(s?0:1)):1!=t.nodeType||"BR"==t.nodeName&&t.nextSibling?null:t;if(e)return Iw(Sw(e,1),!1)}if(null==i&&o<Hx(r)){let t=r.childNodes[o];for(;t.pmViewDesc&&t.pmViewDesc.ignoreForCoords;)t=t.nextSibling;let e=t?3==t.nodeType?zx(t,0,s?0:1):1==t.nodeType?t:null:null;if(e)return Iw(Sw(e,-1),!0)}return Iw(Sw(3==r.nodeType?zx(r):r,-n),n>=0)}function Iw(t,e){if(0==t.width)return t;let n=e?t.left:t.right;return{top:t.top,bottom:t.bottom,left:n,right:n}}function Tw(t,e){if(0==t.height)return t;let n=e?t.top:t.bottom;return{top:n,bottom:n,left:t.left,right:t.right}}function Cw(t,e,n){let r=t.state,o=t.root.activeElement;r!=e&&t.updateState(e),o!=t.dom&&t.focus();try{return n()}finally{r!=e&&t.updateState(r),o!=t.dom&&o&&o.focus()}}var Ew=/[\u0590-\u08ac]/;var Aw=null,Ow=null,Nw=!1;function Rw(t,e,n){return Aw==e&&Ow==n?Nw:(Aw=e,Ow=n,Nw="up"==n||"down"==n?function(t,e,n){let r=e.selection,o="up"==n?r.$from:r.$to;return Cw(t,e,()=>{let{node:e}=t.docView.domFromPos(o.pos,"up"==n?-1:1);for(;;){let n=t.docView.nearestDesc(e,!0);if(!n)break;if(n.node.isBlock){e=n.contentDOM||n.dom;break}e=n.dom.parentNode}let r=Mw(t,o.pos,1);for(let t=e.firstChild;t;t=t.nextSibling){let e;if(1==t.nodeType)e=t.getClientRects();else{if(3!=t.nodeType)continue;e=zx(t,0,t.nodeValue.length).getClientRects()}for(let t=0;t<e.length;t++){let o=e[t];if(o.bottom>o.top+1&&("up"==n?r.top-o.top>2*(o.bottom-r.top):o.bottom-r.bottom>2*(r.bottom-o.top)))return!1}}return!0})}(t,e,n):function(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let o=r.parentOffset,i=!o,s=o==r.parent.content.size,a=t.domSelection();return a?Ew.test(r.parent.textContent)&&a.modify?Cw(t,e,()=>{let{focusNode:e,focusOffset:o,anchorNode:i,anchorOffset:s}=t.domSelectionRange(),l=a.caretBidiLevel;a.modify("move",n,"character");let c=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:d,focusOffset:u}=t.domSelectionRange(),p=d&&!c.contains(1==d.nodeType?d:d.parentNode)||e==d&&o==u;try{a.collapse(i,s),e&&(e!=i||o!=s)&&a.extend&&a.extend(e,o)}catch(h){}return null!=l&&(a.caretBidiLevel=l),p}):"left"==n||"backward"==n?i:s:r.pos==r.start()||r.pos==r.end()}(t,e,n))}var Lw=class{constructor(t,e,n,r){this.parent=t,this.children=e,this.dom=n,this.contentDOM=r,this.dirty=0,n.pmViewDesc=this}matchesWidget(t){return!1}matchesMark(t){return!1}matchesNode(t,e,n){return!1}matchesHack(t){return!1}parseRule(){return null}stopEvent(t){return!1}get size(){let t=0;for(let e=0;e<this.children.length;e++)t+=this.children[e].size;return t}get border(){return 0}destroy(){this.parent=void 0,this.dom.pmViewDesc==this&&(this.dom.pmViewDesc=void 0);for(let t=0;t<this.children.length;t++)this.children[t].destroy()}posBeforeChild(t){for(let e=0,n=this.posAtStart;;e++){let r=this.children[e];if(r==t)return n;n+=r.size}}get posBefore(){return this.parent.posBeforeChild(this)}get posAtStart(){return this.parent?this.parent.posBeforeChild(this)+this.border:0}get posAfter(){return this.posBefore+this.size}get posAtEnd(){return this.posAtStart+this.size-2*this.border}localPosFromDOM(t,e,n){if(this.contentDOM&&this.contentDOM.contains(1==t.nodeType?t:t.parentNode)){if(n<0){let n,r;if(t==this.contentDOM)n=t.childNodes[e-1];else{for(;t.parentNode!=this.contentDOM;)t=t.parentNode;n=t.previousSibling}for(;n&&(!(r=n.pmViewDesc)||r.parent!=this);)n=n.previousSibling;return n?this.posBeforeChild(r)+r.size:this.posAtStart}{let n,r;if(t==this.contentDOM)n=t.childNodes[e];else{for(;t.parentNode!=this.contentDOM;)t=t.parentNode;n=t.nextSibling}for(;n&&(!(r=n.pmViewDesc)||r.parent!=this);)n=n.nextSibling;return n?this.posBeforeChild(r):this.posAtEnd}}let r;if(t==this.dom&&this.contentDOM)r=e>$x(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))r=2&t.compareDocumentPosition(this.contentDOM);else if(this.dom.firstChild){if(0==e)for(let e=t;;e=e.parentNode){if(e==this.dom){r=!1;break}if(e.previousSibling)break}if(null==r&&e==t.childNodes.length)for(let e=t;;e=e.parentNode){if(e==this.dom){r=!0;break}if(e.nextSibling)break}}return(null==r?n>0:r)?this.posAtEnd:this.posAtStart}nearestDesc(t,e=!1){for(let n=!0,r=t;r;r=r.parentNode){let o,i=this.getDesc(r);if(i&&(!e||i.node)){if(!n||!(o=i.nodeDOM)||(1==o.nodeType?o.contains(1==t.nodeType?t:t.parentNode):o==t))return i;n=!1}}}getDesc(t){let e=t.pmViewDesc;for(let n=e;n;n=n.parent)if(n==this)return e}posFromDOM(t,e,n){for(let r=t;r;r=r.parentNode){let o=this.getDesc(r);if(o)return o.localPosFromDOM(t,e,n)}return-1}descAt(t){for(let e=0,n=0;e<this.children.length;e++){let r=this.children[e],o=n+r.size;if(n==t&&o!=n){for(;!r.border&&r.children.length;)for(let t=0;t<r.children.length;t++){let e=r.children[t];if(e.size){r=e;break}}return r}if(t<o)return r.descAt(t-n-r.border);n=o}}domFromPos(t,e){if(!this.contentDOM)return{node:this.dom,offset:0,atom:t+1};let n=0,r=0;for(let o=0;n<this.children.length;n++){let e=this.children[n],i=o+e.size;if(i>t||e instanceof Ww){r=t-o;break}o=i}if(r)return this.children[n].domFromPos(r-this.children[n].border,e);for(let o;n&&!(o=this.children[n-1]).size&&o instanceof $w&&o.side>=0;n--);if(e<=0){let t,r=!0;for(;t=n?this.children[n-1]:null,t&&t.dom.parentNode!=this.contentDOM;n--,r=!1);return t&&e&&r&&!t.border&&!t.domAtom?t.domFromPos(t.size,e):{node:this.contentDOM,offset:t?$x(t.dom)+1:0}}{let t,r=!0;for(;t=n<this.children.length?this.children[n]:null,t&&t.dom.parentNode!=this.contentDOM;n++,r=!1);return t&&r&&!t.border&&!t.domAtom?t.domFromPos(0,e):{node:this.contentDOM,offset:t?$x(t.dom):this.contentDOM.childNodes.length}}}parseRange(t,e,n=0){if(0==this.children.length)return{node:this.contentDOM,from:t,to:e,fromOffset:0,toOffset:this.contentDOM.childNodes.length};let r=-1,o=-1;for(let i=n,s=0;;s++){let n=this.children[s],a=i+n.size;if(-1==r&&t<=a){let o=i+n.border;if(t>=o&&e<=a-n.border&&n.node&&n.contentDOM&&this.contentDOM.contains(n.contentDOM))return n.parseRange(t,e,o);t=i;for(let e=s;e>0;e--){let n=this.children[e-1];if(n.size&&n.dom.parentNode==this.contentDOM&&!n.emptyChildAt(1)){r=$x(n.dom)+1;break}t-=n.size}-1==r&&(r=0)}if(r>-1&&(a>e||s==this.children.length-1)){e=a;for(let t=s+1;t<this.children.length;t++){let n=this.children[t];if(n.size&&n.dom.parentNode==this.contentDOM&&!n.emptyChildAt(-1)){o=$x(n.dom);break}e+=n.size}-1==o&&(o=this.contentDOM.childNodes.length);break}i=a}return{node:this.contentDOM,from:t,to:e,fromOffset:r,toOffset:o}}emptyChildAt(t){if(this.border||!this.contentDOM||!this.children.length)return!1;let e=this.children[t<0?0:this.children.length-1];return 0==e.size||e.emptyChildAt(t)}domAfterPos(t){let{node:e,offset:n}=this.domFromPos(t,0);if(1!=e.nodeType||n==e.childNodes.length)throw new RangeError("No node after pos "+t);return e.childNodes[n]}setSelection(t,e,n,r=!1){let o=Math.min(t,e),i=Math.max(t,e);for(let h=0,f=0;h<this.children.length;h++){let s=this.children[h],a=f+s.size;if(o>f&&i<a)return s.setSelection(t-f-s.border,e-f-s.border,n,r);f=a}let s=this.domFromPos(t,t?-1:1),a=e==t?s:this.domFromPos(e,e?-1:1),l=n.root.getSelection(),c=n.domSelectionRange(),d=!1;if((tw||ow)&&t==e){let{node:t,offset:e}=s;if(3==t.nodeType){if(d=!(!e||"\n"!=t.nodeValue[e-1]),d&&e==t.nodeValue.length)for(let n,r=t;r;r=r.parentNode){if(n=r.nextSibling){"BR"==n.nodeName&&(s=a={node:n.parentNode,offset:$x(n)+1});break}let t=r.pmViewDesc;if(t&&t.node&&t.node.isBlock)break}}else{let n=t.childNodes[e-1];d=n&&("BR"==n.nodeName||"false"==n.contentEditable)}}if(tw&&c.focusNode&&c.focusNode!=a.node&&1==c.focusNode.nodeType){let t=c.focusNode.childNodes[c.focusOffset];t&&"false"==t.contentEditable&&(r=!0)}if(!(r||d&&ow)&&Fx(s.node,s.offset,c.anchorNode,c.anchorOffset)&&Fx(a.node,a.offset,c.focusNode,c.focusOffset))return;let u=!1;if((l.extend||t==e)&&(!d||!tw)){l.collapse(s.node,s.offset);try{t!=e&&l.extend(a.node,a.offset),u=!0}catch(p){}}if(!u){if(t>e){let t=s;s=a,a=t}let n=document.createRange();n.setEnd(a.node,a.offset),n.setStart(s.node,s.offset),l.removeAllRanges(),l.addRange(n)}}ignoreMutation(t){return!this.contentDOM&&"selection"!=t.type}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,e){for(let n=0,r=0;r<this.children.length;r++){let o=this.children[r],i=n+o.size;if(n==i?t<=i&&e>=n:t<i&&e>n){let r=n+o.border,s=i-o.border;if(t>=r&&e<=s)return this.dirty=t==n||e==i?2:1,void(t!=r||e!=s||!o.contentLost&&o.dom.parentNode==this.contentDOM?o.markDirty(t-r,e-r):o.dirty=3);o.dirty=o.dom!=o.contentDOM||o.dom.parentNode!=this.contentDOM||o.children.length?3:2}n=i}this.dirty=2}markParentsDirty(){let t=1;for(let e=this.parent;e;e=e.parent,t++){let n=1==t?2:1;e.dirty<n&&(e.dirty=n)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(t){return!1}},$w=class extends Lw{constructor(t,e,n,r){let o,i=e.type.toDOM;if("function"==typeof i&&(i=i(n,()=>o?o.parent?o.parent.posBeforeChild(o):void 0:r)),!e.type.spec.raw){if(1!=i.nodeType){let t=document.createElement("span");t.appendChild(i),i=t}i.contentEditable="false",i.classList.add("ProseMirror-widget")}super(t,[],i,null),this.widget=e,this.widget=e,o=this}matchesWidget(t){return 0==this.dirty&&t.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(t){let e=this.widget.spec.stopEvent;return!!e&&e(t)}ignoreMutation(t){return"selection"!=t.type||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}},Dw=class extends Lw{constructor(t,e,n,r){super(t,[],e,null),this.textDOM=n,this.text=r}get size(){return this.text.length}localPosFromDOM(t,e){return t!=this.textDOM?this.posAtStart+(e?this.size:0):this.posAtStart+e}domFromPos(t){return{node:this.textDOM,offset:t}}ignoreMutation(t){return"characterData"===t.type&&t.target.nodeValue==t.oldValue}},Bw=class t extends Lw{constructor(t,e,n,r,o){super(t,[],n,r),this.mark=e,this.spec=o}static create(e,n,r,o){let i=o.nodeViews[n.type.name],s=i&&i(n,o,r);return s&&s.dom||(s=Fg.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new t(e,n,s.dom,s.contentDOM||s.dom,s)}parseRule(){return 3&this.dirty||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return 3!=this.dirty&&this.mark.eq(t)}markDirty(t,e){if(super.markDirty(t,e),0!=this.dirty){let t=this.parent;for(;!t.node;)t=t.parent;t.dirty<this.dirty&&(t.dirty=this.dirty),this.dirty=0}}slice(e,n,r){let o=t.create(this.parent,this.mark,!0,r),i=this.children,s=this.size;n<s&&(i=tb(i,n,s,r)),e>0&&(i=tb(i,0,e,r));for(let t=0;t<i.length;t++)i[t].parent=o;return o.children=i,o}ignoreMutation(t){return this.spec.ignoreMutation?this.spec.ignoreMutation(t):super.ignoreMutation(t)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}},zw=class t extends Lw{constructor(t,e,n,r,o,i,s){super(t,[],o,i),this.node=e,this.outerDeco=n,this.innerDeco=r,this.nodeDOM=s}static create(e,n,r,o,i,s){let a,l=i.nodeViews[n.type.name],c=l&&l(n,i,()=>a?a.parent?a.parent.posBeforeChild(a):void 0:s,r,o),d=c&&c.dom,u=c&&c.contentDOM;if(n.isText)if(d){if(3!=d.nodeType)throw new RangeError("Text must be rendered as a DOM text node")}else d=document.createTextNode(n.text);else if(!d){let t=Fg.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs);({dom:d,contentDOM:u}=t)}u||n.isText||"BR"==d.nodeName||(d.hasAttribute("contenteditable")||(d.contentEditable="false"),n.type.spec.draggable&&(d.draggable=!0));let p=d;return d=Yw(d,r,n),c?a=new Hw(e,n,r,o,d,u||null,p,c):n.isText?new jw(e,n,r,o,d,p):new t(e,n,r,o,d,u||null,p)}parseRule(){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if("pre"==this.node.type.whitespace&&(t.preserveWhitespace="full"),this.contentDOM)if(this.contentLost){for(let e=this.children.length-1;e>=0;e--){let n=this.children[e];if(this.dom.contains(n.dom.parentNode)){t.contentElement=n.dom.parentNode;break}}t.contentElement||(t.getContent=()=>Bm.empty)}else t.contentElement=this.contentDOM;else t.getContent=()=>this.node.content;return t}matchesNode(t,e,n){return 0==this.dirty&&t.eq(this.node)&&Jw(e,this.outerDeco)&&n.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(t,e){let n=this.node.inlineContent,r=e,o=t.composing?this.localCompositionInfo(t,e):null,i=o&&o.pos>-1?o:null,s=o&&o.pos<0,a=new Zw(this,i&&i.node,t);!function(t,e,n,r){let o=e.locals(t),i=0;if(0==o.length){for(let n=0;n<t.childCount;n++){let s=t.child(n);r(s,o,e.forChild(i,s),n),i+=s.nodeSize}return}let s=0,a=[],l=null;for(let c=0;;){let d,u,p,h;for(;s<o.length&&o[s].to==i;){let t=o[s++];t.widget&&(d?(u||(u=[d])).push(t):d=t)}if(d)if(u){u.sort(Qw);for(let t=0;t<u.length;t++)n(u[t],c,!!l)}else n(d,c,!!l);if(l)h=-1,p=l,l=null;else{if(!(c<t.childCount))break;h=c,p=t.child(c++)}for(let t=0;t<a.length;t++)a[t].to<=i&&a.splice(t--,1);for(;s<o.length&&o[s].from<=i&&o[s].to>i;)a.push(o[s++]);let f=i+p.nodeSize;if(p.isText){let t=f;s<o.length&&o[s].from<t&&(t=o[s].from);for(let e=0;e<a.length;e++)a[e].to<t&&(t=a[e].to);t<f&&(l=p.cut(t-i),p=p.cut(0,t-i),f=t,h=-1)}else for(;s<o.length&&o[s].to<f;)s++;r(p,p.isInline&&!p.isLeaf?a.filter(t=>!t.inline):a.slice(),e.forChild(i,p),h),i=f}}(this.node,this.innerDeco,(e,o,i)=>{e.spec.marks?a.syncToMarks(e.spec.marks,n,t,o):e.type.side>=0&&!i&&a.syncToMarks(o==this.node.childCount?Wm.none:this.node.child(o).marks,n,t,o),a.placeWidget(e,t,r)},(e,i,l,c)=>{let d;a.syncToMarks(e.marks,n,t,c),a.findNodeMatch(e,i,l,c)||s&&t.state.selection.from>r&&t.state.selection.to<r+e.nodeSize&&(d=a.findIndexWithChild(o.node))>-1&&a.updateNodeAt(e,i,l,d,t)||a.updateNextNode(e,i,l,t,c,r)||a.addNode(e,i,l,t,r),r+=e.nodeSize}),a.syncToMarks([],n,t,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||2==this.dirty)&&(i&&this.protectLocalComposition(t,i),_w(this.contentDOM,this.children,t),iw&&function(t){if("UL"==t.nodeName||"OL"==t.nodeName){let e=t.style.cssText;t.style.cssText=e+"; list-style: square !important",window.getComputedStyle(t).listStyle,t.style.cssText=e}}(this.dom))}localCompositionInfo(t,e){let{from:n,to:r}=t.state.selection;if(!(t.state.selection instanceof jy)||n<e||r>e+this.node.content.size)return null;let o=t.input.compositionNode;if(!o||!this.dom.contains(o.parentNode))return null;if(this.node.inlineContent){let t=o.nodeValue,i=function(t,e,n,r){for(let o=0,i=0;o<t.childCount&&i<=r;){let s=t.child(o++),a=i;if(i+=s.nodeSize,!s.isText)continue;let l=s.text;for(;o<t.childCount;){let e=t.child(o++);if(i+=e.nodeSize,!e.isText)break;l+=e.text}if(i>=n){if(i>=r&&l.slice(r-e.length-a,r-a)==e)return r-e.length;let t=a<r?l.lastIndexOf(e,r-a-1):-1;if(t>=0&&t+e.length+a>=n)return a+t;if(n==r&&l.length>=r+e.length-a&&l.slice(r-a,r-a+e.length)==e)return r}}return-1}(this.node.content,t,n-e,r-e);return i<0?null:{node:o,pos:i,text:t}}return{node:o,pos:-1,text:""}}protectLocalComposition(t,{node:e,pos:n,text:r}){if(this.getDesc(e))return;let o=e;for(;o.parentNode!=this.contentDOM;o=o.parentNode){for(;o.previousSibling;)o.parentNode.removeChild(o.previousSibling);for(;o.nextSibling;)o.parentNode.removeChild(o.nextSibling);o.pmViewDesc&&(o.pmViewDesc=void 0)}let i=new Dw(this,o,e,r);t.input.compositionNodes.push(i),this.children=tb(this.children,n,n+r.length,t,i)}update(t,e,n,r){return!(3==this.dirty||!t.sameMarkup(this.node))&&(this.updateInner(t,e,n,r),!0)}updateInner(t,e,n,r){this.updateOuterDeco(e),this.node=t,this.innerDeco=n,this.contentDOM&&this.updateChildren(r,this.posAtStart),this.dirty=0}updateOuterDeco(t){if(Jw(t,this.outerDeco))return;let e=1!=this.nodeDOM.nodeType,n=this.dom;this.dom=qw(this.dom,this.nodeDOM,Kw(this.outerDeco,this.node,e),Kw(t,this.node,e)),this.dom!=n&&(n.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=t}selectNode(){1==this.nodeDOM.nodeType&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),!this.contentDOM&&this.node.type.spec.draggable||(this.nodeDOM.draggable=!0))}deselectNode(){1==this.nodeDOM.nodeType&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),!this.contentDOM&&this.node.type.spec.draggable||this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}};function Fw(t,e,n,r,o){Yw(r,e,t);let i=new zw(void 0,t,e,n,r,r,r);return i.contentDOM&&i.updateChildren(o,0),i}var jw=class t extends zw{constructor(t,e,n,r,o,i){super(t,e,n,r,o,null,i)}parseRule(){let t=this.nodeDOM.parentNode;for(;t&&t!=this.dom&&!t.pmIsDeco;)t=t.parentNode;return{skip:t||!0}}update(t,e,n,r){return!(3==this.dirty||0!=this.dirty&&!this.inParent()||!t.sameMarkup(this.node))&&(this.updateOuterDeco(e),0==this.dirty&&t.text==this.node.text||t.text==this.nodeDOM.nodeValue||(this.nodeDOM.nodeValue=t.text,r.trackWrites==this.nodeDOM&&(r.trackWrites=null)),this.node=t,this.dirty=0,!0)}inParent(){let t=this.parent.contentDOM;for(let e=this.nodeDOM;e;e=e.parentNode)if(e==t)return!0;return!1}domFromPos(t){return{node:this.nodeDOM,offset:t}}localPosFromDOM(t,e,n){return t==this.nodeDOM?this.posAtStart+Math.min(e,this.node.text.length):super.localPosFromDOM(t,e,n)}ignoreMutation(t){return"characterData"!=t.type&&"selection"!=t.type}slice(e,n,r){let o=this.node.cut(e,n),i=document.createTextNode(o.text);return new t(this.parent,o,this.outerDeco,this.innerDeco,i,i)}markDirty(t,e){super.markDirty(t,e),this.dom==this.nodeDOM||0!=t&&e!=this.nodeDOM.nodeValue.length||(this.dirty=3)}get domAtom(){return!1}isText(t){return this.node.text==t}},Ww=class extends Lw{parseRule(){return{ignore:!0}}matchesHack(t){return 0==this.dirty&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return"IMG"==this.dom.nodeName}},Hw=class extends zw{constructor(t,e,n,r,o,i,s,a){super(t,e,n,r,o,i,s),this.spec=a}update(t,e,n,r){if(3==this.dirty)return!1;if(this.spec.update&&(this.node.type==t.type||this.spec.multiType)){let o=this.spec.update(t,e,n);return o&&this.updateInner(t,e,n,r),o}return!(!this.contentDOM&&!t.isLeaf)&&super.update(t,e,n,r)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(t,e,n,r){this.spec.setSelection?this.spec.setSelection(t,e,n.root):super.setSelection(t,e,n,r)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(t){return!!this.spec.stopEvent&&this.spec.stopEvent(t)}ignoreMutation(t){return this.spec.ignoreMutation?this.spec.ignoreMutation(t):super.ignoreMutation(t)}};function _w(t,e,n){let r=t.firstChild,o=!1;for(let i=0;i<e.length;i++){let s=e[i],a=s.dom;if(a.parentNode==t){for(;a!=r;)r=Gw(r),o=!0;r=r.nextSibling}else o=!0,t.insertBefore(a,r);if(s instanceof Bw){let e=r?r.previousSibling:t.lastChild;_w(s.contentDOM,s.children,n),r=e?e.nextSibling:t.firstChild}}for(;r;)r=Gw(r),o=!0;o&&n.trackWrites==t&&(n.trackWrites=null)}var Uw=function(t){t&&(this.nodeName=t)};Uw.prototype=Object.create(null);var Vw=[new Uw];function Kw(t,e,n){if(0==t.length)return Vw;let r=n?Vw[0]:new Uw,o=[r];for(let i=0;i<t.length;i++){let s=t[i].type.attrs;if(s){s.nodeName&&o.push(r=new Uw(s.nodeName));for(let t in s){let i=s[t];null!=i&&(n&&1==o.length&&o.push(r=new Uw(e.isInline?"span":"div")),"class"==t?r.class=(r.class?r.class+" ":"")+i:"style"==t?r.style=(r.style?r.style+";":"")+i:"nodeName"!=t&&(r[t]=i))}}}return o}function qw(t,e,n,r){if(n==Vw&&r==Vw)return e;let o=e;for(let i=0;i<r.length;i++){let e=r[i],s=n[i];if(i){let n;s&&s.nodeName==e.nodeName&&o!=t&&(n=o.parentNode)&&n.nodeName.toLowerCase()==e.nodeName||(n=document.createElement(e.nodeName),n.pmIsDeco=!0,n.appendChild(o),s=Vw[0]),o=n}Xw(o,s||Vw[0],e)}return o}function Xw(t,e,n){for(let r in e)"class"==r||"style"==r||"nodeName"==r||r in n||t.removeAttribute(r);for(let r in n)"class"!=r&&"style"!=r&&"nodeName"!=r&&n[r]!=e[r]&&t.setAttribute(r,n[r]);if(e.class!=n.class){let r=e.class?e.class.split(" ").filter(Boolean):[],o=n.class?n.class.split(" ").filter(Boolean):[];for(let e=0;e<r.length;e++)-1==o.indexOf(r[e])&&t.classList.remove(r[e]);for(let e=0;e<o.length;e++)-1==r.indexOf(o[e])&&t.classList.add(o[e]);0==t.classList.length&&t.removeAttribute("class")}if(e.style!=n.style){if(e.style){let n,r=/\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g;for(;n=r.exec(e.style);)t.style.removeProperty(n[1])}n.style&&(t.style.cssText+=n.style)}}function Yw(t,e,n){return qw(t,t,Vw,Kw(e,n,1!=t.nodeType))}function Jw(t,e){if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!t[n].type.eq(e[n].type))return!1;return!0}function Gw(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}var Zw=class{constructor(t,e,n){this.lock=e,this.view=n,this.index=0,this.stack=[],this.changed=!1,this.top=t,this.preMatch=function(t,e){let n=e,r=n.children.length,o=t.childCount,i=new Map,s=[];t:for(;o>0;){let a;for(;;)if(r){let t=n.children[r-1];if(!(t instanceof Bw)){a=t,r--;break}n=t,r=t.children.length}else{if(n==e)break t;r=n.parent.children.indexOf(n),n=n.parent}let l=a.node;if(l){if(l!=t.child(o-1))break;--o,i.set(a,o),s.push(a)}}return{index:o,matched:i,matches:s.reverse()}}(t.node.content,t)}destroyBetween(t,e){if(t!=e){for(let n=t;n<e;n++)this.top.children[n].destroy();this.top.children.splice(t,e-t),this.changed=!0}}destroyRest(){this.destroyBetween(this.index,this.top.children.length)}syncToMarks(t,e,n,r){let o=0,i=this.stack.length>>1,s=Math.min(i,t.length);for(;o<s&&(o==i-1?this.top:this.stack[o+1<<1]).matchesMark(t[o])&&!1!==t[o].type.spec.spanning;)o++;for(;o<i;)this.destroyRest(),this.top.dirty=0,this.index=this.stack.pop(),this.top=this.stack.pop(),i--;for(;i<t.length;){this.stack.push(this.top,this.index+1);let o=-1,s=this.top.children.length;r<this.preMatch.index&&(s=Math.min(this.index+3,s));for(let e=this.index;e<s;e++){let n=this.top.children[e];if(n.matchesMark(t[i])&&!this.isLocked(n.dom)){o=e;break}}if(o<0&&this.index<this.top.children.length){let e=this.top.children[this.index];e instanceof Bw&&3!=e.dirty&&e.mark.type==t[i].type&&e.spec.update&&!this.isLocked(e.dom)&&e.spec.update(t[i])&&(e.mark=t[i],o=this.index,this.changed=!0)}if(o>-1)o>this.index&&(this.changed=!0,this.destroyBetween(this.index,o)),this.top=this.top.children[this.index];else{let r=Bw.create(this.top,t[i],e,n);this.top.children.splice(this.index,0,r),this.top=r,this.changed=!0}this.index=0,i++}}findNodeMatch(t,e,n,r){let o,i=-1;if(r>=this.preMatch.index&&(o=this.preMatch.matches[r-this.preMatch.index]).parent==this.top&&o.matchesNode(t,e,n))i=this.top.children.indexOf(o,this.index);else for(let s=this.index,a=Math.min(this.top.children.length,s+5);s<a;s++){let r=this.top.children[s];if(r.matchesNode(t,e,n)&&!this.preMatch.matched.has(r)){i=s;break}}return!(i<0)&&(this.destroyBetween(this.index,i),this.index++,!0)}updateNodeAt(t,e,n,r,o){let i=this.top.children[r];return 3==i.dirty&&i.dom==i.contentDOM&&(i.dirty=2),!!i.update(t,e,n,o)&&(this.destroyBetween(this.index,r),this.index++,!0)}findIndexWithChild(t){for(;;){let e=t.parentNode;if(!e)return-1;if(e==this.top.contentDOM){let e=t.pmViewDesc;if(e)for(let t=this.index;t<this.top.children.length;t++)if(this.top.children[t]==e)return t;return-1}t=e}}updateNextNode(t,e,n,r,o,i){for(let s=this.index;s<this.top.children.length;s++){let a=this.top.children[s];if(a instanceof zw){let l=this.preMatch.matched.get(a);if(null!=l&&l!=o)return!1;let c,d=a.dom,u=this.isLocked(d)&&!(t.isText&&a.node&&a.node.isText&&a.nodeDOM.nodeValue==t.text&&3!=a.dirty&&Jw(e,a.outerDeco));if(!u&&a.update(t,e,n,r))return this.destroyBetween(this.index,s),a.dom!=d&&(this.changed=!0),this.index++,!0;if(!u&&(c=this.recreateWrapper(a,t,e,n,r,i)))return this.destroyBetween(this.index,s),this.top.children[this.index]=c,c.contentDOM&&(c.dirty=2,c.updateChildren(r,i+1),c.dirty=0),this.changed=!0,this.index++,!0;break}}return!1}recreateWrapper(t,e,n,r,o,i){if(t.dirty||e.isAtom||!t.children.length||!t.node.content.eq(e.content)||!Jw(n,t.outerDeco)||!r.eq(t.innerDeco))return null;let s=zw.create(this.top,e,n,r,o,i);if(s.contentDOM){s.children=t.children,t.children=[];for(let t of s.children)t.parent=s}return t.destroy(),s}addNode(t,e,n,r,o){let i=zw.create(this.top,t,e,n,r,o);i.contentDOM&&i.updateChildren(r,o+1),this.top.children.splice(this.index++,0,i),this.changed=!0}placeWidget(t,e,n){let r=this.index<this.top.children.length?this.top.children[this.index]:null;if(!r||!r.matchesWidget(t)||t!=r.widget&&r.widget.type.toDOM.parentNode){let r=new $w(this.top,t,e,n);this.top.children.splice(this.index++,0,r),this.changed=!0}else this.index++}addTextblockHacks(){let t=this.top.children[this.index-1],e=this.top;for(;t instanceof Bw;)e=t,t=e.children[e.children.length-1];(!t||!(t instanceof jw)||/\n$/.test(t.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(t.node.text))&&((ow||nw)&&t&&"false"==t.dom.contentEditable&&this.addHackNode("IMG",e),this.addHackNode("BR",this.top))}addHackNode(t,e){if(e==this.top&&this.index<e.children.length&&e.children[this.index].matchesHack(t))this.index++;else{let n=document.createElement(t);"IMG"==t&&(n.className="ProseMirror-separator",n.alt=""),"BR"==t&&(n.className="ProseMirror-trailingBreak");let r=new Ww(this.top,[],n,null);e!=this.top?e.children.push(r):e.children.splice(this.index++,0,r),this.changed=!0}}isLocked(t){return this.lock&&(t==this.lock||1==t.nodeType&&t.contains(this.lock.parentNode))}};function Qw(t,e){return t.type.side-e.type.side}function tb(t,e,n,r,o){let i=[];for(let s=0,a=0;s<t.length;s++){let l=t[s],c=a,d=a+=l.size;c>=n||d<=e?i.push(l):(c<e&&i.push(l.slice(0,e-c,r)),o&&(i.push(o),o=void 0),d>n&&i.push(l.slice(n-c,l.size,r)))}return i}function eb(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let o=t.docView.nearestDesc(n.focusNode),i=o&&0==o.size,s=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(s<0)return null;let a,l,c=r.resolve(s);if(Ux(n)){for(a=s;o&&!o.node;)o=o.parent;let t=o.node;if(o&&t.isAtom&&Hy.isSelectable(t)&&o.parent&&(!t.isInline||!function(t,e,n){for(let r=0==e,o=e==Hx(t);r||o;){if(t==n)return!0;let e=$x(t);if(!(t=t.parentNode))return!1;r=r&&0==e,o=o&&e==Hx(t)}}(n.focusNode,n.focusOffset,o.dom))){let t=o.posBefore;l=new Hy(s==t?c:r.resolve(t))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let e=s,o=s;for(let r=0;r<n.rangeCount;r++){let i=n.getRangeAt(r);e=Math.min(e,t.docView.posFromDOM(i.startContainer,i.startOffset,1)),o=Math.max(o,t.docView.posFromDOM(i.endContainer,i.endOffset,-1))}if(e<0)return null;[a,s]=o==t.state.selection.anchor?[o,e]:[e,o],c=r.resolve(s)}else a=t.docView.posFromDOM(n.anchorNode,n.anchorOffset,1);if(a<0)return null}let d=r.resolve(a);if(!l){l=db(t,d,c,"pointer"==e||t.state.selection.head<c.pos&&!i?1:-1)}return l}function nb(t){return t.editable?t.hasFocus():pb(t)&&document.activeElement&&document.activeElement.contains(t.dom)}function rb(t,e=!1){let n=t.state.selection;if(lb(t,n),!nb(t))return;let r=t.input.mouseDown;if(!e&&nw&&r){let e=t.domSelectionRange(),n=t.domObserver.currentSelection;if(e.anchorNode&&n.anchorNode&&Fx(e.anchorNode,e.anchorOffset,n.anchorNode,n.anchorOffset)&&r.delaySelUpdate())return void t.domObserver.setCurSelection()}if(t.domObserver.disconnectSelection(),t.cursorWrapper)!function(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r="IMG"==n.nodeName;r?e.collapse(n.parentNode,$x(n)+1):e.collapse(n,0);!r&&!t.state.selection.visible&&Zx&&Qx<=11&&(n.disabled=!0,n.disabled=!1)}(t);else{let r,o,{anchor:i,head:s}=n;!ob||n instanceof jy||(n.$from.parent.inlineContent||(r=ib(t,n.from)),n.empty||n.$from.parent.inlineContent||(o=ib(t,n.to))),t.docView.setSelection(i,s,t,e),ob&&(r&&ab(r),o&&ab(o)),n.visible?t.dom.classList.remove("ProseMirror-hideselection"):(t.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&function(t){let e=t.dom.ownerDocument;e.removeEventListener("selectionchange",t.input.hideSelectionGuard);let n=t.domSelectionRange(),r=n.anchorNode,o=n.anchorOffset;e.addEventListener("selectionchange",t.input.hideSelectionGuard=()=>{n.anchorNode==r&&n.anchorOffset==o||(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{nb(t)&&!t.state.selection.visible||t.dom.classList.remove("ProseMirror-hideselection")},20))})}(t))}t.domObserver.setCurSelection(),t.domObserver.connectSelection()}var ob=ow||nw&&rw<63;function ib(t,e){let{node:n,offset:r}=t.docView.domFromPos(e,0),o=r<n.childNodes.length?n.childNodes[r]:null,i=r?n.childNodes[r-1]:null;if(ow&&o&&"false"==o.contentEditable)return sb(o);if(!(o&&"false"!=o.contentEditable||i&&"false"!=i.contentEditable)){if(o)return sb(o);if(i)return sb(i)}}function sb(t){return t.contentEditable="true",ow&&t.draggable&&(t.draggable=!1,t.wasDraggable=!0),t}function ab(t){t.contentEditable="false",t.wasDraggable&&(t.draggable=!0,t.wasDraggable=null)}function lb(t,e){if(e instanceof Hy){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(cb(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else cb(t)}function cb(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function db(t,e,n,r){return t.someProp("createSelectionBetween",r=>r(t,e,n))||jy.between(e,n,r)}function ub(t){return!(t.editable&&!t.hasFocus())&&pb(t)}function pb(t){let e=t.domSelectionRange();if(!e.anchorNode)return!1;try{return t.dom.contains(3==e.anchorNode.nodeType?e.anchorNode.parentNode:e.anchorNode)&&(t.editable||t.dom.contains(3==e.focusNode.nodeType?e.focusNode.parentNode:e.focusNode))}catch(n){return!1}}function hb(t,e){let{$anchor:n,$head:r}=t.selection,o=e>0?n.max(r):n.min(r),i=o.parent.inlineContent?o.depth?t.doc.resolve(e>0?o.after():o.before()):null:o;return i&&Dy.findFrom(i,e)}function fb(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function mb(t,e,n){let r=t.state.selection;if(!(r instanceof jy)){if(r instanceof Hy&&r.node.isInline)return fb(t,new jy(e>0?r.$to:r.$from));{let n=hb(t.state,e);return!!n&&fb(t,n)}}if(n.indexOf("s")>-1){let{$head:n}=r,o=n.textOffset?null:e<0?n.nodeBefore:n.nodeAfter;if(!o||o.isText||!o.isLeaf)return!1;let i=t.state.doc.resolve(n.pos+o.nodeSize*(e<0?-1:1));return fb(t,new jy(r.$anchor,i))}if(!r.empty)return!1;if(t.endOfTextblock(e>0?"forward":"backward")){let n=hb(t.state,e);return!!(n&&n instanceof Hy)&&fb(t,n)}if(!(sw&&n.indexOf("m")>-1)){let n,o=r.$head,i=o.textOffset?null:e<0?o.nodeBefore:o.nodeAfter;if(!i||i.isText)return!1;let s=e<0?o.pos-i.nodeSize:o.pos;return!!(i.isAtom||(n=t.docView.descAt(s))&&!n.contentDOM)&&(Hy.isSelectable(i)?fb(t,new Hy(e<0?t.state.doc.resolve(o.pos-i.nodeSize):o)):!!cw&&fb(t,new jy(t.state.doc.resolve(e<0?s:s+i.nodeSize))))}}function gb(t){return 3==t.nodeType?t.nodeValue.length:t.childNodes.length}function yb(t,e){let n=t.pmViewDesc;return n&&0==n.size&&(e<0||t.nextSibling||"BR"!=t.nodeName)}function xb(t,e){return e<0?function(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let o,i,s=!1;tw&&1==n.nodeType&&r<gb(n)&&yb(n.childNodes[r],-1)&&(s=!0);for(;;)if(r>0){if(1!=n.nodeType)break;{let t=n.childNodes[r-1];if(yb(t,-1))o=n,i=--r;else{if(3!=t.nodeType)break;n=t,r=n.nodeValue.length}}}else{if(wb(n))break;{let e=n.previousSibling;for(;e&&yb(e,-1);)o=n.parentNode,i=$x(e),e=e.previousSibling;if(e)n=e,r=gb(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}s?bb(t,n,r):o&&bb(t,o,i)}(t):function(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let o,i,s=gb(n);for(;;)if(r<s){if(1!=n.nodeType)break;if(!yb(n.childNodes[r],1))break;o=n,i=++r}else{if(wb(n))break;{let e=n.nextSibling;for(;e&&yb(e,1);)o=e.parentNode,i=$x(e)+1,e=e.nextSibling;if(e)n=e,r=0,s=gb(n);else{if(n=n.parentNode,n==t.dom)break;r=s=0}}}o&&bb(t,o,i)}(t)}function wb(t){let e=t.pmViewDesc;return e&&e.node&&e.node.isBlock}function bb(t,e,n){if(3!=e.nodeType){let t,r;(r=function(t,e){for(;t&&e==t.childNodes.length&&!_x(t);)e=$x(t)+1,t=t.parentNode;for(;t&&e<t.childNodes.length;){let n=t.childNodes[e];if(3==n.nodeType)return n;if(1==n.nodeType&&"false"==n.contentEditable)break;t=n,e=0}}(e,n))?(e=r,n=0):(t=function(t,e){for(;t&&!e&&!_x(t);)e=$x(t),t=t.parentNode;for(;t&&e;){let n=t.childNodes[e-1];if(3==n.nodeType)return n;if(1==n.nodeType&&"false"==n.contentEditable)break;e=(t=n).childNodes.length}}(e,n))&&(e=t,n=t.nodeValue.length)}let r=t.domSelection();if(!r)return;if(Ux(r)){let t=document.createRange();t.setEnd(e,n),t.setStart(e,n),r.removeAllRanges(),r.addRange(t)}else r.extend&&r.extend(e,n);t.domObserver.setCurSelection();let{state:o}=t;setTimeout(()=>{t.state==o&&rb(t)},50)}function vb(t,e){let n=t.state.doc.resolve(e);if(!nw&&!aw&&n.parent.inlineContent){let r=t.coordsAtPos(e);if(e>n.start()){let n=t.coordsAtPos(e-1),o=(n.top+n.bottom)/2;if(o>r.top&&o<r.bottom&&Math.abs(n.left-r.left)>1)return n.left<r.left?"ltr":"rtl"}if(e<n.end()){let n=t.coordsAtPos(e+1),o=(n.top+n.bottom)/2;if(o>r.top&&o<r.bottom&&Math.abs(n.left-r.left)>1)return n.left>r.left?"ltr":"rtl"}}return"rtl"==getComputedStyle(t.dom).direction?"rtl":"ltr"}function kb(t,e,n){let r=t.state.selection;if(r instanceof jy&&!r.empty||n.indexOf("s")>-1)return!1;if(sw&&n.indexOf("m")>-1)return!1;let{$from:o,$to:i}=r;if(!o.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let n=hb(t.state,e);if(n&&n instanceof Hy)return fb(t,n)}if(!o.parent.inlineContent){let n=e<0?o:i,s=r instanceof Uy?Dy.near(n,e):Dy.findFrom(n,e);return!!s&&fb(t,s)}return!1}function Sb(t,e){if(!(t.state.selection instanceof jy))return!0;let{$head:n,$anchor:r,empty:o}=t.state.selection;if(!n.sameParent(r))return!0;if(!o)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let i=!n.textOffset&&(e<0?n.nodeBefore:n.nodeAfter);if(i&&!i.isText){let r=t.state.tr;return e<0?r.delete(n.pos-i.nodeSize,n.pos):r.delete(n.pos,n.pos+i.nodeSize),t.dispatch(r),!0}return!1}function Pb(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function Mb(t,e){let n=e.keyCode,r=function(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}(e);if(8==n||sw&&72==n&&"c"==r)return Sb(t,-1)||xb(t,-1);if(46==n&&!e.shiftKey||sw&&68==n&&"c"==r)return Sb(t,1)||xb(t,1);if(13==n||27==n)return!0;if(37==n||sw&&66==n&&"c"==r){let e=37==n?"ltr"==vb(t,t.state.selection.from)?-1:1:-1;return mb(t,e,r)||xb(t,e)}if(39==n||sw&&70==n&&"c"==r){let e=39==n?"ltr"==vb(t,t.state.selection.from)?1:-1:1;return mb(t,e,r)||xb(t,e)}return 38==n||sw&&80==n&&"c"==r?kb(t,-1,r)||xb(t,-1):40==n||sw&&78==n&&"c"==r?function(t){if(!ow||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(e&&1==e.nodeType&&0==n&&e.firstChild&&"false"==e.firstChild.contentEditable){let n=e.firstChild;Pb(t,n,"true"),setTimeout(()=>Pb(t,n,"false"),20)}return!1}(t)||kb(t,1,r)||xb(t,1):r==(sw?"m":"c")&&(66==n||73==n||89==n||90==n)}function Ib(t,e){t.someProp("transformCopied",n=>{e=n(e,t)});let n=[],{content:r,openStart:o,openEnd:i}=e;for(;o>1&&i>1&&1==r.childCount&&1==r.firstChild.childCount;){o--,i--;let t=r.firstChild;n.push(t.type.name,t.attrs!=t.type.defaultAttrs?t.attrs:null),r=t.content}let s=t.someProp("clipboardSerializer")||Fg.fromSchema(t.state.schema),a=$b(),l=a.createElement("div");l.appendChild(s.serializeFragment(r,{document:a}));let c,d=l.firstChild,u=0;for(;d&&1==d.nodeType&&(c=Lb[d.nodeName.toLowerCase()]);){for(let t=c.length-1;t>=0;t--){let e=a.createElement(c[t]);for(;l.firstChild;)e.appendChild(l.firstChild);l.appendChild(e),u++}d=l.firstChild}return d&&1==d.nodeType&&d.setAttribute("data-pm-slice",`${o} ${i}${u?` -${u}`:""} ${JSON.stringify(n)}`),{dom:l,text:t.someProp("clipboardTextSerializer",n=>n(e,t))||e.content.textBetween(0,e.content.size,"\n\n"),slice:e}}function Tb(t,e,n,r,o){let i,s,a=o.parent.type.spec.code;if(!n&&!e)return null;let l=!!e&&(r||a||!n);if(l){if(t.someProp("transformPastedText",n=>{e=n(e,a||r,t)}),a)return s=new _m(Bm.from(t.state.schema.text(e.replace(/\r\n?/g,"\n"))),0,0),t.someProp("transformPasted",e=>{s=e(s,t,!0)}),s;let n=t.someProp("clipboardTextParser",n=>n(e,o,r,t));if(n)s=n;else{let n=o.marks(),{schema:r}=t.state,s=Fg.fromSchema(r);i=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(t=>{let e=i.appendChild(document.createElement("p"));t&&e.appendChild(s.serializeNode(r.text(t,n)))})}}else t.someProp("transformPastedHTML",e=>{n=e(n,t)}),i=function(t){let e=/^(\s*<meta [^>]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let n,r=$b(),o=r.body,i=/<([a-z][^>\s]+)/i.exec(t);(n=i&&Lb[i[1].toLowerCase()])&&(t=n.map(t=>"<"+t+">").join("")+t+n.map(t=>"</"+t+">").reverse().join(""));if(o.innerHTML=function(t){let e=window.trustedTypes;if(!e)return t;Db||(Db=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:t=>t}));return Db.createHTML(t)}(t),n)for(let s=0;s<n.length;s++)o=o.querySelector(n[s])||o;for(let s=0;s<r.styleSheets.length;s++){let t=r.styleSheets[s];for(let e=0;e<t.rules.length;e++){let n=t.rules[e];if(n instanceof CSSStyleRule){let t=o.querySelectorAll(n.selectorText);for(let e=0;e<t.length;e++)t[e].style.cssText+=n.style.cssText}}}return o}(n),cw&&function(t){let e=t.querySelectorAll(nw?"span:not([class]):not([style])":"span.Apple-converted-space");for(let n=0;n<e.length;n++){let r=e[n];1==r.childNodes.length&&" "==r.textContent&&r.parentNode&&r.parentNode.replaceChild(t.ownerDocument.createTextNode(" "),r)}}(i);let c=i&&i.querySelector("[data-pm-slice]"),d=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(d&&d[3])for(let u=+d[3];u>0;u--){let t=i.firstChild;for(;t&&1!=t.nodeType;)t=t.nextSibling;if(!t)break;i=t}if(s||(s=(t.someProp("clipboardParser")||t.someProp("domParser")||Eg.fromSchema(t.state.schema)).parseSlice(i,{preserveWhitespace:!(!l&&!d),context:o,ruleFromNode:t=>"BR"!=t.nodeName||t.nextSibling||!t.parentNode||Cb.test(t.parentNode.nodeName)?null:{ignore:!0}})),d)s=function(t,e){if(!t.size)return t;let n,r=t.content.firstChild.type.schema;try{n=JSON.parse(e)}catch(a){return t}let{content:o,openStart:i,openEnd:s}=t;for(let l=n.length-2;l>=0;l-=2){let t=r.nodes[n[l]];if(!t||t.hasRequiredAttrs())break;o=Bm.from(t.create(n[l+1],o)),i++,s++}return new _m(o,i,s)}(Rb(s,+d[1],+d[2]),d[4]);else if(s=_m.maxOpen(function(t,e){if(t.childCount<2)return t;for(let n=e.depth;n>=0;n--){let r,o=e.node(n).contentMatchAt(e.index(n)),i=[];if(t.forEach(t=>{if(!i)return;let e,n=o.findWrapping(t.type);if(!n)return i=null;if(e=i.length&&r.length&&Ab(n,r,t,i[i.length-1],0))i[i.length-1]=e;else{i.length&&(i[i.length-1]=Ob(i[i.length-1],r.length));let e=Eb(t,n);i.push(e),o=o.matchType(e.type),r=n}}),i)return Bm.from(i)}return t}(s.content,o),!0),s.openStart||s.openEnd){let t=0,e=0;for(let n=s.content.firstChild;t<s.openStart&&!n.type.spec.isolating;t++,n=n.firstChild);for(let n=s.content.lastChild;e<s.openEnd&&!n.type.spec.isolating;e++,n=n.lastChild);s=Rb(s,t,e)}return t.someProp("transformPasted",e=>{s=e(s,t,l)}),s}var Cb=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function Eb(t,e,n=0){for(let r=e.length-1;r>=n;r--)t=e[r].create(null,Bm.from(t));return t}function Ab(t,e,n,r,o){if(o<t.length&&o<e.length&&t[o]==e[o]){let i=Ab(t,e,n,r.lastChild,o+1);if(i)return r.copy(r.content.replaceChild(r.childCount-1,i));if(r.contentMatchAt(r.childCount).matchType(o==t.length-1?n.type:t[o+1]))return r.copy(r.content.append(Bm.from(Eb(n,t,o+1))))}}function Ob(t,e){if(0==e)return t;let n=t.content.replaceChild(t.childCount-1,Ob(t.lastChild,e-1)),r=t.contentMatchAt(t.childCount).fillBefore(Bm.empty,!0);return t.copy(n.append(r))}function Nb(t,e,n,r,o,i){let s=e<0?t.firstChild:t.lastChild,a=s.content;return t.childCount>1&&(i=0),o<r-1&&(a=Nb(a,e,n,r,o+1,i)),o>=n&&(a=e<0?s.contentMatchAt(0).fillBefore(a,i<=o).append(a):a.append(s.contentMatchAt(s.childCount).fillBefore(Bm.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,s.copy(a))}function Rb(t,e,n){return e<t.openStart&&(t=new _m(Nb(t.content,-1,e,t.openStart,0,t.openEnd),e,t.openEnd)),n<t.openEnd&&(t=new _m(Nb(t.content,1,n,t.openEnd,0,0),t.openStart,n)),t}var Lb={thead:["table"],tbody:["table"],tfoot:["table"],caption:["table"],colgroup:["table"],col:["table","colgroup"],tr:["table","tbody"],td:["table","tbody","tr"],th:["table","tbody","tr"]};function $b(){return document.implementation.createHTMLDocument("title")}var Db=null;var Bb={},zb={},Fb={touchstart:!0,touchmove:!0},jb=class{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}};function Wb(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function Hb(t){t.someProp("handleDOMEvents",e=>{for(let n in e)t.input.eventHandlers[n]||t.dom.addEventListener(n,t.input.eventHandlers[n]=e=>_b(t,e))})}function _b(t,e){return t.someProp("handleDOMEvents",n=>{let r=n[e.type];return!!r&&(r(t,e)||e.defaultPrevented)})}function Ub(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let n=e.target;n!=t.dom;n=n.parentNode)if(!n||11==n.nodeType||n.pmViewDesc&&n.pmViewDesc.stopEvent(e))return!1;return!0}function Vb(t){return{left:t.clientX,top:t.clientY}}function Kb(t,e,n,r,o){if(-1==r)return!1;let i=t.state.doc.resolve(r);for(let s=i.depth+1;s>0;s--)if(t.someProp(e,e=>s>i.depth?e(t,n,i.nodeAfter,i.before(s),o,!0):e(t,n,i.node(s),i.before(s),o,!1)))return!0;return!1}function qb(t,e,n){if(t.focused||t.focus(),t.state.selection.eq(e))return;let r=t.state.tr.setSelection(e);"pointer"==n&&r.setMeta("pointer",!0),t.dispatch(r)}function Xb(t,e,n,r,o){return Kb(t,"handleClickOn",e,n,r)||t.someProp("handleClick",n=>n(t,e,r))||(o?function(t,e){if(-1==e)return!1;let n,r,o=t.state.selection;o instanceof Hy&&(n=o.node);let i=t.state.doc.resolve(e);for(let s=i.depth+1;s>0;s--){let t=s>i.depth?i.nodeAfter:i.node(s);if(Hy.isSelectable(t)){r=n&&o.$from.depth>0&&s>=o.$from.depth&&i.before(o.$from.depth+1)==o.$from.pos?i.before(o.$from.depth):i.before(s);break}}return null!=r&&(qb(t,Hy.create(t.state.doc,r),"pointer"),!0)}(t,n):function(t,e){if(-1==e)return!1;let n=t.state.doc.resolve(e),r=n.nodeAfter;return!!(r&&r.isAtom&&Hy.isSelectable(r))&&(qb(t,new Hy(n),"pointer"),!0)}(t,n))}function Yb(t,e,n,r){return Kb(t,"handleDoubleClickOn",e,n,r)||t.someProp("handleDoubleClick",n=>n(t,e,r))}function Jb(t,e,n,r){return Kb(t,"handleTripleClickOn",e,n,r)||t.someProp("handleTripleClick",n=>n(t,e,r))||function(t,e,n){if(0!=n.button)return!1;let r=Gb(t,e,!0),o=t.state.doc;if(!r)return!1;qb(t,r,"pointer"),r instanceof jy&&o.eq(t.state.doc)&&(t.input.mouseDown=new nv(t,r));return!0}(t,n,r)}function Gb(t,e,n){let r=t.state.doc;if(-1==e)return r.inlineContent?jy.create(r,0,r.content.size):null;let o=r.resolve(e);for(let i=o.depth+1;i>0;i--){let t=i>o.depth?o.nodeAfter:o.node(i),e=o.before(i);if(t.inlineContent)return jy.create(r,e+1,e+1+t.content.size);if(n&&Hy.isSelectable(t))return Hy.create(r,e)}return null}function Zb(t){return lv(t)}zb.keydown=(t,e)=>{let n=e;if(t.input.shiftKey=16==n.keyCode||n.shiftKey,!rv(t)&&(t.input.lastKeyCode=n.keyCode,t.input.lastKeyCodeTime=Date.now(),!lw||!nw||13!=n.keyCode))if(229!=n.keyCode&&t.domObserver.forceFlush(),!iw||13!=n.keyCode||n.ctrlKey||n.altKey||n.metaKey)t.someProp("handleKeyDown",e=>e(t,n))||Mb(t,n)?n.preventDefault():Wb(t,"key");else{let e=Date.now();t.input.lastIOSEnter=e,t.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{t.input.lastIOSEnter==e&&(t.someProp("handleKeyDown",e=>e(t,Vx(13,"Enter"))),t.input.lastIOSEnter=0)},200)}},zb.keyup=(t,e)=>{16==e.keyCode&&(t.input.shiftKey=!1)},zb.keypress=(t,e)=>{let n=e;if(rv(t)||!n.charCode||n.ctrlKey&&!n.altKey||sw&&n.metaKey)return;if(t.someProp("handleKeyPress",e=>e(t,n)))return void n.preventDefault();let r=t.state.selection;if(!(r instanceof jy&&r.$from.sameParent(r.$to))){let e=String.fromCharCode(n.charCode),o=()=>t.state.tr.insertText(e).scrollIntoView();/[\r\n]/.test(e)||t.someProp("handleTextInput",n=>n(t,r.$from.pos,r.$to.pos,e,o))||t.dispatch(o()),n.preventDefault()}};var Qb=sw?"metaKey":"ctrlKey";Bb.mousedown=(t,e)=>{let n=e;t.input.shiftKey=n.shiftKey;let r=Zb(t),o=Date.now(),i="singleClick";o-t.input.lastClick.time<500&&function(t,e){let n=e.x-t.clientX,r=e.y-t.clientY;return n*n+r*r<100}(n,t.input.lastClick)&&!n[Qb]&&t.input.lastClick.button==n.button&&("singleClick"==t.input.lastClick.type?i="doubleClick":"doubleClick"==t.input.lastClick.type&&(i="tripleClick")),t.input.lastClick={time:o,x:n.clientX,y:n.clientY,type:i,button:n.button},t.input.mouseDown&&t.input.mouseDown.done();let s=t.posAtCoords(Vb(n));s&&("singleClick"==i?t.input.mouseDown=new ev(t,s,n,!!r):("doubleClick"==i?Yb:Jb)(t,s.pos,s.inside,n)?n.preventDefault():Wb(t,"pointer"))};var tv=class{constructor(t){this.view=t,this.mightDrag=null,t.root.addEventListener("mouseup",this.up=this.up.bind(this)),t.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(t){this.done()}move(t){0==t.buttons&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}},ev=class extends tv{constructor(t,e,n,r){let o,i;if(super(t),this.pos=e,this.event=n,this.flushed=r,this.delayedSelectionSync=!1,this.startDoc=t.state.doc,this.selectNode=!!n[Qb],this.allowDefault=n.shiftKey,e.inside>-1)o=t.state.doc.nodeAt(e.inside),i=e.inside;else{let n=t.state.doc.resolve(e.pos);o=n.parent,i=n.depth?n.before():0}const s=r?null:n.target,a=s?t.docView.nearestDesc(s,!0):null;this.target=a&&1==a.nodeDOM.nodeType?a.nodeDOM:null;let{selection:l}=t.state;0==n.button&&(o.type.spec.draggable&&!1!==o.type.spec.selectable||l instanceof Hy&&l.from<=i&&l.to>i)&&(this.mightDrag={node:o,pos:i,addAttr:!(!this.target||this.target.draggable),setUneditable:!(!this.target||!tw||this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),Wb(t,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||rb(this.view)})}up(t){if(this.done(),!this.view.dom.contains(t.target))return;let e=this.pos;this.view.state.doc!=this.startDoc&&(e=this.view.posAtCoords(Vb(t))),this.updateAllowDefault(t),this.allowDefault||!e?Wb(this.view,"pointer"):Xb(this.view,e.pos,e.inside,t,this.selectNode)?t.preventDefault():0==t.button&&(this.flushed||ow&&this.mightDrag&&!this.mightDrag.node.isAtom||nw&&!this.view.state.selection.visible&&Math.min(Math.abs(e.pos-this.view.state.selection.from),Math.abs(e.pos-this.view.state.selection.to))<=2)?(qb(this.view,Dy.near(this.view.state.doc.resolve(e.pos)),"pointer"),t.preventDefault()):Wb(this.view,"pointer")}move(t){this.updateAllowDefault(t),Wb(this.view,"pointer"),super.move(t)}updateAllowDefault(t){!this.allowDefault&&(Math.abs(this.event.x-t.clientX)>4||Math.abs(this.event.y-t.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return!!this.allowDefault&&(this.delayedSelectionSync=!0,!0)}},nv=class extends tv{constructor(t,e){super(t),this.startSelection=e,this.startDoc=t.state.doc}move(t){if(0==t.buttons||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc))return void this.done();t.preventDefault(),Wb(this.view,"pointer");let e=this.view.posAtCoords(Vb(t)),n=e&&Gb(this.view,e.inside,!1);if(!n)return;let{doc:r}=this.view.state,o=this.startSelection,[i,s]=n.from<o.from?[o.to,n.from]:[o.from,n.to];qb(this.view,jy.create(r,i,s),"pointer")}};function rv(t,e){return!!t.composing||!!(ow&&Math.abs(Date.now()-t.input.compositionEndedAt)<500)&&(t.input.compositionEndedAt=-2e8,!0)}Bb.touchstart=t=>{t.input.lastTouch=Date.now(),Zb(t),Wb(t,"pointer")},Bb.touchmove=t=>{t.input.lastTouch=Date.now(),Wb(t,"pointer")},Bb.contextmenu=t=>Zb(t);var ov=lw?5e3:-1;function iv(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout(()=>lv(t),e))}function sv(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=Date.now());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function av(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let n=function(t,e){for(;;){if(3==t.nodeType&&e)return t;if(1==t.nodeType&&e>0){if("false"==t.contentEditable)return null;e=Hx(t=t.childNodes[e-1])}else{if(!t.parentNode||_x(t))return null;e=$x(t),t=t.parentNode}}}(e.focusNode,e.focusOffset),r=function(t,e){for(;;){if(3==t.nodeType&&e<t.nodeValue.length)return t;if(1==t.nodeType&&e<t.childNodes.length){if("false"==t.contentEditable)return null;t=t.childNodes[e],e=0}else{if(!t.parentNode||_x(t))return null;e=$x(t)+1,t=t.parentNode}}}(e.focusNode,e.focusOffset);if(n&&r&&n!=r){let e=r.pmViewDesc,o=t.domObserver.lastChangedTextNode;if(n==o||r==o)return o;if(!e||!e.isText(r.nodeValue))return r;if(t.input.compositionNode==r){let t=n.pmViewDesc;if(t&&t.isText(n.nodeValue))return r}}return n||r}function lv(t,e=!1){if(!(lw&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),sv(t),e||t.docView&&t.docView.dirty){let n=eb(t),r=t.state.selection;return n&&!n.eq(r)?t.dispatch(t.state.tr.setSelection(n)):!t.markCursor&&!e||r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?t.updateState(t.state):t.dispatch(t.state.tr.deleteSelection()),!0}return!1}}zb.compositionstart=zb.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,n=e.selection.$to;if(e.selection instanceof jy&&(e.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(t=>!1===t.type.spec.inclusive)||nw&&aw&&function(t){let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(!e||1!=e.nodeType||n>=e.childNodes.length)return!1;let r=e.childNodes[n];return 1==r.nodeType&&"false"==r.contentEditable}(t)))t.markCursor=t.state.storedMarks||n.marks(),lv(t,!0),t.markCursor=null;else if(lv(t,!e.selection.empty),tw&&e.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let e=t.domSelectionRange();for(let n=e.focusNode,r=e.focusOffset;n&&1==n.nodeType&&0!=r;){let e=r<0?n.lastChild:n.childNodes[r-1];if(!e)break;if(3==e.nodeType){let n=t.domSelection();n&&n.collapse(e,e.nodeValue.length);break}n=e,r=-1}}t.input.composing=!0}iv(t,ov)},zb.compositionend=(t,e)=>{t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=Date.now(),t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.badSafariComposition?t.domObserver.forceFlush():t.input.compositionPendingChanges&&Promise.resolve().then(()=>t.domObserver.flush()),t.input.compositionID++,iv(t,20))};var cv=Zx&&Qx<15||iw&&dw<604;function dv(t,e,n,r,o){let i=Tb(t,e,n,r,t.state.selection.$from);if(t.someProp("handlePaste",e=>e(t,o,i||_m.empty)))return!0;if(!i)return!1;let s=function(t){return 0==t.openStart&&0==t.openEnd&&1==t.content.childCount?t.content.firstChild:null}(i),a=s?t.state.tr.replaceSelectionWith(s,r):t.state.tr.replaceSelection(i);return t.dispatch(a.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function uv(t){let e=t.getData("text/plain")||t.getData("Text");if(e)return e;let n=t.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Bb.copy=zb.cut=(t,e)=>{let n=e,r=t.state.selection,o="cut"==n.type;if(r.empty)return;let i=cv?null:n.clipboardData,{dom:s,text:a}=Ib(t,r.content());i?(n.preventDefault(),i.clearData(),i.setData("text/html",s.innerHTML),i.setData("text/plain",a)):function(t,e){if(!t.dom.parentNode)return;let n=t.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(e),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),o=document.createRange();o.selectNodeContents(e),t.dom.blur(),r.removeAllRanges(),r.addRange(o),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),t.focus()},50)}(t,s),o&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))},zb.paste=(t,e)=>{let n=e;if(t.composing&&!lw)return;let r=cv?null:n.clipboardData,o=t.input.shiftKey&&45!=t.input.lastKeyCode;r&&dv(t,uv(r),r.getData("text/html"),o,n)?n.preventDefault():function(t,e){if(!t.dom.parentNode)return;let n=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,r=t.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));n||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let o=t.input.shiftKey&&45!=t.input.lastKeyCode;setTimeout(()=>{t.focus(),r.parentNode&&r.parentNode.removeChild(r),n?dv(t,r.value,null,o,e):dv(t,r.textContent,r.innerHTML,o,e)},50)}(t,n)};var pv=class{constructor(t,e,n){this.slice=t,this.move=e,this.node=n}},hv=sw?"altKey":"ctrlKey";function fv(t,e){let n;return t.someProp("dragCopies",t=>{n=n||t(e)}),null!=n?!n:!e[hv]}Bb.dragstart=(t,e)=>{let n=e,r=t.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let o,i=t.state.selection,s=i.empty?null:t.posAtCoords(Vb(n));if(s&&s.pos>=i.from&&s.pos<=(i instanceof Hy?i.to-1:i.to));else if(r&&r.mightDrag)o=Hy.create(t.state.doc,r.mightDrag.pos);else if(n.target&&1==n.target.nodeType){let e=t.docView.nearestDesc(n.target,!0);e&&e.node.type.spec.draggable&&e!=t.docView&&(o=Hy.create(t.state.doc,e.posBefore))}let{dom:a,text:l,slice:c}=Ib(t,(o||t.state.selection).content());(!n.dataTransfer.files.length||!nw||rw>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(cv?"Text":"text/html",a.innerHTML),n.dataTransfer.effectAllowed="copyMove",cv||n.dataTransfer.setData("text/plain",l),t.dragging=new pv(c,fv(t,n),o)},Bb.dragend=t=>{let e=t.dragging;window.setTimeout(()=>{t.dragging==e&&(t.dragging=null)},50)},zb.dragover=zb.dragenter=(t,e)=>e.preventDefault(),zb.drop=(t,e)=>{try{!function(t,e,n){if(!e.dataTransfer)return;let r=t.posAtCoords(Vb(e));if(!r)return;let o=t.state.doc.resolve(r.pos),i=n&&n.slice;i?t.someProp("transformPasted",e=>{i=e(i,t,!1)}):i=Tb(t,uv(e.dataTransfer),cv?null:e.dataTransfer.getData("text/html"),!1,o);let s=!(!n||!fv(t,e));if(t.someProp("handleDrop",n=>n(t,e,i||_m.empty,s)))return void e.preventDefault();if(!i)return;e.preventDefault();let a=i?wy(t.state.doc,o.pos,i):o.pos;null==a&&(a=o.pos);let l=t.state.tr;if(s){let{node:t}=n;t?t.replace(l):l.deleteSelection()}let c=l.mapping.map(a),d=0==i.openStart&&0==i.openEnd&&1==i.content.childCount,u=l.doc;d?l.replaceRangeWith(c,c,i.content.firstChild):l.replaceRange(c,c,i);if(l.doc.eq(u))return;let p=l.doc.resolve(c);if(d&&Hy.isSelectable(i.content.firstChild)&&p.nodeAfter&&p.nodeAfter.sameMarkup(i.content.firstChild))l.setSelection(new Hy(p));else{let e=l.mapping.map(a);l.mapping.maps[l.mapping.maps.length-1].forEach((t,n,r,o)=>e=o),l.setSelection(db(t,p,l.doc.resolve(e)))}t.focus(),t.dispatch(l.setMeta("uiEvent","drop"))}(t,e,t.dragging)}finally{t.dragging=null}},Bb.focus=t=>{t.input.lastFocus=Date.now(),t.focused||(t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout(()=>{t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange())&&rb(t)},20))},Bb.blur=(t,e)=>{let n=e;t.focused&&(t.domObserver.stop(),t.dom.classList.remove("ProseMirror-focused"),t.domObserver.start(),n.relatedTarget&&t.dom.contains(n.relatedTarget)&&t.domObserver.currentSelection.clear(),t.focused=!1)},Bb.beforeinput=(t,e)=>{if(nw&&lw&&"deleteContentBackward"==e.inputType){t.domObserver.flushSoon();let{domChangeCount:e}=t.input;setTimeout(()=>{if(t.input.domChangeCount!=e)return;if(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",e=>e(t,Vx(8,"Backspace"))))return;let{$cursor:n}=t.state.selection;n&&n.pos>0&&t.dispatch(t.state.tr.delete(n.pos-1,n.pos).scrollIntoView())},50)}};for(let os in zb)Bb[os]=zb[os];function mv(t,e){if(t==e)return!0;for(let n in t)if(t[n]!==e[n])return!1;for(let n in e)if(!(n in t))return!1;return!0}var gv=class t{constructor(t,e){this.toDOM=t,this.spec=e||vv,this.side=this.spec.side||0}map(t,e,n,r){let{pos:o,deleted:i}=t.mapResult(e.from+r,this.side<0?-1:1);return i?null:new wv(o-n,o-n,this)}valid(){return!0}eq(e){return this==e||e instanceof t&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&mv(this.spec,e.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}},yv=class t{constructor(t,e){this.attrs=t,this.spec=e||vv}map(t,e,n,r){let o=t.map(e.from+r,this.spec.inclusiveStart?-1:1)-n,i=t.map(e.to+r,this.spec.inclusiveEnd?1:-1)-n;return o>=i?null:new wv(o,i,this)}valid(t,e){return e.from<e.to}eq(e){return this==e||e instanceof t&&mv(this.attrs,e.attrs)&&mv(this.spec,e.spec)}static is(e){return e.type instanceof t}destroy(){}},xv=class t{constructor(t,e){this.attrs=t,this.spec=e||vv}map(t,e,n,r){let o=t.mapResult(e.from+r,1);if(o.deleted)return null;let i=t.mapResult(e.to+r,-1);return i.deleted||i.pos<=o.pos?null:new wv(o.pos-n,i.pos-n,this)}valid(t,e){let n,{index:r,offset:o}=t.content.findIndex(e.from);return o==e.from&&!(n=t.child(r)).isText&&o+n.nodeSize==e.to}eq(e){return this==e||e instanceof t&&mv(this.attrs,e.attrs)&&mv(this.spec,e.spec)}destroy(){}},wv=class t{constructor(t,e,n){this.from=t,this.to=e,this.type=n}copy(e,n){return new t(e,n,this.type)}eq(t,e=0){return this.type.eq(t.type)&&this.from+e==t.from&&this.to+e==t.to}map(t,e,n){return this.type.map(t,this,e,n)}static widget(e,n,r){return new t(e,e,new gv(n,r))}static inline(e,n,r,o){return new t(e,n,new yv(r,o))}static node(e,n,r,o){return new t(e,n,new xv(r,o))}get spec(){return this.type.spec}get inline(){return this.type instanceof yv}get widget(){return this.type instanceof gv}},bv=[],vv={},kv=class t{constructor(t,e){this.local=t.length?t:bv,this.children=e.length?e:bv}static create(t,e){return e.length?Ev(e,t,0,vv):Sv}find(t,e,n){let r=[];return this.findInner(null==t?0:t,null==e?1e9:e,r,0,n),r}findInner(t,e,n,r,o){for(let i=0;i<this.local.length;i++){let s=this.local[i];s.from<=e&&s.to>=t&&(!o||o(s.spec))&&n.push(s.copy(s.from+r,s.to+r))}for(let i=0;i<this.children.length;i+=3)if(this.children[i]<e&&this.children[i+1]>t){let s=this.children[i]+1;this.children[i+2].findInner(t-s,e-s,n,r+s,o)}}map(t,e,n){return this==Sv||0==t.maps.length?this:this.mapInner(t,e,0,0,n||vv)}mapInner(e,n,r,o,i){let s;for(let t=0;t<this.local.length;t++){let a=this.local[t].map(e,r,o);a&&a.type.valid(n,a)?(s||(s=[])).push(a):i.onRemove&&i.onRemove(this.local[t].spec)}return this.children.length?Mv(this.children,s||[],e,n,r,o,i):s?new t(s.sort(Av),bv):Sv}add(e,n){return n.length?this==Sv?t.create(e,n):this.addInner(e,n,0):this}addInner(e,n,r){let o,i=0;e.forEach((t,e)=>{let s,a=e+r;if(s=Tv(n,t,a)){for(o||(o=this.children.slice());i<o.length&&o[i]<e;)i+=3;o[i]==e?o[i+2]=o[i+2].addInner(t,s,a+1):o.splice(i,0,e,e+t.nodeSize,Ev(s,t,a+1,vv)),i+=3}});let s=Iv(i?Cv(n):n,-r);for(let t=0;t<s.length;t++)s[t].type.valid(e,s[t])||s.splice(t--,1);return new t(s.length?this.local.concat(s).sort(Av):this.local,o||this.children)}remove(t){return 0==t.length||this==Sv?this:this.removeInner(t,0)}removeInner(e,n){let r=this.children,o=this.local;for(let t=0;t<r.length;t+=3){let o,i=r[t]+n,s=r[t+1]+n;for(let t,n=0;n<e.length;n++)(t=e[n])&&t.from>i&&t.to<s&&(e[n]=null,(o||(o=[])).push(t));if(!o)continue;r==this.children&&(r=this.children.slice());let a=r[t+2].removeInner(o,i+1);a!=Sv?r[t+2]=a:(r.splice(t,3),t-=3)}if(o.length)for(let t,i=0;i<e.length;i++)if(t=e[i])for(let e=0;e<o.length;e++)o[e].eq(t,n)&&(o==this.local&&(o=this.local.slice()),o.splice(e--,1));return r==this.children&&o==this.local?this:o.length||r.length?new t(o,r):Sv}forChild(e,n){if(this==Sv)return this;if(n.isLeaf)return t.empty;let r,o;for(let t=0;t<this.children.length;t+=3)if(this.children[t]>=e){this.children[t]==e&&(r=this.children[t+2]);break}let i=e+1,s=i+n.content.size;for(let t=0;t<this.local.length;t++){let e=this.local[t];if(e.from<s&&e.to>i&&e.type instanceof yv){let t=Math.max(i,e.from)-i,n=Math.min(s,e.to)-i;t<n&&(o||(o=[])).push(e.copy(t,n))}}if(o){let e=new t(o.sort(Av),bv);return r?new Pv([e,r]):e}return r||Sv}eq(e){if(this==e)return!0;if(!(e instanceof t)||this.local.length!=e.local.length||this.children.length!=e.children.length)return!1;for(let t=0;t<this.local.length;t++)if(!this.local[t].eq(e.local[t]))return!1;for(let t=0;t<this.children.length;t+=3)if(this.children[t]!=e.children[t]||this.children[t+1]!=e.children[t+1]||!this.children[t+2].eq(e.children[t+2]))return!1;return!0}locals(t){return Ov(this.localsInner(t))}localsInner(t){if(this==Sv)return bv;if(t.inlineContent||!this.local.some(yv.is))return this.local;let e=[];for(let n=0;n<this.local.length;n++)this.local[n].type instanceof yv||e.push(this.local[n]);return e}forEachSet(t){t(this)}};kv.empty=new kv([],[]),kv.removeOverlap=Ov;var Sv=kv.empty,Pv=class t{constructor(t){this.members=t}map(e,n){const r=this.members.map(t=>t.map(e,n,vv));return t.from(r)}forChild(e,n){if(n.isLeaf)return kv.empty;let r=[];for(let o=0;o<this.members.length;o++){let i=this.members[o].forChild(e,n);i!=Sv&&(i instanceof t?r=r.concat(i.members):r.push(i))}return t.from(r)}eq(e){if(!(e instanceof t)||e.members.length!=this.members.length)return!1;for(let t=0;t<this.members.length;t++)if(!this.members[t].eq(e.members[t]))return!1;return!0}locals(t){let e,n=!0;for(let r=0;r<this.members.length;r++){let o=this.members[r].localsInner(t);if(o.length)if(e){n&&(e=e.slice(),n=!1);for(let t=0;t<o.length;t++)e.push(o[t])}else e=o}return e?Ov(n?e:e.sort(Av)):bv}static from(e){switch(e.length){case 0:return Sv;case 1:return e[0];default:return new t(e.every(t=>t instanceof kv)?e:e.reduce((t,e)=>t.concat(e instanceof kv?e:e.members),[]))}}forEachSet(t){for(let e=0;e<this.members.length;e++)this.members[e].forEachSet(t)}};function Mv(t,e,n,r,o,i,s){let a=t.slice();for(let c=0,d=i;c<n.maps.length;c++){let t=0;n.maps[c].forEach((e,n,r,o)=>{let i=o-r-(n-e);for(let s=0;s<a.length;s+=3){let r=a[s+1];if(r<0||e>r+d-t)continue;let o=a[s]+d-t;n>=o?a[s+1]=e<=o?-2:-1:e>=d&&i&&(a[s]+=i,a[s+1]+=i)}t+=i}),d=n.maps[c].map(d,-1)}let l=!1;for(let c=0;c<a.length;c+=3)if(a[c+1]<0){if(-2==a[c+1]){l=!0,a[c+1]=-1;continue}let e=n.map(t[c]+i),d=e-o;if(d<0||d>=r.content.size){l=!0;continue}let u=n.map(t[c+1]+i,-1)-o,{index:p,offset:h}=r.content.findIndex(d),f=r.maybeChild(p);if(f&&h==d&&h+f.nodeSize==u){let r=a[c+2].mapInner(n,f,e+1,t[c]+i+1,s);r!=Sv?(a[c]=d,a[c+1]=u,a[c+2]=r):(a[c+1]=-2,l=!0)}else l=!0}if(l){let l=Ev(function(t,e,n,r,o,i,s){function a(t,e){for(let i=0;i<t.local.length;i++){let a=t.local[i].map(r,o,e);a?n.push(a):s.onRemove&&s.onRemove(t.local[i].spec)}for(let n=0;n<t.children.length;n+=3)a(t.children[n+2],t.children[n]+e+1)}for(let l=0;l<t.length;l+=3)-1==t[l+1]&&a(t[l+2],e[l]+i+1);return n}(a,t,e,n,o,i,s),r,0,s);e=l.local;for(let t=0;t<a.length;t+=3)a[t+1]<0&&(a.splice(t,3),t-=3);for(let t=0,e=0;t<l.children.length;t+=3){let n=l.children[t];for(;e<a.length&&a[e]<n;)e+=3;a.splice(e,0,l.children[t],l.children[t+1],l.children[t+2])}}return new kv(e.sort(Av),a)}function Iv(t,e){if(!e||!t.length)return t;let n=[];for(let r=0;r<t.length;r++){let o=t[r];n.push(new wv(o.from+e,o.to+e,o.type))}return n}function Tv(t,e,n){if(e.isLeaf)return null;let r=n+e.nodeSize,o=null;for(let i,s=0;s<t.length;s++)(i=t[s])&&i.from>n&&i.to<r&&((o||(o=[])).push(i),t[s]=null);return o}function Cv(t){let e=[];for(let n=0;n<t.length;n++)null!=t[n]&&e.push(t[n]);return e}function Ev(t,e,n,r){let o=[],i=!1;e.forEach((e,s)=>{let a=Tv(t,e,s+n);if(a){i=!0;let t=Ev(a,e,n+s+1,r);t!=Sv&&o.push(s,s+e.nodeSize,t)}});let s=Iv(i?Cv(t):t,-n).sort(Av);for(let a=0;a<s.length;a++)s[a].type.valid(e,s[a])||(r.onRemove&&r.onRemove(s[a].spec),s.splice(a--,1));return s.length||o.length?new kv(s,o):Sv}function Av(t,e){return t.from-e.from||t.to-e.to}function Ov(t){let e=t;for(let n=0;n<e.length-1;n++){let r=e[n];if(r.from!=r.to)for(let o=n+1;o<e.length;o++){let i=e[o];if(i.from!=r.from){i.from<r.to&&(e==t&&(e=t.slice()),e[n]=r.copy(r.from,i.from),Nv(e,o,r.copy(i.from,r.to)));break}i.to!=r.to&&(e==t&&(e=t.slice()),e[o]=i.copy(i.from,r.to),Nv(e,o+1,i.copy(r.to,i.to)))}}return e}function Nv(t,e,n){for(;e<t.length&&Av(n,t[e])>0;)e++;t.splice(e,0,n)}function Rv(t){let e=[];return t.someProp("decorations",n=>{let r=n(t.state);r&&r!=Sv&&e.push(r)}),t.cursorWrapper&&e.push(kv.create(t.state.doc,[t.cursorWrapper.deco])),Pv.from(e)}var Lv={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},$v=Zx&&Qx<=11,Dv=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(t){this.anchorNode=t.anchorNode,this.anchorOffset=t.anchorOffset,this.focusNode=t.focusNode,this.focusOffset=t.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(t){return t.anchorNode==this.anchorNode&&t.anchorOffset==this.anchorOffset&&t.focusNode==this.focusNode&&t.focusOffset==this.focusOffset}},Bv=class{constructor(t,e){this.view=t,this.handleDOMChange=e,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Dv,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(e=>{for(let t=0;t<e.length;t++)this.queue.push(e[t]);Zx&&Qx<=11&&e.some(t=>"childList"==t.type&&t.removedNodes.length||"characterData"==t.type&&t.oldValue.length>t.target.nodeValue.length)?this.flushSoon():ow&&t.composing&&e.some(t=>"childList"==t.type&&"TR"==t.target.nodeName)?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),$v&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,Lv)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let t=this.observer.takeRecords();if(t.length){for(let e=0;e<t.length;e++)this.queue.push(t[e]);window.setTimeout(()=>this.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(ub(this.view)){if(this.suppressingSelectionUpdates)return rb(this.view);if(Zx&&Qx<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&Fx(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(t){if(!t.focusNode)return!0;let e,n=new Set;for(let o=t.focusNode;o;o=Dx(o))n.add(o);for(let o=t.anchorNode;o;o=Dx(o))if(n.has(o)){e=o;break}let r=e&&this.view.docView.nearestDesc(e);return r&&r.ignoreMutation({type:"selection",target:3==e.nodeType?e.parentNode:e})?(this.setCurSelection(),!0):void 0}pendingRecords(){if(this.observer)for(let t of this.observer.takeRecords())this.queue.push(t);return this.queue}flush(){let{view:t}=this;if(!t.docView||this.flushingSoon>-1)return;let e=this.pendingRecords();e.length&&(this.queue=[]);let n=t.domSelectionRange(),r=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(n)&&ub(t)&&!this.ignoreSelectionChange(n),o=-1,i=-1,s=!1,a=[];if(t.editable)for(let c=0;c<e.length;c++){let t=this.registerMutation(e[c],a);t&&(o=o<0?t.from:Math.min(t.from,o),i=i<0?t.to:Math.max(t.to,i),t.typeOver&&(s=!0))}if(a.some(t=>"BR"==t.nodeName)&&(8==t.input.lastKeyCode||46==t.input.lastKeyCode||nw&&(t.composing||t.input.compositionEndedAt>Date.now()-50)&&e.some(t=>"childList"==t.type&&t.removedNodes.length))){for(let c of a)if("BR"==c.nodeName&&c.parentNode){let t=c.nextSibling;for(;t&&1==t.nodeType;){if("false"==t.contentEditable){c.parentNode.removeChild(c);break}t=t.firstChild}}}else if(tw&&a.length){let e=a.filter(t=>"BR"==t.nodeName);if(2==e.length){let[t,n]=e;t.parentNode&&t.parentNode.parentNode==n.parentNode?n.remove():t.remove()}else{let{focusNode:n}=this.currentSelection;for(let r of e){let e=r.parentNode;!e||"LI"!=e.nodeName||n&&Wv(t,n)==e||r.remove()}}}let l=null;o<0&&r&&t.input.lastFocus>Date.now()-200&&Math.max(t.input.lastTouch,t.input.lastClick.time)<Date.now()-300&&Ux(n)&&(l=eb(t))&&l.eq(Dy.near(t.state.doc.resolve(0),1))?(t.input.lastFocus=0,rb(t),this.currentSelection.set(n),t.scrollToSelection()):(o>-1||r)&&(o>-1&&(t.docView.markDirty(o,i),function(t){if(zv.has(t))return;if(zv.set(t,null),-1!==["normal","nowrap","pre-line"].indexOf(getComputedStyle(t.dom).whiteSpace)){if(t.requiresGeckoHackNode=tw,Fv)return;console.warn("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package."),Fv=!0}}(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,function(t,e){var n;let{focusNode:r,focusOffset:o}=t.domSelectionRange();for(let i of e)if("TR"==(null===(n=i.parentNode)||void 0===n?void 0:n.nodeName)){let e=i.nextSibling;for(;e&&"TD"!=e.nodeName&&"TH"!=e.nodeName;)e=e.nextSibling;if(e){let n=e;for(;;){let t=n.firstChild;if(!t||1!=t.nodeType||"false"==t.contentEditable||/^(BR|IMG)$/.test(t.nodeName))break;n=t}n.insertBefore(i,n.firstChild),r==i&&t.domSelection().collapse(i,o)}else i.parentNode.removeChild(i)}}(t,a)),this.handleDOMChange(o,i,s,a),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(n)||rb(t),this.currentSelection.set(n))}registerMutation(t,e){if(e.indexOf(t.target)>-1)return null;let n=this.view.docView.nearestDesc(t.target);if("attributes"==t.type&&(n==this.view.docView||"contenteditable"==t.attributeName||"style"==t.attributeName&&!t.oldValue&&!t.target.getAttribute("style")))return null;if(!n||n.ignoreMutation(t))return null;if("childList"==t.type){for(let n=0;n<t.addedNodes.length;n++){let r=t.addedNodes[n];e.push(r),3==r.nodeType&&(this.lastChangedTextNode=r)}if(n.contentDOM&&n.contentDOM!=n.dom&&!n.contentDOM.contains(t.target))return{from:n.posBefore,to:n.posAfter};let r=t.previousSibling,o=t.nextSibling;if(Zx&&Qx<=11&&t.addedNodes.length)for(let e=0;e<t.addedNodes.length;e++){let{previousSibling:n,nextSibling:i}=t.addedNodes[e];(!n||Array.prototype.indexOf.call(t.addedNodes,n)<0)&&(r=n),(!i||Array.prototype.indexOf.call(t.addedNodes,i)<0)&&(o=i)}let i=r&&r.parentNode==t.target?$x(r)+1:0,s=n.localPosFromDOM(t.target,i,-1),a=o&&o.parentNode==t.target?$x(o):t.target.childNodes.length;return{from:s,to:n.localPosFromDOM(t.target,a,1)}}return"attributes"==t.type?{from:n.posAtStart-n.border,to:n.posAtEnd+n.border}:(this.lastChangedTextNode=t.target,{from:n.posAtStart,to:n.posAtEnd,typeOver:t.target.nodeValue==t.oldValue})}},zv=new WeakMap,Fv=!1;function jv(t,e){let n=e.startContainer,r=e.startOffset,o=e.endContainer,i=e.endOffset,s=t.domAtPos(t.state.selection.anchor);return Fx(s.node,s.offset,o,i)&&([n,r,o,i]=[o,i,n,r]),{anchorNode:n,anchorOffset:r,focusNode:o,focusOffset:i}}function Wv(t,e){for(let n=e.parentNode;n&&n!=t.dom;n=n.parentNode){let e=t.docView.nearestDesc(n,!0);if(e&&e.node.isBlock)return n}return null}function Hv(t){let e=t.pmViewDesc;if(e)return e.parseRule();if("BR"==t.nodeName&&t.parentNode){if(ow&&/^(ul|ol)$/i.test(t.parentNode.nodeName)){let t=document.createElement("div");return t.appendChild(document.createElement("li")),{skip:t}}if(t.parentNode.lastChild==t||ow&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if("IMG"==t.nodeName&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null}var _v=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function Uv(t,e,n,r,o){let i=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let e=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,n=eb(t,e);if(n&&!t.state.selection.eq(n)){if(nw&&lw&&13===t.input.lastKeyCode&&Date.now()-100<t.input.lastKeyCodeTime&&t.someProp("handleKeyDown",e=>e(t,Vx(13,"Enter"))))return;let r=t.state.tr.setSelection(n);"pointer"==e?r.setMeta("pointer",!0):"key"==e&&r.scrollIntoView(),i&&r.setMeta("composition",i),t.dispatch(r)}return}let s=t.state.doc.resolve(e),a=s.sharedDepth(n);e=s.before(a+1),n=t.state.doc.resolve(n).after(a+1);let l,c,d=t.state.selection,u=function(t,e,n){let r,{node:o,fromOffset:i,toOffset:s,from:a,to:l}=t.docView.parseRange(e,n),c=t.domSelectionRange(),d=c.anchorNode;if(d&&t.dom.contains(1==d.nodeType?d:d.parentNode)&&(r=[{node:d,offset:c.anchorOffset}],Ux(c)||r.push({node:c.focusNode,offset:c.focusOffset})),nw&&8===t.input.lastKeyCode)for(let g=s;g>i;g--){let t=o.childNodes[g-1],e=t.pmViewDesc;if("BR"==t.nodeName&&!e){s=g;break}if(!e||e.size)break}let u=t.state.doc,p=t.someProp("domParser")||Eg.fromSchema(t.state.schema),h=u.resolve(a),f=null,m=p.parse(o,{topNode:h.parent,topMatch:h.parent.contentMatchAt(h.index()),topOpen:!0,from:i,to:s,preserveWhitespace:"pre"!=h.parent.type.whitespace||"full",findPositions:r,ruleFromNode:Hv,context:h});if(r&&null!=r[0].pos){let t=r[0].pos,e=r[1]&&r[1].pos;null==e&&(e=t),f={anchor:t+a,head:e+a}}return{doc:m,sel:f,from:a,to:l}}(t,e,n),p=t.state.doc,h=p.slice(u.from,u.to);8===t.input.lastKeyCode&&Date.now()-100<t.input.lastKeyCodeTime?(l=t.state.selection.to,c="end"):(l=t.state.selection.from,c="start"),t.input.lastKeyCode=null;let f=function(t,e,n,r,o){let i=t.findDiffStart(e,n),s=n+t.size,a=n+e.size;if(null==i)return null;let{a:l,b:c}=t.findDiffEnd(e,s,a);if("end"==o){r-=l+Math.max(0,i-Math.min(l,c))-i}if(l<i&&s<a){i-=r<=i&&r>=l?i-r:0,c=i+(c-l),l=i}else if(c<i){i-=r<=i&&r>=c?i-r:0,l=i+(l-c),c=i}return{start:i,endA:l,endB:c}}(h.content,u.doc.content,u.from,l,c);if(f&&t.input.domChangeCount++,(iw&&t.input.lastIOSEnter>Date.now()-225||lw)&&o.some(t=>1==t.nodeType&&!_v.test(t.nodeName))&&(!f||f.endA>=f.endB)&&t.someProp("handleKeyDown",e=>e(t,Vx(13,"Enter"))))return void(t.input.lastIOSEnter=0);if(!f){if(!(r&&d instanceof jy&&!d.empty&&d.$head.sameParent(d.$anchor))||t.composing||u.sel&&u.sel.anchor!=u.sel.head){if(u.sel){let e=Vv(t,t.state.doc,u.sel);if(e&&!e.eq(t.state.selection)){let n=t.state.tr.setSelection(e);i&&n.setMeta("composition",i),t.dispatch(n)}}return}f={start:d.from,endA:d.to,endB:d.to}}t.state.selection.from<t.state.selection.to&&f.start==f.endB&&t.state.selection instanceof jy&&(f.start>t.state.selection.from&&f.start<=t.state.selection.from+2&&t.state.selection.from>=u.from?f.start=t.state.selection.from:f.endA<t.state.selection.to&&f.endA>=t.state.selection.to-2&&t.state.selection.to<=u.to&&(f.endB+=t.state.selection.to-f.endA,f.endA=t.state.selection.to)),Zx&&Qx<=11&&f.endB==f.start+1&&f.endA==f.start&&f.start>u.from&&"  "==u.doc.textBetween(f.start-u.from-1,f.start-u.from+1)&&(f.start--,f.endA--,f.endB--);let m=u.doc.resolveNoCache(f.start-u.from),g=u.doc.resolveNoCache(f.endB-u.from),y=p.resolve(f.start),x=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=f.endA;if((iw&&t.input.lastIOSEnter>Date.now()-225&&(!x||o.some(t=>"DIV"==t.nodeName||"P"==t.nodeName))||!x&&m.pos<u.doc.content.size&&(!m.sameParent(g)||!m.parent.inlineContent)&&m.pos<g.pos&&!/\S/.test(u.doc.textBetween(m.pos,g.pos,"","")))&&t.someProp("handleKeyDown",e=>e(t,Vx(13,"Enter"))))return void(t.input.lastIOSEnter=0);if(t.state.selection.anchor>f.start&&function(t,e,n,r,o){if(n-e<=o.pos-r.pos||Kv(r,!0,!1)<o.pos)return!1;let i=t.resolve(e);if(!r.parent.isTextblock){let t=i.nodeAfter;return null!=t&&n==e+t.nodeSize}if(i.parentOffset<i.parent.content.size||!i.parent.isTextblock)return!1;let s=t.resolve(Kv(i,!0,!0));return!(!s.parent.isTextblock||s.pos>n||Kv(s,!0,!1)<n)&&r.parent.content.cut(r.parentOffset).eq(s.parent.content)}(p,f.start,f.endA,m,g)&&t.someProp("handleKeyDown",e=>e(t,Vx(8,"Backspace"))))return void(lw&&nw&&t.domObserver.suppressSelectionUpdates());nw&&f.endB==f.start&&(t.input.lastChromeDelete=Date.now()),lw&&!x&&m.start()!=g.start()&&0==g.parentOffset&&m.depth==g.depth&&u.sel&&u.sel.anchor==u.sel.head&&u.sel.head==f.endA&&(f.endB-=2,g=u.doc.resolveNoCache(f.endB-u.from),setTimeout(()=>{t.someProp("handleKeyDown",function(e){return e(t,Vx(13,"Enter"))})},20));let w,b=f.start,v=f.endA,k=e=>{let n=e||t.state.tr.replace(b,v,u.doc.slice(f.start-u.from,f.endB-u.from));if(u.sel){let e=Vv(t,n.doc,u.sel);e&&!(nw&&t.composing&&e.empty&&(f.start!=f.endB||t.input.lastChromeDelete<Date.now()-100)&&(e.head==b||e.head==n.mapping.map(v)-1)||Zx&&e.empty&&e.head==b)&&n.setSelection(e)}return i&&n.setMeta("composition",i),n.scrollIntoView()};if(x)if(m.pos==g.pos){Zx&&Qx<=11&&0==m.parentOffset&&(t.domObserver.suppressSelectionUpdates(),setTimeout(()=>rb(t),20));let e=k(t.state.tr.delete(b,v)),n=p.resolve(f.start).marksAcross(p.resolve(f.endA));n&&e.ensureMarks(n),t.dispatch(e)}else if(f.endA==f.endB&&(w=function(t,e){let n,r,o,i=t.firstChild.marks,s=e.firstChild.marks,a=i,l=s;for(let d=0;d<s.length;d++)a=s[d].removeFromSet(a);for(let d=0;d<i.length;d++)l=i[d].removeFromSet(l);if(1==a.length&&0==l.length)r=a[0],n="add",o=t=>t.mark(r.addToSet(t.marks));else{if(0!=a.length||1!=l.length)return null;r=l[0],n="remove",o=t=>t.mark(r.removeFromSet(t.marks))}let c=[];for(let d=0;d<e.childCount;d++)c.push(o(e.child(d)));if(Bm.from(c).eq(t))return{mark:r,type:n}}(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,f.endA-y.start())))){let e=k(t.state.tr);"add"==w.type?e.addMark(b,v,w.mark):e.removeMark(b,v,w.mark),t.dispatch(e)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let e=m.parent.textBetween(m.parentOffset,g.parentOffset),n=()=>k(t.state.tr.insertText(e,b,v));t.someProp("handleTextInput",r=>r(t,b,v,e,n))||t.dispatch(n())}else t.dispatch(k());else t.dispatch(k())}function Vv(t,e,n){return Math.max(n.anchor,n.head)>e.content.size?null:db(t,e.resolve(n.anchor),e.resolve(n.head))}function Kv(t,e,n){let r=t.depth,o=e?t.end():t.pos;for(;r>0&&(e||t.indexAfter(r)==t.node(r).childCount);)r--,o++,e=!1;if(n){let e=t.node(r).maybeChild(t.indexAfter(r));for(;e&&!e.isLeaf;)e=e.firstChild,o++}return o}var qv=class{constructor(t,e){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new jb,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=e,this.state=e.state,this.directPlugins=e.plugins||[],this.directPlugins.forEach(Zv),this.dispatch=this.dispatch.bind(this),this.dom=t&&t.mount||document.createElement("div"),t&&(t.appendChild?t.appendChild(this.dom):"function"==typeof t?t(this.dom):t.mount&&(this.mounted=!0)),this.editable=Jv(this),Yv(this),this.nodeViews=Gv(this),this.docView=Fw(this.state.doc,Xv(this),Rv(this),this.dom,this),this.domObserver=new Bv(this,(t,e,n,r)=>Uv(this,t,e,n,r)),this.domObserver.start(),function(t){for(let e in Bb){let n=Bb[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=e=>{!Ub(t,e)||_b(t,e)||!t.editable&&e.type in zb||n(t,e)},Fb[e]?{passive:!0}:void 0)}ow&&t.dom.addEventListener("input",()=>null),Hb(t)}(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let t=this._props;this._props={};for(let e in t)this._props[e]=t[e];this._props.state=this.state}return this._props}update(t){t.handleDOMEvents!=this._props.handleDOMEvents&&Hb(this);let e=this._props;this._props=t,t.plugins&&(t.plugins.forEach(Zv),this.directPlugins=t.plugins),this.updateStateInner(t.state,e)}setProps(t){let e={};for(let n in this._props)e[n]=this._props[n];e.state=this.state;for(let n in t)e[n]=t[n];this.update(e)}updateState(t){this.updateStateInner(t,this._props)}updateStateInner(t,e){var n;let r=this.state,o=!1,i=!1;t.storedMarks&&this.composing&&(sv(this),i=!0),this.state=t;let s=r.plugins!=t.plugins||this._props.plugins!=e.plugins;if(s||this._props.plugins!=e.plugins||this._props.nodeViews!=e.nodeViews){let t=Gv(this);(function(t,e){let n=0,r=0;for(let o in t){if(t[o]!=e[o])return!0;n++}for(let o in e)r++;return n!=r})(t,this.nodeViews)&&(this.nodeViews=t,o=!0)}(s||e.handleDOMEvents!=this._props.handleDOMEvents)&&Hb(this),this.editable=Jv(this),Yv(this);let a=Rv(this),l=Xv(this),c=r.plugins==t.plugins||r.doc.eq(t.doc)?t.scrollToSelection>r.scrollToSelection?"to selection":"preserve":"reset",d=o||!this.docView.matchesNode(t.doc,l,a);!d&&t.selection.eq(r.selection)||(i=!0);let u="preserve"==c&&i&&null==this.dom.style.overflowAnchor&&function(t){let e,n,r=t.dom.getBoundingClientRect(),o=Math.max(0,r.top);for(let i=(r.left+r.right)/2,s=o+1;s<Math.min(innerHeight,r.bottom);s+=5){let r=t.root.elementFromPoint(i,s);if(!r||r==t.dom||!t.dom.contains(r))continue;let a=r.getBoundingClientRect();if(a.top>=o-20){e=r,n=a.top;break}}return{refDOM:e,refTop:n,stack:mw(t.dom)}}(this);if(i){this.domObserver.stop();let e=d&&(Zx||nw)&&!this.composing&&!r.selection.empty&&!t.selection.empty&&function(t,e){let n=Math.min(t.$anchor.sharedDepth(t.head),e.$anchor.sharedDepth(e.head));return t.$anchor.start(n)!=e.$anchor.start(n)}(r.selection,t.selection);if(d){let n=nw?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=av(this)),!o&&this.docView.update(t.doc,l,a,this)||(this.docView.updateOuterDeco(l),this.docView.destroy(),this.docView=Fw(t.doc,l,a,this.dom,this)),!n||this.trackWrites&&this.dom.contains(this.trackWrites)||(e=!0)}let n=this.input.mouseDown;e||!(n&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&function(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Fx(e.node,e.offset,n.anchorNode,n.anchorOffset)}(this)&&n.delaySelUpdate())?rb(this,e):(lb(this,t.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(r),(null===(n=this.dragging)||void 0===n?void 0:n.node)&&!r.doc.eq(t.doc)&&this.updateDraggedNode(this.dragging,r),"reset"==c?this.dom.scrollTop=0:"to selection"==c?this.scrollToSelection():u&&function({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;gw(n,0==r?0:r-e)}(u)}scrollToSelection(){let t=this.domSelectionRange().focusNode;if(t&&this.dom.contains(1==t.nodeType?t:t.parentNode))if(this.someProp("handleScrollToSelection",t=>t(this)));else if(this.state.selection instanceof Hy){let e=this.docView.domAfterPos(this.state.selection.from);1==e.nodeType&&fw(this,e.getBoundingClientRect(),t)}else fw(this,this.coordsAtPos(this.state.selection.head,1),t);else;}destroyPluginViews(){let t;for(;t=this.pluginViews.pop();)t.destroy&&t.destroy()}updatePluginViews(t){if(t&&t.plugins==this.state.plugins&&this.directPlugins==this.prevDirectPlugins)for(let e=0;e<this.pluginViews.length;e++){let n=this.pluginViews[e];n.update&&n.update(this,t)}else{this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t<this.directPlugins.length;t++){let e=this.directPlugins[t];e.spec.view&&this.pluginViews.push(e.spec.view(this))}for(let t=0;t<this.state.plugins.length;t++){let e=this.state.plugins[t];e.spec.view&&this.pluginViews.push(e.spec.view(this))}}}updateDraggedNode(t,e){let n=t.node,r=-1;if(n.from<this.state.doc.content.size&&this.state.doc.nodeAt(n.from)==n.node)r=n.from;else{let t=n.from+(this.state.doc.content.size-e.doc.content.size);(t>0&&t<this.state.doc.content.size&&this.state.doc.nodeAt(t))==n.node&&(r=t)}this.dragging=new pv(t.slice,t.move,r<0?void 0:Hy.create(this.state.doc,r))}someProp(t,e){let n,r=this._props&&this._props[t];if(null!=r&&(n=e?e(r):r))return n;for(let i=0;i<this.directPlugins.length;i++){let r=this.directPlugins[i].props[t];if(null!=r&&(n=e?e(r):r))return n}let o=this.state.plugins;if(o)for(let i=0;i<o.length;i++){let r=o[i].props[t];if(null!=r&&(n=e?e(r):r))return n}}hasFocus(){if(Zx){let t=this.root.activeElement;if(t==this.dom)return!0;if(!t||!this.dom.contains(t))return!1;for(;t&&this.dom!=t&&this.dom.contains(t);){if("false"==t.contentEditable)return!1;t=t.parentElement}return!0}return this.root.activeElement==this.dom}focus(){this.domObserver.stop(),this.editable&&function(t){if(t.setActive)return t.setActive();if(yw)return t.focus(yw);let e=mw(t);t.focus(null==yw?{get preventScroll(){return yw={preventScroll:!0},!0}}:void 0),yw||(yw=!1,gw(e,0))}(this.dom),rb(this),this.domObserver.start()}get root(){let t=this._root;if(null==t)for(let e=this.dom.parentNode;e;e=e.parentNode)if(9==e.nodeType||11==e.nodeType&&e.host)return e.getSelection||(Object.getPrototypeOf(e).getSelection=()=>e.ownerDocument.getSelection()),this._root=e;return t||document}updateRoot(){this._root=null}posAtCoords(t){return vw(this,t)}coordsAtPos(t,e=1){return Mw(this,t,e)}domAtPos(t,e=0){return this.docView.domFromPos(t,e)}nodeDOM(t){let e=this.docView.descAt(t);return e?e.nodeDOM:null}posAtDOM(t,e,n=-1){let r=this.docView.posFromDOM(t,e,n);if(null==r)throw new RangeError("DOM position not inside the editor");return r}endOfTextblock(t,e){return Rw(this,e||this.state,t)}pasteHTML(t,e){return dv(this,"",t,!1,e||new ClipboardEvent("paste"))}pasteText(t,e){return dv(this,t,null,!0,e||new ClipboardEvent("paste"))}serializeForClipboard(t){return Ib(this,t)}destroy(){this.docView&&(!function(t){t.input.mouseDown&&t.input.mouseDown.done(),t.domObserver.stop();for(let e in t.input.eventHandlers)t.dom.removeEventListener(e,t.input.eventHandlers[e]);clearTimeout(t.input.composingTimeout),clearTimeout(t.input.lastIOSEnterFallbackTimeout)}(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],Rv(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Bx=null)}get isDestroyed(){return null==this.docView}dispatchEvent(t){return function(t,e){_b(t,e)||!Bb[e.type]||!t.editable&&e.type in zb||Bb[e.type](t,e)}(this,t)}domSelectionRange(){let t=this.domSelection();return t?ow&&11===this.root.nodeType&&function(t){let e=t.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}(this.dom.ownerDocument)==this.dom&&function(t,e){if(e.getComposedRanges){let n=e.getComposedRanges(t.root)[0];if(n)return jv(t,n)}let n;function r(t){t.preventDefault(),t.stopImmediatePropagation(),n=t.getTargetRanges()[0]}return t.dom.addEventListener("beforeinput",r,!0),document.execCommand("indent"),t.dom.removeEventListener("beforeinput",r,!0),n?jv(t,n):null}(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}};function Xv(t){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",n=>{if("function"==typeof n&&(n=n(t.state)),n)for(let t in n)"class"==t?e.class+=" "+n[t]:"style"==t?e.style=(e.style?e.style+";":"")+n[t]:e[t]||"contenteditable"==t||"nodeName"==t||(e[t]=String(n[t]))}),e.translate||(e.translate="no"),[wv.node(0,t.state.doc.content.size,e)]}function Yv(t){if(t.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),t.cursorWrapper={dom:e,deco:wv.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function Jv(t){return!t.someProp("editable",e=>!1===e(t.state))}function Gv(t){let e=Object.create(null);function n(t){for(let n in t)Object.prototype.hasOwnProperty.call(e,n)||(e[n]=t[n])}return t.someProp("nodeViews",n),t.someProp("markViews",n),e}function Zv(t){if(t.spec.state||t.spec.filterTransaction||t.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}qv.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};for(var Qv={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},tk={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},ek="undefined"!=typeof navigator&&/Mac/.test(navigator.platform),nk="undefined"!=typeof navigator&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),rk=0;rk<10;rk++)Qv[48+rk]=Qv[96+rk]=String(rk);for(rk=1;rk<=24;rk++)Qv[rk+111]="F"+rk;for(rk=65;rk<=90;rk++)Qv[rk]=String.fromCharCode(rk+32),tk[rk]=String.fromCharCode(rk);for(var ok in Qv)tk.hasOwnProperty(ok)||(tk[ok]=Qv[ok]);var ik="undefined"!=typeof navigator&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),sk="undefined"!=typeof navigator&&/Win/.test(navigator.platform);function ak(t){let e,n,r,o,i=t.split(/-(?!$)/),s=i[i.length-1];"Space"==s&&(s=" ");for(let a=0;a<i.length-1;a++){let t=i[a];if(/^(cmd|meta|m)$/i.test(t))o=!0;else if(/^a(lt)?$/i.test(t))e=!0;else if(/^(c|ctrl|control)$/i.test(t))n=!0;else if(/^s(hift)?$/i.test(t))r=!0;else{if(!/^mod$/i.test(t))throw new Error("Unrecognized modifier name: "+t);ik?o=!0:n=!0}}return e&&(s="Alt-"+s),n&&(s="Ctrl-"+s),o&&(s="Meta-"+s),r&&(s="Shift-"+s),s}function lk(t,e,n=!0){return e.altKey&&(t="Alt-"+t),e.ctrlKey&&(t="Ctrl-"+t),e.metaKey&&(t="Meta-"+t),n&&e.shiftKey&&(t="Shift-"+t),t}function ck(t){let e=function(t){let e=Object.create(null);for(let n in t)e[ak(n)]=t[n];return e}(t);return function(t,n){let r,o=function(t){var e=!(ek&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||nk&&t.shiftKey&&t.key&&1==t.key.length||"Unidentified"==t.key)&&t.key||(t.shiftKey?tk:Qv)[t.keyCode]||t.key||"Unidentified";return"Esc"==e&&(e="Escape"),"Del"==e&&(e="Delete"),"Left"==e&&(e="ArrowLeft"),"Up"==e&&(e="ArrowUp"),"Right"==e&&(e="ArrowRight"),"Down"==e&&(e="ArrowDown"),e}(n),i=e[lk(o,n)];if(i&&i(t.state,t.dispatch,t))return!0;if(1==o.length&&" "!=o){if(n.shiftKey){let r=e[lk(o,n,!1)];if(r&&r(t.state,t.dispatch,t))return!0}if((n.altKey||n.metaKey||n.ctrlKey)&&!(sk&&n.ctrlKey&&n.altKey)&&(r=Qv[n.keyCode])&&r!=o){let o=e[lk(r,n)];if(o&&o(t.state,t.dispatch,t))return!0}}return!1}}var dk=Om(),uk=Object.defineProperty,pk=(t,e)=>{for(var n in e)uk(t,n,{get:e[n],enumerable:!0})};function hk(t){const{state:e,transaction:n}=t;let{selection:r}=n,{doc:o}=n,{storedMarks:i}=n;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return i},get selection(){return r},get doc(){return o},get tr(){return r=n.selection,o=n.doc,i=n.storedMarks,n}}}var fk=class{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:e,state:n}=this,{view:r}=e,{tr:o}=n,i=this.buildProps(o);return Object.fromEntries(Object.entries(t).map(([t,e])=>[t,(...t)=>{const n=e(...t)(i);return o.getMeta("preventDispatch")||this.hasCustomState||r.dispatch(o),n}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,e=!0){const{rawCommands:n,editor:r,state:o}=this,{view:i}=r,s=[],a=!!t,l=t||o.tr,c={...Object.fromEntries(Object.entries(n).map(([t,n])=>[t,(...t)=>{const r=this.buildProps(l,e),o=n(...t)(r);return s.push(o),c}])),run:()=>(a||!e||l.getMeta("preventDispatch")||this.hasCustomState||i.dispatch(l),s.every(t=>!0===t))};return c}createCan(t){const{rawCommands:e,state:n}=this,r=!1,o=t||n.tr,i=this.buildProps(o,r);return{...Object.fromEntries(Object.entries(e).map(([t,e])=>[t,(...t)=>e(...t)({...i,dispatch:void 0})])),chain:()=>this.createChain(o,r)}}buildProps(t,e=!0){const{rawCommands:n,editor:r,state:o}=this,{view:i}=r,s={tr:t,editor:r,view:i,state:hk({state:o,transaction:t}),dispatch:e?()=>{}:void 0,chain:()=>this.createChain(t,e),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(n).map(([t,e])=>[t,(...t)=>e(...t)(s)]))}};return s}},mk={};pk(mk,{blur:()=>gk,clearContent:()=>yk,clearNodes:()=>xk,command:()=>wk,createParagraphNear:()=>bk,cut:()=>vk,deleteCurrentNode:()=>kk,deleteNode:()=>Pk,deleteRange:()=>Mk,deleteSelection:()=>Tk,enter:()=>Ck,exitCode:()=>Ek,extendMarkRange:()=>Dk,first:()=>Bk,focus:()=>_k,forEach:()=>Uk,insertContent:()=>Vk,insertContentAt:()=>Yk,joinBackward:()=>Zk,joinDown:()=>Gk,joinForward:()=>Qk,joinItemBackward:()=>tS,joinItemForward:()=>eS,joinTextblockBackward:()=>nS,joinTextblockForward:()=>rS,joinUp:()=>Jk,keyboardShortcut:()=>iS,lift:()=>aS,liftEmptyBlock:()=>lS,liftListItem:()=>cS,newlineInCode:()=>dS,resetAttributes:()=>hS,scrollIntoView:()=>fS,selectAll:()=>mS,selectNodeBackward:()=>gS,selectNodeForward:()=>yS,selectParentNode:()=>xS,selectTextblockEnd:()=>wS,selectTextblockStart:()=>bS,setContent:()=>kS,setMark:()=>rP,setMeta:()=>oP,setNode:()=>iP,setNodeSelection:()=>sP,setTextDirection:()=>aP,setTextSelection:()=>lP,sinkListItem:()=>cP,splitBlock:()=>uP,splitListItem:()=>pP,toggleList:()=>yP,toggleMark:()=>xP,toggleNode:()=>wP,toggleWrap:()=>bP,undoInputRule:()=>vP,unsetAllMarks:()=>kP,unsetMark:()=>SP,unsetTextDirection:()=>PP,updateAttributes:()=>MP,wrapIn:()=>IP,wrapInList:()=>TP});var gk=()=>({editor:t,view:e})=>(requestAnimationFrame(()=>{var n;t.isDestroyed||(e.dom.blur(),null==(n=null==window?void 0:window.getSelection())||n.removeAllRanges())}),!0),yk=(t=!0)=>({commands:e})=>e.setContent("",{emitUpdate:t}),xk=()=>({state:t,tr:e,dispatch:n})=>{const{selection:r}=e,{ranges:o}=r;return!n||(o.forEach(({$from:n,$to:r})=>{t.doc.nodesBetween(n.pos,r.pos,(t,n)=>{if(t.type.isText)return;const{doc:r,mapping:o}=e,i=r.resolve(o.map(n)),s=r.resolve(o.map(n+t.nodeSize)),a=i.blockRange(s);if(!a)return;const l=dy(a);if(t.type.isTextblock){const{defaultType:t}=i.parent.contentMatchAt(i.index());e.setNodeMarkup(a.start,t)}(l||0===l)&&e.lift(a,l)})}),!0)},wk=t=>e=>t(e),bk=()=>({state:t,dispatch:e})=>wx(t,e),vk=(t,e)=>({editor:n,tr:r})=>{const{state:o}=n,i=o.doc.slice(t.from,t.to);r.deleteRange(t.from,t.to);const s=r.mapping.map(e);return r.insert(s,i.content),r.setSelection(new jy(r.doc.resolve(Math.max(s-1,0)))),!0},kk=()=>({tr:t,dispatch:e})=>{const{selection:n}=t,r=n.$anchor.node();if(r.content.size>0)return!1;const o=t.selection.$anchor;for(let i=o.depth;i>0;i-=1)if(o.node(i).type===r.type){if(e){const e=o.before(i),n=o.after(i);t.delete(e,n).scrollIntoView()}return!0}return!1};function Sk(t,e){if("string"==typeof t){if(!e.nodes[t])throw Error(`There is no node type named '${t}'. Maybe you forgot to add the extension?`);return e.nodes[t]}return t}var Pk=t=>({tr:e,state:n,dispatch:r})=>{const o=Sk(t,n.schema),i=e.selection.$anchor;for(let t=i.depth;t>0;t-=1)if(i.node(t).type===o){if(r){const n=i.before(t),r=i.after(t);e.delete(n,r).scrollIntoView()}return!0}return!1},Mk=t=>({tr:e,dispatch:n})=>{const{from:r,to:o}=t;return n&&e.delete(r,o),!0},Ik=(t,e,n)=>{if(!t.parent.isInline)return t.pos;if("left"===n&&t.pos>t.start()||"right"===n&&t.pos<t.end())return t.pos;const r=e.nodes[t.parent.type.name].spec;return(o=r).content&&/^text(\*|\+)/.test(o.content)?"left"===n?t.start()-1:t.end()+1:t.pos;var o},Tk=()=>({state:t,dispatch:e})=>{if(t.selection.empty)return!1;if(e){const n=t.tr,{ranges:r}=t.selection,o=n.steps.length;r.forEach(e=>{const r=n.mapping.slice(o),{from:i,to:s}=(a=n.doc.resolve(r.map(e.$from.pos)),l=n.doc.resolve(r.map(e.$to.pos)),c=t.schema,{from:Ik(a,c,"left"),to:Ik(l,c,"right")});var a,l,c;n.deleteRange(i,s)}),n.scrollIntoView(),e(n)}return!0},Ck=()=>({commands:t})=>t.keyboardShortcut("Enter"),Ek=()=>({state:t,dispatch:e})=>xx(t,e);function Ak(t){return"[object RegExp]"===Object.prototype.toString.call(t)}function Ok(t,e,n={strict:!0}){const r=Object.keys(e);return!r.length||r.every(r=>n.strict?e[r]===t[r]:Ak(e[r])?e[r].test(t[r]):e[r]===t[r])}function Nk(t,e,n={}){return t.find(t=>t.type===e&&Ok(Object.fromEntries(Object.keys(n).map(e=>[e,t.attrs[e]])),n))}function Rk(t,e,n={}){return!!Nk(t,e,n)}function Lk(t,e,n){if(!t||!e)return;let r=t.parent.childAfter(t.parentOffset);if(r.node&&r.node.marks.some(t=>t.type===e)||(r=t.parent.childBefore(t.parentOffset)),!r.node||!r.node.marks.some(t=>t.type===e))return;if(!n){const t=r.node.marks.find(t=>t.type===e);t&&(n=t.attrs)}if(!Nk([...r.node.marks],e,n))return;let o=r.index,i=t.start()+r.offset,s=o+1,a=i+r.node.nodeSize;for(;o>0&&Rk([...t.parent.child(o-1).marks],e,n);)o-=1,i-=t.parent.child(o).nodeSize;for(;s<t.parent.childCount&&Rk([...t.parent.child(s).marks],e,n);)a+=t.parent.child(s).nodeSize,s+=1;return{from:i,to:a}}function $k(t,e){if("string"==typeof t){if(!e.marks[t])throw Error(`There is no mark type named '${t}'. Maybe you forgot to add the extension?`);return e.marks[t]}return t}var Dk=(t,e)=>({tr:n,state:r,dispatch:o})=>{const i=$k(t,r.schema),{doc:s,selection:a}=n,{$from:l,from:c,to:d}=a;if(o){const t=Lk(l,i,e);if(t&&t.from<=c&&t.to>=d){const e=jy.create(s,t.from,t.to);n.setSelection(e)}}return!0},Bk=t=>e=>{const n="function"==typeof t?t(e):t;for(let t=0;t<n.length;t+=1)if(n[t](e))return!0;return!1};function zk(t){return t instanceof jy}function Fk(t=0,e=0,n=0){return Math.min(Math.max(t,e),n)}function jk(t,e=null){if(!e)return null;const n=Dy.atStart(t),r=Dy.atEnd(t);if("start"===e||!0===e)return n;if("end"===e)return r;const o=n.from,i=r.to;return"all"===e?jy.create(t,Fk(0,o,i),Fk(t.content.size,o,i)):jy.create(t,Fk(e,o,i),Fk(e,o,i))}function Wk(){return"Android"===navigator.platform||/android/i.test(navigator.userAgent)}function Hk(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}var _k=(t=null,e={})=>({editor:n,view:r,tr:o,dispatch:i})=>{e={scrollIntoView:!0,...e};const s=()=>{(Hk()||Wk())&&r.dom.focus(),"undefined"==typeof navigator||!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||Hk()||Wk()||r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),(null==e?void 0:e.scrollIntoView)&&n.commands.scrollIntoView())})};try{if(r.hasFocus()&&null===t||!1===t)return!0}catch{return!1}if(i&&null===t&&!zk(n.state.selection))return s(),!0;const a=jk(o.doc,t)||n.state.selection,l=n.state.selection.eq(a);return i&&(l||o.setSelection(a),l&&o.storedMarks&&o.setStoredMarks(o.storedMarks),s()),!0},Uk=(t,e)=>n=>t.every((t,r)=>e(t,{...n,index:r})),Vk=(t,e)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},t,e),Kk=t=>{const e=t.childNodes;for(let n=e.length-1;n>=0;n-=1){const r=e[n];3===r.nodeType&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?t.removeChild(r):1===r.nodeType&&Kk(r)}return t};function qk(t){if("undefined"==typeof window)throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`<body>${t}</body>`,n=(new window.DOMParser).parseFromString(e,"text/html").body;return Kk(n)}function Xk(t,e,n){if(t instanceof ag||t instanceof Bm)return t;n={slice:!0,parseOptions:{},...n};const r="string"==typeof t;if("object"==typeof t&&null!==t)try{if(Array.isArray(t)&&t.length>0)return Bm.fromArray(t.map(t=>e.nodeFromJSON(t)));const r=e.nodeFromJSON(t);return n.errorOnInvalidContent&&r.check(),r}catch(o){if(n.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:o});return console.warn("[tiptap warn]: Invalid content.","Passed value:",t,"Error:",o),Xk("",e,n)}if(r){if(n.errorOnInvalidContent){let r=!1,o="";const i=new Tg({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:t=>(r=!0,o="string"==typeof t?t:t.outerHTML,null)}]}})});if(n.slice?Eg.fromSchema(i).parseSlice(qk(t),n.parseOptions):Eg.fromSchema(i).parse(qk(t),n.parseOptions),n.errorOnInvalidContent&&r)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const r=Eg.fromSchema(e);return n.slice?r.parseSlice(qk(t),n.parseOptions).content:r.parse(qk(t),n.parseOptions)}return Xk("",e,n)}var Yk=(t,e,n)=>({tr:r,dispatch:o,editor:i})=>{var s,a;if(o){let o;const c=t=>{i.emit("contentError",{editor:i,error:t,disableCollaboration:()=>{"collaboration"in i.storage&&"object"==typeof i.storage.collaboration&&i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...(n={parseOptions:i.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n}).parseOptions};if(!n.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{Xk(e,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(l){c(l)}try{o=Xk(e,i.schema,{parseOptions:d,errorOnInvalidContent:null!=(s=n.errorOnInvalidContent)?s:i.options.enableContentCheck})}catch(l){return c(l),!1}let u,{from:p,to:h}="number"==typeof t?{from:t,to:t}:{from:t.from,to:t.to},f=!0,m=!0;if((a=o,"type"in a?[o]:o).forEach(t=>{t.check(),f=!!f&&(t.isText&&0===t.marks.length),m=!!m&&t.isBlock}),p===h&&m){const{parent:t}=r.doc.resolve(p);!t.isTextblock||t.type.spec.code||t.childCount||(p-=1,h+=1)}if(f){if(Array.isArray(e))u=e.map(t=>t.text||"").join("");else if(e instanceof Bm){let t="";e.forEach(e=>{e.text&&(t+=e.text)}),u=t}else u="object"==typeof e&&e&&e.text?e.text:e;r.insertText(u,p,h)}else{u=o;const t=r.doc.resolve(p),e=t.node(),n=0===t.parentOffset,i=e.isText||e.isTextblock,s=e.content.size>0;n&&i&&s&&m&&(p=Math.max(0,p-1)),r.replaceWith(p,h,u)}n.updateSelection&&function(t,e,n){const r=t.steps.length-1;if(r<e)return;const o=t.steps[r];if(!(o instanceof iy||o instanceof sy))return;const i=t.mapping.maps[r];let s=0;i.forEach((t,e,n,r)=>{0===s&&(s=r)}),t.setSelection(Dy.near(t.doc.resolve(s),n))}(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:p,text:u}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:p,text:u})}return!0},Jk=()=>({state:t,dispatch:e})=>((t,e)=>{let n,r=t.selection,o=r instanceof Hy;if(o){if(r.node.isTextblock||!gy(t.doc,r.from))return!1;n=r.from}else if(n=xy(t.doc,r.from,-1),null==n)return!1;if(e){let r=t.tr.join(n);o&&r.setSelection(Hy.create(r.doc,n-t.doc.resolve(n).nodeBefore.nodeSize)),e(r.scrollIntoView())}return!0})(t,e),Gk=()=>({state:t,dispatch:e})=>((t,e)=>{let n,r=t.selection;if(r instanceof Hy){if(r.node.isTextblock||!gy(t.doc,r.to))return!1;n=r.to}else if(n=xy(t.doc,r.to,1),null==n)return!1;return e&&e(t.tr.join(n).scrollIntoView()),!0})(t,e),Zk=()=>({state:t,dispatch:e})=>ax(t,e),Qk=()=>({state:t,dispatch:e})=>hx(t,e),tS=()=>({state:t,dispatch:e,tr:n})=>{try{const r=xy(t.doc,t.selection.$from.pos,-1);return null!=r&&(n.join(r,2),e&&e(n),!0)}catch{return!1}},eS=()=>({state:t,dispatch:e,tr:n})=>{try{const r=xy(t.doc,t.selection.$from.pos,1);return null!=r&&(n.join(r,2),e&&e(n),!0)}catch{return!1}},nS=()=>({state:t,dispatch:e})=>((t,e,n)=>{let r=sx(t,n);if(!r)return!1;let o=ux(r);return!!o&&lx(t,o,e)})(t,e),rS=()=>({state:t,dispatch:e})=>((t,e,n)=>{let r=px(t,n);if(!r)return!1;let o=mx(r);return!!o&&lx(t,o,e)})(t,e);function oS(){return"undefined"!=typeof navigator&&/Mac/.test(navigator.platform)}var iS=t=>({editor:e,view:n,tr:r,dispatch:o})=>{const i=function(t){const e=t.split(/-(?!$)/);let n,r,o,i,s=e[e.length-1];"Space"===s&&(s=" ");for(let a=0;a<e.length-1;a+=1){const t=e[a];if(/^(cmd|meta|m)$/i.test(t))i=!0;else if(/^a(lt)?$/i.test(t))n=!0;else if(/^(c|ctrl|control)$/i.test(t))r=!0;else if(/^s(hift)?$/i.test(t))o=!0;else{if(!/^mod$/i.test(t))throw new Error(`Unrecognized modifier name: ${t}`);Hk()||oS()?i=!0:r=!0}}return n&&(s=`Alt-${s}`),r&&(s=`Ctrl-${s}`),i&&(s=`Meta-${s}`),o&&(s=`Shift-${s}`),s}(t).split(/-(?!$)/),s=i.find(t=>!["Alt","Ctrl","Meta","Shift"].includes(t)),a=new KeyboardEvent("keydown",{key:"Space"===s?" ":s,altKey:i.includes("Alt"),ctrlKey:i.includes("Ctrl"),metaKey:i.includes("Meta"),shiftKey:i.includes("Shift"),bubbles:!0,cancelable:!0});return e.captureTransaction(()=>{n.someProp("handleKeyDown",t=>t(n,a))})?.steps.forEach(t=>{const e=t.map(r.mapping);e&&o&&r.maybeStep(e)}),!0};function sS(t,e,n={}){const{from:r,to:o,empty:i}=t.selection,s=e?Sk(e,t.schema):null,a=[];t.doc.nodesBetween(r,o,(t,e)=>{if(t.isText)return;const n=Math.max(r,e),i=Math.min(o,e+t.nodeSize);a.push({node:t,from:n,to:i})});const l=o-r,c=a.filter(t=>!s||s.name===t.node.type.name).filter(t=>Ok(t.node.attrs,n,{strict:!1}));return i?!!c.length:c.reduce((t,e)=>t+e.to-e.from,0)>=l}var aS=(t,e={})=>({state:n,dispatch:r})=>!!sS(n,Sk(t,n.schema),e)&&((t,e)=>{let{$from:n,$to:r}=t.selection,o=n.blockRange(r),i=o&&dy(o);return null!=i&&(e&&e(t.tr.lift(o,i).scrollIntoView()),!0)})(n,r),lS=()=>({state:t,dispatch:e})=>bx(t,e),cS=t=>({state:e,dispatch:n})=>Lx(Sk(t,e.schema))(e,n),dS=()=>({state:t,dispatch:e})=>gx(t,e);function uS(t,e){return e.nodes[t]?"node":e.marks[t]?"mark":null}function pS(t,e){const n="string"==typeof e?[e]:e;return Object.keys(t).reduce((e,r)=>(n.includes(r)||(e[r]=t[r]),e),{})}var hS=(t,e)=>({tr:n,state:r,dispatch:o})=>{let i=null,s=null;const a=uS("string"==typeof t?t:t.name,r.schema);if(!a)return!1;"node"===a&&(i=Sk(t,r.schema)),"mark"===a&&(s=$k(t,r.schema));let l=!1;return n.selection.ranges.forEach(t=>{r.doc.nodesBetween(t.$from.pos,t.$to.pos,(t,r)=>{i&&i===t.type&&(l=!0,o&&n.setNodeMarkup(r,void 0,pS(t.attrs,e))),s&&t.marks.length&&t.marks.forEach(i=>{s===i.type&&(l=!0,o&&n.addMark(r,r+t.nodeSize,s.create(pS(i.attrs,e))))})})}),l},fS=()=>({tr:t,dispatch:e})=>(e&&t.scrollIntoView(),!0),mS=()=>({tr:t,dispatch:e})=>{if(e){const e=new Uy(t.doc);t.setSelection(e)}return!0},gS=()=>({state:t,dispatch:e})=>dx(t,e),yS=()=>({state:t,dispatch:e})=>fx(t,e),xS=()=>({state:t,dispatch:e})=>((t,e)=>{let n,{$from:r,to:o}=t.selection,i=r.sharedDepth(o);return 0!=i&&(n=r.before(i),e&&e(t.tr.setSelection(Hy.create(t.doc,n))),!0)})(t,e),wS=()=>({state:t,dispatch:e})=>Ix(t,e),bS=()=>({state:t,dispatch:e})=>Mx(t,e);function vS(t,e,n={},r={}){return Xk(t,e,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}var kS=(t,{errorOnInvalidContent:e,emitUpdate:n=!0,parseOptions:r={}}={})=>({editor:o,tr:i,dispatch:s,commands:a})=>{const{doc:l}=i;if("full"!==r.preserveWhitespace){const a=vS(t,o.schema,r,{errorOnInvalidContent:null!=e?e:o.options.enableContentCheck});return s&&i.replaceWith(0,l.content.size,a).setMeta("preventUpdate",!n),!0}return s&&i.setMeta("preventUpdate",!n),a.insertContentAt({from:0,to:l.content.size},t,{parseOptions:r,errorOnInvalidContent:null!=e?e:o.options.enableContentCheck})};function SS(t,e){const n=$k(e,t.schema),{from:r,to:o,empty:i}=t.selection,s=[];i?(t.storedMarks&&s.push(...t.storedMarks),s.push(...t.selection.$head.marks())):t.doc.nodesBetween(r,o,t=>{s.push(...t.marks)});const a=s.find(t=>t.type.name===n.name);return a?{...a.attrs}:{}}function PS(t,e){const n=new Ly(t);return e.forEach(t=>{t.steps.forEach(t=>{n.step(t)})}),n}function MS(t){return e=>function(t,e){for(let n=t.depth;n>0;n-=1){const r=t.node(n);if(e(r))return{pos:n>0?t.before(n):0,start:t.start(n),depth:n,node:r}}}(e.$from,t)}function IS(t,e,n){return void 0===t.config[e]&&t.parent?IS(t.parent,e,n):"function"==typeof t.config[e]?t.config[e].bind({...n,parent:t.parent?IS(t.parent,e,n):null}):t.config[e]}function TS(t){return t.map(t=>{const e=IS(t,"addExtensions",{name:t.name,options:t.options,storage:t.storage});return e?[t,...TS(e())]:t}).flat(10)}function CS(t,e){const n=Fg.fromSchema(e).serializeFragment(t),r=document.implementation.createHTMLDocument().createElement("div");return r.appendChild(n),r.innerHTML}function ES(t){return"function"==typeof t}function AS(t,e=void 0,...n){return ES(t)?e?t.bind(e)(...n):t(...n):t}function OS(t){return{baseExtensions:t.filter(t=>"extension"===t.type),nodeExtensions:t.filter(t=>"node"===t.type),markExtensions:t.filter(t=>"mark"===t.type)}}function NS(t){const e=[],{nodeExtensions:n,markExtensions:r}=OS(t),o=[...n,...r],i={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},s=n.filter(t=>"text"!==t.name).map(t=>t.name),a=r.map(t=>t.name),l=[...s,...a];return t.forEach(t=>{const n=IS(t,"addGlobalAttributes",{name:t.name,options:t.options,storage:t.storage,extensions:o});n&&n().forEach(t=>{let n;n=Array.isArray(t.types)?t.types:"*"===t.types?l:"nodes"===t.types?s:"marks"===t.types?a:[],n.forEach(n=>{Object.entries(t.attributes).forEach(([t,r])=>{e.push({type:n,name:t,attribute:{...i,...r}})})})})}),o.forEach(t=>{const n=IS(t,"addAttributes",{name:t.name,options:t.options,storage:t.storage});if(!n)return;const r=n();Object.entries(r).forEach(([n,r])=>{const o={...i,...r};"function"==typeof(null==o?void 0:o.default)&&(o.default=o.default()),(null==o?void 0:o.isRequired)&&void 0===(null==o?void 0:o.default)&&delete o.default,e.push({type:t.name,name:n,attribute:o})})}),e}function RS(t){const e=[],n=function(t){const e=[];let n="",r=!1,o=!1,i=0;const s=t.length;for(let a=0;a<s;a+=1){const s=t[a];if("'"!==s||o)if('"'!==s||r){if(!r&&!o){if("("===s){i+=1,n+=s;continue}if(")"===s&&i>0){i-=1,n+=s;continue}if(";"===s&&0===i){e.push(n),n="";continue}}n+=s}else o=!o,n+=s;else r=!r,n+=s}return n&&e.push(n),e}(t||""),r=n.length;for(let o=0;o<r;o+=1){const t=n[o],r=t.indexOf(":");if(-1===r)continue;const i=t.slice(0,r).trim(),s=t.slice(r+1).trim();i&&s&&e.push([i,s])}return e}function LS(...t){return t.filter(t=>!!t).reduce((t,e)=>{const n={...t};return Object.entries(e).forEach(([t,e])=>{if(n[t])if("class"===t){const r=e?String(e).split(" "):[],o=n[t]?n[t].split(" "):[],i=r.filter(t=>!o.includes(t));n[t]=[...o,...i].join(" ")}else if("style"===t){const r=new Map([...RS(n[t]),...RS(e)]);n[t]=Array.from(r.entries()).map(([t,e])=>`${t}: ${e}`).join("; ")}else n[t]=e;else n[t]=e}),n},{})}function $S(t,e){return e.filter(e=>e.type===t.type.name).filter(t=>t.attribute.rendered).map(e=>e.attribute.renderHTML?e.attribute.renderHTML(t.attrs)||{}:{[e.name]:t.attrs[e.name]}).reduce((t,e)=>LS(t,e),{})}function DS(t,e){return"style"in t?t:{...t,getAttrs:n=>{const r=t.getAttrs?t.getAttrs(n):t.attrs;if(!1===r)return!1;const o=e.reduce((t,e)=>{const r=e.attribute.parseHTML?e.attribute.parseHTML(n):function(t){return"string"!=typeof t?t:t.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(t):"true"===t||"false"!==t&&t}(n.getAttribute(e.name));return null==r?t:{...t,[e.name]:r}},{});return{...r,...o}}}}function BS(t){return Object.fromEntries(Object.entries(t).filter(([t,e])=>("attrs"!==t||!function(t={}){return 0===Object.keys(t).length&&t.constructor===Object}(e))&&null!=e))}function zS(t){var e,n;const r={};return!(null==(e=null==t?void 0:t.attribute)?void 0:e.isRequired)&&"default"in((null==t?void 0:t.attribute)||{})&&(r.default=t.attribute.default),void 0!==(null==(n=null==t?void 0:t.attribute)?void 0:n.validate)&&(r.validate=t.attribute.validate),[t.name,r]}function FS(t){return t.sort((t,e)=>{const n=IS(t,"priority")||100,r=IS(e,"priority")||100;return n>r?-1:n<r?1:0})}function jS(t){const e=FS(TS(t)),n=function(t){const e=t.filter((e,n)=>t.indexOf(e)!==n);return Array.from(new Set(e))}(e.map(t=>t.name));return n.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${n.map(t=>`'${t}'`).join(", ")}]. This can lead to issues.`),e}function WS(t,e,n){const{from:r,to:o}=e,{blockSeparator:i="\n\n",textSerializers:s={}}=n||{};let a="";return t.nodesBetween(r,o,(t,n,l,c)=>{var d;t.isBlock&&n>r&&(a+=i);const u=null==s?void 0:s[t.type.name];if(u)return l&&(a+=u({node:t,pos:n,parent:l,index:c,range:e})),!1;t.isText&&(a+=null==(d=null==t?void 0:t.text)?void 0:d.slice(Math.max(r,n)-n,o-n))}),a}function HS(t){return Object.fromEntries(Object.entries(t.nodes).filter(([,t])=>t.spec.toText).map(([t,e])=>[t,e.spec.toText]))}function _S(t,e){const n=uS("string"==typeof e?e:e.name,t.schema);return"node"===n?function(t,e){const n=Sk(e,t.schema),{from:r,to:o}=t.selection,i=[];t.doc.nodesBetween(r,o,t=>{i.push(t)});const s=i.reverse().find(t=>t.type.name===n.name);return s?{...s.attrs}:{}}(t,e):"mark"===n?SS(t,e):{}}function US(t){const e=function(t,e=JSON.stringify){const n={};return t.filter(t=>{const r=e(t);return!Object.prototype.hasOwnProperty.call(n,r)&&(n[r]=!0)})}(t);return 1===e.length?e:e.filter((t,n)=>!e.filter((t,e)=>e!==n).some(e=>t.oldRange.from>=e.oldRange.from&&t.oldRange.to<=e.oldRange.to&&t.newRange.from>=e.newRange.from&&t.newRange.to<=e.newRange.to))}function VS(t){const{mapping:e,steps:n}=t,r=[];return e.maps.forEach((t,o)=>{const i=[];if(t.ranges.length)t.forEach((t,e)=>{i.push({from:t,to:e})});else{const{from:t,to:e}=n[o];if(void 0===t||void 0===e)return;i.push({from:t,to:e})}i.forEach(({from:t,to:n})=>{const i=e.slice(o).map(t,-1),s=e.slice(o).map(n),a=e.invert().map(i,-1),l=e.invert().map(s);r.push({oldRange:{from:a,to:l},newRange:{from:i,to:s}})})}),US(r)}function KS(t,e,n){const r=[];return t===e?n.resolve(t).marks().forEach(e=>{const o=Lk(n.resolve(t),e.type);o&&r.push({mark:e,...o})}):n.nodesBetween(t,e,(t,e)=>{t&&void 0!==(null==t?void 0:t.nodeSize)&&r.push(...t.marks.map(n=>({from:e,to:e+t.nodeSize,mark:n})))}),r}function qS(t,e){return e.nodes[t]||e.marks[t]||null}function XS(t,e,n){return Object.fromEntries(Object.entries(n).filter(([n])=>{const r=t.find(t=>t.type===e&&t.name===n);return!!r&&r.attribute.keepOnSplit}))}function YS(t,e,n={}){const{empty:r,ranges:o}=t.selection,i=e?$k(e,t.schema):null;if(r)return!!(t.storedMarks||t.selection.$from.marks()).filter(t=>!i||i.name===t.type.name).find(t=>Ok(t.attrs,n,{strict:!1}));let s=0;const a=[];if(o.forEach(({$from:e,$to:n})=>{const r=e.pos,o=n.pos;t.doc.nodesBetween(r,o,(t,e)=>{if(i&&t.inlineContent&&!t.type.allowsMarkType(i))return!1;if(!t.isText&&!t.marks.length)return;const n=Math.max(r,e),l=Math.min(o,e+t.nodeSize);s+=l-n,a.push(...t.marks.map(t=>({mark:t,from:n,to:l})))})}),0===s)return!1;const l=a.filter(t=>!i||i.name===t.mark.type.name).filter(t=>Ok(t.mark.attrs,n,{strict:!1})).reduce((t,e)=>t+e.to-e.from,0),c=a.filter(t=>!i||t.mark.type!==i&&t.mark.type.excludes(i)).reduce((t,e)=>t+e.to-e.from,0);return(l>0?l+c:l)>=s}function JS(t,e){return Array.isArray(e)?e.some(e=>("string"==typeof e?e:e.name)===t.name):e}function GS(t,e){const{nodeExtensions:n}=OS(e),r=n.find(e=>e.name===t);if(!r)return!1;const o=AS(IS(r,"group",{name:r.name,options:r.options,storage:r.storage}));return"string"==typeof o&&o.split(" ").includes("list")}function ZS(t,{checkChildren:e=!0,ignoreWhitespace:n=!1}={}){var r;if(n){if("hardBreak"===t.type.name)return!0;if(t.isText)return!/\S/.test(null!=(r=t.text)?r:"")}if(t.isText)return!t.text;if(t.isAtom||t.isLeaf)return!1;if(0===t.content.childCount)return!0;if(e){let r=!0;return t.content.forEach(t=>{!1!==r&&(ZS(t,{ignoreWhitespace:n,checkChildren:e})||(r=!1))}),r}return!1}function QS(t){return t instanceof Hy}var tP=class t{constructor(t){this.position=t}static fromJSON(e){return new t(e.position)}toJSON(){return{position:this.position}}};function eP(t,e){const n=e.mapping.mapResult(t.position);return{position:new tP(n.pos),mapResult:n}}function nP(t){return new tP(t)}var rP=(t,e={})=>({tr:n,state:r,dispatch:o})=>{const{selection:i}=n,{empty:s,ranges:a}=i,l=$k(t,r.schema);if(o)if(s){const t=SS(r,l);n.addStoredMark(l.create({...t,...e}))}else a.forEach(t=>{const o=t.$from.pos,i=t.$to.pos;r.doc.nodesBetween(o,i,(t,r)=>{const s=Math.max(r,o),a=Math.min(r+t.nodeSize,i);t.marks.find(t=>t.type===l)?t.marks.forEach(t=>{l===t.type&&n.addMark(s,a,l.create({...t.attrs,...e}))}):n.addMark(s,a,l.create(e))})});return function(t,e,n){var r;const{selection:o}=e;let i=null;if(zk(o)&&(i=o.$cursor),i){const e=null!=(r=t.storedMarks)?r:i.marks();return i.parent.type.allowsMarkType(n)&&(!!n.isInSet(e)||!e.some(t=>t.type.excludes(n)))}const{ranges:s}=o;return s.some(({$from:e,$to:r})=>{let o=0===e.depth&&t.doc.inlineContent&&t.doc.type.allowsMarkType(n);return t.doc.nodesBetween(e.pos,r.pos,(t,e,r)=>{if(o)return!1;if(t.isInline){const e=!r||r.type.allowsMarkType(n),i=!!n.isInSet(t.marks)||!t.marks.some(t=>t.type.excludes(n));o=e&&i}return!o}),o})}(r,n,l)},oP=(t,e)=>({tr:n})=>(n.setMeta(t,e),!0),iP=(t,e={})=>({state:n,dispatch:r,chain:o})=>{const i=Sk(t,n.schema);let s;return n.selection.$anchor.sameParent(n.selection.$head)&&(s=n.selection.$anchor.parent.attrs),i.isTextblock?o().command(({commands:t})=>!!Tx(i,{...s,...e})(n)||t.clearNodes()).command(({state:t})=>Tx(i,{...s,...e})(t,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},sP=t=>({tr:e,dispatch:n})=>{if(n){const{doc:n}=e,r=Fk(t,0,n.content.size),o=Hy.create(n,r);e.setSelection(o)}return!0},aP=(t,e)=>({tr:n,state:r,dispatch:o})=>{const{selection:i}=r;let s,a;return"number"==typeof e?(s=e,a=e):e&&"from"in e&&"to"in e?(s=e.from,a=e.to):(s=i.from,a=i.to),o&&n.doc.nodesBetween(s,a,(e,r)=>{e.isText||n.setNodeMarkup(r,void 0,{...e.attrs,dir:t})}),!0},lP=t=>({tr:e,dispatch:n})=>{if(n){const{doc:n}=e,{from:r,to:o}="number"==typeof t?{from:t,to:t}:t,i=jy.atStart(n).from,s=jy.atEnd(n).to,a=Fk(r,i,s),l=Fk(o,i,s),c=jy.create(n,a,l);e.setSelection(c)}return!0},cP=t=>({state:e,dispatch:n})=>{return(r=Sk(t,e.schema),function(t,e){let{$from:n,$to:o}=t.selection,i=n.blockRange(o,t=>t.childCount>0&&t.firstChild.type==r);if(!i)return!1;let s=i.startIndex;if(0==s)return!1;let a=i.parent,l=a.child(s-1);if(l.type!=r)return!1;if(e){let n=l.lastChild&&l.lastChild.type==a.type,o=Bm.from(n?r.create():null),s=new _m(Bm.from(r.create(null,Bm.from(a.type.create(null,o)))),n?3:1,0),c=i.start,d=i.end;e(t.tr.step(new sy(c-(n?3:1),d,c,d,s,1,!0)).scrollIntoView())}return!0})(e,n);var r};function dP(t,e){const n=t.storedMarks||t.selection.$to.parentOffset&&t.selection.$from.marks();if(n){const r=n.filter(t=>null==e?void 0:e.includes(t.type.name));t.tr.ensureMarks(r)}}var uP=({keepMarks:t=!0}={})=>({tr:e,state:n,dispatch:r,editor:o})=>{const{selection:i,doc:s}=e,{$from:a,$to:l}=i,c=XS(o.extensionManager.attributes,a.node().type.name,a.node().attrs);if(i instanceof Hy&&i.node.isBlock)return!(!a.parentOffset||!my(s,a.pos))&&(r&&(t&&dP(n,o.extensionManager.splittableMarks),e.split(a.pos).scrollIntoView()),!0);if(!a.parent.isBlock)return!1;const d=l.parentOffset===l.parent.content.size,u=0===a.depth?void 0:function(t){for(let e=0;e<t.edgeCount;e+=1){const{type:n}=t.edge(e);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}(a.node(-1).contentMatchAt(a.indexAfter(-1)));let p=d&&u?[{type:u,attrs:c}]:void 0,h=my(e.doc,e.mapping.map(a.pos),1,p);if(p||h||!my(e.doc,e.mapping.map(a.pos),1,u?[{type:u}]:void 0)||(h=!0,p=u?[{type:u,attrs:c}]:void 0),r){if(h&&(i instanceof jy&&e.deleteSelection(),e.split(e.mapping.map(a.pos),1,p),u&&!d&&!a.parentOffset&&a.parent.type!==u)){const t=e.mapping.map(a.before()),n=e.doc.resolve(t);a.node(-1).canReplaceWith(n.index(),n.index()+1,u)&&e.setNodeMarkup(e.mapping.map(a.before()),u)}t&&dP(n,o.extensionManager.splittableMarks),e.scrollIntoView()}return h},pP=(t,e={})=>({tr:n,state:r,dispatch:o,editor:i})=>{var s;const a=Sk(t,r.schema),{$from:l,$to:c}=r.selection,d=r.selection.node;if(d&&d.isBlock||l.depth<2||!l.sameParent(c))return!1;const u=l.node(-1);if(u.type!==a)return!1;const p=i.extensionManager.attributes;if(0===l.parent.content.size&&l.node(-1).childCount===l.indexAfter(-1)){if(2===l.depth||l.node(-3).type!==a||l.index(-2)!==l.node(-2).childCount-1)return!1;if(o){let t=Bm.empty;const r=l.index(-1)?1:l.index(-2)?2:3;for(let e=l.depth-r;e>=l.depth-3;e-=1)t=Bm.from(l.node(e).copy(t));const o=l.indexAfter(-1)<l.node(-2).childCount?1:l.indexAfter(-2)<l.node(-3).childCount?2:3,i={...XS(p,l.node().type.name,l.node().attrs),...e},c=(null==(s=a.contentMatch.defaultType)?void 0:s.createAndFill(i))||void 0;t=t.append(Bm.from(a.createAndFill(null,c)||void 0));const d=l.before(l.depth-(r-1));n.replace(d,l.after(-o),new _m(t,4-r,0));let u=-1;n.doc.nodesBetween(d,n.doc.content.size,(t,e)=>{if(u>-1)return!1;t.isTextblock&&0===t.content.size&&(u=e+1)}),u>-1&&n.setSelection(jy.near(n.doc.resolve(u))),n.scrollIntoView()}return!0}const h=c.pos===l.end()?u.contentMatchAt(0).defaultType:null,f={...XS(p,u.type.name,u.attrs),...e},m={...XS(p,l.node().type.name,l.node().attrs),...e};n.delete(l.pos,c.pos);const g=h?[{type:a,attrs:f},{type:h,attrs:m}]:[{type:a,attrs:f}];if(!my(n.doc,l.pos,2))return!1;if(o){const{selection:t,storedMarks:e}=r,{splittableMarks:s}=i.extensionManager,a=e||t.$to.parentOffset&&t.$from.marks();if(n.split(l.pos,2,g).scrollIntoView(),!a||!o)return!0;const c=a.filter(t=>s.includes(t.type.name));n.ensureMarks(c)}return!0};function hP(t){return t&&"1"!==t?t:null}function fP(t,e){return hP(t)===hP(e)}var mP=(t,e)=>{const n=MS(t=>t.type===e)(t.selection);if(!n)return!0;const r=t.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(void 0===r)return!0;const o=t.doc.nodeAt(r);return n.node.type!==(null==o?void 0:o.type)||!gy(t.doc,n.pos)||(!fP(n.node.attrs.type,null==o?void 0:o.attrs.type)||(t.join(n.pos),!0))},gP=(t,e)=>{const n=MS(t=>t.type===e)(t.selection);if(!n)return!0;const r=t.doc.resolve(n.start).after(n.depth);if(void 0===r)return!0;const o=t.doc.nodeAt(r);return n.node.type!==(null==o?void 0:o.type)||!gy(t.doc,r)||(!fP(n.node.attrs.type,null==o?void 0:o.attrs.type)||(t.join(r),!0))};var yP=(t,e,n,r={})=>({editor:o,tr:i,state:s,dispatch:a,chain:l,commands:c,can:d})=>{const{extensions:u,splittableMarks:p}=o.extensionManager,h=Sk(t,s.schema),f=Sk(e,s.schema),{selection:m,storedMarks:g}=s,{$from:y,$to:x}=m,w=y.blockRange(x),b=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const v=MS(t=>GS(t.type.name,u))(m),k=0===m.from&&m.to===s.doc.content.size,S=s.doc.content.content,P=1===S.length?S[0]:null,M=k&&P&&GS(P.type.name,u)?{node:P,pos:0,depth:0}:null,I=null!=v?v:M,T=!!M;if((!!v&&w.depth>=1&&w.depth-v.depth<=1||T)&&I){if(I.node.type===h)return k&&T?l().command(({tr:t,dispatch:e})=>{const n=function(t){const e=t.doc,n=e.firstChild;if(!n)return null;const r=e.resolve(1),o=e.resolve(n.nodeSize-1);return jy.between(r,o)}(t);return!!n&&(t.setSelection(n),e&&e(t),!0)}).liftListItem(f).run():c.liftListItem(f);if(GS(I.node.type.name,u)&&h.validContent(I.node.content))return l().command(()=>(i.setNodeMarkup(I.pos,h),!0)).command(()=>mP(i,h)).command(()=>gP(i,h)).run()}return n&&b&&a?l().command(()=>{const t=d().wrapInList(h,r),e=b.filter(t=>p.includes(t.type.name));return i.ensureMarks(e),!!t||c.clearNodes()}).wrapInList(h,r).command(()=>mP(i,h)).command(()=>gP(i,h)).run():l().command(()=>!!d().wrapInList(h,r)||c.clearNodes()).wrapInList(h,r).command(()=>mP(i,h)).command(()=>gP(i,h)).run()},xP=(t,e={},n={})=>({state:r,commands:o})=>{const{extendEmptyMarkRange:i=!1}=n,s=$k(t,r.schema);return YS(r,s,e)?o.unsetMark(s,{extendEmptyMarkRange:i}):o.setMark(s,e)},wP=(t,e,n={})=>({state:r,commands:o})=>{const i=Sk(t,r.schema),s=Sk(e,r.schema),a=sS(r,i,n);let l;return r.selection.$anchor.sameParent(r.selection.$head)&&(l=r.selection.$anchor.parent.attrs),a?o.setNode(s,l):o.setNode(i,{...l,...n})},bP=(t,e={})=>({state:n,commands:r})=>{const o=Sk(t,n.schema);return sS(n,o,e)?r.lift(o):r.wrapIn(o,e)},vP=()=>({state:t,dispatch:e})=>{const n=t.plugins;for(let r=0;r<n.length;r+=1){const o=n[r];let i;if(o.spec.isInputRules&&(i=o.getState(t))){if(e){const e=t.tr,n=i.transform;for(let t=n.steps.length-1;t>=0;t-=1)e.step(n.steps[t].invert(n.docs[t]));if(i.text){const n=e.doc.resolve(i.from).marks();e.replaceWith(i.from,i.to,t.schema.text(i.text,n))}else e.delete(i.from,i.to)}return!0}}return!1},kP=(t={})=>({tr:e,dispatch:n,editor:r})=>{const{ignoreClearable:o=!1}=t,{selection:i}=e,{empty:s,ranges:a}=i;if(s)return!0;const{nonClearableMarks:l}=r.extensionManager;if(n){const t=Object.values(r.schema.marks).filter(t=>o||!l.includes(t.name));a.forEach(n=>{for(const r of t)e.removeMark(n.$from.pos,n.$to.pos,r)})}return!0},SP=(t,e={})=>({tr:n,state:r,dispatch:o})=>{var i;const{extendEmptyMarkRange:s=!1}=e,{selection:a}=n,l=$k(t,r.schema),{$from:c,empty:d,ranges:u}=a;if(!o)return!0;if(d&&s){let{from:t,to:e}=a;const r=Lk(c,l,null==(i=c.marks().find(t=>t.type===l))?void 0:i.attrs);r&&(t=r.from,e=r.to),n.removeMark(t,e,l)}else u.forEach(t=>{n.removeMark(t.$from.pos,t.$to.pos,l)});return n.removeStoredMark(l),!0},PP=t=>({tr:e,state:n,dispatch:r})=>{const{selection:o}=n;let i,s;return"number"==typeof t?(i=t,s=t):t&&"from"in t&&"to"in t?(i=t.from,s=t.to):(i=o.from,s=o.to),r&&e.doc.nodesBetween(i,s,(t,n)=>{if(t.isText)return;const r={...t.attrs};delete r.dir,e.setNodeMarkup(n,void 0,r)}),!0},MP=(t,e={})=>({tr:n,state:r,dispatch:o})=>{let i=null,s=null;const a=uS("string"==typeof t?t:t.name,r.schema);if(!a)return!1;"node"===a&&(i=Sk(t,r.schema)),"mark"===a&&(s=$k(t,r.schema));let l=!1;return n.selection.ranges.forEach(t=>{const a=t.$from.pos,c=t.$to.pos;let d,u,p,h;n.selection.empty?r.doc.nodesBetween(a,c,(t,e)=>{i&&i===t.type&&(l=!0,p=Math.max(e,a),h=Math.min(e+t.nodeSize,c),d=e,u=t)}):r.doc.nodesBetween(a,c,(t,r)=>{r<a&&i&&i===t.type&&(l=!0,p=Math.max(r,a),h=Math.min(r+t.nodeSize,c),d=r,u=t),r>=a&&r<=c&&(i&&i===t.type&&(l=!0,o&&n.setNodeMarkup(r,void 0,{...t.attrs,...e})),s&&t.marks.length&&t.marks.forEach(i=>{if(s===i.type&&(l=!0,o)){const o=Math.max(r,a),l=Math.min(r+t.nodeSize,c);n.addMark(o,l,s.create({...i.attrs,...e}))}}))}),u&&(void 0!==d&&o&&n.setNodeMarkup(d,void 0,{...u.attrs,...e}),s&&u.marks.length&&u.marks.forEach(t=>{s===t.type&&o&&n.addMark(p,h,s.create({...t.attrs,...e}))}))}),l},IP=(t,e={})=>({state:n,dispatch:r})=>function(t,e=null){return function(n,r){let{$from:o,$to:i}=n.selection,s=o.blockRange(i),a=s&&uy(s,t,e);return!!a&&(r&&r(n.tr.wrap(s,a).scrollIntoView()),!0)}}(Sk(t,n.schema),e)(n,r),TP=(t,e={})=>({state:n,dispatch:r})=>Rx(Sk(t,n.schema),e)(n,r),CP=class{constructor(){this.callbacks={}}on(t,e){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(e),this}emit(t,...e){const n=this.callbacks[t];return n&&n.forEach(t=>t.apply(this,e)),this}off(t,e){const n=this.callbacks[t];return n&&(e?this.callbacks[t]=n.filter(t=>t!==e):delete this.callbacks[t]),this}once(t,e){const n=(...r)=>{this.off(t,n),e.apply(this,r)};return this.on(t,n)}removeAllListeners(){this.callbacks={}}};function EP(t,e,n){const r=document.querySelector(`style[data-tiptap-style${n?`-${n}`:""}]`);if(null!==r)return r;const o=document.createElement("style");return e&&o.setAttribute("nonce",e),o.setAttribute("data-tiptap-style"+(n?`-${n}`:""),""),o.innerHTML=t,document.getElementsByTagName("head")[0].appendChild(o),o}function AP(t,e){const n=t.getAttribute("style");if(!n)return null;const r=n.split(";").map(t=>t.trim()).filter(Boolean),o=e.toLowerCase();for(let i=r.length-1;i>=0;i-=1){const t=r[i],e=t.indexOf(":");if(-1!==e&&t.slice(0,e).trim().toLowerCase()===o)return t.slice(e+1).trim()}return null}function OP(t){return"Object"===function(t){return Object.prototype.toString.call(t).slice(8,-1)}(t)&&(t.constructor===Object&&Object.getPrototypeOf(t)===Object.prototype)}function NP(t){if(!(null==t?void 0:t.trim()))return{};const e={},n=[],r=t.replace(/["']([^"']*)["']/g,t=>(n.push(t),`__QUOTED_${n.length-1}__`)),o=r.match(/(?:^|\s)\.([\w-]+)/g);o&&(e.class=o.map(t=>t.trim().slice(1)).join(" "));const i=r.match(/(?:^|\s)#([\w-]+)/);i&&(e.id=i[1]),Array.from(r.matchAll(/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g)).forEach(([,t,r])=>{var o;const i=n[parseInt((null==(o=r.match(/__QUOTED_(\d+)__/))?void 0:o[1])||"0",10)];i&&(e[t]=i.slice(1,-1))});const s=r.replace(/(?:^|\s)\.([\w-]+)/g,"").replace(/(?:^|\s)#([\w-]+)/g,"").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,"").trim();return s&&s.split(/\s+/).filter(Boolean).forEach(t=>{t.match(/^[a-zA-Z][\w-]*$/)&&(e[t]=!0)}),e}function RP(t){if(!t||0===Object.keys(t).length)return"";const e=[];return t.class&&String(t.class).split(/\s+/).filter(Boolean).forEach(t=>e.push(`.${t}`)),t.id&&e.push(`#${t.id}`),Object.entries(t).forEach(([t,n])=>{"class"!==t&&"id"!==t&&(!0===n?e.push(t):!1!==n&&null!=n&&e.push(`${t}="${String(n)}"`))}),e.join(" ")}function LP(t){const{nodeName:e,name:n,parseAttributes:r=NP,serializeAttributes:o=RP,defaultAttributes:i={},requiredAttributes:s=[],allowedAttributes:a}=t,l=n||e;return{parseMarkdown:(t,n)=>{const r={...i,...t.attributes};return n.createNode(e,r,[])},markdownTokenizer:{name:e,level:"block",start(t){var e;const n=new RegExp(`^:::${l}(?:\\s|$)`,"m"),r=null==(e=t.match(n))?void 0:e.index;return void 0!==r?r:-1},tokenize(t,n,o){const i=new RegExp(`^:::${l}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),a=t.match(i);if(!a)return;const c=r(a[1]||"");return s.find(t=>!(t in c))?void 0:{type:e,raw:a[0],attributes:c}}},renderMarkdown:t=>{const e=o((t=>{if(!a)return t;const e={};return a.forEach(n=>{n in t&&(e[n]=t[n])}),e})(t.attrs||{}));return`:::${l}${e?` {${e}}`:""} :::`}}}function $P(t){const{nodeName:e,name:n,getContent:r,parseAttributes:o=NP,serializeAttributes:i=RP,defaultAttributes:s={},content:a="block",allowedAttributes:l}=t,c=n||e;return{parseMarkdown:(t,n)=>{let o;if(r){const e=r(t);o="string"==typeof e?[{type:"text",text:e}]:e}else o="block"===a?n.parseChildren(t.tokens||[]):n.parseInline(t.tokens||[]);const i={...s,...t.attributes};return n.createNode(e,i,o)},markdownTokenizer:{name:e,level:"block",start(t){var e;const n=new RegExp(`^:::${c}`,"m"),r=null==(e=t.match(n))?void 0:e.index;return void 0!==r?r:-1},tokenize(t,n,r){var i;const s=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),l=t.match(s);if(!l)return;const[d,u=""]=l,p=o(u);let h=1;const f=d.length;let m="";const g=/^:::([\w-]*)(\s.*)?/gm,y=t.slice(f);for(g.lastIndex=0;;){const n=g.exec(y);if(null===n)break;const o=n.index,s=n[1];if(!(null==(i=n[2])?void 0:i.endsWith(":::")))if(s)h+=1;else if(h-=1,0===h){const i=y.slice(0,o);m=i.trim();const s=t.slice(0,f+o+n[0].length);let l=[];if(m)if("block"===a)for(l=r.blockTokens(i),l.forEach(t=>{!t.text||t.tokens&&0!==t.tokens.length||(t.tokens=r.inlineTokens(t.text))});l.length>0;){const t=l[l.length-1];if("paragraph"!==t.type||t.text&&""!==t.text.trim())break;l.pop()}else l=r.inlineTokens(m);return{type:e,raw:s,attributes:p,content:m,tokens:l}}}}},renderMarkdown:(t,e)=>{const n=i((t=>{if(!l)return t;const e={};return l.forEach(n=>{n in t&&(e[n]=t[n])}),e})(t.attrs||{}));return`:::${c}${n?` {${n}}`:""}\n\n${e.renderChildren(t.content||[],"\n\n")}\n\n:::`}}}function DP(t){if(!t.trim())return{};const e={},n=/(\w+)=(?:"([^"]*)"|'([^']*)')/g;let r=n.exec(t);for(;null!==r;){const[,o,i,s]=r;e[o]=i||s,r=n.exec(t)}return e}function BP(t){return Object.entries(t).filter(([,t])=>null!=t).map(([t,e])=>`${t}="${e}"`).join(" ")}function zP(t){const{nodeName:e,name:n,getContent:r,parseAttributes:o=DP,serializeAttributes:i=BP,defaultAttributes:s={},selfClosing:a=!1,allowedAttributes:l}=t,c=n||e,d=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(t,n)=>{const o={...s,...t.attributes};if(a)return n.createNode(e,o);const i=r?r(t):t.content||"";return i?n.createNode(e,o,[n.createTextNode(i)]):n.createNode(e,o,[])},markdownTokenizer:{name:e,level:"inline",start(t){const e=a?new RegExp(`\\[${d}\\s*[^\\]]*\\]`):new RegExp(`\\[${d}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${d}\\]`),n=t.match(e),r=null==n?void 0:n.index;return void 0!==r?r:-1},tokenize(t,n,r){const i=a?new RegExp(`^\\[${d}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${d}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${d}\\]`),s=t.match(i);if(!s)return;let l="",c="";if(a){const[,t]=s;c=t}else{const[,t,e]=s;c=t,l=e||""}const u=o(c.trim());return{type:e,raw:s[0],content:l.trim(),attributes:u}}},renderMarkdown:t=>{let e="";r?e=r(t):t.content&&t.content.length>0&&(e=t.content.filter(t=>"text"===t.type).map(t=>t.text).join(""));const n=i((t=>{if(!l)return t;const e={};return l.forEach(n=>{const r="string"==typeof n?n:n.name,o="string"==typeof n?void 0:n.skipIfDefault;if(r in t){const n=t[r];if(void 0!==o&&n===o)return;e[r]=n}}),e})(t.attrs||{})),o=n?` ${n}`:"";return a?`[${c}${o}]`:`[${c}${o}]${e}[/${c}]`}}}function FP(t,e,n){var r,o,i,s;const a=t.split("\n"),l=[];let c="",d=0;const u=e.baseIndentSize||2;for(;d<a.length;){const t=a[d],p=t.match(e.itemPattern);if(!p){if(l.length>0)break;if(""===t.trim()){d+=1,c=`${c}${t}\n`;continue}return}const h=e.extractItemData(p),{indentLevel:f,mainContent:m}=h;c=`${c}${t}\n`;const g=[m];for(d+=1;d<a.length;){const t=a[d];if(""===t.trim()){const e=a.slice(d+1).findIndex(t=>""!==t.trim());if(-1===e)break;if(((null==(o=null==(r=a[d+1+e].match(/^(\s*)/))?void 0:r[1])?void 0:o.length)||0)>f){g.push(t),c=`${c}${t}\n`,d+=1;continue}break}if(!(((null==(s=null==(i=t.match(/^(\s*)/))?void 0:i[1])?void 0:s.length)||0)>f))break;g.push(t),c=`${c}${t}\n`,d+=1}let y;const x=g.slice(1);if(x.length>0){const t=x.map(t=>t.slice(f+u)).join("\n");t.trim()&&(y=e.customNestedParser?e.customNestedParser(t):n.blockTokens(t))}const w=e.createToken(h,y);l.push(w)}if(0!==l.length)return{items:l,raw:c}}function jP(t,e,n,r){if(!t||!Array.isArray(t.content))return"";const o="function"==typeof n?n(r):n,[i,...s]=t.content;let a=`${o}${e.renderChildren([i])}`;return s&&s.length>0&&s.forEach((t,n)=>{var r,o;const i=null!=(o=null==(r=e.renderChild)?void 0:r.call(e,t,n+1))?o:e.renderChildren([t]);if(null!=i){const n=i.split("\n").map(t=>t?e.indent(t):e.indent("")).join("\n");a+="paragraph"===t.type?`\n\n${n}`:`\n${n}`}}),a}function WP(t,e){const n={...t};return OP(t)&&OP(e)&&Object.keys(e).forEach(r=>{OP(e[r])&&OP(t[r])?n[r]=WP(t[r],e[r]):n[r]=e[r]}),n}pk({},{createAtomBlockMarkdownSpec:()=>LP,createBlockMarkdownSpec:()=>$P,createInlineMarkdownSpec:()=>zP,parseAttributes:()=>NP,parseIndentedBlocks:()=>FP,renderNestedMarkdownContent:()=>jP,serializeAttributes:()=>RP});var HP=class{constructor(t){var e;this.find=t.find,this.handler=t.handler,this.undoable=null==(e=t.undoable)||e}};function _P(t){var e;const{editor:n,from:r,to:o,text:i,rules:s,plugin:a}=t,{view:l}=n;if(l.composing)return!1;const c=l.state.doc.resolve(r);if(c.parent.type.spec.code||(null==(e=c.nodeBefore||c.nodeAfter)?void 0:e.marks.find(t=>t.type.spec.code)))return!1;let d=!1;const u=((t,e=500)=>{let n="";const r=t.parentOffset;return t.parent.nodesBetween(Math.max(0,r-e),r,(t,e,o,i)=>{var s,a;const l=(null==(a=(s=t.type.spec).toText)?void 0:a.call(s,{node:t,pos:e,parent:o,index:i}))||t.textContent||"%leaf%";n+=t.isAtom&&!t.isText?l:l.slice(0,Math.max(0,r-e))}),n})(c)+i;return s.forEach(t=>{if(d)return;const e=((t,e)=>{if(Ak(e))return e.exec(t);const n=e(t);if(!n)return null;const r=[n.text];return r.index=n.index,r.input=t,r.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(n.replaceWith)),r})(u,t.find);if(!e)return;const s=l.state.tr,c=hk({state:l.state,transaction:s}),p={from:r-(e[0].length-i.length),to:o},{commands:h,chain:f,can:m}=new fk({editor:n,state:c});null!==t.handler({state:c,range:p,match:e,commands:h,chain:f,can:m})&&s.steps.length&&(t.undoable&&s.setMeta(a,{transform:s,from:r,to:o,text:i}),l.dispatch(s),d=!0)}),d}var UP=class{constructor(t={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...t},this.name=this.config.name}get options(){return{...AS(IS(this,"addOptions",{name:this.name}))}}get storage(){return{...AS(IS(this,"addStorage",{name:this.name,options:this.options}))}}configure(t={}){const e=this.extend({...this.config,addOptions:()=>WP(this.options,t)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(t={}){const e=new this.constructor({...this.config,...t});return e.parent=this,this.child=e,e.name="name"in t?t.name:e.parent.name,e}},VP=class t extends UP{constructor(){super(...arguments),this.type="mark"}static create(e={}){return new t("function"==typeof e?e():e)}static handleExit({editor:t,mark:e}){const{tr:n}=t.state,r=t.state.selection.$from;if(r.pos===r.end()){const o=r.marks();if(!o.find(t=>(null==t?void 0:t.type.name)===e.name))return!1;const i=o.find(t=>(null==t?void 0:t.type.name)===e.name);return i&&n.removeStoredMark(i),n.insertText(" ",r.pos),t.view.dispatch(n),!0}return!1}configure(t){return super.configure(t)}extend(t){const e="function"==typeof t?t():t;return super.extend(e)}},KP=class{constructor(t){this.find=t.find,this.handler=t.handler}};function qP(t){const{editor:e,state:n,from:r,to:o,rule:i,pasteEvent:s,dropEvent:a}=t,{commands:l,chain:c,can:d}=new fk({editor:e,state:n}),u=[];return n.doc.nodesBetween(r,o,(t,e)=>{var p,h,f,m,g;if((null==(h=null==(p=t.type)?void 0:p.spec)?void 0:h.code)||!(t.isText||t.isTextblock||t.isInline))return;const y=null!=(g=null!=(m=null==(f=t.content)?void 0:f.size)?m:t.nodeSize)?g:0,x=Math.max(r,e),w=Math.min(o,e+y);x>=w||((t,e,n)=>{if(Ak(e))return[...t.matchAll(e)];const r=e(t,n);return r?r.map(e=>{const n=[e.text];return n.index=e.index,n.input=t,n.data=e.data,e.replaceWith&&(e.text.includes(e.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),n.push(e.replaceWith)),n}):[]})(t.isText?t.text||"":t.textBetween(x-e,w-e,void 0,""),i.find,s).forEach(t=>{if(void 0===t.index)return;const e=x+t.index+1,r=e+t[0].length,o={from:n.tr.mapping.map(e),to:n.tr.mapping.map(r)},p=i.handler({state:n,range:o,match:t,commands:l,chain:c,can:d,pasteEvent:s,dropEvent:a});u.push(p)})}),u.every(t=>null!==t)}var XP=null;function YP(t){const{editor:e,rules:n}=t;let r,o=null,i=!1,s=!1,a="undefined"!=typeof ClipboardEvent?new ClipboardEvent("paste"):null;try{r="undefined"!=typeof DragEvent?new DragEvent("drop"):null}catch{r=null}const l=({state:t,from:n,to:o,rule:i,pasteEvt:s})=>{const l=t.tr;if(qP({editor:e,state:hk({state:t,transaction:l}),from:Math.max(n-1,0),to:o.b-1,rule:i,pasteEvent:s,dropEvent:r})&&l.steps.length){try{r="undefined"!=typeof DragEvent?new DragEvent("drop"):null}catch{r=null}return a="undefined"!=typeof ClipboardEvent?new ClipboardEvent("paste"):null,l}};return n.map(t=>new ex({view(t){const n=n=>{var r;o=(null==(r=t.dom.parentElement)?void 0:r.contains(n.target))?t.dom.parentElement:null,o&&(XP=e)},r=()=>{XP&&(XP=null)};return window.addEventListener("dragstart",n),window.addEventListener("dragend",r),{destroy(){window.removeEventListener("dragstart",n),window.removeEventListener("dragend",r)}}},props:{handleDOMEvents:{drop:(t,e)=>{if(s=o===t.dom.parentElement,r=e,!s){const t=XP;(null==t?void 0:t.isEditable)&&setTimeout(()=>{const e=t.state.selection;e&&t.commands.deleteRange({from:e.from,to:e.to})},10)}return!1},paste:(t,e)=>{var n;const r=null==(n=e.clipboardData)?void 0:n.getData("text/html");return a=e,i=!!(null==r?void 0:r.includes("data-pm-slice")),!1}}},appendTransaction:(e,n,r)=>{const o=e[0],c="paste"===o.getMeta("uiEvent")&&!i,d="drop"===o.getMeta("uiEvent")&&!s,u=o.getMeta("applyPasteRules"),p=!!u;if(!c&&!d&&!p)return;if(p){let{text:e}=u;"string"==typeof e||(e=CS(Bm.from(e),r.schema));const{from:n}=u,o=n+e.length,i=(t=>{var e;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return null==(e=n.clipboardData)||e.setData("text/html",t),n})(e);return l({rule:t,state:r,from:n,to:{b:o},pasteEvt:i})}const h=n.doc.content.findDiffStart(r.doc.content),f=n.doc.content.findDiffEnd(r.doc.content);return"number"==typeof h&&f&&h!==f.b?l({rule:t,state:r,from:h,to:f,pasteEvt:a}):void 0}}))}var JP=class{constructor(t,e){this.splittableMarks=[],this.nonClearableMarks=[],this.editor=e,this.baseExtensions=t,this.extensions=jS(t),this.schema=function(t,e){var n;const r=NS(t),{nodeExtensions:o,markExtensions:i}=OS(t);return new Tg({topNode:null==(n=o.find(t=>IS(t,"topNode")))?void 0:n.name,nodes:Object.fromEntries(o.map(n=>{const o=r.filter(t=>t.type===n.name),i={name:n.name,options:n.options,storage:n.storage,editor:e},s=BS({...t.reduce((t,e)=>{const r=IS(e,"extendNodeSchema",i);return{...t,...r?r(n):{}}},{}),content:AS(IS(n,"content",i)),marks:AS(IS(n,"marks",i)),group:AS(IS(n,"group",i)),inline:AS(IS(n,"inline",i)),atom:AS(IS(n,"atom",i)),selectable:AS(IS(n,"selectable",i)),draggable:AS(IS(n,"draggable",i)),code:AS(IS(n,"code",i)),whitespace:AS(IS(n,"whitespace",i)),linebreakReplacement:AS(IS(n,"linebreakReplacement",i)),defining:AS(IS(n,"defining",i)),isolating:AS(IS(n,"isolating",i)),attrs:Object.fromEntries(o.map(zS))}),a=AS(IS(n,"parseHTML",i));a&&(s.parseDOM=a.map(t=>DS(t,o)));const l=IS(n,"renderHTML",i);l&&(s.toDOM=t=>l({node:t,HTMLAttributes:$S(t,o)}));const c=IS(n,"renderText",i);return c&&(s.toText=c),[n.name,s]})),marks:Object.fromEntries(i.map(n=>{const o=r.filter(t=>t.type===n.name),i={name:n.name,options:n.options,storage:n.storage,editor:e},s=BS({...t.reduce((t,e)=>{const r=IS(e,"extendMarkSchema",i);return{...t,...r?r(n):{}}},{}),inclusive:AS(IS(n,"inclusive",i)),excludes:AS(IS(n,"excludes",i)),group:AS(IS(n,"group",i)),spanning:AS(IS(n,"spanning",i)),code:AS(IS(n,"code",i)),attrs:Object.fromEntries(o.map(zS))}),a=AS(IS(n,"parseHTML",i));a&&(s.parseDOM=a.map(t=>DS(t,o)));const l=IS(n,"renderHTML",i);return l&&(s.toDOM=t=>l({mark:t,HTMLAttributes:$S(t,o)})),[n.name,s]}))})}(this.extensions,e),this.setupExtensions()}get commands(){return this.extensions.reduce((t,e)=>{const n=IS(e,"addCommands",{name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:qS(e.name,this.schema)});return n?{...t,...n()}:t},{})}get plugins(){const{editor:t}=this;return FS([...this.extensions].reverse()).flatMap(e=>{const n={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:t,type:qS(e.name,this.schema)},r=[],o=IS(e,"addKeyboardShortcuts",n);let i={};if("mark"===e.type&&IS(e,"exitable",n)&&(i.ArrowRight=()=>VP.handleExit({editor:t,mark:e})),o){const e=Object.fromEntries(Object.entries(o()).map(([e,n])=>[e,()=>n({editor:t})]));i={...i,...e}}const s=new ex({props:{handleKeyDown:ck(i)}});r.push(s);const a=IS(e,"addInputRules",n);if(JS(e,t.options.enableInputRules)&&a){const e=a();if(e&&e.length){const n=function(t){const{editor:e,rules:n}=t,r=new ex({state:{init:()=>null,apply(t,o,i){const s=t.getMeta(r);if(s)return s;const a=t.getMeta("applyInputRules");return a&&setTimeout(()=>{let{text:t}=a;"string"==typeof t||(t=CS(Bm.from(t),i.schema));const{from:o}=a;_P({editor:e,from:o,to:o+t.length,text:t,rules:n,plugin:r})}),t.selectionSet||t.docChanged?null:o}},props:{handleTextInput:(t,o,i,s)=>_P({editor:e,from:o,to:i,text:s,rules:n,plugin:r}),handleDOMEvents:{compositionend:t=>(setTimeout(()=>{const{$cursor:o}=t.state.selection;o&&_P({editor:e,from:o.pos,to:o.pos,text:"",rules:n,plugin:r})}),!1)},handleKeyDown(t,o){if("Enter"!==o.key)return!1;const{$cursor:i}=t.state.selection;return!!i&&_P({editor:e,from:i.pos,to:i.pos,text:"\n",rules:n,plugin:r})}},isInputRules:!0});return r}({editor:t,rules:e}),o=Array.isArray(n)?n:[n];r.push(...o)}}const l=IS(e,"addPasteRules",n);if(JS(e,t.options.enablePasteRules)&&l){const e=l();if(e&&e.length){const n=YP({editor:t,rules:e});r.push(...n)}}const c=IS(e,"addProseMirrorPlugins",n);if(c){const t=c();r.push(...t)}return r})}get attributes(){return NS(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:e}=OS(this.extensions);return Object.fromEntries(e.filter(t=>!!IS(t,"addNodeView")).map(e=>{const n=this.attributes.filter(t=>t.type===e.name),r=IS(e,"addNodeView",{name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:t,type:Sk(e.name,this.schema)});if(!r)return[];const o=r();if(!o)return[];return[e.name,(r,i,s,a,l)=>o({node:r,view:i,getPos:s,decorations:a,innerDecorations:l,editor:t,extension:e,HTMLAttributes:$S(r,n)})]}))}dispatchTransaction(t){const{editor:e}=this;return FS([...this.extensions].reverse()).reduceRight((t,n)=>{const r={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:e,type:qS(n.name,this.schema)},o=IS(n,"dispatchTransaction",r);return o?e=>{o.call(r,{transaction:e,next:t})}:t},t)}transformPastedHTML(t){const{editor:e}=this;return FS([...this.extensions]).reduce((t,n)=>{const r={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:e,type:qS(n.name,this.schema)},o=IS(n,"transformPastedHTML",r);return o?(e,n)=>{const i=t(e,n);return o.call(r,i)}:t},t||(t=>t))}get markViews(){const{editor:t}=this,{markExtensions:e}=OS(this.extensions);return Object.fromEntries(e.filter(t=>!!IS(t,"addMarkView")).map(e=>{const n=this.attributes.filter(t=>t.type===e.name),r=IS(e,"addMarkView",{name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:t,type:$k(e.name,this.schema)});if(!r)return[];return[e.name,(o,i,s)=>{const a=$S(o,n);return r()({mark:o,view:i,inline:s,editor:t,extension:e,HTMLAttributes:a,updateAttributes:e=>{!function(t,e,n={}){const{state:r}=e,{doc:o,tr:i}=r,s=t;o.descendants((e,r)=>{const o=i.mapping.map(r),a=i.mapping.map(r)+e.nodeSize;let l=null;if(e.marks.forEach(t=>{if(t!==s)return!1;l=t}),!l)return;let c=!1;if(Object.keys(n).forEach(t=>{n[t]!==l.attrs[t]&&(c=!0)}),c){const e=t.type.create({...t.attrs,...n});i.removeMark(o,a,t.type),i.addMark(o,a,e)}}),i.docChanged&&e.view.dispatch(i)}(o,t,e)}})}]}))}destroy(){this.extensions.forEach(t=>{let e=t;for(;e.parent;){const t=e.parent;t.child===e&&(t.child=null),e=t}}),this.extensions=[],this.baseExtensions=[],this.schema=null,this.editor=null}setupExtensions(){const t=this.extensions;this.editor.extensionStorage=Object.fromEntries(t.map(t=>[t.name,t.storage])),t.forEach(t=>{var e,n;const r={name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:this.editor,type:qS(t.name,this.schema)};"mark"===t.type&&((null==(e=AS(IS(t,"keepOnSplit",r)))||e)&&this.splittableMarks.push(t.name),null==(n=AS(IS(t,"clearable",r)))||n||this.nonClearableMarks.push(t.name));const o=IS(t,"onBeforeCreate",r),i=IS(t,"onCreate",r),s=IS(t,"onUpdate",r),a=IS(t,"onSelectionUpdate",r),l=IS(t,"onTransaction",r),c=IS(t,"onFocus",r),d=IS(t,"onBlur",r),u=IS(t,"onDestroy",r);o&&this.editor.on("beforeCreate",o),i&&this.editor.on("create",i),s&&this.editor.on("update",s),a&&this.editor.on("selectionUpdate",a),l&&this.editor.on("transaction",l),c&&this.editor.on("focus",c),d&&this.editor.on("blur",d),u&&this.editor.on("destroy",u)})}};JP.resolve=jS,JP.sort=FS,JP.flatten=TS;pk({},{ClipboardTextSerializer:()=>ZP,Commands:()=>QP,Delete:()=>tM,Drop:()=>eM,Editable:()=>nM,FocusEvents:()=>oM,Keymap:()=>iM,Paste:()=>sM,Tabindex:()=>aM,TextDirection:()=>lM,focusEventsPluginKey:()=>rM});var GP=class t extends UP{constructor(){super(...arguments),this.type="extension"}static create(e={}){return new t("function"==typeof e?e():e)}configure(t){return super.configure(t)}extend(t){const e="function"==typeof t?t():t;return super.extend(e)}},ZP=GP.create({name:"clipboardTextSerializer",addOptions:()=>({blockSeparator:void 0}),addProseMirrorPlugins(){return[new ex({key:new ox("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:t}=this,{state:e,schema:n}=t,{doc:r,selection:o}=e,i=HS(n),{blockSeparator:s}=this.options,a={...void 0!==s?{blockSeparator:s}:{},textSerializers:i};return[...o.ranges].sort((t,e)=>t.$from.pos-e.$from.pos).map(({$from:t,$to:e})=>WS(r,{from:t.pos,to:e.pos},a)).join(null!=s?s:"\n\n")}}})]}}),QP=GP.create({name:"commands",addCommands:()=>({...mk})}),tM=GP.create({name:"delete",onUpdate({transaction:t,appendedTransactions:e}){var n,r,o;const i=()=>{var n,r,o,i;if(null!=(i=null==(o=null==(r=null==(n=this.editor.options.coreExtensionOptions)?void 0:n.delete)?void 0:r.filterTransaction)?void 0:o.call(r,t))?i:t.getMeta("y-sync$"))return;const s=PS(t.before,[t,...e]);VS(s).forEach(e=>{s.mapping.mapResult(e.oldRange.from).deletedAfter&&s.mapping.mapResult(e.oldRange.to).deletedBefore&&s.before.nodesBetween(e.oldRange.from,e.oldRange.to,(n,r)=>{const o=r+n.nodeSize-2,i=e.oldRange.from<=r&&o<=e.oldRange.to;this.editor.emit("delete",{type:"node",node:n,from:r,to:o,newFrom:s.mapping.map(r),newTo:s.mapping.map(o),deletedRange:e.oldRange,newRange:e.newRange,partial:!i,editor:this.editor,transaction:t,combinedTransform:s})})});const a=s.mapping;s.steps.forEach((e,n)=>{var r,o;if(e instanceof ny){const i=a.slice(n).map(e.from,-1),l=a.slice(n).map(e.to),c=a.invert().map(i,-1),d=a.invert().map(l),u=i>0&&(null==(r=s.doc.nodeAt(i-1))?void 0:r.marks.some(t=>t.eq(e.mark))),p=null==(o=s.doc.nodeAt(l))?void 0:o.marks.some(t=>t.eq(e.mark));this.editor.emit("delete",{type:"mark",mark:e.mark,from:e.from,to:e.to,deletedRange:{from:c,to:d},newRange:{from:i,to:l},partial:Boolean(p||u),editor:this.editor,transaction:t,combinedTransform:s})}})};null==(o=null==(r=null==(n=this.editor.options.coreExtensionOptions)?void 0:n.delete)?void 0:r.async)||o?setTimeout(i,0):i()}}),eM=GP.create({name:"drop",addProseMirrorPlugins(){return[new ex({key:new ox("tiptapDrop"),props:{handleDrop:(t,e,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:n,moved:r})}}})]}}),nM=GP.create({name:"editable",addProseMirrorPlugins(){return[new ex({key:new ox("editable"),props:{editable:()=>this.editor.options.editable}})]}}),rM=new ox("focusEvents"),oM=GP.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:t}=this;return[new ex({key:rM,props:{handleDOMEvents:{focus:(e,n)=>{t.isFocused=!0;const r=t.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,n)=>{t.isFocused=!1;const r=t.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),iM=GP.create({name:"keymap",addKeyboardShortcuts(){const t=()=>this.editor.commands.first(({commands:t})=>[()=>t.undoInputRule(),()=>t.command(({tr:e})=>{const{selection:n,doc:r}=e,{empty:o,$anchor:i}=n,{pos:s,parent:a}=i,l=i.parent.isTextblock&&s>0?e.doc.resolve(s-1):i,c=l.parent.type.spec.isolating,d=i.pos-i.parentOffset,u=c&&1===l.parent.childCount?d===i.pos:Dy.atStart(r).from===s;return!(!o||!a.type.isTextblock||a.textContent.length||!u||u&&"paragraph"===i.parent.type.name)&&t.clearNodes()}),()=>t.deleteSelection(),()=>t.joinBackward(),()=>t.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:t})=>[()=>t.deleteSelection(),()=>t.deleteCurrentNode(),()=>t.joinForward(),()=>t.selectNodeForward()]),n={Enter:()=>this.editor.commands.first(({commands:t})=>[()=>t.newlineInCode(),()=>t.createParagraphNear(),()=>t.liftEmptyBlock(),()=>t.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:t,"Mod-Backspace":t,"Shift-Backspace":t,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},r={...n},o={...n,"Ctrl-h":t,"Alt-Backspace":t,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return Hk()||oS()?o:r},addProseMirrorPlugins(){return[new ex({key:new ox("clearDocument"),appendTransaction:(t,e,n)=>{if(t.some(t=>t.getMeta("composition")))return;const r=t.some(t=>t.docChanged)&&!e.doc.eq(n.doc),o=t.some(t=>t.getMeta("preventClearDocument"));if(!r||o)return;const{empty:i,from:s,to:a}=e.selection,l=Dy.atStart(e.doc).from,c=Dy.atEnd(e.doc).to;if(i||s!==l||a!==c)return;if(!ZS(n.doc))return;const d=n.tr,u=hk({state:n,transaction:d}),{commands:p}=new fk({editor:this.editor,state:u});return p.clearNodes(),d.steps.length?d:void 0}})]}}),sM=GP.create({name:"paste",addProseMirrorPlugins(){return[new ex({key:new ox("tiptapPaste"),props:{handlePaste:(t,e,n)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:n})}}})]}}),aM=GP.create({name:"tabindex",addOptions:()=>({value:void 0}),addProseMirrorPlugins(){return[new ex({key:new ox("tabindex"),props:{attributes:()=>{var t;return this.editor.isEditable||void 0!==this.options.value?{tabindex:null!=(t=this.options.value)?t:"0"}:{}}}})]}}),lM=GP.create({name:"textDirection",addOptions:()=>({direction:void 0}),addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:t}=OS(this.extensions);return[{types:t.filter(t=>"text"!==t.name).map(t=>t.name),attributes:{dir:{default:this.options.direction,parseHTML:t=>{const e=t.getAttribute("dir");return!e||"ltr"!==e&&"rtl"!==e&&"auto"!==e?this.options.direction:e},renderHTML:t=>t.dir?{dir:t.dir}:{}}}}]},addProseMirrorPlugins(){return[new ex({key:new ox("textDirection"),props:{attributes:()=>{const t=this.options.direction;return t?{dir:t}:{}}}})]}}),cM=class t{constructor(t,e,n=!1,r=null){this.currentNode=null,this.actualDepth=null,this.isBlock=n,this.resolvedPos=t,this.editor=e,this.currentNode=r}get name(){return this.node.type.name}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var t;return null!=(t=this.actualDepth)?t:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(t){let e=this.from,n=this.to;if(this.isBlock){if(0===this.content.size)return void console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);e=this.from+1,n=this.to-1}this.editor.commands.insertContentAt({from:e,to:n},t)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(0===this.depth)return null;const e=this.resolvedPos.start(this.resolvedPos.depth-1);return new t(this.resolvedPos.doc.resolve(e),this.editor)}get before(){let e=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.from-3)),new t(e,this.editor)}get after(){let e=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.to+3)),new t(e,this.editor)}get children(){const e=[];return this.node.content.forEach((n,r)=>{const o=n.isBlock&&!n.isTextblock,i=n.isAtom&&!n.isText,s=n.isInline,a=this.pos+r+(i?0:1);if(a<0||a>this.resolvedPos.doc.nodeSize-2)return;const l=this.resolvedPos.doc.resolve(a);if(!o&&!s&&l.depth<=this.depth)return;const c=new t(l,this.editor,o,o||s?n:null);o&&(c.actualDepth=this.depth+1),e.push(c)}),e}get firstChild(){return this.children[0]||null}get lastChild(){const t=this.children;return t[t.length-1]||null}closest(t,e={}){let n=null,r=this.parent;for(;r&&!n;){if(r.node.type.name===t)if(Object.keys(e).length>0){const t=r.node.attrs,n=Object.keys(e);for(let r=0;r<n.length;r+=1){const o=n[r];if(t[o]!==e[o])break}}else n=r;r=r.parent}return n}querySelector(t,e={}){return this.querySelectorAll(t,e,!0)[0]||null}querySelectorAll(t,e={},n=!1){let r=[];if(!this.children||0===this.children.length)return r;const o=Object.keys(e);return this.children.forEach(i=>{n&&r.length>0||(i.node.type.name===t&&o.every(t=>e[t]===i.node.attrs[t])&&r.push(i),n&&r.length>0||(r=r.concat(i.querySelectorAll(t,e,n))))}),r}setAttribute(t){const{tr:e}=this.editor.state;e.setNodeMarkup(this.from,void 0,{...this.node.attrs,...t}),this.editor.view.dispatch(e)}},dM=class extends CP{constructor(t={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.destroyed=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.options={element:"undefined"!=typeof document?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:t})=>{throw t},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:eP,createMappablePosition:nP},this.setOptions(t),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:t,slice:e,moved:n})=>this.options.onDrop(t,e,n)),this.on("paste",({event:t,slice:e})=>this.options.onPaste(t,e)),this.on("delete",this.options.onDelete);const e=this.createDoc(),n=jk(e,this.options.autofocus);this.editorState=Qy.create({doc:e,schema:this.schema,selection:n||void 0}),this.options.element&&this.mount(this.options.element)}mount(t){if("undefined"==typeof document)throw new Error("[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.");this.createView(t),this.emit("mount",{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(!1!==this.options.autofocus&&null!==this.options.autofocus&&this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){const t=this.editorView.dom;(null==t?void 0:t.editor)&&delete t.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{"function"==typeof this.css.remove?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(t){console.warn("Failed to remove CSS element:",t)}this.css=null,this.emit("unmount",{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&"undefined"!=typeof document&&(this.css=EP('.ProseMirror {\n position: relative;\n}\n\n.ProseMirror {\n word-wrap: break-word;\n white-space: pre-wrap;\n white-space: break-spaces;\n -webkit-font-variant-ligatures: none;\n font-variant-ligatures: none;\n font-feature-settings: "liga" 0; /* the above doesn\'t seem to work in Edge */\n}\n\n.ProseMirror [contenteditable="false"] {\n white-space: normal;\n}\n\n.ProseMirror [contenteditable="false"] [contenteditable="true"] {\n white-space: pre-wrap;\n}\n\n.ProseMirror pre {\n white-space: pre-wrap;\n}\n\nimg.ProseMirror-separator {\n display: inline !important;\n border: none !important;\n margin: 0 !important;\n width: 0 !important;\n height: 0 !important;\n}\n\n.ProseMirror-gapcursor {\n display: none;\n pointer-events: none;\n position: absolute;\n margin: 0;\n}\n\n.ProseMirror-gapcursor:after {\n content: "";\n display: block;\n position: absolute;\n top: -2px;\n width: 20px;\n border-top: 1px solid black;\n animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;\n}\n\n@keyframes ProseMirror-cursor-blink {\n to {\n visibility: hidden;\n }\n}\n\n.ProseMirror-hideselection *::selection {\n background: transparent;\n}\n\n.ProseMirror-hideselection *::-moz-selection {\n background: transparent;\n}\n\n.ProseMirror-hideselection * {\n caret-color: transparent;\n}\n\n.ProseMirror-focused .ProseMirror-gapcursor {\n display: block;\n}',this.options.injectNonce))}setOptions(t={}){this.options={...this.options,...t},this.editorView&&this.state&&!this.isDestroyed&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(t,e=!0){this.setOptions({editable:t}),e&&this.emit("update",{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:t=>{this.editorState=t},dispatch:t=>{this.dispatchTransaction(t)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(t,e)=>{if(this.editorView)return this.editorView[e];if("state"===e)return this.editorState;if(e in t)return Reflect.get(t,e);throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${e}']. The editor may not be mounted yet.`)}})}get state(){return this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(t,e){const n=ES(e)?e(t,[...this.state.plugins]):[...this.state.plugins,t],r=this.state.reconfigure({plugins:n});return this.view.updateState(r),r}unregisterPlugin(t){if(this.isDestroyed)return;const e=this.state.plugins;let n=e;if([].concat(t).forEach(t=>{const e="string"==typeof t?`${t}$`:t.key;n=n.filter(t=>!t.key.startsWith(e))}),e.length===n.length)return;const r=this.state.reconfigure({plugins:n});return this.view.updateState(r),r}createExtensionManager(){var t,e,n,r;const o=[...this.options.enableCoreExtensions?[nM,ZP.configure({blockSeparator:null==(e=null==(t=this.options.coreExtensionOptions)?void 0:t.clipboardTextSerializer)?void 0:e.blockSeparator}),QP,oM,iM,aM.configure({value:null==(r=null==(n=this.options.coreExtensionOptions)?void 0:n.tabindex)?void 0:r.value}),eM,sM,tM,lM.configure({direction:this.options.textDirection})].filter(t=>"object"!=typeof this.options.enableCoreExtensions||!1!==this.options.enableCoreExtensions[t.name]):[],...this.options.extensions].filter(t=>["extension","node","mark"].includes(null==t?void 0:t.type));this.extensionManager=new JP(o,this)}createCommandManager(){this.commandManager=new fk({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let t;try{t=vS(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(e){if(!(e instanceof Error&&["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(e.message)))throw e;this.emit("contentError",{editor:this,error:e,disableCollaboration:()=>{"collaboration"in this.storage&&"object"==typeof this.storage.collaboration&&this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(t=>"collaboration"!==t.name),this.createExtensionManager()}}),t=vS(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}return t}createView(t){const{editorProps:e,enableExtensionDispatchTransaction:n}=this.options,r=e.dispatchTransaction||this.dispatchTransaction.bind(this),o=n?this.extensionManager.dispatchTransaction(r):r,i=e.transformPastedHTML,s=this.extensionManager.transformPastedHTML(i);this.editorView=new qv(t,{...e,attributes:{role:"textbox",...null==e?void 0:e.attributes},dispatchTransaction:o,transformPastedHTML:s,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const a=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(a),this.prependClass(),this.injectCSS();this.view.dom.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(t){this.isCapturingTransaction=!0,t(),this.isCapturingTransaction=!1;const e=this.capturedTransaction;return this.capturedTransaction=null,e}dispatchTransaction(t){if(this.view.isDestroyed)return;if(this.isCapturingTransaction)return this.capturedTransaction?void t.steps.forEach(t=>{var e;return null==(e=this.capturedTransaction)?void 0:e.step(t)}):void(this.capturedTransaction=t);const{state:e,transactions:n}=this.state.applyTransaction(t),r=!this.state.selection.eq(e.selection),o=n.includes(t),i=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:t,nextState:e}),!o)return;this.view.updateState(e),this.emit("transaction",{editor:this,transaction:t,appendedTransactions:n.slice(1)}),r&&this.emit("selectionUpdate",{editor:this,transaction:t});const s=n.findLast(t=>t.getMeta("focus")||t.getMeta("blur")),a=null==s?void 0:s.getMeta("focus"),l=null==s?void 0:s.getMeta("blur");a&&this.emit("focus",{editor:this,event:a.event,transaction:s}),l&&this.emit("blur",{editor:this,event:l.event,transaction:s}),t.getMeta("preventUpdate")||!n.some(t=>t.docChanged)||i.doc.eq(e.doc)||this.emit("update",{editor:this,transaction:t,appendedTransactions:n.slice(1)})}getAttributes(t){return _S(this.state,t)}isActive(t,e){const n="string"==typeof t?t:null,r="string"==typeof t?e:t;return function(t,e,n={}){if(!e)return sS(t,null,n)||YS(t,null,n);const r=uS(e,t.schema);return"node"===r?sS(t,e,n):"mark"===r&&YS(t,e,n)}(this.state,n,r)}getJSON(){return this.state.doc.toJSON()}getHTML(){return CS(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:e="\n\n",textSerializers:n={}}=t||{};return function(t,e){return WS(t,{from:0,to:t.content.size},e)}(this.state.doc,{blockSeparator:e,textSerializers:{...HS(this.schema),...n}})}get isEmpty(){return ZS(this.state.doc)}destroy(){this.destroyed||(this.destroyed=!0,this.emit("destroy"),this.unmount(),this.removeAllListeners(),this.extensionManager.destroy(),this.extensionManager=null,this.schema=null,this.commandManager=null,this.extensionStorage={})}get isDestroyed(){var t,e;return null==(e=null==(t=this.editorView)?void 0:t.isDestroyed)||e}$node(t,e){var n;return(null==(n=this.$doc)?void 0:n.querySelector(t,e))||null}$nodes(t,e){var n;return(null==(n=this.$doc)?void 0:n.querySelectorAll(t,e))||null}$pos(t){const e=this.state.doc.resolve(t),n=t>0&&e.nodeAfter&&!e.nodeAfter.isText?e.nodeAfter:null;return new cM(e,this,!1,n)}get $doc(){return this.$pos(0)}};function uM(t){return new HP({find:t.find,handler:({state:e,range:n,match:r})=>{const o=AS(t.getAttributes,void 0,r);if(!1===o||null===o)return null;const{tr:i}=e,s=r[r.length-1],a=r[0];if(s){const r=a.search(/\S/),l=n.from+a.indexOf(s),c=l+s.length;if(KS(n.from,n.to,e.doc).filter(e=>e.mark.type.excluded.find(n=>n===t.type&&n!==e.mark.type)).filter(t=>t.to>l).length)return null;c<n.to&&i.delete(c,n.to),l>n.from&&i.delete(n.from+r,l);const d=n.from+r+s.length;i.addMark(n.from+r,d,t.type.create(o||{})),i.removeStoredMark(t.type)}},undoable:t.undoable})}function pM(t){return new HP({find:t.find,handler:({state:e,range:n,match:r})=>{const o=e.doc.resolve(n.from),i=AS(t.getAttributes,void 0,r)||{};if(!o.node(-1).canReplaceWith(o.index(-1),o.indexAfter(-1),t.type))return null;e.tr.delete(n.from,n.to).setBlockType(n.from,n.from,t.type,i)},undoable:t.undoable})}function hM(t){return new HP({find:t.find,handler:({state:e,range:n,match:r,chain:o})=>{const i=AS(t.getAttributes,void 0,r)||{},s=e.tr.delete(n.from,n.to),a=s.doc.resolve(n.from).blockRange(),l=a&&uy(a,t.type,i);if(!l)return null;if(s.wrap(a,l),t.keepMarks&&t.editor){const{selection:n,storedMarks:r}=e,{splittableMarks:o}=t.editor.extensionManager,i=r||n.$to.parentOffset&&n.$from.marks();if(i){const t=i.filter(t=>o.includes(t.type.name));s.ensureMarks(t)}}if(t.keepAttributes){const e="bulletList"===t.type.name||"orderedList"===t.type.name?"listItem":"taskList";o().updateAttributes(e,i).run()}const c=s.doc.resolve(n.from-1).nodeBefore;c&&c.type===t.type&&gy(s.doc,n.from-1)&&(!t.joinPredicate||t.joinPredicate(r,c))&&s.join(n.from-1)},undoable:t.undoable})}var fM=class t extends UP{constructor(){super(...arguments),this.type="node"}static create(e={}){return new t("function"==typeof e?e():e)}configure(t){return super.configure(t)}extend(t){const e="function"==typeof t?t():t;return super.extend(e)}};function mM(t){return new KP({find:t.find,handler:({state:e,range:n,match:r,pasteEvent:o})=>{const i=AS(t.getAttributes,void 0,r,o);if(!1===i||null===i)return null;const{tr:s}=e,a=r[r.length-1],l=r[0];let c=n.to;if(a){const o=l.search(/\S/),d=n.from+l.indexOf(a),u=d+a.length;if(KS(n.from,n.to,e.doc).filter(e=>e.mark.type.excluded.find(n=>n===t.type&&n!==e.mark.type)).filter(t=>t.to>d).length)return null;u<n.to&&s.delete(u,n.to),d>n.from&&s.delete(n.from+o,d),c=n.from+o+a.length,s.addMark(n.from+o,c,t.type.create(i||{})),void 0!==r.index&&void 0!==r.input&&r.index+r[0].length>=r.input.length||s.removeStoredMark(t.type)}}})}var{getOwnPropertyNames:gM,getOwnPropertySymbols:yM}=Object,{hasOwnProperty:xM}=Object.prototype;function wM(t,e){return function(n,r,o){return t(n,r,o)&&e(n,r,o)}}function bM(t){return function(e,n,r){if(!e||!n||"object"!=typeof e||"object"!=typeof n)return t(e,n,r);const{cache:o}=r,i=o.get(e),s=o.get(n);if(i&&s)return i===n&&s===e;o.set(e,n),o.set(n,e);const a=t(e,n,r);return o.delete(e),o.delete(n),a}}function vM(t){return gM(t).concat(yM(t))}var kM=Object.hasOwn||((t,e)=>xM.call(t,e));function SM(t,e){return t===e||!t&&!e&&t!=t&&e!=e}var{getOwnPropertyDescriptor:PM,keys:MM}=Object;function IM(t,e){return t.byteLength===e.byteLength&&FM(new Uint8Array(t),new Uint8Array(e))}function TM(t,e,n){let r=t.length;if(e.length!==r)return!1;for(;r-- >0;)if(!n.equals(t[r],e[r],r,r,t,e,n))return!1;return!0}function CM(t,e){return t.byteLength===e.byteLength&&FM(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}function EM(t,e){return SM(t.getTime(),e.getTime())}function AM(t,e){return t.name===e.name&&t.message===e.message&&t.cause===e.cause&&t.stack===e.stack}function OM(t,e){return t===e}function NM(t,e,n){const r=t.size;if(r!==e.size)return!1;if(!r)return!0;const o=new Array(r),i=t.entries();let s,a,l=0;for(;(s=i.next())&&!s.done;){const r=e.entries();let i=!1,c=0;for(;(a=r.next())&&!a.done;){if(o[c]){c++;continue}const r=s.value,d=a.value;if(n.equals(r[0],d[0],l,c,t,e,n)&&n.equals(r[1],d[1],r[0],d[0],t,e,n)){i=o[c]=!0;break}c++}if(!i)return!1;l++}return!0}var RM=SM;function LM(t,e,n){const r=MM(t);let o=r.length;if(MM(e).length!==o)return!1;for(;o-- >0;)if(!WM(t,e,n,r[o]))return!1;return!0}function $M(t,e,n){const r=vM(t);let o,i,s,a=r.length;if(vM(e).length!==a)return!1;for(;a-- >0;){if(o=r[a],!WM(t,e,n,o))return!1;if(i=PM(t,o),s=PM(e,o),(i||s)&&(!i||!s||i.configurable!==s.configurable||i.enumerable!==s.enumerable||i.writable!==s.writable))return!1}return!0}function DM(t,e){return SM(t.valueOf(),e.valueOf())}function BM(t,e){return t.source===e.source&&t.flags===e.flags}function zM(t,e,n){const r=t.size;if(r!==e.size)return!1;if(!r)return!0;const o=new Array(r),i=t.values();let s,a;for(;(s=i.next())&&!s.done;){const r=e.values();let i=!1,l=0;for(;(a=r.next())&&!a.done;){if(!o[l]&&n.equals(s.value,a.value,s.value,a.value,t,e,n)){i=o[l]=!0;break}l++}if(!i)return!1}return!0}function FM(t,e){let n=t.byteLength;if(e.byteLength!==n||t.byteOffset!==e.byteOffset)return!1;for(;n-- >0;)if(t[n]!==e[n])return!1;return!0}function jM(t,e){return t.hostname===e.hostname&&t.pathname===e.pathname&&t.protocol===e.protocol&&t.port===e.port&&t.hash===e.hash&&t.username===e.username&&t.password===e.password}function WM(t,e,n,r){return!("_owner"!==r&&"__o"!==r&&"__v"!==r||!t.$$typeof&&!e.$$typeof)||kM(e,r)&&n.equals(t[r],e[r],r,r,t,e,n)}var HM={"[object Int8Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Int16Array]":!0,"[object Uint16Array]":!0,"[object Int32Array]":!0,"[object Uint32Array]":!0,"[object Float16Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0,"[object BigInt64Array]":!0,"[object BigUint64Array]":!0},_M=Object.prototype.toString;function UM({areArrayBuffersEqual:t,areArraysEqual:e,areDataViewsEqual:n,areDatesEqual:r,areErrorsEqual:o,areFunctionsEqual:i,areMapsEqual:s,areNumbersEqual:a,areObjectsEqual:l,arePrimitiveWrappersEqual:c,areRegExpsEqual:d,areSetsEqual:u,areTypedArraysEqual:p,areUrlsEqual:h,unknownTagComparators:f}){return function(m,g,y){if(m===g)return!0;if(null==m||null==g)return!1;const x=typeof m;if(x!==typeof g)return!1;if("object"!==x)return"number"===x?a(m,g,y):"function"===x&&i(m,g,y);const w=m.constructor;if(w!==g.constructor)return!1;if(w===Object)return l(m,g,y);if(Array.isArray(m))return e(m,g,y);if(w===Date)return r(m,g,y);if(w===RegExp)return d(m,g,y);if(w===Map)return s(m,g,y);if(w===Set)return u(m,g,y);const b=_M.call(m);if("[object Date]"===b)return r(m,g,y);if("[object RegExp]"===b)return d(m,g,y);if("[object Map]"===b)return s(m,g,y);if("[object Set]"===b)return u(m,g,y);if("[object Object]"===b)return"function"!=typeof m.then&&"function"!=typeof g.then&&l(m,g,y);if("[object URL]"===b)return h(m,g,y);if("[object Error]"===b)return o(m,g,y);if("[object Arguments]"===b)return l(m,g,y);if(HM[b])return p(m,g,y);if("[object ArrayBuffer]"===b)return t(m,g,y);if("[object DataView]"===b)return n(m,g,y);if("[object Boolean]"===b||"[object Number]"===b||"[object String]"===b)return c(m,g,y);if(f){let t=f[b];if(!t){const e=null!=(v=m)?v[Symbol.toStringTag]:void 0;e&&(t=f[e])}if(t)return t(m,g,y)}var v;return!1}}var VM=KM();KM({strict:!0}),KM({circular:!0}),KM({circular:!0,strict:!0}),KM({createInternalComparator:()=>SM}),KM({strict:!0,createInternalComparator:()=>SM}),KM({circular:!0,createInternalComparator:()=>SM}),KM({circular:!0,createInternalComparator:()=>SM,strict:!0});function KM(t={}){const{circular:e=!1,createInternalComparator:n,createState:r,strict:o=!1}=t,i=UM(function({circular:t,createCustomConfig:e,strict:n}){let r={areArrayBuffersEqual:IM,areArraysEqual:n?$M:TM,areDataViewsEqual:CM,areDatesEqual:EM,areErrorsEqual:AM,areFunctionsEqual:OM,areMapsEqual:n?wM(NM,$M):NM,areNumbersEqual:RM,areObjectsEqual:n?$M:LM,arePrimitiveWrappersEqual:DM,areRegExpsEqual:BM,areSetsEqual:n?wM(zM,$M):zM,areTypedArraysEqual:n?wM(FM,$M):FM,areUrlsEqual:jM,unknownTagComparators:void 0};if(e&&(r=Object.assign({},r,e(r))),t){const t=bM(r.areArraysEqual),e=bM(r.areMapsEqual),n=bM(r.areObjectsEqual),o=bM(r.areSetsEqual);r=Object.assign({},r,{areArraysEqual:t,areMapsEqual:e,areObjectsEqual:n,areSetsEqual:o})}return r}(t));return function({circular:t,comparator:e,createState:n,equals:r,strict:o}){if(n)return function(i,s){const{cache:a=(t?new WeakMap:void 0),meta:l}=n();return e(i,s,{cache:a,equals:r,meta:l,strict:o})};if(t)return function(t,n){return e(t,n,{cache:new WeakMap,equals:r,meta:void 0,strict:o})};const i={cache:void 0,equals:r,meta:void 0,strict:o};return function(t,n){return e(t,n,i)}}({circular:e,comparator:i,createState:r,equals:n?n(i):(s=i,function(t,e,n,r,o,i,a){return s(t,e,a)}),strict:o});var s}var qM=T(t=>{var e=Cm(),n=Om();var r="function"==typeof Object.is?Object.is:function(t,e){return t===e&&(0!==t||1/t==1/e)||t!=t&&e!=e},o=n.useSyncExternalStore,i=e.useRef,s=e.useEffect,a=e.useMemo,l=e.useDebugValue;t.useSyncExternalStoreWithSelector=function(t,e,n,c,d){var u=i(null);if(null===u.current){var p={hasValue:!1,value:null};u.current=p}else p=u.current;u=a(function(){function t(t){if(!s){if(s=!0,o=t,t=c(t),void 0!==d&&p.hasValue){var e=p.value;if(d(e,t))return i=e}return i=t}if(e=i,r(o,t))return e;var n=c(t);return void 0!==d&&d(e,n)?(o=t,e):(o=t,i=n)}var o,i,s=!1,a=void 0===n?null:n;return[function(){return t(e())},null===a?void 0:function(){return t(a())}]},[e,n,c,d]);var h=o(t,u[0],u[1]);return s(function(){p.hasValue=!0,p.value=h},[h]),l(h),h}}),XM=T(t=>{"production"!==process.env.NODE_ENV&&function(){"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var e=Cm(),n=Om(),r="function"==typeof Object.is?Object.is:function(t,e){return t===e&&(0!==t||1/t==1/e)||t!=t&&e!=e},o=n.useSyncExternalStore,i=e.useRef,s=e.useEffect,a=e.useMemo,l=e.useDebugValue;t.useSyncExternalStoreWithSelector=function(t,e,n,c,d){var u=i(null);if(null===u.current){var p={hasValue:!1,value:null};u.current=p}else p=u.current;u=a(function(){function t(t){if(!s){if(s=!0,o=t,t=c(t),void 0!==d&&p.hasValue){var e=p.value;if(d(e,t))return i=e}return i=t}if(e=i,r(o,t))return e;var n=c(t);return void 0!==d&&d(e,n)?(o=t,e):(o=t,i=n)}var o,i,s=!1,a=void 0===n?null:n;return[function(){return t(e())},null===a?void 0:function(){return t(a())}]},[e,n,c,d]);var h=o(t,u[0],u[1]);return s(function(){p.hasValue=!0,p.value=h},[h]),l(h),h},"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()}),YM=T((t,e)=>{"production"===process.env.NODE_ENV?e.exports=qM():e.exports=XM()})(),JM=(...t)=>e=>{t.forEach(t=>{"function"==typeof t?t(e):t&&(t.current=e)})},GM=({contentComponent:t})=>{const e=(0,dk.useSyncExternalStore)(t.subscribe,t.getSnapshot,t.getServerSnapshot);
39
- return l(a,{children:Object.values(e)})};var ZM=class extends u.Component{constructor(t){super(t),this.editorContentRef=u.createRef()}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){var t;const e=this.props.editor;if(e&&!e.isDestroyed&&(null==(t=e.view.dom)?void 0:t.parentNode)){if(e.contentComponent)return;const t=this.editorContentRef.current;t.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:t}),e.contentComponent=function(){const t=new Set;let e={};return{subscribe:e=>(t.add(e),()=>{t.delete(e)}),getSnapshot:()=>e,getServerSnapshot:()=>e,setRenderer(n,r){e={...e,[n]:M.createPortal(r.reactElement,r.element,n)},t.forEach(t=>t())},removeRenderer(n){const r={...e};delete r[n],e=r,t.forEach(t=>t())}}}(),e.createNodeViews(),e.isEditorContentInitialized=!0,this.forceUpdate()}}componentWillUnmount(){var t;const e=this.props.editor;if(e){e.isEditorContentInitialized=!1,e.isDestroyed||e.view.setProps({nodeViews:{}}),e.contentComponent=null;try{if(!(null==(t=e.view.dom)?void 0:t.parentNode))return;const n=document.createElement("div");n.append(...e.view.dom.parentNode.childNodes),e.setOptions({element:n})}catch{}}}render(){const{editor:t,innerRef:e,...n}=this.props;
40
- return c(a,{children:[l("div",{ref:JM(e,this.editorContentRef),...n}),(null==t?void 0:t.contentComponent)&&l(GM,{contentComponent:t.contentComponent})]})}},QM=f((t,e)=>{const n=u.useMemo(()=>Math.floor(4294967295*Math.random()).toString(),[t.editor]);return u.createElement(ZM,{key:n,innerRef:e,...t})}),tI=u.memo(QM),eI="undefined"!=typeof window?b:w,nI=class{constructor(t){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=t,this.lastSnapshot={editor:t,transactionNumber:0},this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.watch=this.watch.bind(this),this.subscribe=this.subscribe.bind(this)}getSnapshot(){return this.transactionNumber===this.lastTransactionNumber||(this.lastTransactionNumber=this.transactionNumber,this.lastSnapshot={editor:this.editor,transactionNumber:this.transactionNumber}),this.lastSnapshot}getServerSnapshot(){return{editor:null,transactionNumber:0}}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}watch(t){if(this.editor=t,this.editor){const t=()=>{this.transactionNumber+=1,this.subscribers.forEach(t=>t())},e=this.editor;return e.on("transaction",t),()=>{e.off("transaction",t)}}}};var rI="production"!==process.env.NODE_ENV,oI="undefined"==typeof window,iI=oI||Boolean("undefined"!=typeof window&&window.next),sI=class t{constructor(t){this.editor=null,this.subscriptions=new Set,this.isComponentMounted=!1,this.previousDeps=null,this.instanceId="",this.options=t,this.subscriptions=new Set,this.setEditor(this.getInitialEditor()),this.scheduleDestroy(),this.getEditor=this.getEditor.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.subscribe=this.subscribe.bind(this),this.refreshEditorInstance=this.refreshEditorInstance.bind(this),this.scheduleDestroy=this.scheduleDestroy.bind(this),this.onRender=this.onRender.bind(this),this.createEditor=this.createEditor.bind(this)}setEditor(t){this.editor=t,this.instanceId=Math.random().toString(36).slice(2,9),this.subscriptions.forEach(t=>t())}getInitialEditor(){const t=this.options.current.immediatelyRender;let e=null==t||t;return oI?(e&&rI&&console.warn("SSR detected. `immediatelyRender` has been set to false to avoid hydration mismatches"),e=!1):iI&&void 0===t&&(e=!1,rI&&console.warn("Next.js detected. `immediatelyRender` defaults to false to avoid hydration mismatches. Pass `immediatelyRender: true` explicitly if you are rendering the editor only on the client.")),e?this.createEditor():null}createEditor(){return new dM({...this.options.current,onBeforeCreate:(...t)=>{var e,n;return null==(n=(e=this.options.current).onBeforeCreate)?void 0:n.call(e,...t)},onBlur:(...t)=>{var e,n;return null==(n=(e=this.options.current).onBlur)?void 0:n.call(e,...t)},onCreate:(...t)=>{var e,n;return null==(n=(e=this.options.current).onCreate)?void 0:n.call(e,...t)},onDestroy:(...t)=>{var e,n;return null==(n=(e=this.options.current).onDestroy)?void 0:n.call(e,...t)},onFocus:(...t)=>{var e,n;return null==(n=(e=this.options.current).onFocus)?void 0:n.call(e,...t)},onSelectionUpdate:(...t)=>{var e,n;return null==(n=(e=this.options.current).onSelectionUpdate)?void 0:n.call(e,...t)},onTransaction:(...t)=>{var e,n;return null==(n=(e=this.options.current).onTransaction)?void 0:n.call(e,...t)},onUpdate:(...t)=>{var e,n;return null==(n=(e=this.options.current).onUpdate)?void 0:n.call(e,...t)},onContentError:(...t)=>{var e,n;return null==(n=(e=this.options.current).onContentError)?void 0:n.call(e,...t)},onDrop:(...t)=>{var e,n;return null==(n=(e=this.options.current).onDrop)?void 0:n.call(e,...t)},onPaste:(...t)=>{var e,n;return null==(n=(e=this.options.current).onPaste)?void 0:n.call(e,...t)},onDelete:(...t)=>{var e,n;return null==(n=(e=this.options.current).onDelete)?void 0:n.call(e,...t)}})}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(t){return this.subscriptions.add(t),()=>{this.subscriptions.delete(t)}}static compareOptions(t,e){return Object.keys(t).every(n=>!!["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(n)||("extensions"===n&&t.extensions&&e.extensions?t.extensions.length===e.extensions.length&&t.extensions.every((t,n)=>{var r;return t===(null==(r=e.extensions)?void 0:r[n])}):t[n]===e[n]))}onRender(e){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&0===e.length?t.compareOptions(this.options.current,this.editor.options)||this.editor.setOptions({...this.options.current,editable:this.editor.isEditable}):this.refreshEditorInstance(e),()=>{this.isComponentMounted=!1,this.scheduleDestroy()})}refreshEditorInstance(t){if(this.editor&&!this.editor.isDestroyed){if(null===this.previousDeps)return void(this.previousDeps=t);if(this.previousDeps.length===t.length&&this.previousDeps.every((e,n)=>e===t[n]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=t}scheduleDestroy(){const t=this.instanceId,e=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{this.isComponentMounted&&this.instanceId===t?e&&e.setOptions(this.options.current):e&&!e.isDestroyed&&(e.destroy(),this.instanceId===t&&this.setEditor(null))},1)}};function aI(t={},e=[]){const n=k(t);n.current=t;const[r]=S(()=>new sI(n)),o=(0,dk.useSyncExternalStore)(r.subscribe,r.getEditor,r.getServerSnapshot);return x(o),w(r.onRender(e)),function(t){var e;const[n]=S(()=>new nI(t.editor)),r=(0,YM.useSyncExternalStoreWithSelector)(n.subscribe,n.getSnapshot,n.getServerSnapshot,t.selector,null!=(e=t.equalityFn)?e:VM);eI(()=>n.watch(t.editor),[t.editor,n]),x(r)}({editor:o,selector:({transactionNumber:e})=>!1===t.shouldRerenderOnTransaction||void 0===t.shouldRerenderOnTransaction?null:t.immediatelyRender&&0===e?0:e+1}),o}var lI=p({editor:null}),cI=(lI.Consumer,p({onDragStart:()=>{},nodeViewContentChildren:void 0,nodeViewContentRef:()=>{}})),dI=(u.forwardRef((t,e)=>{const{onDragStart:n}=y(cI);
41
- return l(t.as||"div",{...t,ref:e,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...t.style}})}),u.createContext({markViewContentRef:()=>{}}),p({get editor(){throw new Error("useTiptap must be used within a <Tiptap> provider")}}));dI.displayName="TiptapContext";function uI({children:t,...e}){const n="editor"in e?e.editor:e.instance;if(!n)throw new Error("Tiptap: An editor instance is required. Pass a non-null `editor` prop.");const r=v(()=>({editor:n}),[n]),o=v(()=>({editor:n}),[n]);
42
- return l(lI.Provider,{value:o,children:l(dI.Provider,{value:r,children:t})})}function pI({...t}){const{editor:e}=y(dI);
43
- return l(tI,{editor:e,...t})}uI.displayName="Tiptap",pI.displayName="Tiptap.Content";Object.assign(uI,{Content:pI});var hI=(t,e)=>{if("slot"===t)return 0;if(t instanceof Function)return t(e);const{children:n,...r}=null!=e?e:{};if("svg"===t)throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[t,r,n]},fI=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,mI=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,gI=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,yI=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,xI=VP.create({name:"bold",addOptions:()=>({HTMLAttributes:{}}),parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:t=>"normal"!==t.style.fontWeight&&null},{style:"font-weight=400",clearMark:t=>t.type.name===this.name},{style:"font-weight",getAttrs:t=>/^(bold(er)?|[5-9]\d{2,})$/.test(t)&&null}]},renderHTML({HTMLAttributes:t}){
44
- return hI("strong",{...LS(this.options.HTMLAttributes,t),children:hI("slot",{})})},markdownTokenName:"strong",parseMarkdown:(t,e)=>e.applyMark("bold",e.parseInline(t.tokens||[])),markdownOptions:{htmlReopen:{open:"<strong>",close:"</strong>"}},renderMarkdown:(t,e)=>`**${e.renderChildren(t)}**`,addCommands(){return{setBold:()=>({commands:t})=>t.setMark(this.name),toggleBold:()=>({commands:t})=>t.toggleMark(this.name),unsetBold:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[uM({find:fI,type:this.type}),uM({find:gI,type:this.type})]},addPasteRules(){return[mM({find:mI,type:this.type}),mM({find:yI,type:this.type})]}}),wI=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,bI=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,vI=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,kI=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,SI=VP.create({name:"italic",addOptions:()=>({HTMLAttributes:{}}),parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:t=>"normal"!==t.style.fontStyle&&null},{style:"font-style=normal",clearMark:t=>t.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:t}){return["em",LS(this.options.HTMLAttributes,t),0]},addCommands(){return{setItalic:()=>({commands:t})=>t.setMark(this.name),toggleItalic:()=>({commands:t})=>t.toggleMark(this.name),unsetItalic:()=>({commands:t})=>t.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(t,e)=>e.applyMark("italic",e.parseInline(t.tokens||[])),markdownOptions:{htmlReopen:{open:"<em>",close:"</em>"}},renderMarkdown:(t,e)=>`*${e.renderChildren(t)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[uM({find:wI,type:this.type}),uM({find:vI,type:this.type})]},addPasteRules(){return[mM({find:bI,type:this.type}),mM({find:kI,type:this.type})]}}),PI="numeric",MI="ascii",II="alpha",TI="asciinumeric",CI="alphanumeric",EI="domain",AI="emoji",OI="scheme",NI="slashscheme",RI="whitespace";function LI(t,e){return t in e||(e[t]=[]),e[t]}function $I(t,e,n){e[PI]&&(e[TI]=!0,e[CI]=!0),e[MI]&&(e[TI]=!0,e[II]=!0),e[TI]&&(e[CI]=!0),e[II]&&(e[CI]=!0),e[CI]&&(e[EI]=!0),e[AI]&&(e[EI]=!0);for(const r in e){const e=LI(r,n);e.indexOf(t)<0&&e.push(t)}}function DI(t=null){this.j={},this.jr=[],this.jd=null,this.t=t}DI.groups={},DI.prototype={accepts(){return!!this.t},go(t){const e=this,n=e.j[t];if(n)return n;for(let r=0;r<e.jr.length;r++){const n=e.jr[r][0],o=e.jr[r][1];if(o&&n.test(t))return o}return e.jd},has(t,e=!1){return e?t in this.j:!!this.go(t)},ta(t,e,n,r){for(let o=0;o<t.length;o++)this.tt(t[o],e,n,r)},tr(t,e,n,r){let o;return r=r||DI.groups,e&&e.j?o=e:(o=new DI(e),n&&r&&$I(e,n,r)),this.jr.push([t,o]),o},ts(t,e,n,r){let o=this;const i=t.length;if(!i)return o;for(let s=0;s<i-1;s++)o=o.tt(t[s]);return o.tt(t[i-1],e,n,r)},tt(t,e,n,r){r=r||DI.groups;const o=this;if(e&&e.j)return o.j[t]=e,e;const i=e;let s,a=o.go(t);return a?(s=new DI,Object.assign(s.j,a.j),s.jr.push.apply(s.jr,a.jr),s.jd=a.jd,s.t=a.t):s=new DI,i&&(r&&(s.t&&"string"==typeof s.t?$I(i,Object.assign(function(t,e){const n={};for(const r in e)e[r].indexOf(t)>=0&&(n[r]=!0);return n}(s.t,r),n),r):n&&$I(i,n,r)),s.t=i),o.j[t]=s,s}};var BI=(t,e,n,r,o)=>t.ta(e,n,r,o),zI=(t,e,n,r,o)=>t.tr(e,n,r,o),FI=(t,e,n,r,o)=>t.ts(e,n,r,o),jI=(t,e,n,r,o)=>t.tt(e,n,r,o),WI="WORD",HI="UWORD",_I="ASCIINUMERICAL",UI="ALPHANUMERICAL",VI="LOCALHOST",KI="TLD",qI="UTLD",XI="SCHEME",YI="SLASH_SCHEME",JI="NUM",GI="WS",ZI="NL",QI="OPENBRACE",tT="CLOSEBRACE",eT="OPENBRACKET",nT="CLOSEBRACKET",rT="OPENPAREN",oT="CLOSEPAREN",iT="OPENANGLEBRACKET",sT="CLOSEANGLEBRACKET",aT="FULLWIDTHLEFTPAREN",lT="FULLWIDTHRIGHTPAREN",cT="LEFTCORNERBRACKET",dT="RIGHTCORNERBRACKET",uT="LEFTWHITECORNERBRACKET",pT="RIGHTWHITECORNERBRACKET",hT="FULLWIDTHLESSTHAN",fT="FULLWIDTHGREATERTHAN",mT="AMPERSAND",gT="APOSTROPHE",yT="ASTERISK",xT="AT",wT="BACKSLASH",bT="BACKTICK",vT="CARET",kT="COLON",ST="COMMA",PT="DOLLAR",MT="DOT",IT="EQUALS",TT="EXCLAMATION",CT="HYPHEN",ET="PERCENT",AT="PIPE",OT="PLUS",NT="POUND",RT="QUERY",LT="QUOTE",$T="FULLWIDTHMIDDLEDOT",DT="SEMI",BT="SLASH",zT="TILDE",FT="UNDERSCORE",jT="EMOJI",WT="SYM",HT=Object.freeze({__proto__:null,ALPHANUMERICAL:UI,AMPERSAND:mT,APOSTROPHE:gT,ASCIINUMERICAL:_I,ASTERISK:yT,AT:xT,BACKSLASH:wT,BACKTICK:bT,CARET:vT,CLOSEANGLEBRACKET:sT,CLOSEBRACE:tT,CLOSEBRACKET:nT,CLOSEPAREN:oT,COLON:kT,COMMA:ST,DOLLAR:PT,DOT:MT,EMOJI:jT,EQUALS:IT,EXCLAMATION:TT,FULLWIDTHGREATERTHAN:fT,FULLWIDTHLEFTPAREN:aT,FULLWIDTHLESSTHAN:hT,FULLWIDTHMIDDLEDOT:$T,FULLWIDTHRIGHTPAREN:lT,HYPHEN:CT,LEFTCORNERBRACKET:cT,LEFTWHITECORNERBRACKET:uT,LOCALHOST:VI,NL:ZI,NUM:JI,OPENANGLEBRACKET:iT,OPENBRACE:QI,OPENBRACKET:eT,OPENPAREN:rT,PERCENT:ET,PIPE:AT,PLUS:OT,POUND:NT,QUERY:RT,QUOTE:LT,RIGHTCORNERBRACKET:dT,RIGHTWHITECORNERBRACKET:pT,SCHEME:XI,SEMI:DT,SLASH:BT,SLASH_SCHEME:YI,SYM:WT,TILDE:zT,TLD:KI,UNDERSCORE:FT,UTLD:qI,UWORD:HI,WORD:WI,WS:GI}),_T=/[a-z]/,UT=/\p{L}/u,VT=/\p{Emoji}/u,KT=/\d/,qT=/\s/,XT=null,YT=null;function JT(t,e){const n=function(t){const e=[],n=t.length;let r=0;for(;r<n;){let o,i=t.charCodeAt(r),s=i<55296||i>56319||r+1===n||(o=t.charCodeAt(r+1))<56320||o>57343?t[r]:t.slice(r,r+2);e.push(s),r+=s.length}return e}(e.replace(/[A-Z]/g,t=>t.toLowerCase())),r=n.length,o=[];let i=0,s=0;for(;s<r;){let a=t,l=null,c=0,d=null,u=-1,p=-1;for(;s<r&&(l=a.go(n[s]));)a=l,a.accepts()?(u=0,p=0,d=a):u>=0&&(u+=n[s].length,p++),c+=n[s].length,i+=n[s].length,s++;i-=u,s-=p,c-=u,o.push({t:d.t,v:e.slice(i-c,i),s:i-c,e:i})}return o}function GT(t,e,n,r,o){let i;const s=e.length;for(let a=0;a<s-1;a++){const n=e[a];t.j[n]?i=t.j[n]:(i=new DI(r),i.jr=o.slice(),t.j[n]=i),t=i}return i=new DI(n),i.jr=o.slice(),t.j[e[s-1]]=i,i}function ZT(t){const e=[],n=[];let r=0;for(;r<t.length;){let o=0;for(;"0123456789".indexOf(t[r+o])>=0;)o++;if(o>0){e.push(n.join(""));for(let e=parseInt(t.substring(r,r+o),10);e>0;e--)n.pop();r+=o}else n.push(t[r]),r++}return e}var QT={defaultProtocol:"http",events:null,format:eC,formatHref:eC,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function tC(t,e=null){let n=Object.assign({},QT);t&&(n=Object.assign(n,t instanceof tC?t.o:t));const r=n.ignoreTags,o=[];for(let i=0;i<r.length;i++)o.push(r[i].toUpperCase());this.o=n,e&&(this.defaultRender=e),this.ignoreTags=o}function eC(t){return t}function nC(t,e){this.t="token",this.v=t,this.tk=e}function rC(t,e){class n extends nC{constructor(e,n){super(e,n),this.t=t}}for(const r in e)n.prototype[r]=e[r];return n.t=t,n}tC.prototype={o:QT,ignoreTags:[],defaultRender:t=>t,check(t){return this.get("validate",t.toString(),t)},get(t,e,n){const r=null!=e;let o=this.o[t];return o?("object"==typeof o?(o=n.t in o?o[n.t]:QT[t],"function"==typeof o&&r&&(o=o(e,n))):"function"==typeof o&&r&&(o=o(e,n.t,n)),o):o},getObj(t,e,n){let r=this.o[t];return"function"==typeof r&&null!=e&&(r=r(e,n.t,n)),r},render(t){const e=t.render(this);return(this.get("render",null,t)||this.defaultRender)(e,t.t,t)}},nC.prototype={isLink:!1,toString(){return this.v},toHref(t){return this.toString()},toFormattedString(t){const e=this.toString(),n=t.get("truncate",e,this),r=t.get("format",e,this);return n&&r.length>n?r.substring(0,n)+"…":r},toFormattedHref(t){return t.get("formatHref",this.toHref(t.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(t=QT.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(t),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(t){return{type:this.t,value:this.toFormattedString(t),isLink:this.isLink,href:this.toFormattedHref(t),start:this.startIndex(),end:this.endIndex()}},validate(t){return t.get("validate",this.toString(),this)},render(t){const e=this,n=this.toHref(t.get("defaultProtocol")),r=t.get("formatHref",n,this),o=t.get("tagName",n,e),i=this.toFormattedString(t),s={},a=t.get("className",n,e),l=t.get("target",n,e),c=t.get("rel",n,e),d=t.getObj("attributes",n,e),u=t.getObj("events",n,e);return s.href=r,a&&(s.class=a),l&&(s.target=l),c&&(s.rel=c),d&&Object.assign(s,d),{tagName:o,attributes:s,content:i,eventListeners:u}}};var oC=rC("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),iC=rC("text"),sC=rC("nl"),aC=rC("url",{isLink:!0,toHref(t=QT.defaultProtocol){return this.hasProtocol()?this.v:`${t}://${this.v}`},hasProtocol(){const t=this.tk;return t.length>=2&&t[0].t!==VI&&t[1].t===kT}}),lC=t=>new DI(t);function cC(t,e,n){const r=n[0].s,o=n[n.length-1].e;return new t(e.slice(r,o),n)}var dC="undefined"!=typeof console&&console&&console.warn||(()=>{}),uC={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function pC(t,e=!1){if(uC.initialized&&dC(`linkifyjs: already initialized - will not register custom scheme "${t}" until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(t))throw new Error('linkifyjs: incorrect scheme format.\n1. Must only contain digits, lowercase ASCII letters or "-"\n2. Cannot start or end with "-"\n3. "-" cannot repeat');uC.customSchemes.push([t,e])}function hC(){uC.scanner=function(t=[]){const e={};DI.groups=e;const n=new DI;null==XT&&(XT=ZT("aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2")),null==YT&&(YT=ZT("ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2")),jI(n,"'",gT),jI(n,"{",QI),jI(n,"}",tT),jI(n,"[",eT),jI(n,"]",nT),jI(n,"(",rT),jI(n,")",oT),jI(n,"<",iT),jI(n,">",sT),jI(n,"(",aT),jI(n,")",lT),jI(n,"「",cT),jI(n,"」",dT),jI(n,"『",uT),jI(n,"』",pT),jI(n,"<",hT),jI(n,">",fT),jI(n,"&",mT),jI(n,"*",yT),jI(n,"@",xT),jI(n,"`",bT),jI(n,"^",vT),jI(n,":",kT),jI(n,",",ST),jI(n,"$",PT),jI(n,".",MT),jI(n,"=",IT),jI(n,"!",TT),jI(n,"-",CT),jI(n,"%",ET),jI(n,"|",AT),jI(n,"+",OT),jI(n,"#",NT),jI(n,"?",RT),jI(n,'"',LT),jI(n,"/",BT),jI(n,";",DT),jI(n,"~",zT),jI(n,"_",FT),jI(n,"\\",wT),jI(n,"・",$T);const r=zI(n,KT,JI,{[PI]:!0});zI(r,KT,r);const o=zI(r,_T,_I,{[TI]:!0}),i=zI(r,UT,UI,{[CI]:!0}),s=zI(n,_T,WI,{[MI]:!0});zI(s,KT,o),zI(s,_T,s),zI(o,KT,o),zI(o,_T,o);const a=zI(n,UT,HI,{[II]:!0});zI(a,_T),zI(a,KT,i),zI(a,UT,a),zI(i,KT,i),zI(i,_T),zI(i,UT,i);const l=jI(n,"\n",ZI,{[RI]:!0}),c=jI(n,"\r",GI,{[RI]:!0}),d=zI(n,qT,GI,{[RI]:!0});jI(n,"",d),jI(c,"\n",l),jI(c,"",d),zI(c,qT,d),jI(d,"\r"),jI(d,"\n"),zI(d,qT,d),jI(d,"",d);const u=zI(n,VT,jT,{[AI]:!0});jI(u,"#"),zI(u,VT,u),jI(u,"️",u);const p=jI(u,"‍");jI(p,"#"),zI(p,VT,u);const h=[[_T,s],[KT,o]],f=[[_T,null],[UT,a],[KT,i]];for(let m=0;m<XT.length;m++)GT(n,XT[m],KI,WI,h);for(let m=0;m<YT.length;m++)GT(n,YT[m],qI,HI,f);$I(KI,{tld:!0,ascii:!0},e),$I(qI,{utld:!0,alpha:!0},e),GT(n,"file",XI,WI,h),GT(n,"mailto",XI,WI,h),GT(n,"http",YI,WI,h),GT(n,"https",YI,WI,h),GT(n,"ftp",YI,WI,h),GT(n,"ftps",YI,WI,h),$I(XI,{scheme:!0,ascii:!0},e),$I(YI,{slashscheme:!0,ascii:!0},e),t=t.sort((t,e)=>t[0]>e[0]?1:-1);for(let m=0;m<t.length;m++){const e=t[m][0],r=t[m][1]?{[OI]:!0}:{[NI]:!0};e.indexOf("-")>=0?r[EI]=!0:_T.test(e)?KT.test(e)?r[TI]=!0:r[MI]=!0:r[PI]=!0,FI(n,e,e,r)}return FI(n,"localhost",VI,{ascii:!0}),n.jd=new DI(WT),{start:n,tokens:Object.assign({groups:e},HT)}}(uC.customSchemes);for(let t=0;t<uC.tokenQueue.length;t++)uC.tokenQueue[t][1]({scanner:uC.scanner});uC.parser=function({groups:t}){const e=t.domain.concat([mT,yT,xT,wT,bT,vT,PT,IT,CT,JI,ET,AT,OT,NT,BT,WT,zT,FT]),n=[gT,kT,ST,MT,TT,ET,RT,LT,DT,iT,sT,QI,tT,nT,eT,rT,oT,aT,lT,cT,dT,uT,pT,hT,fT],r=[mT,gT,yT,wT,bT,vT,PT,IT,CT,QI,tT,ET,AT,OT,NT,RT,BT,WT,zT,FT],o=lC(),i=jI(o,zT);BI(i,r,i),BI(i,t.domain,i);const s=lC(),a=lC(),l=lC();BI(o,t.domain,s),BI(o,t.scheme,a),BI(o,t.slashscheme,l),BI(s,r,i),BI(s,t.domain,s);const c=jI(s,xT);jI(i,xT,c),jI(a,xT,c),jI(l,xT,c);const d=jI(i,MT);BI(d,r,i),BI(d,t.domain,i);const u=lC();BI(c,t.domain,u),BI(u,t.domain,u);const p=jI(u,MT);BI(p,t.domain,u);const h=lC(oC);BI(p,t.tld,h),BI(p,t.utld,h),jI(c,VI,h);const f=jI(u,CT);jI(f,CT,f),BI(f,t.domain,u),BI(h,t.domain,u),jI(h,MT,p),jI(h,CT,f);const m=jI(s,CT),g=jI(s,MT);jI(m,CT,m),BI(m,t.domain,s),BI(g,r,i),BI(g,t.domain,s);const y=lC(aC);BI(g,t.tld,y),BI(g,t.utld,y),BI(y,t.domain,s),BI(y,r,i),jI(y,MT,g),jI(y,CT,m),jI(y,xT,c);const x=jI(y,kT),w=lC(aC);BI(x,t.numeric,w);const b=lC(aC),v=lC();BI(b,e,b),BI(b,n,v),BI(v,e,b),BI(v,n,v),jI(y,BT,b),jI(w,BT,b);const k=jI(a,kT),S=jI(jI(jI(l,kT),BT),BT);BI(a,t.domain,s),jI(a,MT,g),jI(a,CT,m),BI(l,t.domain,s),jI(l,MT,g),jI(l,CT,m),BI(k,t.domain,b),jI(k,BT,b),jI(k,RT,b),BI(S,t.domain,b),BI(S,e,b),jI(S,BT,b);const P=[[QI,tT],[eT,nT],[rT,oT],[iT,sT],[aT,lT],[cT,dT],[uT,pT],[hT,fT]];for(let M=0;M<P.length;M++){const[t,r]=P[M],o=jI(b,t);jI(v,t,o);const i=lC(aC);BI(o,e,i);const s=lC();BI(o,n,s),jI(o,r,b),BI(i,e,i),BI(i,n,s),BI(s,e,i),BI(s,n,s),jI(i,r,b),jI(s,r,b)}return jI(o,VI,y),jI(o,ZI,sC),{start:o,tokens:HT}}(uC.scanner.tokens);for(let t=0;t<uC.pluginQueue.length;t++)uC.pluginQueue[t][1]({scanner:uC.scanner,parser:uC.parser});return uC.initialized=!0,uC}function fC(t){return uC.initialized||hC(),function(t,e,n){let r=n.length,o=0,i=[],s=[];for(;o<r;){let a=t,l=null,c=null,d=0,u=null,p=-1;for(;o<r&&!(l=a.go(n[o].t));)s.push(n[o++]);for(;o<r&&(c=l||a.go(n[o].t));)l=null,a=c,a.accepts()?(p=0,u=a):p>=0&&p++,o++,d++;if(p<0)o-=d,o<r&&(s.push(n[o]),o++);else{s.length>0&&(i.push(cC(iC,e,s)),s=[]),o-=p,d-=p;const t=u.t,r=n.slice(o-d,o);i.push(cC(t,e,r))}}return s.length>0&&i.push(cC(iC,e,s)),i}(uC.parser.start,t,JT(uC.scanner.start,t))}function mC(t,e=null,n=null){if(e&&"object"==typeof e){if(n)throw Error(`linkifyjs: Invalid link type ${e}; must be a string`);n=e,e=null}const r=new tC(n),o=fC(t),i=[];for(let s=0;s<o.length;s++){const t=o[s];!t.isLink||e&&t.t!==e||!r.check(t)||i.push(t.toFormattedObject(r))}return i}fC.scan=JT;var gC="[\0-   ᠎ -\u2029  ]",yC=new RegExp(gC),xC=new RegExp(`${gC}$`),wC=new RegExp(gC,"g");function bC(t,e){const n=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(t=>{const e="string"==typeof t?t:t.scheme;e&&n.push(e)}),!t||t.replace(wC,"").match(new RegExp(`^(?:(?:${n.map(t=>t.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")).join("|")}):|[^a-z]|[a-z0-9+.\\-]+(?:[^a-z+.\\-:]|$))`,"i"))}var vC=VP.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(t=>{"string"!=typeof t?pC(t.scheme,t.optionalSlashes):pC(t)})},onDestroy(){DI.groups={},uC.scanner=null,uC.parser=null,uC.tokenQueue=[],uC.pluginQueue=[],uC.customSchemes=[],uC.initialized=!1},inclusive(){return this.options.autolink},addOptions:()=>({openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(t,e)=>!!bC(t,e.protocols),validate:t=>!!t,shouldAutoLink:t=>{const e=/^[a-z][a-z0-9+.-]*:\/\//i.test(t),n=/^[a-z][a-z0-9+.-]*:/i.test(t);if(e||n&&!t.includes("@"))return!0;const r=(t.includes("@")?t.split("@").pop():t).split(/[/?#:]/)[0];return!/^\d{1,3}(\.\d{1,3}){3}$/.test(r)&&!!/\./.test(r)}}),addAttributes(){var t,e,n;return{href:{default:null,parseHTML:t=>t.getAttribute("href")},target:{default:null!=(t=this.options.HTMLAttributes.target)?t:null},rel:{default:null!=(e=this.options.HTMLAttributes.rel)?e:null},class:{default:null!=(n=this.options.HTMLAttributes.class)?n:null},title:{default:null}}},parseHTML(){return[{tag:"a[href]",getAttrs:t=>{const e=t.getAttribute("href");return!(!e||!this.options.isAllowedUri(e,{defaultValidate:t=>!!bC(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol}))&&null}}]},renderHTML({HTMLAttributes:t}){return this.options.isAllowedUri(t.href,{defaultValidate:t=>!!bC(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",LS(this.options.HTMLAttributes,t),0]:["a",LS(this.options.HTMLAttributes,{...t,href:""}),0]},markdownTokenName:"link",parseMarkdown:(t,e)=>e.applyMark("link",e.parseInline(t.tokens||[]),{href:t.href,title:t.title||null}),renderMarkdown:(t,e)=>{var n,r,o,i;const s=null!=(r=null==(n=t.attrs)?void 0:n.href)?r:"",a=null!=(i=null==(o=t.attrs)?void 0:o.title)?i:"",l=e.renderChildren(t);return a?`[${l}](${s} "${a}")`:`[${l}](${s})`},addCommands(){return{setLink:t=>({chain:e})=>{const{href:n}=t;return!!this.options.isAllowedUri(n,{defaultValidate:t=>!!bC(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})&&e().setMark(this.name,t).setMeta("preventAutolink",!0).run()},toggleLink:t=>({chain:e})=>{const{href:n}=t||{};return!(n&&!this.options.isAllowedUri(n,{defaultValidate:t=>!!bC(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol}))&&e().toggleMark(this.name,t,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()},unsetLink:()=>({chain:t})=>t().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[mM({find:t=>{const e=[];if(t){const{protocols:n,defaultProtocol:r}=this.options,o=mC(t).filter(t=>t.isLink&&this.options.isAllowedUri(t.value,{defaultValidate:t=>!!bC(t,n),protocols:n,defaultProtocol:r}));o.length&&o.forEach(t=>{this.options.shouldAutoLink(t.value)&&e.push({text:t.value,data:{href:t.href},index:t.start})})}return e},type:this.type,getAttributes:t=>{var e;return{href:null==(e=t.data)?void 0:e.href}}})]},addProseMirrorPlugins(){const t=[],{protocols:e,defaultProtocol:n}=this.options;var r;return this.options.autolink&&t.push((r={type:this.type,defaultProtocol:this.options.defaultProtocol,validate:t=>this.options.isAllowedUri(t,{defaultValidate:t=>!!bC(t,e),protocols:e,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink},new ex({key:new ox("autolink"),appendTransaction:(t,e,n)=>{const o=t.some(t=>t.docChanged)&&!e.doc.eq(n.doc),i=t.some(t=>t.getMeta("preventAutolink"));if(!o||i)return;const{tr:s}=n;return VS(PS(e.doc,[...t])).forEach(({newRange:t})=>{const e=function(t,e,n){const r=[];return t.nodesBetween(e.from,e.to,(t,e)=>{n(t)&&r.push({node:t,pos:e})}),r}(n.doc,t,t=>t.isTextblock);let o,i;if(e.length>1)o=e[0],i=n.doc.textBetween(o.pos,o.pos+o.node.nodeSize,void 0," ");else if(e.length){const r=n.doc.textBetween(t.from,t.to," "," ");if(!xC.test(r))return;o=e[0],i=n.doc.textBetween(o.pos,t.to,void 0," ")}if(o&&i){const t=i.split(yC).filter(Boolean);if(t.length<=0)return!1;const e=t[t.length-1],l=o.pos+i.lastIndexOf(e);if(!e)return!1;const c=fC(e).map(t=>t.toObject(r.defaultProtocol));if(!(1===(a=c).length?a[0].isLink:3===a.length&&a[1].isLink&&["()","[]"].includes(a[0].value+a[2].value)))return!1;c.filter(t=>t.isLink).map(t=>({...t,from:l+t.start+1,to:l+t.end+1})).filter(t=>!n.schema.marks.code||!n.doc.rangeHasMark(t.from,t.to,n.schema.marks.code)).filter(t=>r.validate(t.value)).filter(t=>r.shouldAutoLink(t.value)).forEach(t=>{KS(t.from,t.to,n.doc).some(t=>t.mark.type===r.type)||s.addMark(t.from,t.to,r.type.create({href:t.href}))})}var a}),s.steps.length?s:void 0}}))),t.push(function(t){return new ex({key:new ox("handleClickLink"),props:{handleClick:(e,n,r)=>{var o,i;if(0!==r.button)return!1;if(!e.editable)return!1;let s=null;if(r.target instanceof HTMLAnchorElement)s=r.target;else{const e=r.target;if(!e)return!1;const n=t.editor.view.dom;s=e.closest("a"),s&&!n.contains(s)&&(s=null)}if(!s)return!1;let a=!1;if(t.enableClickSelection&&(a=t.editor.commands.extendMarkRange(t.type.name)),t.openOnClick){const n=_S(e.state,t.type.name),r=null!=(o=s.href)?o:n.href,l=null!=(i=s.target)?i:n.target;r&&(window.open(r,l),a=!0)}return a}}})}({type:this.type,editor:this.editor,openOnClick:"whenNotEditable"===this.options.openOnClick||this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&t.push(function(t){return new ex({key:new ox("handlePasteLink"),props:{handlePaste:(e,n,r)=>{const{shouldAutoLink:o}=t,{state:i}=e,{selection:s}=i,{empty:a}=s;if(a)return!1;let l="";r.content.forEach(t=>{l+=t.textContent});const c=mC(l,{defaultProtocol:t.defaultProtocol}).find(t=>t.isLink&&t.value===l);return!(!l||!c||void 0!==o&&!o(c.value))&&t.editor.commands.setMark(t.type,{href:c.href})}}})}({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),t}}),kC=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,SC=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,PC=VP.create({name:"strike",addOptions:()=>({HTMLAttributes:{}}),parseHTML:()=>[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:t=>!!t.includes("line-through")&&{}}],renderHTML({HTMLAttributes:t}){return["s",LS(this.options.HTMLAttributes,t),0]},markdownTokenName:"del",parseMarkdown:(t,e)=>e.applyMark("strike",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`~~${e.renderChildren(t)}~~`,addCommands(){return{setStrike:()=>({commands:t})=>t.setMark(this.name),toggleStrike:()=>({commands:t})=>t.toggleMark(this.name),unsetStrike:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[uM({find:kC,type:this.type})]},addPasteRules(){return[mM({find:SC,type:this.type})]}}),MC=GP.create({name:"textAlign",addOptions:()=>({types:[],alignments:["left","center","right","justify"],defaultAlignment:null}),addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:t=>{const e=t.style.textAlign;return this.options.alignments.includes(e)?e:this.options.defaultAlignment},renderHTML:t=>t.textAlign?{style:`text-align: ${t.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:t=>({commands:e})=>!!this.options.alignments.includes(t)&&this.options.types.map(n=>e.updateAttributes(n,{textAlign:t})).some(t=>t),unsetTextAlign:()=>({commands:t})=>this.options.types.map(e=>t.resetAttributes(e,"textAlign")).some(t=>t),toggleTextAlign:t=>({editor:e,commands:n})=>!!this.options.alignments.includes(t)&&(e.isActive({textAlign:t})?n.unsetTextAlign():n.setTextAlign(t))}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign("left"),"Mod-Shift-e":()=>this.editor.commands.setTextAlign("center"),"Mod-Shift-r":()=>this.editor.commands.setTextAlign("right"),"Mod-Shift-j":()=>this.editor.commands.setTextAlign("justify")}}}),IC=(t,e=0)=>{const n=[];return!t.children.length||e>20||Array.from(t.children).forEach(t=>{"SPAN"===t.tagName?n.push(t):t.children.length&&n.push(...IC(t,e+1))}),n},TC=VP.create({name:"textStyle",priority:101,addOptions:()=>({HTMLAttributes:{},mergeNestedSpanStyles:!0}),parseHTML(){return[{tag:"span",consuming:!1,getAttrs:t=>!!t.hasAttribute("style")&&(this.options.mergeNestedSpanStyles&&(t=>{if(!t.children.length)return;const e=IC(t);e&&e.forEach(t=>{var e,n;const r=t.getAttribute("style"),o=null==(n=null==(e=t.parentElement)?void 0:e.closest("span"))?void 0:n.getAttribute("style");t.setAttribute("style",`${o};${r}`)})})(t),{})}]},renderHTML({HTMLAttributes:t}){return["span",LS(this.options.HTMLAttributes,t),0]},addCommands(){return{toggleTextStyle:t=>({commands:e})=>e.toggleMark(this.name,t),removeEmptyTextStyle:()=>({tr:t})=>{const{selection:e}=t;return t.doc.nodesBetween(e.from,e.to,(e,n)=>{if(e.isTextblock)return!0;e.marks.filter(t=>t.type===this.type).some(t=>Object.values(t.attrs).some(t=>!!t))||t.removeMark(n,n+e.nodeSize,this.type)}),!0}}}}),CC=GP.create({name:"backgroundColor",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{backgroundColor:{default:null,parseHTML:t=>{var e;const n=null!=(e=AP(t,"background-color"))?e:t.style.backgroundColor;return null==n?void 0:n.replace(/['"]+/g,"")},renderHTML:t=>t.backgroundColor?{style:`background-color: ${t.backgroundColor}`}:{}}}}]},addCommands:()=>({setBackgroundColor:t=>({chain:e})=>e().setMark("textStyle",{backgroundColor:t}).run(),unsetBackgroundColor:()=>({chain:t})=>t().setMark("textStyle",{backgroundColor:null}).removeEmptyTextStyle().run()})}),EC=GP.create({name:"color",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{color:{default:null,parseHTML:t=>{var e;const n=null!=(e=AP(t,"color"))?e:t.style.color;return null==n?void 0:n.replace(/['"]+/g,"")},renderHTML:t=>t.color?{style:`color: ${t.color}`}:{}}}}]},addCommands:()=>({setColor:t=>({chain:e})=>e().setMark("textStyle",{color:t}).run(),unsetColor:()=>({chain:t})=>t().setMark("textStyle",{color:null}).removeEmptyTextStyle().run()})}),AC=GP.create({name:"fontFamily",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{fontFamily:{default:null,parseHTML:t=>{var e;return null!=(e=AP(t,"font-family"))?e:t.style.fontFamily},renderHTML:t=>t.fontFamily?{style:`font-family: ${t.fontFamily}`}:{}}}}]},addCommands:()=>({setFontFamily:t=>({chain:e})=>e().setMark("textStyle",{fontFamily:t}).run(),unsetFontFamily:()=>({chain:t})=>t().setMark("textStyle",{fontFamily:null}).removeEmptyTextStyle().run()})}),OC=GP.create({name:"fontSize",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{fontSize:{default:null,parseHTML:t=>{var e;return null!=(e=AP(t,"font-size"))?e:t.style.fontSize},renderHTML:t=>t.fontSize?{style:`font-size: ${t.fontSize}`}:{}}}}]},addCommands:()=>({setFontSize:t=>({chain:e})=>e().setMark("textStyle",{fontSize:t}).run(),unsetFontSize:()=>({chain:t})=>t().setMark("textStyle",{fontSize:null}).removeEmptyTextStyle().run()})}),NC=GP.create({name:"lineHeight",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{lineHeight:{default:null,parseHTML:t=>{var e;return null!=(e=AP(t,"line-height"))?e:t.style.lineHeight},renderHTML:t=>t.lineHeight?{style:`line-height: ${t.lineHeight}`}:{}}}}]},addCommands:()=>({setLineHeight:t=>({chain:e})=>e().setMark("textStyle",{lineHeight:t}).run(),unsetLineHeight:()=>({chain:t})=>t().setMark("textStyle",{lineHeight:null}).removeEmptyTextStyle().run()})}),RC=(GP.create({name:"textStyleKit",addExtensions(){const t=[];return!1!==this.options.backgroundColor&&t.push(CC.configure(this.options.backgroundColor)),!1!==this.options.color&&t.push(EC.configure(this.options.color)),!1!==this.options.fontFamily&&t.push(AC.configure(this.options.fontFamily)),!1!==this.options.fontSize&&t.push(OC.configure(this.options.fontSize)),!1!==this.options.lineHeight&&t.push(NC.configure(this.options.lineHeight)),!1!==this.options.textStyle&&t.push(TC.configure(this.options.textStyle)),t}}),VP.create({name:"underline",addOptions:()=>({HTMLAttributes:{}}),parseHTML:()=>[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:t=>!!t.includes("underline")&&{}}],renderHTML({HTMLAttributes:t}){return["u",LS(this.options.HTMLAttributes,t),0]},parseMarkdown(t,e){return e.applyMark(this.name||"underline",e.parseInline(t.tokens||[]))},renderMarkdown:(t,e)=>`++${e.renderChildren(t)}++`,markdownTokenizer:{name:"underline",level:"inline",start:t=>t.indexOf("++"),tokenize(t,e,n){const r=/^(\+\+)([\s\S]+?)(\+\+)/.exec(t);if(!r)return;const o=r[2].trim();return{type:"underline",raw:r[0],text:o,tokens:n.inlineTokens(o)}}},addCommands(){return{setUnderline:()=>({commands:t})=>t.setMark(this.name),toggleUnderline:()=>({commands:t})=>t.toggleMark(this.name),unsetUnderline:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}})),LC=GP.create({name:"selection",addOptions:()=>({className:"selection"}),addProseMirrorPlugins(){const{editor:t,options:e}=this;return t.options.injectCSS&&"undefined"!=typeof document&&EP(".ProseMirror:not(.ProseMirror-focused) *::selection {\n background: transparent;\n}\n\n.ProseMirror:not(.ProseMirror-focused) *::-moz-selection {\n background: transparent;\n}",t.options.injectNonce,"selection"),[new ex({key:new ox("selection"),props:{decorations:n=>n.selection.empty||t.isFocused||!t.isEditable||QS(n.selection)||t.view.dragging?null:kv.create(n.doc,[wv.inline(n.selection.from,n.selection.to,{class:e.className})])}})]}});function $C(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let o=t.child(r),i=e.child(r);if(o!=i){if(!o.sameMarkup(i))return n;if(o.isText&&o.text!=i.text){let t=o.text,e=i.text,r=0;for(;t[r]==e[r];r++)n++;return r&&r<t.length&&r<e.length&&zC(t.charCodeAt(r-1))&&BC(t.charCodeAt(r))&&n--,n}if(o.content.size||i.content.size){let t=$C(o.content,i.content,n+1);if(null!=t)return t}n+=o.nodeSize}else n+=o.nodeSize}}function DC(t,e,n,r){for(let o=t.childCount,i=e.childCount;;){if(0==o||0==i)return o==i?null:{a:n,b:r};let s=t.child(--o),a=e.child(--i),l=s.nodeSize;if(s!=a){if(!s.sameMarkup(a))return{a:n,b:r};if(s.isText&&s.text!=a.text){let t=s.text,e=a.text,o=t.length,i=e.length;for(;o>0&&i>0&&t[o-1]==e[i-1];)o--,i--,n--,r--;return o&&i&&o<t.length&&zC(t.charCodeAt(o-1))&&BC(t.charCodeAt(o))&&(n++,r++),{a:n,b:r}}if(s.content.size||a.content.size){let t=DC(s.content,a.content,n-1,r-1);if(t)return t}n-=l,r-=l}else n-=l,r-=l}}function BC(t){return t>=56320&&t<57344}function zC(t){return t>=55296&&t<56320}var FC=class t{constructor(t,e){if(this.content=t,this.size=e||0,null==e)for(let n=0;n<t.length;n++)this.size+=t[n].nodeSize}nodesBetween(t,e,n,r=0,o){for(let i=0,s=0;s<e;i++){let a=this.content[i],l=s+a.nodeSize;if(l>t&&!1!==n(a,r+s,o||null,i)&&a.content.size){let o=s+1;a.nodesBetween(Math.max(0,t-o),Math.min(a.content.size,e-o),n,r+o)}s=l}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,e,n,r){let o="",i=!0;return this.nodesBetween(t,e,(s,a)=>{let l=s.isText?s.text.slice(Math.max(t,a)-a,e-a):s.isLeaf?r?"function"==typeof r?r(s):r:s.type.spec.leafText?s.type.spec.leafText(s):"":"";s.isBlock&&(s.isLeaf&&l||s.isTextblock)&&n&&(i?i=!1:o+=n),o+=l},0),o}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,o=this.content.slice(),i=0;for(n.isText&&n.sameMarkup(r)&&(o[o.length-1]=n.withText(n.text+r.text),i=1);i<e.content.length;i++)o.push(e.content[i]);return new t(o,this.size+e.size)}cut(e,n=this.size){if(0==e&&n==this.size)return this;let r=[],o=0;if(n>e)for(let t=0,i=0;i<n;t++){let s=this.content[t],a=i+s.nodeSize;a>e&&((i<e||a>n)&&(s=s.isText?s.cut(Math.max(0,e-i),Math.min(s.text.length,n-i)):s.cut(Math.max(0,e-i-1),Math.min(s.content.size,n-i-1))),r.push(s),o+=s.nodeSize),i=a}return new t(r,o)}cutByIndex(e,n){return e==n?t.empty:0==e&&n==this.content.length?this:new t(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let o=this.content.slice(),i=this.size+n.nodeSize-r.nodeSize;return o[e]=n,new t(o,i)}addToStart(e){return new t([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new t(this.content.concat(e),this.size+e.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let e=0;e<this.content.length;e++)if(!this.content[e].eq(t.content[e]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(t){let e=this.content[t];if(!e)throw new RangeError("Index "+t+" out of range for "+this);return e}maybeChild(t){return this.content[t]||null}forEach(t){for(let e=0,n=0;e<this.content.length;e++){let r=this.content[e];t(r,n,e),n+=r.nodeSize}}findDiffStart(t,e=0){return $C(this,t,e)}findDiffEnd(t,e=this.size,n=t.size){return DC(this,t,e,n)}findIndex(t){if(0==t)return WC(0,t);if(t==this.size)return WC(this.content.length,t);if(t>this.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let e=0,n=0;;e++){let r=n+this.child(e).nodeSize;if(r>=t)return r==t?WC(e+1,r):WC(e,n);n=r}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(t=>t.toJSON()):null}static fromJSON(e,n){if(!n)return t.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return t.fromArray(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return t.empty;let n,r=0;for(let t=0;t<e.length;t++){let o=e[t];r+=o.nodeSize,t&&o.isText&&e[t-1].sameMarkup(o)?(n||(n=e.slice(0,t)),n[n.length-1]=o.withText(n[n.length-1].text+o.text)):n&&n.push(o)}return new t(n||e,r)}static from(e){if(!e)return t.empty;if(e instanceof t)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new t([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}};FC.empty=new FC([],0);var jC={index:0,offset:0};function WC(t,e){return jC.index=t,jC.offset=e,jC}function HC(t,e){if(t===e)return!0;if(!t||"object"!=typeof t||!e||"object"!=typeof e)return!1;let n=Array.isArray(t);if(Array.isArray(e)!=n)return!1;if(n){if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!HC(t[n],e[n]))return!1}else{for(let n in t)if(!(n in e)||!HC(t[n],e[n]))return!1;for(let n in e)if(!(n in t))return!1}return!0}var _C=class t{constructor(t,e){this.type=t,this.attrs=e}addToSet(t){let e,n=!1;for(let r=0;r<t.length;r++){let o=t[r];if(this.eq(o))return t;if(this.type.excludes(o.type))e||(e=t.slice(0,r));else{if(o.type.excludes(this.type))return t;!n&&o.type.rank>this.type.rank&&(e||(e=t.slice(0,r)),e.push(this),n=!0),e&&e.push(o)}}return e||(e=t.slice()),n||e.push(this),e}removeFromSet(t){for(let e=0;e<t.length;e++)if(this.eq(t[e]))return t.slice(0,e).concat(t.slice(e+1));return t}isInSet(t){for(let e=0;e<t.length;e++)if(this.eq(t[e]))return!0;return!1}eq(t){return this==t||this.type==t.type&&HC(this.attrs,t.attrs)}toJSON(){let t={type:this.type.name};for(let e in this.attrs){t.attrs=this.attrs;break}return t}static fromJSON(t,e){if(!e)throw new RangeError("Invalid input for Mark.fromJSON");let n=t.marks[e.type];if(!n)throw new RangeError(`There is no mark type ${e.type} in this schema`);let r=n.create(e.attrs);return n.checkAttrs(r.attrs),r}static sameSet(t,e){if(t==e)return!0;if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!t[n].eq(e[n]))return!1;return!0}static setFrom(e){if(!e||Array.isArray(e)&&0==e.length)return t.none;if(e instanceof t)return[e];let n=e.slice();return n.sort((t,e)=>t.type.rank-e.type.rank),n}};_C.none=[];var UC=class extends Error{},VC=class t{constructor(t,e,n){this.content=t,this.openStart=e,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let r=qC(this.content,e+this.openStart,n,this.openStart+1,this.openEnd+1);return r&&new t(r,this.openStart,this.openEnd)}removeBetween(e,n){return new t(KC(this.content,e+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(e,n){if(!n)return t.empty;let r=n.openStart||0,o=n.openEnd||0;if("number"!=typeof r||"number"!=typeof o)throw new RangeError("Invalid input for Slice.fromJSON");return new t(FC.fromJSON(e,n.content),r,o)}static maxOpen(e,n=!0){let r=0,o=0;for(let t=e.firstChild;t&&!t.isLeaf&&(n||!t.type.spec.isolating);t=t.firstChild)r++;for(let t=e.lastChild;t&&!t.isLeaf&&(n||!t.type.spec.isolating);t=t.lastChild)o++;return new t(e,r,o)}};function KC(t,e,n){let{index:r,offset:o}=t.findIndex(e),i=t.maybeChild(r),{index:s,offset:a}=t.findIndex(n);if(o==e||i.isText){if(a!=n&&!t.child(s).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=s)throw new RangeError("Removing non-flat range");return t.replaceChild(r,i.copy(KC(i.content,e-o-1,n-o-1)))}function qC(t,e,n,r,o,i){let{index:s,offset:a}=t.findIndex(e),l=t.maybeChild(s);if(a==e||l.isText)return i&&r<=0&&o<=0&&!i.canReplace(s,s,n)?null:t.cut(0,e).append(n).append(t.cut(e));let c=qC(l.content,e-a-1,n,0==s?r-1:0,s==t.childCount-1?o-1:0,l);return c&&t.replaceChild(s,l.copy(c))}VC.empty=new VC(FC.empty,0,0);var XC=class t{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new YC(e,n);if(null==r.next)return t.empty;let o=JC(r);r.next&&r.err("Unexpected trailing text");let i=function(t){let e=Object.create(null);return n(nE(t,0));function n(r){let o=[];r.forEach(e=>{t[e].forEach(({term:e,to:n})=>{if(!e)return;let r;for(let t=0;t<o.length;t++)o[t][0]==e&&(r=o[t][1]);nE(t,n).forEach(t=>{r||o.push([e,r=[]]),-1==r.indexOf(t)&&r.push(t)})})});let i=e[r.join(",")]=new XC(r.indexOf(t.length-1)>-1);for(let t=0;t<o.length;t++){let r=o[t][1].sort(eE);i.next.push({type:o[t][0],next:e[r.join(",")]||n(r)})}return i}}(function(t){let e=[[]];return o(i(t,0),n()),e;function n(){return e.push([])-1}function r(t,n,r){let o={term:r,to:n};return e[t].push(o),o}function o(t,e){t.forEach(t=>t.to=e)}function i(t,e){if("choice"==t.type)return t.exprs.reduce((t,n)=>t.concat(i(n,e)),[]);if("seq"!=t.type){if("star"==t.type){let s=n();return r(e,s),o(i(t.expr,s),s),[r(s)]}if("plus"==t.type){let s=n();return o(i(t.expr,e),s),o(i(t.expr,s),s),[r(s)]}if("opt"==t.type)return[r(e)].concat(i(t.expr,e));if("range"==t.type){let s=e;for(let e=0;e<t.min;e++){let e=n();o(i(t.expr,s),e),s=e}if(-1==t.max)o(i(t.expr,s),s);else for(let e=t.min;e<t.max;e++){let e=n();r(s,e),o(i(t.expr,s),e),s=e}return[r(s)]}if("name"==t.type)return[r(e,void 0,t.value)];throw new Error("Unknown expr type")}for(let r=0;;r++){let s=i(t.exprs[r],e);if(r==t.exprs.length-1)return s;o(s,e=n())}}}(o));return function(t,e){for(let n=0,r=[t];n<r.length;n++){let t=r[n],o=!t.validEnd,i=[];for(let e=0;e<t.next.length;e++){let{type:n,next:s}=t.next[e];i.push(n.name),!o||n.isText||n.hasRequiredAttrs()||(o=!1),-1==r.indexOf(s)&&r.push(s)}o&&e.err("Only non-generatable nodes ("+i.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}(i,r),i}matchType(t){for(let e=0;e<this.next.length;e++)if(this.next[e].type==t)return this.next[e].next;return null}matchFragment(t,e=0,n=t.childCount){let r=this;for(let o=e;r&&o<n;o++)r=r.matchType(t.child(o).type);return r}get inlineContent(){return 0!=this.next.length&&this.next[0].type.isInline}get defaultType(){for(let t=0;t<this.next.length;t++){let{type:e}=this.next[t];if(!e.isText&&!e.hasRequiredAttrs())return e}return null}compatible(t){for(let e=0;e<this.next.length;e++)for(let n=0;n<t.next.length;n++)if(this.next[e].type==t.next[n].type)return!0;return!1}fillBefore(t,e=!1,n=0){let r=[this];return function o(i,s){let a=i.matchFragment(t,n);if(a&&(!e||a.validEnd))return FC.from(s.map(t=>t.createAndFill()));for(let t=0;t<i.next.length;t++){let{type:e,next:n}=i.next[t];if(!e.isText&&!e.hasRequiredAttrs()&&-1==r.indexOf(n)){r.push(n);let t=o(n,s.concat(e));if(t)return t}}return null}(this,[])}findWrapping(t){for(let n=0;n<this.wrapCache.length;n+=2)if(this.wrapCache[n]==t)return this.wrapCache[n+1];let e=this.computeWrapping(t);return this.wrapCache.push(t,e),e}computeWrapping(t){let e=Object.create(null),n=[{match:this,type:null,via:null}];for(;n.length;){let r=n.shift(),o=r.match;if(o.matchType(t)){let t=[];for(let e=r;e.type;e=e.via)t.push(e.type);return t.reverse()}for(let t=0;t<o.next.length;t++){let{type:i,next:s}=o.next[t];i.isLeaf||i.hasRequiredAttrs()||i.name in e||r.type&&!s.validEnd||(n.push({match:i.contentMatch,type:i,via:r}),e[i.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(t){if(t>=this.next.length)throw new RangeError(`There's no ${t}th edge in this content match`);return this.next[t]}toString(){let t=[];return function e(n){t.push(n);for(let r=0;r<n.next.length;r++)-1==t.indexOf(n.next[r].next)&&e(n.next[r].next)}(this),t.map((e,n)=>{let r=n+(e.validEnd?"*":" ")+" ";for(let o=0;o<e.next.length;o++)r+=(o?", ":"")+e.next[o].type.name+"->"+t.indexOf(e.next[o].next);return r}).join("\n")}};XC.empty=new XC(!0);var YC=class{constructor(t,e){this.string=t,this.nodeTypes=e,this.inline=null,this.pos=0,this.tokens=t.split(/\s*(?=\b|\W|$)/),""==this.tokens[this.tokens.length-1]&&this.tokens.pop(),""==this.tokens[0]&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(t){return this.next==t&&(this.pos++||!0)}err(t){throw new SyntaxError(t+" (in content expression '"+this.string+"')")}};function JC(t){let e=[];do{e.push(GC(t))}while(t.eat("|"));return 1==e.length?e[0]:{type:"choice",exprs:e}}function GC(t){let e=[];do{e.push(ZC(t))}while(t.next&&")"!=t.next&&"|"!=t.next);return 1==e.length?e[0]:{type:"seq",exprs:e}}function ZC(t){let e=function(t){if(t.eat("(")){let e=JC(t);return t.eat(")")||t.err("Missing closing paren"),e}if(!/\W/.test(t.next)){let e=function(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let o=[];for(let i in n){let t=n[i];t.isInGroup(e)&&o.push(t)}0==o.length&&t.err("No node type or group '"+e+"' found");return o}(t,t.next).map(e=>(null==t.inline?t.inline=e.isInline:t.inline!=e.isInline&&t.err("Mixing inline and block content"),{type:"name",value:e}));return t.pos++,1==e.length?e[0]:{type:"choice",exprs:e}}t.err("Unexpected token '"+t.next+"'")}(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else{if(!t.eat("{"))break;e=tE(t,e)}return e}function QC(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function tE(t,e){let n=QC(t),r=n;return t.eat(",")&&(r="}"!=t.next?QC(t):-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function eE(t,e){return e-t}function nE(t,e){let n=[];return function e(r){let o=t[r];if(1==o.length&&!o[0].term)return e(o[0].to);n.push(r);for(let t=0;t<o.length;t++){let{term:r,to:i}=o[t];r||-1!=n.indexOf(i)||e(i)}}(e),n.sort(eE)}var rE=Math.pow(2,16);function oE(t,e){return t+e*rE}function iE(t){return 65535&t}var sE=class{constructor(t,e,n){this.pos=t,this.delInfo=e,this.recover=n}get deleted(){return(8&this.delInfo)>0}get deletedBefore(){return(5&this.delInfo)>0}get deletedAfter(){return(6&this.delInfo)>0}get deletedAcross(){return(4&this.delInfo)>0}},aE=class t{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&t.empty)return t.empty}recover(t){let e=0,n=iE(t);if(!this.inverted)for(let r=0;r<n;r++)e+=this.ranges[3*r+2]-this.ranges[3*r+1];return this.ranges[3*n]+e+function(t){return(t-(65535&t))/rE}(t)}mapResult(t,e=1){return this._map(t,e,!1)}map(t,e=1){return this._map(t,e,!0)}_map(t,e,n){let r=0,o=this.inverted?2:1,i=this.inverted?1:2;for(let s=0;s<this.ranges.length;s+=3){let a=this.ranges[s]-(this.inverted?r:0);if(a>t)break;let l=this.ranges[s+o],c=this.ranges[s+i],d=a+l;if(t<=d){let o=a+r+((l?t==a?-1:t==d?1:e:e)<0?0:c);if(n)return o;let i=t==(e<0?a:d)?null:oE(s/3,t-a),u=t==a?2:t==d?1:4;return(e<0?t!=a:t!=d)&&(u|=8),new sE(o,u,i)}r+=c-l}return n?t+r:new sE(t+r,0,null)}touches(t,e){let n=0,r=iE(e),o=this.inverted?2:1,i=this.inverted?1:2;for(let s=0;s<this.ranges.length;s+=3){let e=this.ranges[s]-(this.inverted?n:0);if(e>t)break;let a=this.ranges[s+o];if(t<=e+a&&s==3*r)return!0;n+=this.ranges[s+i]-a}return!1}forEach(t){let e=this.inverted?2:1,n=this.inverted?1:2;for(let r=0,o=0;r<this.ranges.length;r+=3){let i=this.ranges[r],s=i-(this.inverted?o:0),a=i+(this.inverted?0:o),l=this.ranges[r+e],c=this.ranges[r+n];t(s,s+l,a,a+c),o+=c-l}}invert(){return new t(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return 0==e?t.empty:new t(e<0?[0,-e,0]:[0,0,e])}};aE.empty=new aE([]);var lE=Object.create(null),cE=class{getMap(){return aE.empty}merge(t){return null}static fromJSON(t,e){if(!e||!e.stepType)throw new RangeError("Invalid input for Step.fromJSON");let n=lE[e.stepType];if(!n)throw new RangeError(`No step type ${e.stepType} defined`);return n.fromJSON(t,e)}static jsonID(t,e){if(t in lE)throw new RangeError("Duplicate use of step JSON ID "+t);return lE[t]=e,e.prototype.jsonID=t,e}},dE=class t{constructor(t,e){this.doc=t,this.failed=e}static ok(e){return new t(e,null)}static fail(e){return new t(null,e)}static fromReplace(e,n,r,o){try{return t.ok(e.replace(n,r,o))}catch(i){if(i instanceof UC)return t.fail(i.message);throw i}}};function uE(t,e,n){let r=[];for(let o=0;o<t.childCount;o++){let i=t.child(o);i.content.size&&(i=i.copy(uE(i.content,e,i))),i.isInline&&(i=e(i,n,o)),r.push(i)}return FC.fromArray(r)}var pE=class t extends cE{constructor(t,e,n){super(),this.from=t,this.to=e,this.mark=n}apply(t){let e=t.slice(this.from,this.to),n=t.resolve(this.from),r=n.node(n.sharedDepth(this.to)),o=new VC(uE(e.content,(t,e)=>t.isAtom&&e.type.allowsMarkType(this.mark.type)?t.mark(this.mark.addToSet(t.marks)):t,r),e.openStart,e.openEnd);return dE.fromReplace(t,this.from,this.to,o)}invert(){return new hE(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new t(n.pos,r.pos,this.mark)}merge(e){return e instanceof t&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new t(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if("number"!=typeof n.from||"number"!=typeof n.to)throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new t(n.from,n.to,e.markFromJSON(n.mark))}};cE.jsonID("addMark",pE);var hE=class t extends cE{constructor(t,e,n){super(),this.from=t,this.to=e,this.mark=n}apply(t){let e=t.slice(this.from,this.to),n=new VC(uE(e.content,t=>t.mark(this.mark.removeFromSet(t.marks)),t),e.openStart,e.openEnd);return dE.fromReplace(t,this.from,this.to,n)}invert(){return new pE(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new t(n.pos,r.pos,this.mark)}merge(e){return e instanceof t&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new t(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if("number"!=typeof n.from||"number"!=typeof n.to)throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new t(n.from,n.to,e.markFromJSON(n.mark))}};cE.jsonID("removeMark",hE);var fE=class t extends cE{constructor(t,e){super(),this.pos=t,this.mark=e}apply(t){let e=t.nodeAt(this.pos);if(!e)return dE.fail("No node at mark step's position");let n=e.type.create(e.attrs,null,this.mark.addToSet(e.marks));return dE.fromReplace(t,this.pos,this.pos+1,new VC(FC.from(n),0,e.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);if(n){let e=this.mark.addToSet(n.marks);if(e.length==n.marks.length){for(let r=0;r<n.marks.length;r++)if(!n.marks[r].isInSet(e))return new t(this.pos,n.marks[r]);return new t(this.pos,this.mark)}}return new mE(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new t(n.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,n){if("number"!=typeof n.pos)throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new t(n.pos,e.markFromJSON(n.mark))}};cE.jsonID("addNodeMark",fE);var mE=class t extends cE{constructor(t,e){super(),this.pos=t,this.mark=e}apply(t){let e=t.nodeAt(this.pos);if(!e)return dE.fail("No node at mark step's position");let n=e.type.create(e.attrs,null,this.mark.removeFromSet(e.marks));return dE.fromReplace(t,this.pos,this.pos+1,new VC(FC.from(n),0,e.isLeaf?0:1))}invert(t){let e=t.nodeAt(this.pos);return e&&this.mark.isInSet(e.marks)?new fE(this.pos,this.mark):this}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new t(n.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,n){if("number"!=typeof n.pos)throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new t(n.pos,e.markFromJSON(n.mark))}};cE.jsonID("removeNodeMark",mE);var gE=class t extends cE{constructor(t,e,n,r=!1){super(),this.from=t,this.to=e,this.slice=n,this.structure=r}apply(t){return this.structure&&xE(t,this.from,this.to)?dE.fail("Structure replace would overwrite content"):dE.fromReplace(t,this.from,this.to,this.slice)}getMap(){return new aE([this.from,this.to-this.from,this.slice.size])}invert(e){return new t(this.from,this.from+this.slice.size,e.slice(this.from,this.to))}map(e){let n=e.mapResult(this.to,-1),r=this.from==this.to&&t.MAP_BIAS<0?n:e.mapResult(this.from,1);return r.deletedAcross&&n.deletedAcross?null:new t(r.pos,Math.max(r.pos,n.pos),this.slice,this.structure)}merge(e){if(!(e instanceof t)||e.structure||this.structure)return null;if(this.from+this.slice.size!=e.from||this.slice.openEnd||e.slice.openStart){if(e.to!=this.from||this.slice.openStart||e.slice.openEnd)return null;{let n=this.slice.size+e.slice.size==0?VC.empty:new VC(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new t(e.from,this.to,n,this.structure)}}{let n=this.slice.size+e.slice.size==0?VC.empty:new VC(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new t(this.from,this.to+(e.to-e.from),n,this.structure)}}toJSON(){let t={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(e,n){if("number"!=typeof n.from||"number"!=typeof n.to)throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new t(n.from,n.to,VC.fromJSON(e,n.slice),!!n.structure)}};gE.MAP_BIAS=1,cE.jsonID("replace",gE);var yE=class t extends cE{constructor(t,e,n,r,o,i,s=!1){super(),this.from=t,this.to=e,this.gapFrom=n,this.gapTo=r,this.slice=o,this.insert=i,this.structure=s}apply(t){if(this.structure&&(xE(t,this.from,this.gapFrom)||xE(t,this.gapTo,this.to)))return dE.fail("Structure gap-replace would overwrite content");let e=t.slice(this.gapFrom,this.gapTo);if(e.openStart||e.openEnd)return dE.fail("Gap is not a flat range");let n=this.slice.insertAt(this.insert,e.content);return n?dE.fromReplace(t,this.from,this.to,n):dE.fail("Content does not fit in gap")}getMap(){return new aE([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(e){let n=this.gapTo-this.gapFrom;return new t(this.from,this.from+this.slice.size+n,this.from+this.insert,this.from+this.insert+n,e.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1),o=this.from==this.gapFrom?n.pos:e.map(this.gapFrom,-1),i=this.to==this.gapTo?r.pos:e.map(this.gapTo,1);return n.deletedAcross&&r.deletedAcross||o<n.pos||i>r.pos?null:new t(n.pos,r.pos,o,i,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(e,n){if("number"!=typeof n.from||"number"!=typeof n.to||"number"!=typeof n.gapFrom||"number"!=typeof n.gapTo||"number"!=typeof n.insert)throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new t(n.from,n.to,n.gapFrom,n.gapTo,VC.fromJSON(e,n.slice),n.insert,!!n.structure)}};function xE(t,e,n){let r=t.resolve(e),o=n-e,i=r.depth;for(;o>0&&i>0&&r.indexAfter(i)==r.node(i).childCount;)i--,o--;if(o>0){let t=r.node(i).maybeChild(r.indexAfter(i));for(;o>0;){if(!t||t.isLeaf)return!0;t=t.firstChild,o--}}return!1}cE.jsonID("replaceAround",yE);cE.jsonID("attr",class t extends cE{constructor(t,e,n){super(),this.pos=t,this.attr=e,this.value=n}apply(t){let e=t.nodeAt(this.pos);if(!e)return dE.fail("No node at attribute step's position");let n=Object.create(null);for(let o in e.attrs)n[o]=e.attrs[o];n[this.attr]=this.value;let r=e.type.create(n,null,e.marks);return dE.fromReplace(t,this.pos,this.pos+1,new VC(FC.from(r),0,e.isLeaf?0:1))}getMap(){return aE.empty}invert(e){return new t(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new t(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,n){if("number"!=typeof n.pos||"string"!=typeof n.attr)throw new RangeError("Invalid input for AttrStep.fromJSON");return new t(n.pos,n.attr,n.value)}});cE.jsonID("docAttr",class t extends cE{constructor(t,e){super(),this.attr=t,this.value=e}apply(t){let e=Object.create(null);for(let r in t.attrs)e[r]=t.attrs[r];e[this.attr]=this.value;let n=t.type.create(e,t.content,t.marks);return dE.ok(n)}getMap(){return aE.empty}invert(e){return new t(this.attr,e.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,n){if("string"!=typeof n.attr)throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new t(n.attr,n.value)}});var wE=Error;((wE=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n}).prototype=Object.create(Error.prototype)).constructor=wE,wE.prototype.name="TransformError";var bE=Object.create(null),vE=class{constructor(t,e,n){this.$anchor=t,this.$head=e,this.ranges=n||[new kE(t.min(e),t.max(e))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let t=this.ranges;for(let e=0;e<t.length;e++)if(t[e].$from.pos!=t[e].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(t,e=VC.empty){let n=e.content.lastChild,r=null;for(let s=0;s<e.openEnd;s++)r=n,n=n.lastChild;let o=t.steps.length,i=this.ranges;for(let s=0;s<i.length;s++){let{$from:a,$to:l}=i[s],c=t.mapping.slice(o);t.replaceRange(c.map(a.pos),c.map(l.pos),s?VC.empty:e),0==s&&NE(t,o,(n?n.isInline:r&&r.isTextblock)?-1:1)}}replaceWith(t,e){let n=t.steps.length,r=this.ranges;for(let o=0;o<r.length;o++){let{$from:i,$to:s}=r[o],a=t.mapping.slice(n),l=a.map(i.pos),c=a.map(s.pos);o?t.deleteRange(l,c):(t.replaceRangeWith(l,c,e),NE(t,n,e.isInline?-1:1))}}static findFrom(t,e,n=!1){let r=t.parent.inlineContent?new ME(t):OE(t.node(0),t.parent,t.pos,t.index(),e,n);if(r)return r;for(let o=t.depth-1;o>=0;o--){let r=e<0?OE(t.node(0),t.node(o),t.before(o+1),t.index(o),e,n):OE(t.node(0),t.node(o),t.after(o+1),t.index(o)+1,e,n);if(r)return r}return null}static near(t,e=1){return this.findFrom(t,e)||this.findFrom(t,-e)||new EE(t.node(0))}static atStart(t){return OE(t,t,0,0,1)||new EE(t)}static atEnd(t){return OE(t,t,t.content.size,t.childCount,-1)||new EE(t)}static fromJSON(t,e){if(!e||!e.type)throw new RangeError("Invalid input for Selection.fromJSON");let n=bE[e.type];if(!n)throw new RangeError(`No selection type ${e.type} defined`);return n.fromJSON(t,e)}static jsonID(t,e){if(t in bE)throw new RangeError("Duplicate use of selection JSON ID "+t);return bE[t]=e,e.prototype.jsonID=t,e}getBookmark(){return ME.between(this.$anchor,this.$head).getBookmark()}};vE.prototype.visible=!0;var kE=class{constructor(t,e){this.$from=t,this.$to=e}},SE=!1;function PE(t){SE||t.parent.inlineContent||(SE=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}var ME=class t extends vE{constructor(t,e=t){PE(t),PE(e),super(t,e)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,n){let r=e.resolve(n.map(this.head));if(!r.parent.inlineContent)return vE.near(r);let o=e.resolve(n.map(this.anchor));return new t(o.parent.inlineContent?o:r,r)}replace(t,e=VC.empty){if(super.replace(t,e),e==VC.empty){let e=this.$from.marksAcross(this.$to);e&&t.ensureMarks(e)}}eq(e){return e instanceof t&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new IE(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,n){if("number"!=typeof n.anchor||"number"!=typeof n.head)throw new RangeError("Invalid input for TextSelection.fromJSON");return new t(e.resolve(n.anchor),e.resolve(n.head))}static create(t,e,n=e){let r=t.resolve(e);return new this(r,n==e?r:t.resolve(n))}static between(e,n,r){let o=e.pos-n.pos;if(r&&!o||(r=o>=0?1:-1),!n.parent.inlineContent){let t=vE.findFrom(n,r,!0)||vE.findFrom(n,-r,!0);if(!t)return vE.near(n,r);n=t.$head}return e.parent.inlineContent||(0==o||(e=(vE.findFrom(e,-r,!0)||vE.findFrom(e,r,!0)).$anchor).pos<n.pos!=o<0)&&(e=n),new t(e,n)}};vE.jsonID("text",ME);var IE=class t{constructor(t,e){this.anchor=t,this.head=e}map(e){return new t(e.map(this.anchor),e.map(this.head))}resolve(t){return ME.between(t.resolve(this.anchor),t.resolve(this.head))}},TE=class t extends vE{constructor(t){let e=t.nodeAfter,n=t.node(0).resolve(t.pos+e.nodeSize);super(t,n),this.node=e}map(e,n){let{deleted:r,pos:o}=n.mapResult(this.anchor),i=e.resolve(o);return r?vE.near(i):new t(i)}content(){return new VC(FC.from(this.node),0,0)}eq(e){return e instanceof t&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new CE(this.anchor)}static fromJSON(e,n){if("number"!=typeof n.anchor)throw new RangeError("Invalid input for NodeSelection.fromJSON");return new t(e.resolve(n.anchor))}static create(e,n){return new t(e.resolve(n))}static isSelectable(t){return!t.isText&&!1!==t.type.spec.selectable}};TE.prototype.visible=!1,vE.jsonID("node",TE);var CE=class t{constructor(t){this.anchor=t}map(e){let{deleted:n,pos:r}=e.mapResult(this.anchor);return n?new IE(r,r):new t(r)}resolve(t){let e=t.resolve(this.anchor),n=e.nodeAfter;return n&&TE.isSelectable(n)?new TE(e):vE.near(e)}},EE=class t extends vE{constructor(t){super(t.resolve(0),t.resolve(t.content.size))}replace(t,e=VC.empty){if(e==VC.empty){t.delete(0,t.doc.content.size);let e=vE.atStart(t.doc);e.eq(t.selection)||t.setSelection(e)}else super.replace(t,e)}toJSON(){return{type:"all"}}static fromJSON(e){return new t(e)}map(e){return new t(e)}eq(e){return e instanceof t}getBookmark(){return AE}};vE.jsonID("all",EE);var AE={map(){return this},resolve:t=>new EE(t)};function OE(t,e,n,r,o,i=!1){if(e.inlineContent)return ME.create(t,n);for(let s=r-(o>0?0:1);o>0?s<e.childCount:s>=0;s+=o){let r=e.child(s);if(r.isAtom){if(!i&&TE.isSelectable(r))return TE.create(t,n-(o<0?r.nodeSize:0))}else{let e=OE(t,r,n+o,o<0?r.childCount:0,o,i);if(e)return e}n+=r.nodeSize*o}return null}function NE(t,e,n){let r=t.steps.length-1;if(r<e)return;let o,i=t.steps[r];(i instanceof gE||i instanceof yE)&&(t.mapping.maps[r].forEach((t,e,n,r)=>{null==o&&(o=r)}),t.setSelection(vE.near(t.doc.resolve(o),n)))}function RE(t,e){return e&&t?t.bind(e):t}var LE=class{constructor(t,e,n){this.name=t,this.init=RE(e.init,n),this.apply=RE(e.apply,n)}};new LE("doc",{init:t=>t.doc||t.schema.topNodeType.createAndFill(),apply:t=>t.doc}),new LE("selection",{init:(t,e)=>t.selection||vE.atStart(e.doc),apply:t=>t.selection}),new LE("storedMarks",{init:t=>t.storedMarks||null,apply:(t,e,n,r)=>r.selection.$cursor?t.storedMarks:null}),new LE("scrollToSelection",{init:()=>0,apply:(t,e)=>t.scrolledIntoView?e+1:e});var $E=/^\s*>\s$/,DE=fM.create({name:"blockquote",addOptions:()=>({HTMLAttributes:{}}),content:"block+",group:"block",defining:!0,parseHTML:()=>[{tag:"blockquote"}],renderHTML({HTMLAttributes:t}){
45
- return hI("blockquote",{...LS(this.options.HTMLAttributes,t),children:hI("slot",{})})},parseMarkdown:(t,e)=>{var n;const r=null!=(n=e.parseBlockChildren)?n:e.parseChildren;return e.createNode("blockquote",void 0,r(t.tokens||[]))},renderMarkdown:(t,e)=>{if(!t.content)return"";const n=[];return t.content.forEach((t,r)=>{var o,i;const s=(null!=(i=null==(o=e.renderChild)?void 0:o.call(e,t,r))?i:e.renderChildren([t])).split("\n").map(t=>""===t.trim()?">":`> ${t}`);n.push(s.join("\n"))}),n.join("\n>\n")},addCommands(){return{setBlockquote:()=>({commands:t})=>t.wrapIn(this.name),toggleBlockquote:()=>({commands:t})=>t.toggleWrap(this.name),unsetBlockquote:()=>({commands:t})=>t.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote(),Backspace:()=>((t,e)=>{var n;const{state:r,view:o}=t,{selection:i}=r;if(!i.empty)return!1;const{$from:s}=i;if(0!==s.parentOffset)return!1;const a=s.depth-1,l=s.node(a),c=s.index(a);if(0===c)return!1;if(l.type===e)return t.commands.lift(e.name);const d=l.child(c-1);if(d.type!==e||!(null==(n=d.lastChild)?void 0:n.isTextblock))return!1;const u=s.before(),p=u-1-1,{tr:h}=r;return h.delete(u,s.after()).insert(p,s.parent.content),h.setSelection(ME.create(h.doc,p)),o.dispatch(h.scrollIntoView()),!0})(this.editor,this.type)}},addInputRules(){return[hM({find:$E,type:this.type})]}}),BE=t=>{const e=/`([^`]+)`(?!`)$/.exec(t);return e?e.index>0&&"`"===t[e.index-1]?null:{index:e.index,text:e[0],replaceWith:e[1]}:null},zE=t=>{const e=/`([^`]+)`(?!`)/g,n=[];let r;for(;null!==(r=e.exec(t));)r.index>0&&"`"===t[r.index-1]||n.push({index:r.index,text:r[0],replaceWith:r[1]});return n},FE=VP.create({name:"code",addOptions:()=>({HTMLAttributes:{}}),excludes:"_",code:!0,exitable:!0,parseHTML:()=>[{tag:"code"}],renderHTML({HTMLAttributes:t}){return["code",LS(this.options.HTMLAttributes,t),0]},markdownTokenName:"codespan",parseMarkdown:(t,e)=>e.applyMark("code",[{type:"text",text:t.text||""}]),renderMarkdown:(t,e)=>t.content?`\`${e.renderChildren(t.content)}\``:"",addCommands(){return{setCode:()=>({commands:t})=>t.setMark(this.name),toggleCode:()=>({commands:t})=>t.toggleMark(this.name),unsetCode:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[uM({find:BE,type:this.type})]},addPasteRules(){return[mM({find:zE,type:this.type})]}}),jE=/^```([a-z]+)?[\s\n]$/,WE=/^~~~([a-z]+)?[\s\n]$/,HE=fM.create({name:"codeBlock",addOptions:()=>({languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:4,HTMLAttributes:{}}),content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:t=>{var e;const{languageClassPrefix:n}=this.options;if(!n)return null;const r=[...(null==(e=t.firstElementChild)?void 0:e.classList)||[]].filter(t=>t.startsWith(n)).map(t=>t.replace(n,""))[0];return r||null},rendered:!1}}},parseHTML:()=>[{tag:"pre",preserveWhitespace:"full"}],renderHTML({node:t,HTMLAttributes:e}){return["pre",LS(this.options.HTMLAttributes,e),["code",{class:t.attrs.language?this.options.languageClassPrefix+t.attrs.language:null},0]]},markdownTokenName:"code",parseMarkdown:(t,e)=>{var n,r;return!1===(null==(n=t.raw)?void 0:n.startsWith("```"))&&!1===(null==(r=t.raw)?void 0:r.startsWith("~~~"))&&"indented"!==t.codeBlockStyle?[]:e.createNode("codeBlock",{language:t.lang||null},t.text?[e.createTextNode(t.text)]:[])},renderMarkdown:(t,e)=>{var n;let r="";const o=(null==(n=t.attrs)?void 0:n.language)||"";return r=t.content?[`\`\`\`${o}`,e.renderChildren(t.content),"```"].join("\n"):`\`\`\`${o}\n\n\`\`\``,r},addCommands(){return{setCodeBlock:t=>({commands:e})=>e.setNode(this.name,t),toggleCodeBlock:t=>({commands:e})=>e.toggleNode(this.name,"paragraph",t)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:t,$anchor:e}=this.editor.state.selection,n=1===e.pos;return!(!t||e.parent.type.name!==this.name)&&(!(!n&&e.parent.textContent.length)&&this.editor.commands.clearNodes())},Tab:({editor:t})=>{var e;if(!this.options.enableTabIndentation)return!1;const n=null!=(e=this.options.tabSize)?e:4,{state:r}=t,{selection:o}=r,{$from:i,empty:s}=o;if(i.parent.type!==this.type)return!1;const a=" ".repeat(n);return s?t.commands.insertContent(a):t.commands.command(({tr:t})=>{const{from:e,to:n}=o,i=r.doc.textBetween(e,n,"\n","\n").split("\n").map(t=>a+t).join("\n");return t.replaceWith(e,n,r.schema.text(i)),!0})},"Shift-Tab":({editor:t})=>{var e;if(!this.options.enableTabIndentation)return!1;const n=null!=(e=this.options.tabSize)?e:4,{state:r}=t,{selection:o}=r,{$from:i,empty:s}=o;return i.parent.type===this.type&&(s?t.commands.command(({tr:t})=>{var e;const{pos:o}=i,s=i.start(),a=i.end(),l=r.doc.textBetween(s,a,"\n","\n").split("\n");let c=0,d=0;const u=o-s;for(let n=0;n<l.length;n+=1){if(d+l[n].length>=u){c=n;break}d+=l[n].length+1}const p=(null==(e=l[c].match(/^ */))?void 0:e[0])||"",h=Math.min(p.length,n);if(0===h)return!0;let f=s;for(let n=0;n<c;n+=1)f+=l[n].length+1;return t.delete(f,f+h),o-f<=h&&t.setSelection(jy.create(t.doc,f)),!0}):t.commands.command(({tr:t})=>{const{from:e,to:i}=o,s=r.doc.textBetween(e,i,"\n","\n").split("\n").map(t=>{var e;const r=(null==(e=t.match(/^ */))?void 0:e[0])||"",o=Math.min(r.length,n);return t.slice(o)}).join("\n");return t.replaceWith(e,i,r.schema.text(s)),!0}))},Enter:({editor:t})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:e}=t,{selection:n}=e,{$from:r,empty:o}=n;if(!o||r.parent.type!==this.type)return!1;const i=r.parentOffset===r.parent.nodeSize-2,s=r.parent.textContent.endsWith("\n\n");return!(!i||!s)&&t.chain().command(({tr:t})=>(t.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowDown:({editor:t})=>{if(!this.options.exitOnArrowDown)return!1;const{state:e}=t,{selection:n,doc:r}=e,{$from:o,empty:i}=n;if(!i||o.parent.type!==this.type)return!1;if(o.parentOffset!==o.parent.nodeSize-2)return!1;const s=o.after();return void 0!==s&&(r.nodeAt(s)?t.commands.command(({tr:t})=>(t.setSelection(Dy.near(r.resolve(s))),!0)):t.commands.exitCode())}}},addInputRules(){return[pM({find:jE,type:this.type,getAttributes:t=>({language:t[1]})}),pM({find:WE,type:this.type,getAttributes:t=>({language:t[1]})})]},addProseMirrorPlugins(){return[new ex({key:new ox("codeBlockVSCodeHandler"),props:{handlePaste:(t,e)=>{if(!e.clipboardData)return!1;if(this.editor.isActive(this.type.name))return!1;const n=e.clipboardData.getData("text/plain"),r=e.clipboardData.getData("vscode-editor-data"),o=r?JSON.parse(r):void 0,i=null==o?void 0:o.mode;if(!n||!i)return!1;const{tr:s,schema:a}=t.state,l=a.text(n.replace(/\r\n?/g,"\n"));return s.replaceSelectionWith(this.type.create({language:i},l)),s.selection.$from.parent.type!==this.type&&s.setSelection(jy.near(s.doc.resolve(Math.max(0,s.selection.from-2)))),s.setMeta("paste",!0),t.dispatch(s),!0}}})]}}),_E=fM.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,"\n\n"):""}),UE=fM.create({name:"hardBreak",markdownTokenName:"br",addOptions:()=>({keepMarks:!0,HTMLAttributes:{}}),inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML:()=>[{tag:"br"}],renderHTML({HTMLAttributes:t}){return["br",LS(this.options.HTMLAttributes,t)]},renderText:()=>"\n",renderMarkdown:()=>" \n",parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:t,chain:e,state:n,editor:r})=>t.first([()=>t.exitCode(),()=>t.command(()=>{const{selection:t,storedMarks:o}=n;if(t.$from.parent.type.spec.isolating)return!1;const{keepMarks:i}=this.options,{splittableMarks:s}=r.extensionManager,a=o||t.$to.parentOffset&&t.$from.marks();return e().insertContent({type:this.name}).command(({tr:t,dispatch:e})=>{if(e&&a&&i){const e=a.filter(t=>s.includes(t.type.name));t.ensureMarks(e)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),VE=fM.create({name:"heading",addOptions:()=>({levels:[1,2,3,4,5,6],HTMLAttributes:{}}),content:"inline*",group:"block",defining:!0,addAttributes:()=>({level:{default:1,rendered:!1}}),parseHTML(){return this.options.levels.map(t=>({tag:`h${t}`,attrs:{level:t}}))},renderHTML({node:t,HTMLAttributes:e}){return[`h${this.options.levels.includes(t.attrs.level)?t.attrs.level:this.options.levels[0]}`,LS(this.options.HTMLAttributes,e),0]},parseMarkdown:(t,e)=>e.createNode("heading",{level:t.depth||1},e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>{var n;const r=(null==(n=t.attrs)?void 0:n.level)?parseInt(t.attrs.level,10):1,o="#".repeat(r);return t.content?`${o} ${e.renderChildren(t.content)}`:""},addCommands(){return{setHeading:t=>({commands:e})=>!!this.options.levels.includes(t.level)&&e.setNode(this.name,t),toggleHeading:t=>({commands:e})=>!!this.options.levels.includes(t.level)&&e.toggleNode(this.name,"paragraph",t)}},addKeyboardShortcuts(){return this.options.levels.reduce((t,e)=>({...t,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(t=>pM({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${t}})\\s$`),type:this.type,getAttributes:{level:t}}))}}),KE=fM.create({name:"horizontalRule",addOptions:()=>({HTMLAttributes:{},nextNodeType:"paragraph"}),group:"block",parseHTML:()=>[{tag:"hr"}],renderHTML({HTMLAttributes:t}){return["hr",LS(this.options.HTMLAttributes,t)]},markdownTokenName:"hr",parseMarkdown:(t,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:t,state:e})=>{if(!function(t,e){const{selection:n}=t,{$from:r}=n;if(n instanceof Hy){const t=r.index();return r.parent.canReplaceWith(t,t+1,e)}let o=r.depth;for(;o>=0;){const t=r.index(o);if(r.node(o).contentMatchAt(t).matchType(e))return!0;o-=1}return!1}(e,e.schema.nodes[this.name]))return!1;const{selection:n}=e,{$to:r}=n,o=t();return QS(n)?o.insertContentAt(r.pos,{type:this.name}):o.insertContent({type:this.name}),o.command(({state:t,tr:e,dispatch:n})=>{if(n){const{$to:n}=e.selection,r=n.end();if(n.nodeAfter)n.nodeAfter.isTextblock?e.setSelection(jy.create(e.doc,n.pos+1)):n.nodeAfter.isBlock?e.setSelection(Hy.create(e.doc,n.pos)):e.setSelection(jy.create(e.doc,n.pos));else{const o=t.schema.nodes[this.options.nextNodeType]||n.parent.type.contentMatch.defaultType,i=null==o?void 0:o.create();i&&(e.insert(r,i),e.setSelection(jy.create(e.doc,r+1)))}e.scrollIntoView()}return!0}).run()}}},addInputRules(){return[(t={find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type},new HP({find:t.find,handler:({state:e,range:n,match:r})=>{const o=AS(t.getAttributes,void 0,r)||{},{tr:i}=e,s=n.from;let a=n.to;const l=t.type.create(o);if(r[1]){let t=s+r[0].lastIndexOf(r[1]);t>a?t=a:a=t+r[1].length;const e=r[0][r[0].length-1];i.insertText(e,s+r[0].length-1),i.replaceWith(t,a,l)}else if(r[0]){const e=t.type.isInline?s:s-1;i.insert(e,t.type.create(o)).delete(i.mapping.map(s),i.mapping.map(a))}i.scrollIntoView()},undoable:t.undoable}))];var t}}),qE=Object.defineProperty,XE="textStyle",YE=/^\s*([-+*])\s$/,JE=fM.create({name:"bulletList",addOptions:()=>({itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}),group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML:()=>[{tag:"ul"}],renderHTML({HTMLAttributes:t}){return["ul",LS(this.options.HTMLAttributes,t),0]},markdownTokenName:"list",parseMarkdown:(t,e)=>"list"!==t.type||t.ordered?[]:{type:"bulletList",content:t.items?e.parseChildren(t.items):[]},renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,"\n"):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes("listItem",this.editor.getAttributes(XE)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let t=hM({find:YE,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(t=hM({find:YE,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(XE),editor:this.editor})),[t]}}),GE=(t,e,n)=>((t,e,n,r)=>{const o=((t,e,n)=>{const{selection:r}=t;if(!r.empty)return null;const{$from:o}=r;if(!o.parent.isTextblock)return null;if(o.parentOffset!==o.parent.content.size)return null;let i=-1;for(let h=o.depth;h>0;h-=1)if(o.node(h).type.name===e){i=h;break}if(i<0)return null;const s=o.node(i),a=o.index(i);if(a+1>=s.childCount)return null;const l=s.child(a+1);if(!n.includes(l.type.name))return null;const c=t.schema.nodes[e];let d=!1;if(l.forEach(t=>{t.type===c&&t.childCount>1&&(d=!0)}),!d)return null;const u=t.doc.resolve(o.after()).nodeAfter;if(!u||!n.includes(u.type.name))return null;const p=[];return u.forEach(t=>{p.push(t)}),0===p.length?null:{listItemDepth:i,nestedList:u,nestedListPos:o.after(),insertPos:o.after(i),items:p}})(t,n,r);if(!o)return!1;const{selection:i}=t,{nestedList:s,nestedListPos:a,insertPos:l,items:c}=o,d=t.tr;d.delete(a,a+s.nodeSize);const u=d.mapping.map(l);return d.insert(u,Bm.from(c)),d.setSelection(i.map(d.doc,d.mapping)),e&&e(d),!0})(t.state,t.view.dispatch,e,n),ZE=(t,e)=>GP.create({name:`${t}BranchingDeleteKeymap`,priority:101,addKeyboardShortcuts(){const n=()=>GE(this.editor,t,e);return{Delete:n,"Mod-Delete":n}}}),QE=[[1e3,"m"],[900,"cm"],[500,"d"],[400,"cd"],[100,"c"],[90,"xc"],[50,"l"],[40,"xl"],[10,"x"],[9,"ix"],[5,"v"],[4,"iv"],[1,"i"]],tA="abcdefghijklmnopqrstuvwxyz",eA=String.raw`\d+|[ivxlcdmIVXLCDM]+|${"[a-zA-Z]{1,2}"}`;function nA(t){let e=t,n="";for(const[r,o]of QE)for(;e>=r;)n+=o,e-=r;return n}function rA(t){return nA(t).toUpperCase()}function oA(t){const e=t.toLowerCase();let n=0,r=0;for(;n<e.length;){let t=!1;for(const[o,i]of QE)if(e.startsWith(i,n)){r+=o,n+=i.length,t=!0;break}if(!t)return 0}return r}function iA(t){if(t<=26)return tA[t-1];const e=Math.floor((t-1)/26)-1,n=(t-1)%26;return e<0?tA[n]:tA[e]+tA[n]}function sA(t){if(t&&!/^\d+$/.test(t))return function(t){if(!/^[ivxlcdmIVXLCDM]+$/.test(t))return!1;const e=oA(t);return!(e<=0)&&(t===t.toLowerCase()?nA(e):rA(e))===t}(t)?t===t.toLowerCase()?"i":"I":/^[a-z]{1,2}$/.test(t)?"a":/^[A-Z]{1,2}$/.test(t)?"A":void 0}function aA(t){if(/^\d+$/.test(t))return parseInt(t,10);const e=sA(t);if("i"===e||"I"===e)return oA(t);if("a"===e||"A"===e){const e=function(t){const e=t.toLowerCase();if(1===e.length)return e.charCodeAt(0)-"a".charCodeAt(0)+1;if(2===e.length)return 26*(e.charCodeAt(0)-"a".charCodeAt(0)+1)+(e.charCodeAt(1)-"a".charCodeAt(0))+1;return 0}(t);return e>0?e:1}const n=parseInt(t,10);return Number.isNaN(n)?1:n}function lA(t,e){if("numeric"===t)return String(e);switch(t){case"a":return iA(e);case"A":return iA(e).toUpperCase();case"i":return nA(e);case"I":return rA(e);default:return String(e)}}function cA(t){const{type:e,start:n}=function(t){return{type:sA(t),start:aA(t)}}(t),r={};return e&&(r.type=e),1!==n&&(r.start=n),r}function dA(t,e){return e.tokenizeInline?e.parseInline(e.tokenizeInline(t)):e.parseInline([{type:"text",raw:t,text:t}])}var uA=fM.create({name:"listItem",addOptions:()=>({HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}),content:"paragraph block*",defining:!0,parseHTML:()=>[{tag:"li"}],renderHTML({HTMLAttributes:t}){return["li",LS(this.options.HTMLAttributes,t),0]},markdownTokenName:"list_item",parseMarkdown:(t,e)=>{var n;if("list_item"!==t.type)return[];const r=null!=(n=e.parseBlockChildren)?n:e.parseChildren;let o=[];if(t.tokens&&t.tokens.length>0){if(function(t){var e,n;const r=null==(e=t.tokens)?void 0:e[0];return Boolean(t.text&&1===(null==(n=t.tokens)?void 0:n.length)&&"list"===(null==r?void 0:r.type)&&r.ordered&&r.raw===t.text)}(t))return{type:"listItem",content:[{type:"paragraph",content:dA(t.text||"",e)}]};if(t.tokens.some(t=>"paragraph"===t.type))o=r(t.tokens);else{const n=t.tokens[0];if(n&&"text"===n.type&&n.tokens&&n.tokens.length>0){if(o=[{type:"paragraph",content:e.parseInline(n.tokens)}],t.tokens.length>1){const e=r(t.tokens.slice(1));o.push(...e)}}else o=r(t.tokens)}}return 0===o.length&&(o=[{type:"paragraph",content:[]}]),{type:"listItem",content:o}},renderMarkdown:(t,e,n)=>jP(t,e,t=>{var e,n,r,o;if("bulletList"===t.parentType)return"- ";if("orderedList"===t.parentType){const i=(null==(n=null==(e=t.meta)?void 0:e.parentAttrs)?void 0:n.start)||1;return function(t,e,n=". "){const r=e+1;if(!t||"1"===t)return`${r}${n}`;switch(t){case"a":return`${iA(r)}${n}`;case"A":return`${iA(r).toUpperCase()}${n}`;case"i":return`${nA(r)}${n}`;case"I":return`${rA(r)}${n}`;default:return`${r}${n}`}}(null==(o=null==(r=t.meta)?void 0:r.parentAttrs)?void 0:o.type,i-1+(t.index||0),". ")}return"- "},n),addExtensions(){return[ZE(this.name,[this.options.bulletListTypeName,this.options.orderedListTypeName])]},addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}});((t,e)=>{for(var n in e)qE(t,n,{get:e[n],enumerable:!0})})({},{findListItemPos:()=>pA,getNextListDepth:()=>hA,handleBackspace:()=>mA,handleDelete:()=>xA,hasListBefore:()=>fA,hasListItemAfter:()=>wA,hasListItemBefore:()=>bA,listItemHasSubList:()=>vA,nextListIsDeeper:()=>gA,nextListIsHigher:()=>yA});var pA=(t,e)=>{const{$from:n}=e.selection,r=Sk(t,e.schema);let o=null,i=n.depth,s=n.pos,a=null;for(;i>0&&null===a;)o=n.node(i),o.type===r?a=i:(i-=1,s-=1);return null===a?null:{$pos:e.doc.resolve(s),depth:a}},hA=(t,e)=>{const n=pA(t,e);if(!n)return!1;const[,r]=((t,e,n,r=20)=>{const o=t.doc.resolve(n);let i=r,s=null;for(;i>0&&null===s;){const t=o.node(i);(null==t?void 0:t.type.name)===e?s=t:i-=1}return[s,i]})(e,t,n.$pos.pos+4);return r},fA=(t,e,n)=>{const{$anchor:r}=t.selection,o=Math.max(0,r.pos-2),i=t.doc.resolve(o).node();return!(!i||!n.includes(i.type.name))},mA=(t,e,n)=>{if(t.commands.undoInputRule())return!0;if(t.state.selection.from!==t.state.selection.to)return!1;if(!sS(t.state,e)&&fA(t.state,e,n)){const{$anchor:n}=t.state.selection,r=t.state.doc.resolve(n.before()-1),o=[];r.node().descendants((t,n)=>{t.type.name===e&&o.push({node:t,pos:n})});const i=o.at(-1);if(!i)return!1;const s=t.state.doc.resolve(r.start()+i.pos+1);return t.chain().cut({from:n.start()-1,to:n.end()+1},s.end()).joinForward().run()}return!!sS(t.state,e)&&(!!(t=>{const{$from:e,$to:n}=t.selection;return!(e.parentOffset>0||e.pos!==n.pos)})(t.state)&&t.chain().liftListItem(e).run())},gA=(t,e)=>{const n=hA(t,e),r=pA(t,e);return!(!r||!n)&&n>r.depth},yA=(t,e)=>{const n=hA(t,e),r=pA(t,e);return!(!r||!n)&&n<r.depth},xA=(t,e)=>{if(!sS(t.state,e))return!1;if(!((t,e)=>{const{$from:n,$to:r,$anchor:o}=t.selection;if(e){const n=MS(t=>t.type.name===e)(t.selection);if(!n)return!1;const r=t.doc.resolve(n.pos+1);return o.pos+1===r.end()}return!(r.parentOffset<r.parent.nodeSize-2||n.pos!==r.pos)})(t.state,e))return!1;const{selection:n}=t.state,{$from:r,$to:o}=n;return!(!n.empty&&r.sameParent(o))&&(gA(e,t.state)?t.chain().focus(t.state.selection.from+4).lift(e).joinBackward().run():yA(e,t.state)?t.chain().joinForward().joinBackward().run():t.commands.joinItemForward())},wA=(t,e)=>{var n;const{$anchor:r}=e.selection,o=e.doc.resolve(r.pos-r.parentOffset-2);return o.index()!==o.parent.childCount-1&&(null==(n=o.nodeAfter)?void 0:n.type.name)===t},bA=(t,e)=>{var n;const{$anchor:r}=e.selection,o=e.doc.resolve(r.pos-2);return 0!==o.index()&&(null==(n=o.nodeBefore)?void 0:n.type.name)===t},vA=(t,e,n)=>{if(!n)return!1;const r=Sk(t,e.schema);let o=!1;return n.descendants(t=>{t.type===r&&(o=!0)}),o},kA=GP.create({name:"listKeymap",addOptions:()=>({listTypes:[{itemName:"listItem",wrapperNames:["bulletList","orderedList"]},{itemName:"taskItem",wrapperNames:["taskList"]}]}),addKeyboardShortcuts(){return{Delete:({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n})=>{void 0!==t.state.schema.nodes[n]&&xA(t,n)&&(e=!0)}),e},"Mod-Delete":({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n})=>{void 0!==t.state.schema.nodes[n]&&xA(t,n)&&(e=!0)}),e},Backspace:({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:r})=>{void 0!==t.state.schema.nodes[n]&&mA(t,n,r)&&(e=!0)}),e},"Mod-Backspace":({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:r})=>{void 0!==t.state.schema.nodes[n]&&mA(t,n,r)&&(e=!0)}),e}}}}),SA=new RegExp(`^(\\s*)(${eA})([.)])\\s+(.*)$`),PA=new RegExp(`^(\\s*)(${eA})([.)])\\s+`),MA=/^\s/,IA={heading:/^#{1,6}(?:\s|$)/,bulletItem:/^[-+*]\s+/,codeFence:/^(?:```|~~~)/,thematicBreak:/^(?:(?:-[ \t]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})$/};function TA(t){const e=t.trimStart();return IA.bulletItem.test(e)||function(t){return SA.test(t.trimStart())}(e)||IA.heading.test(e)||IA.thematicBreak.test(e)&&!e.startsWith("-")||/^>\s?/.test(e)||IA.codeFence.test(e)}function CA(t){return Object.values(IA).some(e=>e.test(t))}function EA(t){const e=[],n=[];let r=!1;return t.forEach(t=>{if(!r)return""===t.trim()||e.length>0&&TA(t)?(r=!0,void n.push(t)):void e.push(t);n.push(t)}),{paragraphLines:e,blockLines:n}}var AA=new RegExp(`^(${eA})([.)])\\s+(.+)$`);function OA(t){const e=t.split("\n").filter(t=>t.trim().length>0);if(0===e.length)return null;const n=[];for(const r of e){const t=r.trim().match(AA);if(!t)return null;n.push({marker:t[1],content:t[3]})}return function(t){var e;if(0===t.length)return!1;const n=null!=(e=sA(t[0]))?e:"numeric",r=aA(t[0]);if(r<1)return!1;for(let o=0;o<t.length;o++){const e=lA(n,r+o);if(t[o]!==e)return!1}return!0}(n.map(t=>t.marker))?{type:"orderedList",attrs:cA(n[0].marker),content:n.map(t=>({type:"listItem",content:[{type:"paragraph",content:[{type:"text",text:t.content}]}]}))}:null}function NA(t,e,n){const r=[];let o=0;for(;o<t.length;){const i=t[o];if(i.indent===e){const{paragraphLines:s,blockLines:a}=EA(i.contentLines),l=s.join("\n").trim(),c=[];l&&c.push({type:"paragraph",raw:l,tokens:n.inlineTokens(l)});const d=a.join("\n").trim();if(d){const t=n.blockTokens(d);c.push(...t)}let u=o+1;const p=[];for(;u<t.length&&t[u].indent>e;)p.push(t[u]),u+=1;if(p.length>0){const t=NA(p,Math.min(...p.map(t=>t.indent)),n);c.push({type:"list",ordered:!0,start:p[0].number,typeMarker:p[0].type,items:t,raw:p.map(t=>t.raw).join("\n")})}r.push({type:"list_item",raw:i.raw,tokens:c}),o=u}else o+=1}return r}var RA="textStyle",LA=/^(\d+)\.\s$/;function $A(t){const e=t.match(/list-style-type\s*:\s*([^;]+)/i);if(!e)return null;switch(e[1].trim().toLowerCase()){case"upper-roman":return"I";case"lower-roman":return"i";case"upper-alpha":case"upper-latin":return"A";case"lower-alpha":case"lower-latin":return"a";default:return null}}var DA=fM.create({name:"orderedList",addOptions:()=>({itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}),group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes:()=>({start:{default:1,parseHTML:t=>t.hasAttribute("start")?parseInt(t.getAttribute("start")||"",10):1},type:{default:null,parseHTML:t=>{const e=t.getAttribute("type");if(e)return e;const n=t.getAttribute("style");if(n){const t=$A(n);if(t)return t}const r=t.querySelector("li");if(r){const t=r.getAttribute("style");if(t){const e=$A(t);if(e)return e}}return null}}}),parseHTML:()=>[{tag:"ol"}],renderHTML({HTMLAttributes:t}){const{start:e,type:n,...r}=t,o=LS(this.options.HTMLAttributes,r);return 1!==e&&(o.start=e),n&&"1"!==n&&(o.type=n),["ol",o,0]},markdownTokenName:"list",parseMarkdown:(t,e)=>{if("list"!==t.type||!t.ordered)return[];const n=t.start||1,r=t.typeMarker,o=t.items?function(t,e){return t.map(t=>{if("list_item"!==t.type)return e.parseChildren([t])[0];const n=[];return t.tokens&&t.tokens.length>0&&t.tokens.forEach(t=>{if("paragraph"===t.type||"list"===t.type||"blockquote"===t.type||"code"===t.type)n.push(...e.parseChildren([t]));else if("text"===t.type&&t.tokens){const r=e.parseChildren([t]);n.push({type:"paragraph",content:r})}else{const r=e.parseChildren([t]);r.length>0&&n.push(...r)}}),{type:"listItem",content:n}})}(t.items,e):[],i={};return 1!==n&&(i.start=n),r&&(i.type=r),Object.keys(i).length>0?{type:"orderedList",attrs:i,content:o}:{type:"orderedList",content:o}},renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,"\n"):"",markdownTokenizer:{name:"orderedList",level:"block",start:t=>{const e=t.match(PA),n=null==e?void 0:e.index;return void 0!==n?n:-1},tokenize:(t,e,n)=>{var r,o;const i=t.split("\n"),[s,a]=function(t){const e=[];let n=0,r=0;for(;n<t.length;){const o=t[n],i=o.match(SA);if(!i)break;const[,s,a,l,c]=i,d=s.length,u=parseInt(a,10),p=isNaN(u)?sA(a):void 0,h=isNaN(u)?aA(a):u,f=[c];let m=n+1;const g=[o];let y=!1;for(;m<t.length;){const e=t[m];if(e.match(SA))break;if(""===e.trim())g.push(e),f.push(""),y=!0,m+=1;else if(e.match(MA)){const t=e.length-e.trimStart().length,n=d+a.length+1;g.push(e),f.push(e.slice(Math.min(t,n))),m+=1}else{if(y||CA(e))break;g.push(e),f.push(e),m+=1}}e.push({indent:d,number:h,type:p,content:f.join("\n").trim(),contentLines:f,raw:g.join("\n")}),r=m,n=m}return[e,r]}(i);if(0===s.length)return;const l=NA(s,s[0].indent,n);return 0!==l.length?{type:"list",ordered:!0,start:(null==(r=s[0])?void 0:r.number)||1,typeMarker:null==(o=s[0])?void 0:o.type,items:l,raw:i.slice(0,a).join("\n")}:void 0}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes("listItem",this.editor.getAttributes(RA)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addProseMirrorPlugins:()=>[new ex({props:{handlePaste:(t,e)=>{var n,r;const o=null==(n=e.clipboardData)?void 0:n.getData("text/html");if(null==o?void 0:o.trim())return!1;const i=null==(r=e.clipboardData)?void 0:r.getData("text/plain");if(!i)return!1;const s=OA(i);if(!s)return!1;try{const e=t.state.schema.nodeFromJSON(s),n=t.state.tr.replaceSelectionWith(e);return t.dispatch(n),!0}catch{return!1}}}})],addInputRules(){const t=(t,e)=>(!e.attrs.type||"1"===e.attrs.type)&&e.childCount+e.attrs.start===+t[1];let e=hM({find:LA,type:this.type,getAttributes:t=>({start:+t[1]}),joinPredicate:t});return(this.options.keepMarks||this.options.keepAttributes)&&(e=hM({find:LA,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(RA)}),joinPredicate:t,editor:this.editor})),[e]}}),BA=/^\s*(\[([( |x])?\])\s$/,zA=fM.create({name:"taskItem",addOptions:()=>({nested:!1,HTMLAttributes:{},taskListTypeName:"taskList",a11y:void 0}),content(){return this.options.nested?"paragraph block*":"paragraph+"},defining:!0,addAttributes:()=>({checked:{default:!1,keepOnSplit:!1,parseHTML:t=>{const e=t.getAttribute("data-checked");return""===e||"true"===e},renderHTML:t=>({"data-checked":t.checked})}}),parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51}]},renderHTML({node:t,HTMLAttributes:e}){return["li",LS(this.options.HTMLAttributes,e,{"data-type":this.name}),["label",["input",{type:"checkbox",checked:t.attrs.checked?"checked":null}],["span"]],["div",0]]},parseMarkdown:(t,e)=>{const n=[];if(t.tokens&&t.tokens.length>0?n.push(e.createNode("paragraph",{},e.parseInline(t.tokens))):t.text?n.push(e.createNode("paragraph",{},[e.createNode("text",{text:t.text})])):n.push(e.createNode("paragraph",{},[])),t.nestedTokens&&t.nestedTokens.length>0){const r=e.parseChildren(t.nestedTokens);n.push(...r)}return e.createNode("taskItem",{checked:t.checked||!1},n)},renderMarkdown:(t,e)=>{var n;return jP(t,e,`- [${(null==(n=t.attrs)?void 0:n.checked)?"x":" "}] `)},addExtensions(){return this.options.nested?[ZE(this.name,[this.options.taskListTypeName])]:[]},addKeyboardShortcuts(){const t={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...t,Tab:()=>this.editor.commands.sinkListItem(this.name)}:t},addNodeView(){return({node:t,HTMLAttributes:e,getPos:n,editor:r})=>{const o=document.createElement("li"),i=document.createElement("label"),s=document.createElement("span"),a=document.createElement("input"),l=document.createElement("div"),c=t=>{var e,n;a.ariaLabel=(null==(n=null==(e=this.options.a11y)?void 0:e.checkboxLabel)?void 0:n.call(e,t,a.checked))||`Task item checkbox for ${t.textContent||"empty task item"}`};c(t),i.contentEditable="false",a.type="checkbox",a.addEventListener("mousedown",t=>t.preventDefault()),a.addEventListener("change",e=>{if(!r.isEditable&&!this.options.onReadOnlyChecked)return void(a.checked=!a.checked);const{checked:o}=e.target;r.isEditable&&"function"==typeof n&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:t})=>{const e=n();if("number"!=typeof e)return!1;const r=t.doc.nodeAt(e);return t.setNodeMarkup(e,void 0,{...null==r?void 0:r.attrs,checked:o}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(t,o)||(a.checked=!a.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([t,e])=>{o.setAttribute(t,e)}),o.dataset.checked=t.attrs.checked,a.checked=t.attrs.checked,i.append(a,s),o.append(i,l),Object.entries(e).forEach(([t,e])=>{o.setAttribute(t,e)});let d=new Set(Object.keys(e));return{dom:o,contentDOM:l,update:t=>{if(t.type!==this.type)return!1;o.dataset.checked=t.attrs.checked,a.checked=t.attrs.checked,c(t);const e=$S(t,r.extensionManager.attributes),n=new Set(Object.keys(e)),i=this.options.HTMLAttributes;return d.forEach(t=>{n.has(t)||(t in i?o.setAttribute(t,i[t]):o.removeAttribute(t))}),Object.entries(e).forEach(([t,e])=>{null==e?t in i?o.setAttribute(t,i[t]):o.removeAttribute(t):o.setAttribute(t,e)}),d=n,!0}}}},addInputRules(){return[hM({find:BA,type:this.type,getAttributes:t=>({checked:"x"===t[t.length-1]})})]}}),FA=fM.create({name:"taskList",addOptions:()=>({itemTypeName:"taskItem",HTMLAttributes:{}}),group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`ul[data-type="${this.name}"]`,priority:51}]},renderHTML({HTMLAttributes:t}){return["ul",LS(this.options.HTMLAttributes,t,{"data-type":this.name}),0]},parseMarkdown:(t,e)=>e.createNode("taskList",{},e.parseChildren(t.items||[])),renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,"\n"):"",markdownTokenizer:{name:"taskList",level:"block",start(t){var e;const n=null==(e=t.match(/^\s*[-+*]\s+\[([ xX])\]\s+/))?void 0:e.index;return void 0!==n?n:-1},tokenize(t,e,n){const r=t=>{const e=FP(t,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:t=>({indentLevel:t[1].length,mainContent:t[4],checked:"x"===t[3].toLowerCase()}),createToken:(t,e)=>({type:"taskItem",raw:"",mainContent:t.mainContent,indentLevel:t.indentLevel,checked:t.checked,text:t.mainContent,tokens:n.inlineTokens(t.mainContent),nestedTokens:e}),customNestedParser:r},n);return e?[{type:"taskList",raw:e.raw,items:e.items}]:n.blockTokens(t)},o=FP(t,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:t=>({indentLevel:t[1].length,mainContent:t[4],checked:"x"===t[3].toLowerCase()}),createToken:(t,e)=>({type:"taskItem",raw:"",mainContent:t.mainContent,indentLevel:t.indentLevel,checked:t.checked,text:t.mainContent,tokens:n.inlineTokens(t.mainContent),nestedTokens:e}),customNestedParser:r},n);if(o)return{type:"taskList",raw:o.raw,items:o.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:t})=>t.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}}),jA=(GP.create({name:"listKit",addExtensions(){const t=[];return!1!==this.options.bulletList&&t.push(JE.configure(this.options.bulletList)),!1!==this.options.listItem&&t.push(uA.configure(this.options.listItem)),!1!==this.options.listKeymap&&t.push(kA.configure(this.options.listKeymap)),!1!==this.options.orderedList&&t.push(DA.configure(this.options.orderedList)),!1!==this.options.taskItem&&t.push(zA.configure(this.options.taskItem)),!1!==this.options.taskList&&t.push(FA.configure(this.options.taskList)),t}}),"&nbsp;"),WA=fM.create({name:"paragraph",priority:1e3,addOptions:()=>({HTMLAttributes:{}}),group:"block",content:"inline*",parseHTML:()=>[{tag:"p"}],renderHTML({HTMLAttributes:t}){return["p",LS(this.options.HTMLAttributes,t),0]},parseMarkdown:(t,e)=>{const n=t.tokens||[];if(1===n.length&&"image"===n[0].type)return e.parseChildren([n[0]]);const r=e.parseInline(n);return 1!==n.length||"text"!==n[0].type||n[0].raw!==jA&&n[0].text!==jA&&" "!==n[0].raw&&" "!==n[0].text||1!==r.length||"text"!==r[0].type||r[0].text!==jA&&" "!==r[0].text?e.createNode("paragraph",void 0,r):e.createNode("paragraph",void 0,[])},renderMarkdown:(t,e,n)=>{var r,o;if(!t)return"";const i=Array.isArray(t.content)?t.content:[];if(0===i.length){const t=Array.isArray(null==(r=null==n?void 0:n.previousNode)?void 0:r.content)?n.previousNode.content:[];return"paragraph"===(null==(o=null==n?void 0:n.previousNode)?void 0:o.type)&&0===t.length?jA:""}return e.renderChildren(i)},addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),HA=fM.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""});function _A(t={}){return new ex({view:e=>new UA(e,t)})}var UA=class{constructor(t,e){var n;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=null!==(n=e.width)&&void 0!==n?n:1,this.color=!1===e.color?void 0:e.color||"black",this.class=e.class,this.handlers=["dragover","dragend","drop","dragleave"].map(e=>{let n=t=>{this[e](t)};return t.dom.addEventListener(e,n),{name:e,handler:n}})}destroy(){this.handlers.forEach(({name:t,handler:e})=>this.editorView.dom.removeEventListener(t,e))}update(t,e){null!=this.cursorPos&&e.doc!=t.state.doc&&(this.cursorPos>t.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(t){t!=this.cursorPos&&(this.cursorPos=t,null==t?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let t,e=this.editorView.state.doc.resolve(this.cursorPos),n=!e.parent.inlineContent,r=this.editorView.dom,o=r.getBoundingClientRect(),i=o.width/r.offsetWidth,s=o.height/r.offsetHeight;if(n){let n=e.nodeBefore,r=e.nodeAfter;if(n||r){let e=this.editorView.nodeDOM(this.cursorPos-(n?n.nodeSize:0));if(e){let o=e.getBoundingClientRect(),i=n?o.bottom:o.top;n&&r&&(i=(i+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let a=this.width/2*s;t={left:o.left,right:o.right,top:i-a,bottom:i+a}}}}if(!t){let e=this.editorView.coordsAtPos(this.cursorPos),n=this.width/2*i;t={left:e.left-n,right:e.left+n,top:e.top,bottom:e.bottom}}let a,l,c=this.editorView.dom.offsetParent;if(this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n),!c||c==document.body&&"static"==getComputedStyle(c).position)a=-pageXOffset,l=-pageYOffset;else{let t=c.getBoundingClientRect(),e=t.width/c.offsetWidth,n=t.height/c.offsetHeight;a=t.left-c.scrollLeft*e,l=t.top-c.scrollTop*n}this.element.style.left=(t.left-a)/i+"px",this.element.style.top=(t.top-l)/s+"px",this.element.style.width=(t.right-t.left)/i+"px",this.element.style.height=(t.bottom-t.top)/s+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}dragover(t){if(!this.editorView.editable)return;let e=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),n=e&&e.inside>=0&&this.editorView.state.doc.nodeAt(e.inside),r=n&&n.type.spec.disableDropCursor,o="function"==typeof r?r(this.editorView,e,t):r;if(e&&!o){let t=e.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let e=wy(this.editorView.state.doc,t,this.editorView.dragging.slice);null!=e&&(t=e)}this.setCursor(t),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(t){this.editorView.dom.contains(t.relatedTarget)||this.setCursor(null)}},VA=class t extends Dy{constructor(t){super(t,t)}map(e,n){let r=e.resolve(n.map(this.head));return t.valid(r)?new t(r):Dy.near(r)}content(){return _m.empty}eq(e){return e instanceof t&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,n){if("number"!=typeof n.pos)throw new RangeError("Invalid input for GapCursor.fromJSON");return new t(e.resolve(n.pos))}getBookmark(){return new KA(this.anchor)}static valid(t){let e=t.parent;if(e.inlineContent||!function(t){for(let e=t.depth;e>=0;e--){let n=t.index(e),r=t.node(e);if(0!=n)for(let t=r.child(n-1);;t=t.lastChild){if(0==t.childCount&&!t.inlineContent||qA(t.type))return!0;if(t.inlineContent)return!1}else if(r.type.spec.isolating)return!0}return!0}(t)||!function(t){for(let e=t.depth;e>=0;e--){let n=t.indexAfter(e),r=t.node(e);if(n!=r.childCount)for(let t=r.child(n);;t=t.firstChild){if(0==t.childCount&&!t.inlineContent||qA(t.type))return!0;if(t.inlineContent)return!1}else if(r.type.spec.isolating)return!0}return!0}(t))return!1;let n=e.type.spec.allowGapCursor;if(null!=n)return n;let r=e.contentMatchAt(t.index()).defaultType;return r&&r.isTextblock}static findGapCursorFrom(e,n,r=!1){t:for(;;){if(!r&&t.valid(e))return e;let o=e.pos,i=null;for(let r=e.depth;;r--){let s=e.node(r);if(n>0?e.indexAfter(r)<s.childCount:e.index(r)>0){i=s.child(n>0?e.indexAfter(r):e.index(r)-1);break}if(0==r)return null;o+=n;let a=e.doc.resolve(o);if(t.valid(a))return a}for(;;){let s=n>0?i.firstChild:i.lastChild;if(!s){if(i.isAtom&&!i.isText&&!Hy.isSelectable(i)){e=e.doc.resolve(o+i.nodeSize*n),r=!1;continue t}break}i=s,o+=n;let a=e.doc.resolve(o);if(t.valid(a))return a}return null}}};VA.prototype.visible=!1,VA.findFrom=VA.findGapCursorFrom,Dy.jsonID("gapcursor",VA);var KA=class t{constructor(t){this.pos=t}map(e){return new t(e.map(this.pos))}resolve(t){let e=t.resolve(this.pos);return VA.valid(e)?new VA(e):Dy.near(e)}};function qA(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}var XA=ck({ArrowLeft:YA("horiz",-1),ArrowRight:YA("horiz",1),ArrowUp:YA("vert",-1),ArrowDown:YA("vert",1)});function YA(t,e){const n="vert"==t?e>0?"down":"up":e>0?"right":"left";return function(t,r,o){let i=t.selection,s=e>0?i.$to:i.$from,a=i.empty;if(i instanceof jy){if(!o.endOfTextblock(n)||0==s.depth)return!1;a=!1,s=t.doc.resolve(e>0?s.after():s.before())}let l=VA.findGapCursorFrom(s,e,a);return!!l&&(r&&r(t.tr.setSelection(new VA(l))),!0)}}function JA(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!VA.valid(r))return!1;let o=t.posAtCoords({left:n.clientX,top:n.clientY});return!(o&&o.inside>-1&&Hy.isSelectable(t.state.doc.nodeAt(o.inside)))&&(t.dispatch(t.state.tr.setSelection(new VA(r))),!0)}function GA(t,e){if("insertCompositionText"!=e.inputType||!(t.state.selection instanceof VA))return!1;let{$from:n}=t.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(t.state.schema.nodes.text);if(!r)return!1;let o=Bm.empty;for(let s=r.length-1;s>=0;s--)o=Bm.from(r[s].createAndFill(null,o));let i=t.state.tr.replace(n.pos,n.pos,new _m(o,0,0));return i.setSelection(jy.near(i.doc.resolve(n.pos+1))),t.dispatch(i),!1}function ZA(t){if(!(t.selection instanceof VA))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",kv.create(t.doc,[wv.widget(t.selection.head,e,{key:"gapcursor"})])}var QA=200,tO=function(){};tO.prototype.append=function(t){return t.length?(t=tO.from(t),!this.length&&t||t.length<QA&&this.leafAppend(t)||this.length<QA&&t.leafPrepend(this)||this.appendInner(t)):this},tO.prototype.prepend=function(t){return t.length?tO.from(t).append(this):this},tO.prototype.appendInner=function(t){return new nO(this,t)},tO.prototype.slice=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=this.length),t>=e?tO.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,e))},tO.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)},tO.prototype.forEach=function(t,e,n){void 0===e&&(e=0),void 0===n&&(n=this.length),e<=n?this.forEachInner(t,e,n,0):this.forEachInvertedInner(t,e,n,0)},tO.prototype.map=function(t,e,n){void 0===e&&(e=0),void 0===n&&(n=this.length);var r=[];return this.forEach(function(e,n){return r.push(t(e,n))},e,n),r},tO.from=function(t){return t instanceof tO?t:t&&t.length?new eO(t):tO.empty};var eO=function(t){function e(e){t.call(this),this.values=e}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var n={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(t,n){return 0==t&&n==this.length?this:new e(this.values.slice(t,n))},e.prototype.getInner=function(t){return this.values[t]},e.prototype.forEachInner=function(t,e,n,r){for(var o=e;o<n;o++)if(!1===t(this.values[o],r+o))return!1},e.prototype.forEachInvertedInner=function(t,e,n,r){for(var o=e-1;o>=n;o--)if(!1===t(this.values[o],r+o))return!1},e.prototype.leafAppend=function(t){if(this.length+t.length<=QA)return new e(this.values.concat(t.flatten()))},e.prototype.leafPrepend=function(t){if(this.length+t.length<=QA)return new e(t.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(e.prototype,n),e}(tO);tO.empty=new eO([]);var nO=function(t){function e(e,n){t.call(this),this.left=e,this.right=n,this.length=e.length+n.length,this.depth=Math.max(e.depth,n.depth)+1}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(t){return t<this.left.length?this.left.get(t):this.right.get(t-this.left.length)},e.prototype.forEachInner=function(t,e,n,r){var o=this.left.length;return!(e<o&&!1===this.left.forEachInner(t,e,Math.min(n,o),r))&&(!(n>o&&!1===this.right.forEachInner(t,Math.max(e-o,0),Math.min(this.length,n)-o,r+o))&&void 0)},e.prototype.forEachInvertedInner=function(t,e,n,r){var o=this.left.length;return!(e>o&&!1===this.right.forEachInvertedInner(t,e-o,Math.max(n,o)-o,r+o))&&(!(n<o&&!1===this.left.forEachInvertedInner(t,Math.min(e,o),n,r))&&void 0)},e.prototype.sliceInner=function(t,e){if(0==t&&e==this.length)return this;var n=this.left.length;return e<=n?this.left.slice(t,e):t>=n?this.right.slice(t-n,e-n):this.left.slice(t,n).append(this.right.slice(0,e-n))},e.prototype.leafAppend=function(t){var n=this.right.leafAppend(t);if(n)return new e(this.left,n)},e.prototype.leafPrepend=function(t){var n=this.left.leafPrepend(t);if(n)return new e(n,this.right)},e.prototype.appendInner=function(t){return this.left.depth>=Math.max(this.right.depth,t.depth)+1?new e(this.left,new e(this.right,t)):new e(this,t)},e}(tO),rO=class t{constructor(t,e){this.items=t,this.eventCount=e}popEvent(e,n){if(0==this.eventCount)return null;let r,o,i=this.items.length;for(;;i--)if(this.items.get(i-1).selection){--i;break}n&&(r=this.remapping(i,this.items.length),o=r.maps.length);let s,a,l=e.tr,c=[],d=[];return this.items.forEach((e,n)=>{if(!e.step)return r||(r=this.remapping(i,n+1),o=r.maps.length),o--,void d.push(e);if(r){d.push(new oO(e.map));let t,n=e.step.map(r.slice(o));n&&l.maybeStep(n).doc&&(t=l.mapping.maps[l.mapping.maps.length-1],c.push(new oO(t,void 0,void 0,c.length+d.length))),o--,t&&r.appendMap(t,o)}else l.maybeStep(e.step);return e.selection?(s=r?e.selection.map(r.slice(o)):e.selection,a=new t(this.items.slice(0,i).append(d.reverse().concat(c)),this.eventCount-1),!1):void 0},this.items.length,0),{remaining:a,transform:l,selection:s}}addTransform(e,n,r,o){let i=[],s=this.eventCount,a=this.items,l=!o&&a.length?a.get(a.length-1):null;for(let t=0;t<e.steps.length;t++){let r,c=e.steps[t].invert(e.docs[t]),d=new oO(e.mapping.maps[t],c,n);(r=l&&l.merge(d))&&(d=r,t?i.pop():a=a.slice(0,a.length-1)),i.push(d),n&&(s++,n=void 0),o||(l=d)}let c=s-r.depth;return c>sO&&(a=function(t,e){let n;return t.forEach((t,r)=>{if(t.selection&&0==e--)return n=r,!1}),t.slice(n)}(a,c),s-=c),new t(a.append(i),s)}remapping(t,e){let n=new Jg;return this.items.forEach((e,r)=>{let o=null!=e.mirrorOffset&&r-e.mirrorOffset>=t?n.maps.length-e.mirrorOffset:void 0;n.appendMap(e.map,o)},t,e),n}addMaps(e){return 0==this.eventCount?this:new t(this.items.append(e.map(t=>new oO(t))),this.eventCount)}rebased(e,n){if(!this.eventCount)return this;let r=[],o=Math.max(0,this.items.length-n),i=e.mapping,s=e.steps.length,a=this.eventCount;this.items.forEach(t=>{t.selection&&a--},o);let l=n;this.items.forEach(t=>{let n=i.getMirror(--l);if(null==n)return;s=Math.min(s,n);let o=i.maps[n];if(t.step){let s=e.steps[n].invert(e.docs[n]),c=t.selection&&t.selection.map(i.slice(l+1,n));c&&a++,r.push(new oO(o,s,c))}else r.push(new oO(o))},o);let c=[];for(let t=n;t<s;t++)c.push(new oO(i.maps[t]));let d=new t(this.items.slice(0,o).append(c).append(r),a);return d.emptyItemCount()>500&&(d=d.compress(this.items.length-r.length)),d}emptyItemCount(){let t=0;return this.items.forEach(e=>{e.step||t++}),t}compress(e=this.items.length){let n=this.remapping(0,e),r=n.maps.length,o=[],i=0;return this.items.forEach((t,s)=>{if(s>=e)o.push(t),t.selection&&i++;else if(t.step){let e=t.step.map(n.slice(r)),s=e&&e.getMap();if(r--,s&&n.appendMap(s,r),e){let a=t.selection&&t.selection.map(n.slice(r));a&&i++;let l,c=new oO(s.invert(),e,a),d=o.length-1;(l=o.length&&o[d].merge(c))?o[d]=l:o.push(c)}}else t.map&&r--},this.items.length,0),new t(tO.from(o.reverse()),i)}};rO.empty=new rO(tO.empty,0);var oO=class t{constructor(t,e,n,r){this.map=t,this.step=e,this.selection=n,this.mirrorOffset=r}merge(e){if(this.step&&e.step&&!e.selection){let n=e.step.merge(this.step);if(n)return new t(n.getMap().invert(),n,this.selection)}}},iO=class{constructor(t,e,n,r,o){this.done=t,this.undone=e,this.prevRanges=n,this.prevTime=r,this.prevComposition=o}},sO=20;function aO(t){let e=[];for(let n=t.length-1;n>=0&&0==e.length;n--)t[n].forEach((t,n,r,o)=>e.push(r,o));return e}function lO(t,e){if(!t)return null;let n=[];for(let r=0;r<t.length;r+=2){let o=e.map(t[r],1),i=e.map(t[r+1],-1);o<=i&&n.push(o,i)}return n}var cO=!1,dO=null;function uO(t){let e=t.plugins;if(dO!=e){cO=!1,dO=e;for(let t=0;t<e.length;t++)if(e[t].spec.historyPreserveItems){cO=!0;break}}return cO}var pO=new ox("history"),hO=new ox("closeHistory");function fO(t={}){return t={depth:t.depth||100,newGroupDelay:t.newGroupDelay||500},new ex({key:pO,state:{init:()=>new iO(rO.empty,rO.empty,null,0,-1),apply:(e,n,r)=>function(t,e,n,r){let o,i=n.getMeta(pO);if(i)return i.historyState;n.getMeta(hO)&&(t=new iO(t.done,t.undone,null,0,-1));let s=n.getMeta("appendedTransaction");if(0==n.steps.length)return t;if(s&&s.getMeta(pO))return s.getMeta(pO).redo?new iO(t.done.addTransform(n,void 0,r,uO(e)),t.undone,aO(n.mapping.maps),t.prevTime,t.prevComposition):new iO(t.done,t.undone.addTransform(n,void 0,r,uO(e)),null,t.prevTime,t.prevComposition);if(!1===n.getMeta("addToHistory")||s&&!1===s.getMeta("addToHistory"))return(o=n.getMeta("rebased"))?new iO(t.done.rebased(n,o),t.undone.rebased(n,o),lO(t.prevRanges,n.mapping),t.prevTime,t.prevComposition):new iO(t.done.addMaps(n.mapping.maps),t.undone.addMaps(n.mapping.maps),lO(t.prevRanges,n.mapping),t.prevTime,t.prevComposition);{let o=n.getMeta("composition"),i=0==t.prevTime||!s&&t.prevComposition!=o&&(t.prevTime<(n.time||0)-r.newGroupDelay||!function(t,e){if(!e)return!1;if(!t.docChanged)return!0;let n=!1;return t.mapping.maps[0].forEach((t,r)=>{for(let o=0;o<e.length;o+=2)t<=e[o+1]&&r>=e[o]&&(n=!0)}),n}(n,t.prevRanges)),a=s?lO(t.prevRanges,n.mapping):aO(n.mapping.maps);return new iO(t.done.addTransform(n,i?e.selection.getBookmark():void 0,r,uO(e)),rO.empty,a,n.time,null==o?t.prevComposition:o)}}(n,r,e,t)},config:t,props:{handleDOMEvents:{beforeinput(t,e){let n=e.inputType,r="historyUndo"==n?gO:"historyRedo"==n?yO:null;return!(!r||!t.editable)&&(e.preventDefault(),r(t.state,t.dispatch))}}}})}function mO(t,e){return(n,r)=>{let o=pO.getState(n);if(!o||0==(t?o.undone:o.done).eventCount)return!1;if(r){let i=function(t,e,n){let r=uO(e),o=pO.get(e).spec.config,i=(n?t.undone:t.done).popEvent(e,r);if(!i)return null;let s=i.selection.resolve(i.transform.doc),a=(n?t.done:t.undone).addTransform(i.transform,e.selection.getBookmark(),o,r),l=new iO(n?a:i.remaining,n?i.remaining:a,null,0,-1);return i.transform.setSelection(s).setMeta(pO,{redo:n,historyState:l})}(o,n,t);i&&r(e?i.scrollIntoView():i)}return!0}}var gO=mO(!1,!0),yO=mO(!0,!0),xO=(mO(!1,!1),mO(!0,!1),GP.create({name:"characterCount",addOptions:()=>({limit:null,autoTrim:!0,mode:"textSize",textCounter:t=>t.length,wordCounter:t=>t.split(" ").filter(t=>""!==t).length}),addStorage:()=>({characters:()=>0,words:()=>0}),onBeforeCreate(){this.storage.characters=t=>{const e=(null==t?void 0:t.node)||this.editor.state.doc;if("textSize"===((null==t?void 0:t.mode)||this.options.mode)){const t=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(t)}return e.nodeSize},this.storage.words=t=>{const e=(null==t?void 0:t.node)||this.editor.state.doc,n=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(n)}},addProseMirrorPlugins(){let t=!1;return[new ex({key:new ox("characterCount"),appendTransaction:(e,n,r)=>{if(t)return;const o=this.options.limit,i=this.options.autoTrim;if(null==o||0===o||!1===i)return void(t=!0);const s=this.storage.characters({node:r.doc});if(s>o){const e=0,n=s-o;console.warn(`[CharacterCount] Initial content exceeded limit of ${o} characters. Content was automatically trimmed.`);const i=r.tr.deleteRange(e,n);return t=!0,i}t=!0},filterTransaction:(t,e)=>{const n=this.options.limit;if(!t.docChanged||0===n||null==n)return!0;const r=this.storage.characters({node:e.doc}),o=this.storage.characters({node:t.doc});if(o<=n)return!0;if(r>n&&o>n&&o<=r)return!0;if(r>n&&o>n&&o>r)return!1;if(!t.getMeta("paste"))return!1;const i=t.selection.$head.pos,s=i-(o-n),a=i;return t.deleteRange(s,a),!(this.storage.characters({node:t.doc})>n)}})]}}),GP.create({name:"dropCursor",addOptions:()=>({color:"currentColor",width:1,class:void 0}),addProseMirrorPlugins(){return[_A(this.options)]}})),wO=(GP.create({name:"focus",addOptions:()=>({className:"has-focus",mode:"all"}),addProseMirrorPlugins(){return[new ex({key:new ox("focus"),props:{decorations:({doc:t,selection:e})=>{const{isEditable:n,isFocused:r}=this.editor,{anchor:o}=e,i=[];if(!n||!r)return kv.create(t,[]);let s=0;"deepest"===this.options.mode&&t.descendants((t,e)=>{if(!t.isText)return o>=e&&o<=e+t.nodeSize-1&&void(s+=1)});let a=0;return t.descendants((t,e)=>!t.isText&&(o>=e&&o<=e+t.nodeSize-1&&(a+=1,"deepest"===this.options.mode&&s-a>0||"shallowest"===this.options.mode&&a>1?"deepest"===this.options.mode:void i.push(wv.node(e,e+t.nodeSize,{class:this.options.className}))))),kv.create(t,i)}}})]}}),GP.create({name:"gapCursor",addProseMirrorPlugins:()=>[new ex({props:{decorations:ZA,createSelectionBetween:(t,e,n)=>e.pos==n.pos&&VA.valid(n)?new VA(n):null,handleClick:JA,handleKeyDown:XA,handleDOMEvents:{beforeinput:GA}}})],extendNodeSchema(t){var e;return{allowGapCursor:null!=(e=AS(IS(t,"allowGapCursor",{name:t.name,options:t.options,storage:t.storage})))?e:null}}})),bO="placeholder",vO=new ox("tiptap__placeholder");function kO(t){const{editor:e,placeholder:n,dataAttribute:r,pos:o,node:i,isEmptyDoc:s,hasAnchor:a,classes:{emptyNode:l,emptyEditor:c}}=t,d=[l];return s&&d.push(c),wv.node(o,o+i.nodeSize,{class:d.join(" "),[r]:"function"==typeof n?n({editor:e,node:i,pos:o,hasAnchor:a}):n})}function SO(t,e){return"function"==typeof t?t(e):t}function PO({editor:t,options:e,dataAttribute:n,doc:r,selection:o,from:i,to:s}){const{anchor:a}=o,l=[],c=t.isEmpty;return r.nodesBetween(i,s,(r,o)=>{const i=a>=o&&a<=o+r.nodeSize,s=!r.isLeaf&&ZS(r);return r.type.isTextblock?(!i&&e.showOnlyCurrent||!s||l.push(kO({editor:t,isEmptyDoc:c,dataAttribute:n,hasAnchor:i,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:SO(e.emptyNodeClass,{editor:t,node:r,pos:o,hasAnchor:i})},node:r,pos:o})),e.includeChildren):e.includeChildren}),l}function MO({editor:t,options:e,dataAttribute:n,doc:r,selection:o}){if(!t.isEditable&&e.showOnlyWhenEditable)return null;const{anchor:i}=o,s=[],a=t.isEmpty;if(e.showOnlyCurrent&&!e.includeChildren){const o=r.resolve(i),l=o.depth>0?o.node(1):o.nodeAfter,c=o.depth>0?o.before(1):i;if(l&&l.type.isTextblock&&ZS(l)){const r=i>=c&&i<=c+l.nodeSize;s.push(kO({editor:t,isEmptyDoc:a,dataAttribute:n,hasAnchor:r,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:SO(e.emptyNodeClass,{editor:t,node:l,pos:c,hasAnchor:r})},node:l,pos:c}))}}else s.push(...PO({editor:t,options:e,dataAttribute:n,doc:r,selection:o,from:0,to:r.content.size}));return kv.create(r,s)}function IO(t,e){var n;const r=t.resolve(e);if(0===r.depth){const t=null!=(n=r.nodeAfter)?n:r.nodeBefore;if(!t)return{from:e,to:e};const o=r.nodeAfter?e:e-t.nodeSize;return{from:o,to:o+t.nodeSize}}const o=r.before(1);return{from:o,to:o+r.node(1).nodeSize}}function TO(t,e){return{from:Math.max(0,e.from-1),to:Math.min(t.content.size,e.to-1)}}function CO(t,e){const n=function(t,e,n){const r=[];return t.forEach((t,o)=>{const i=o,s=i+t.nodeSize;i+1<n&&s+1>e&&r.push({from:i,to:s})}),r}(t,e.from,e.to);return n.push(TO(t,IO(t,e.from))),e.to>e.from?n.push(TO(t,IO(t,Math.min(e.to,t.content.size+1)-1))):e.from<t.content.size+1&&n.push(TO(t,IO(t,Math.min(e.from+1,t.content.size)))),n}function EO(t,e,n){const r=[];if(t.docChanged){const e=VS(t);for(const t of e)r.push(...CO(n.doc,t.newRange))}return t.selectionSet&&(r.push(TO(n.doc,IO(n.doc,t.mapping.map(e.selection.anchor)))),r.push(TO(n.doc,IO(n.doc,n.selection.anchor)))),function(t){if(0===t.length)return[];const e=[...t].sort((t,e)=>t.from-e.from),n=[{...e[0]}];for(let r=1;r<e.length;r+=1){const t=n[n.length-1],o=e[r];o.from<=t.to?t.to=Math.max(t.to,o.to):n.push({...o})}return n}(r)}function AO(t,e,n){const r=Math.max(0,Math.min(t,n.content.size));return{from:r,to:Math.max(r,Math.min(e,n.content.size))}}function OO({editor:t,options:e,dataAttribute:n}){return{init(r,o){const i=MO({editor:t,options:e,dataAttribute:n,doc:o.doc,selection:o.selection});return null!=i?i:kv.empty},apply:(r,o,i,s)=>r.docChanged||r.selectionSet?function({decorations:t,ranges:e,editor:n,options:r,dataAttribute:o,doc:i,selection:s}){let a=t;for(const l of e){const{from:t,to:e}=AO(l.from,l.to,i),c=a.find(t,e).filter(n=>n.from>=t&&n.to<=e);c.length&&(a=a.remove(c));const d=PO({editor:n,options:r,dataAttribute:o,doc:i,selection:s,from:t,to:e});d.length&&(a=a.add(i,d))}return a}({decorations:o.map(r.mapping,r.doc),ranges:EO(r,i,s),editor:t,options:e,dataAttribute:n,doc:s.doc,selection:s.selection}):o}}function NO({editor:t,options:e}){const n=e.dataAttribute?`data-${r=e.dataAttribute,r.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}`:`data-${bO}`;var r;const o=e.showOnlyCurrent&&!e.includeChildren;return new ex({key:vO,...o?{}:{state:OO({editor:t,options:e,dataAttribute:n})},props:{decorations:o?({doc:r,selection:o})=>MO({editor:t,options:e,dataAttribute:n,doc:r,selection:o}):n=>{var r;return e.showOnlyWhenEditable&&!t.isEditable?kv.empty:null!=(r=vO.getState(n))?r:kv.empty}}})}GP.create({name:"placeholder",addOptions:()=>({emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:bO,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}),addProseMirrorPlugins(){return[NO({editor:this.editor,options:this.options})]}}),GP.create({name:"selection",addOptions:()=>({className:"selection"}),addProseMirrorPlugins(){const{editor:t,options:e}=this;return t.options.injectCSS&&"undefined"!=typeof document&&EP(".ProseMirror:not(.ProseMirror-focused) *::selection {\n background: transparent;\n}\n\n.ProseMirror:not(.ProseMirror-focused) *::-moz-selection {\n background: transparent;\n}",t.options.injectNonce,"selection"),[new ex({key:new ox("selection"),props:{decorations:n=>n.selection.empty||t.isFocused||!t.isEditable||QS(n.selection)||t.view.dragging?null:kv.create(n.doc,[wv.inline(n.selection.from,n.selection.to,{class:e.className})])}})]}});function RO({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||(null==e?void 0:e.type)===t}var LO=GP.create({name:"trailingNode",addOptions:()=>({node:void 0,notAfter:[]}),addProseMirrorPlugins(){var t;const e=new ox(this.name),n=this.options.node||(null==(t=this.editor.schema.topNodeType.contentMatch.defaultType)?void 0:t.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,t])=>t).filter(t=>(this.options.notAfter||[]).concat(n).includes(t.name));return[new ex({key:e,appendTransaction:(t,r,o)=>{const{doc:i,tr:s,schema:a}=o,l=e.getState(o),c=i.content.size,d=a.nodes[n];if(!t.some(t=>t.getMeta("skipTrailingNode"))&&l)return s.insert(c,d.create())},state:{init:(t,e)=>!RO({node:e.tr.doc.lastChild,types:r}),apply:(t,e)=>{if(!t.docChanged)return e;if(t.getMeta("__uniqueIDTransaction"))return e;return!RO({node:t.doc.lastChild,types:r})}}})]}}),$O=GP.create({name:"undoRedo",addOptions:()=>({depth:100,newGroupDelay:500}),addCommands:()=>({undo:()=>({state:t,dispatch:e})=>gO(t,e),redo:()=>({state:t,dispatch:e})=>yO(t,e)}),addProseMirrorPlugins(){return[fO(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-я":()=>this.editor.commands.undo(),"Shift-Mod-я":()=>this.editor.commands.redo()}}}),DO=GP.create({name:"starterKit",addExtensions(){var t,e,n,r;const o=[];return!1!==this.options.bold&&o.push(xI.configure(this.options.bold)),!1!==this.options.blockquote&&o.push(DE.configure(this.options.blockquote)),!1!==this.options.bulletList&&o.push(JE.configure(this.options.bulletList)),!1!==this.options.code&&o.push(FE.configure(this.options.code)),!1!==this.options.codeBlock&&o.push(HE.configure(this.options.codeBlock)),!1!==this.options.document&&o.push(_E.configure(this.options.document)),!1!==this.options.dropcursor&&o.push(xO.configure(this.options.dropcursor)),!1!==this.options.gapcursor&&o.push(wO.configure(this.options.gapcursor)),!1!==this.options.hardBreak&&o.push(UE.configure(this.options.hardBreak)),!1!==this.options.heading&&o.push(VE.configure(this.options.heading)),!1!==this.options.undoRedo&&o.push($O.configure(this.options.undoRedo)),!1!==this.options.horizontalRule&&o.push(KE.configure(this.options.horizontalRule)),!1!==this.options.italic&&o.push(SI.configure(this.options.italic)),!1!==this.options.listItem&&o.push(uA.configure(this.options.listItem)),!1!==this.options.listKeymap&&o.push(kA.configure(null==(t=this.options)?void 0:t.listKeymap)),!1!==this.options.link&&o.push(vC.configure(null==(e=this.options)?void 0:e.link)),!1!==this.options.orderedList&&o.push(DA.configure(this.options.orderedList)),!1!==this.options.paragraph&&o.push(WA.configure(this.options.paragraph)),!1!==this.options.strike&&o.push(PC.configure(this.options.strike)),!1!==this.options.text&&o.push(HA.configure(this.options.text)),!1!==this.options.underline&&o.push(RC.configure(null==(n=this.options)?void 0:n.underline)),!1!==this.options.trailingNode&&o.push(LO.configure(null==(r=this.options)?void 0:r.trailingNode)),o}}),BO=new WeakMap;function zO(t,e){const n=function(t){const e=BO.get(t);if(e)return e;const n={api:null,disposeApiSubscription:null,listeners:new Set};return BO.set(t,n),n}(t);return n.disposeApiSubscription?.(),n.api=e,n.disposeApiSubscription=e.subscribe(()=>{jO(n)}),jO(n),()=>{n.api===e&&(n.disposeApiSubscription?.(),n.disposeApiSubscription=null,n.api=null,jO(n))}}function FO(t){return BO.get(t)?.api??null}function jO(t){for(const e of t.listeners)e()}function WO(t){const e=t.content.map(t=>"orderedList"===t.type||"bulletList"===t.type?{blockType:t.type,isEmptyTrailingParagraph:!1}:"blockquote"===t.type?{blockType:"blockquote",isEmptyTrailingParagraph:!1}:"paragraph"===t.type?{blockType:"paragraph",isEmptyTrailingParagraph:0===(t.content?.length??0)}:null).filter(t=>null!==t);if(0===e.length)return"paragraph";const n=e.some(({blockType:t})=>"paragraph"!==t)?e.filter(({isEmptyTrailingParagraph:t})=>!t):e,r=n[0]?.blockType??"paragraph";return n.every(({blockType:t})=>t===r)?r:"mixed"}function HO(t,e){if(WO(t)===e)return t;const n=function(t){const e=[],n=t=>{if("paragraph"!==t.type)if("codeBlock"!==t.type)for(const e of t.content??[])n(e);else e.push({type:"paragraph",content:t.content??[]});else e.push(t)},r=t.at(-1),o=t.length>1&&"paragraph"===r?.type&&0===(r.content?.length??0)&&t.slice(0,-1).some(t=>"orderedList"===t.type||"bulletList"===t.type||"blockquote"===t.type)?t.slice(0,-1):t;for(const i of o)n(i);return e.length>0?e:[{type:"paragraph"}]}(t.content),r="paragraph"===e?n:"blockquote"===e?[{type:"blockquote",content:n}]:[{type:e,content:n.map(t=>({type:"listItem",content:[t]}))}];return Af({...t,content:r})}var _O={bold:["bold","strong"],italic:["italic","em"],strike:["strike","s"],underline:["underline","u"]};function UO(t,e){const n=_O[e];let r=!1,o=!1;return XO(t.content,(t,e)=>{"text"!==t.type||!t.text||e.insideCodeBlock||t.marks?.some(t=>"code"===t.type)||(t.marks?.some(t=>n.includes(t.type))?r=!0:o=!0)}),r&&o?"mixed":r}function VO(t,e,n){const r=_O[e],o=YO(t.content,(t,o)=>{if("text"!==t.type||!t.text)return t;const i=t.marks??[],s=i.filter(t=>r.includes(t.type));if(n&&(o.insideCodeBlock||i.some(t=>"code"===t.type)))return t;if(n&&1===s.length&&s[0]?.type===e)return t;const a=i.filter(t=>!r.includes(t.type)),l=n?[...a,{type:e}]:a;return i.length===l.length&&i.every((t,e)=>t===l[e])?t:{...t,marks:l.length>0?l:void 0}});return o.changed?Af({...t,content:o.nodes}):t}function KO(t,e){const n=YO(t.content,(t,n)=>{if("text"!==t.type||!t.text)return t;const r=t.marks??[],o=r.filter(t=>"link"===t.type);if(null===e){if(0===o.length)return t;const e=r.filter(t=>"link"!==t.type);return{...t,marks:e.length>0?e:void 0}}if(n.insideCodeBlock||r.some(t=>"code"===t.type))return t;if(1===o.length&&o[0]?.attrs?.href===e)return t;const i=o[0];return{...t,marks:[...r.filter(t=>"link"!==t.type),{type:"link",attrs:{...i?.attrs,href:e}}]}});return n.changed?Af({...t,content:n.nodes}):t}function qO(t){const e=YO(t.content,t=>"text"===t.type&&t.marks&&t.marks.length>0?{...t,marks:void 0}:function(t){if("paragraph"!==t.type||void 0===t.attrs?.textAlign)return t;const e={...t.attrs};return delete e.textAlign,{...t,attrs:Object.keys(e).length>0?e:void 0}}(t));return e.changed?Af({...t,content:e.nodes}):t}function XO(t,e,n=!1){for(const r of t)e(r,{insideCodeBlock:n}),r.content&&XO(r.content,e,n||"codeBlock"===r.type)}function YO(t,e,n=!1){let r=!1;return{nodes:t.map(t=>{const o=e(t,{insideCodeBlock:n}),i=o.content;if(!i)return o!==t&&(r=!0),o;const s=YO(i,e,n||"codeBlock"===o.type);return s.changed?(r=!0,{...o,content:s.nodes}):(o!==t&&(r=!0),o)}),changed:r}}function JO(t){try{return t.view.dom.isConnected}catch{return!1}}function GO(t){!t.isDestroyed&&JO(t)&&(t.view.dom.focus(),t.view.focus())}function ZO(t){if(!JO(t))return{type:null,text:null};const e=function(t){if(!t)return{type:null,text:null};const e=window.getSelection();if(!e||0===e.rangeCount)return{type:e?.type??null,text:null};const n=e.anchorNode,r=e.focusNode,o=t instanceof HTMLElement?t:t.parentElement,i=!!n&&!!r&&null!==o&&o.contains(n)&&o.contains(r);return{type:i?e.type:null,text:i?e.toString():null}}(t.view.dom);if(null!==e.type)return e;const n=t.state.selection;return{type:n.empty?"Caret":"Range",text:n.empty?"":t.state.doc.textBetween(n.from,n.to,"\n")}}var QO={s:14,m:16,l:20,xl:28},tN=QO.m,eN={[QO.s]:20,[QO.m]:24,[QO.l]:28,[QO.xl]:36};function nN(t,e=tN){return"number"==typeof t&&Number.isFinite(t)?Math.max(1,t):e}function rN(t,e){return Sm(e,t).cssFamily}function oN(t){return nN(t)}function iN(t){const e=nN(t);return eN[e]??Math.ceil(1.4*e)}function sN(t,e=1){return Math.max(1,Math.ceil(iN(t)*e))}function aN(t){switch(t){case"middle":return"center";case"end":return"right";default:return"left"}}function lN(t,e,n,r){if(0===t.getText().trim().length)return dN(e,r);const o=function(t,e){const n=t.ownerDocument.defaultView?.getComputedStyle(t);return mN(t.ownerDocument).measureElement(t,e,n)}(t.view.dom,{shape:e,fontCatalog:n,...pN(e,r)});return!r&&t.view.dom.scrollHeight>e.props.h+1&&(o.h=Math.max(o.h,t.view.dom.scrollHeight)),uN(e,o,r)}function cN(t,e,n,r){return 0===Ef(t).trim().length?dN(e,r):uN(e,(o=function(t){return t.content.map(t=>Bf(t)).join("")}(t),i={...pN(e,r),shape:e,fontCatalog:n},mN(document).measureHtml(o,i)),r);var o,i}function dN(t,e){const n=e?e.minWidth:t.props.autoSize?16:t.props.w,r=sN(t.props.size);if(t.props.w!==n||t.props.h!==r)return{w:n,h:r}}function uN(t,e,n){const r=n?Math.min(n.maxWidth,Math.max(n.minWidth,Math.ceil(e.w+2*n.paddingInline))):t.props.autoSize?Math.max(16,Math.ceil(e.w)):t.props.w,o=Math.max(sN(t.props.size),Math.ceil(e.h));if(r!==t.props.w||o!==t.props.h)return{w:r,h:o}}function pN(t,e){if(e){const t=im(e,e.maxWidth);return{maxWidth:Math.max(1,e.maxWidth-2*t)}}return t.props.autoSize?{}:{width:t.props.w}}var hN=class{ownerDocument;element;constructor(t){this.ownerDocument=t,this.element=t.createElement("div"),this.element.setAttribute("aria-hidden","true"),this.element.style.position="absolute",this.element.style.left="-10000px",this.element.style.top="0",this.element.style.visibility="hidden",this.element.style.pointerEvents="none",t.body.appendChild(this.element)}measureHtml(t,e){const n=this.prepareElement(e);return n.innerHTML=t,this.measurePreparedElement(n)}measureElement(t,e,n){const r=this.prepareElement(e);return r.replaceChildren(...Array.from(t.childNodes).map(t=>t.cloneNode(!0))),gN(r,"whiteSpace",n?.whiteSpace),gN(r,"overflowWrap",n?.overflowWrap),gN(r,"lineHeight",n?.lineHeight),gN(r,"letterSpacing",n?.letterSpacing),gN(r,"textAlign",n?.textAlign),this.measurePreparedElement(r)}prepareElement(t){const e=this.element;return e.removeAttribute("contenteditable"),e.className="",e.textContent="",t?.shape&&t.fontCatalog&&function(t,e,n){t.className="land-text-editor__content",t.dir="auto",t.style.color=K(e.props.color),t.style.fontFamily=rN(e.props.font,n),t.style.fontSize=`${oN(e.props.size)}px`,t.style.lineHeight=`${iN(e.props.size)}px`,t.style.textAlign=aN(e.props.textAlign)}(e,t.shape,t.fontCatalog),e.style.position="absolute",e.style.left="-10000px",e.style.top="0",e.style.visibility="hidden",e.style.pointerEvents="none",e.style.width="number"==typeof t?.width?`${t.width}px`:"max-content",e.style.minWidth="0",e.style.height="auto",e.style.minHeight="0",e.style.maxHeight="none",e.style.maxWidth="number"==typeof t?.width?`${t.width}px`:"number"==typeof t?.maxWidth?`${t.maxWidth}px`:"none",e}measurePreparedElement(t){return t.querySelectorAll("p").forEach(t=>{t instanceof HTMLElement&&(t.style.margin="0")}),[t,...Array.from(t.querySelectorAll("*")).filter(t=>t instanceof HTMLElement)].reduce((t,e)=>{const n=e.getBoundingClientRect();return{w:Math.max(t.w,n.width,e.scrollWidth,e.offsetWidth),h:Math.max(t.h,n.height,e.scrollHeight,e.offsetHeight)}},{w:0,h:0})}},fN=new WeakMap;function mN(t){const e=fN.get(t);if(e)return e;const n=new hN(t);return fN.set(t,n),n}function gN(t,e,n){n&&"normal"!==n&&"auto"!==n&&(t.style[e]=n)}function yN(t,e,n){if(e.isDestroyed()||!e.isConnected())return;const r=e.measure(n);r&&wN(t,n,r,"user")}function xN(t,e,n,r="system"){const o=cN(e.props.richText,e,n,pm(t,e));o&&wN(t,e,o,r)}function wN(t,e,n,r){const o=t.shapes.get(e.id);Gf(o)&&o.props.w===n.w&&o.props.h===n.h||t.commands.updateShapes([{id:e.id,props:n}],{source:r})}var bN=/[;{}<>\u0000-\u001f\u007f]/u,vN=/(?:url|expression)\s*\(|!\s*important|@\s*import|javascript\s*:/iu;function kN({editor:t,fontCatalog:e,landEditor:n,shapeId:r}){const o=()=>{const t=n.shapes.get(r);return Gf(t)?t:null},i={shapeId:r,getSnapshot(){if(t.isDestroyed)return null;const n=o();return n?function({editor:t,fontCatalog:e,shape:n}){const r=t.state.selection,o=function(t){const{selection:e,doc:n}=t.state;return e.empty?{from:0,to:n.content.size}:{from:e.from,to:e.to}}(t),i=r.empty?"shape":"selection",s=q(n.props.color),a=X(n.props.backgroundColor)?null:q(n.props.backgroundColor),l=n.props.textAlign;return{shapeId:n.id,target:i,bold:CN(t,o,"bold"),italic:CN(t,o,"italic"),strike:CN(t,o,"strike"),underline:CN(t,o,"underline"),blockType:EN(t,o),color:AN(t,o,"color",s),backgroundColor:AN(t,o,"backgroundColor",0===t.state.doc.textContent.length?a:null),font:LN(AN(t,o,"fontFamily",n.props.font),t=>function(t,e){return e.fontOptions.find(e=>e.cssFamily===t)?.id??t}(t,e)),size:LN(AN(t,o,"fontSize",n.props.size),t=>function(t,e){if("number"==typeof t)return t;const n=Number.parseFloat(t);return Number.isFinite(n)&&n>0?n:e}(t,n.props.size)),textAlign:ON(t,o,l),linkHref:NN(t,o),canSetLink:!r.empty||t.state.doc.textContent.length>0}}({editor:t,fontCatalog:e,shape:n}):null},subscribe(e){if(t.isDestroyed)return()=>{};const o=()=>e();t.on("transaction",o),t.on("focus",o),t.on("blur",o);const i=Tt(`TextFormattingApi(${r})`,n.shapes.getSignal(r),o,{fireImmediately:!1});return()=>{i(),t.off("transaction",o),t.off("focus",o),t.off("blur",o)}},focus(){t.isDestroyed||t.commands.focus()},toggle:e=>function(t,e,n){if(t.isDestroyed||void 0===t.schema.marks[e])return!1;const r=t.state.selection;if(!r.empty)return t.chain().focus().toggleMark(e).run();const o=!0!==n?.[e];if(0===t.state.doc.textContent.length){const n=t.chain().focus();return(o?n.setMark(e):n.unsetMark(e)).run()}let i=t.chain().focus().selectAll();return i=o?i.setMark(e):i.unsetMark(e),i=i.setTextSelection(TN(r)),i=o?i.setMark(e):i.unsetMark(e),i.run()}(t,e,i.getSnapshot()),setBlockType:e=>function(t,e){if(t.isDestroyed)return!1;const n=t.state.selection;if(n.empty&&t.state.doc.textContent.length>0){const r=t.getJSON(),o=HO(r,e);if(o===r)return!1;const i=function(t,e,n){const r=t.schema.nodeFromJSON(e);let o=Math.max(0,n),i=1,s=!1;return r.descendants((t,e)=>!s&&t.isText&&t.text?o<=t.text.length?(i=e+o,s=!0,!1):(o-=t.text.length,i=e+t.text.length,!1):!s),i}(t,o,function(t,e){let n=0,r=!1;return t.state.doc.descendants((t,o)=>!r&&t.isText&&t.text?e<=o+t.text.length?(n+=Math.max(0,e-o),r=!0,!1):(n+=t.text.length,!1):!r),n}(t,n.from));return t.chain().focus().setContent(o).setTextSelection(i).run()}let r=t.chain().focus();r=r.clearNodes(),r="orderedList"===e?r.toggleOrderedList():"bulletList"===e?r.toggleBulletList():"blockquote"===e?r.toggleBlockquote():r.setParagraph();return r.run()}(t,e),setColor(e){if(null!==e&&!$N(e))return!1;const r=o();return!!r&&function({editor:t,landEditor:e,shape:n,color:r}){if(t.isDestroyed||void 0===t.schema.marks.textStyle)return!1;if(!t.state.selection.empty)return null===r?t.chain().focus().unsetColor().run():t.chain().focus().setColor(r).run();const o=PN(t,"color");null!==r&&IN(e,n,{color:H(r)});return o||null!==r}({editor:t,landEditor:n,shape:r,color:e})},setBackgroundColor(e){if(null!==e&&!$N(e))return!1;const r=o();return!!r&&function({editor:t,landEditor:e,shape:n,color:r}){if(t.isDestroyed||void 0===t.schema.marks.textStyle)return!1;const o=t.state.selection,i=t=>null===r?t.unsetBackgroundColor():t.setBackgroundColor(r);if(!o.empty)return IN(e,n,{backgroundColor:H("transparent")}),i(t.chain().focus()).run();const s=i(i(t.chain().focus().selectAll()).setTextSelection(TN(o))).run();return IN(e,n,{backgroundColor:H(r??"transparent")}),s}({editor:t,landEditor:n,shape:r,color:e})},setFont(r){const i=o();if(!i)return!1;if(null===r)return SN({editor:t,font:null,fontFamily:null,landEditor:n,shape:i});const s=e.fontOptions.find(t=>t.id===r);return!!s&&(Mm(r,e).then(()=>{if(t.isDestroyed)return;const r=o();r&&xN(n,r,e,"system")}),SN({editor:t,fontFamily:s.cssFamily,font:r,landEditor:n,shape:i}))},setSize(e){const r=null===e?null:Math.round(1e3*e)/1e3;if(null!==e&&(!Number.isFinite(e)||e<1||e>512||null===r||Math.abs(e-r)>Number.EPSILON*Math.max(1,Math.abs(e))))return!1;const i=o();return!!i&&function({editor:t,landEditor:e,shape:n,size:r}){if(t.isDestroyed||void 0===t.schema.marks.textStyle)return!1;const o=t.state.selection,i=null===r?null:`${r}px`,s=null===r?null:`${iN(r)}px`,a=t=>null===i||null===s?t.unsetFontSize().unsetLineHeight():t.setFontSize(i).setLineHeight(s);if(!o.empty)return a(t.chain().focus()).run();const l=function(t){const e=t.state.selection;let n=t.chain().focus();t.state.doc.textContent.length>0&&(n=n.selectAll());return MN(n.unsetFontSize().unsetLineHeight().setTextSelection(TN(e)).unsetFontSize().unsetLineHeight()).run()}(t);null!==r&&IN(e,n,{size:r});return l||null!==r}({editor:t,landEditor:n,shape:i,size:r})},setTextAlign(e){const r=o();return!!r&&function({editor:t,landEditor:e,shape:n,align:r}){if(t.isDestroyed)return!1;const o=function(t){switch(t){case"middle":return"center";case"end":return"right";default:return"left"}}(r),i=t.state.selection;if(!i.empty)return t.chain().focus().setTextAlign(o).run();const s=t.chain().focus().selectAll().unsetTextAlign().setTextSelection(TN(i)).run();return IN(e,n,{textAlign:r}),s||n.props.textAlign!==r}({editor:t,landEditor:n,shape:r,align:e})},setLink(e){if(t.isDestroyed||void 0===t.schema.marks.link)return!1;const n=null===e?null:wf(e);if(null!==e&&null===n)return!1;const r=t.state.selection;if(!r.empty)return null===n?!!t.isActive("link")&&t.chain().focus().unsetLink().run():t.chain().focus().setLink({href:n}).run();if(0===t.state.doc.textContent.length)return!1;const o=t.chain().focus().selectAll();return(null===n?o.unsetLink():o.setLink({href:n})).setTextSelection(TN(r)).run()},clearFormatting(){if(t.isDestroyed)return!1;const e=o();e&&IN(n,e,{backgroundColor:H("transparent")});const r=t.state.selection;return r.empty?t.chain().focus().selectAll().unsetAllMarks().unsetTextAlign().setTextSelection(TN(r)).command(({tr:t})=>(t.setStoredMarks([]),!0)).run():t.chain().focus().unsetAllMarks().unsetTextAlign().run()},getUnsafeTiptapEditor:()=>t.isDestroyed?null:t};return i}function SN({editor:t,font:e,fontFamily:n,landEditor:r,shape:o}){if(t.isDestroyed||void 0===t.schema.marks.textStyle)return!1;if(!t.state.selection.empty)return null===n?t.chain().focus().unsetFontFamily().run():t.chain().focus().setFontFamily(n).run();const i=PN(t,"fontFamily");return null!==e&&r&&o&&IN(r,o,{font:e}),i||null!==e}function PN(t,e){const n=t.state.selection;let r=t.chain().focus();return t.state.doc.textContent.length>0&&(r=r.selectAll()),r="color"===e?r.unsetColor():r.unsetFontFamily(),r=r.setTextSelection(TN(n)),r="color"===e?r.unsetColor():r.unsetFontFamily(),MN(r).run()}function MN(t){return t.command(({state:t,tr:e})=>{const n=t.schema.marks.textStyle;if(!n)return!0;const r=(e.storedMarks??t.storedMarks)?.find(t=>t.type===n);return r&&Object.values(r.attrs).every(t=>null==t||""===t)&&e.removeStoredMark(n),!0})}function IN(t,e,n){t.commands.updateShapes([{id:e.id,props:n}],{source:"user"})}function TN(t){return t.from===t.to?t.from:{from:t.from,to:t.to}}function CN(t,e,n){if(!t.schema.marks[n])return!1;const r=[];return t.state.doc.nodesBetween(e.from,e.to,(t,e,o)=>{const i=o?.type.schema.marks[n];t.isText&&i&&o?.type.allowsMarkType(i)&&!t.marks.some(t=>"code"===t.type.name)&&r.push(t.marks.some(t=>t.type.name===n))}),0===r.length?(t.state.storedMarks??t.state.selection.$from.marks()).some(t=>t.type.name===n):RN(r)??!1}function EN(t,e){const n=[];return t.state.doc.nodesBetween(e.from,e.to,(e,r)=>{if(!e.isTextblock)return;const o=t.state.doc.resolve(Math.min(r+1,t.state.doc.content.size));let i="paragraph";for(let t=o.depth;t>=0;t-=1){const e=o.node(t).type.name;if("orderedList"===e||"bulletList"===e){i=e;break}if("blockquote"===e){i="blockquote";break}}n.push({blockType:i,isEmptyTrailingParagraph:"paragraph"===i&&0===e.content.size})}),RN((n.some(({blockType:t})=>"paragraph"!==t)?n.filter(({isEmptyTrailingParagraph:t})=>!t):n).map(({blockType:t})=>t))??"paragraph"}function AN(t,e,n,r){const o=[];if(t.state.doc.nodesBetween(e.from,e.to,(t,e,i)=>{if(!t.isText)return;if("backgroundColor"===n&&(t.marks.some(t=>"code"===t.type.name)||"codeBlock"===i?.type.name))return;const s=t.marks.find(t=>"textStyle"===t.type.name)?.attrs[n];o.push("string"==typeof s&&s.length>0?s:r)}),0===o.length){const e=(t.state.storedMarks??t.state.selection.$from.marks()).find(t=>"textStyle"===t.type.name)?.attrs[n];return"string"==typeof e&&e.length>0?e:r}return RN(o)}function ON(t,e,n){const r=[];return t.state.doc.nodesBetween(e.from,e.to,t=>{t.isTextblock&&r.push(function(t,e){switch(t){case"center":return"middle";case"right":return"end";case"left":return"start";default:return e}}(t.attrs.textAlign,n))}),RN(r)??n}function NN(t,e){const n=[];if(t.state.doc.nodesBetween(e.from,e.to,(t,e,r)=>{if(!t.isText||"codeBlock"===r?.type.name||t.marks.some(t=>"code"===t.type.name))return;const o=t.marks.find(t=>"link"===t.type.name)?.attrs.href;n.push("string"==typeof o&&o.length>0?o:null)}),0===n.length)return null;const r=n[0]??null;return n.every(t=>t===r)?r:"mixed"}function RN(t){if(0===t.length)return null;const e=t[0];return t.every(t=>Object.is(t,e))?e:"mixed"}function LN(t,e){return null===t?null:"mixed"===t?"mixed":e(t)}function $N(t){const e=t.trim();return e.length>0&&e.length<=128&&!bN.test(e)&&!vN.test(e)}function DN({shapeId:t,editor:e,fontCatalog:n,landEditor:r}){return{shapeId:t,formatting:kN({editor:e,fontCatalog:n,landEditor:r,shapeId:t}),isDestroyed:()=>e.isDestroyed,isConnected:()=>!e.isDestroyed&&JO(e),isFocused:()=>!e.isDestroyed&&JO(e)&&e.view.dom.contains(document.activeElement),getValue:()=>Af(e.getJSON()),setValue(t){e.commands.setContent(t)},focus(){GO(e)},focusEnd(){!e.isDestroyed&&JO(e)&&e.commands.focus("end")},focusSelectAll(){!e.isDestroyed&&JO(e)&&(GO(e),e.chain().focus().selectAll().run())},focusAtPagePoint(t,n){!function(t,e,n){GO(e);const r=t.viewport.pageToScreen(new O(n.x,n.y)),o=e.view.posAtCoords({left:r.x,top:r.y})?.pos;if(o)return void e.chain().focus().setTextSelection(o).run();e.chain().focus().selectAll().run()}(t,e,n)},getSelectionSnapshot:()=>e.isDestroyed||!JO(e)?{type:null,text:null}:ZO(e),collapseSelectionAtClientPoint(t,n){!e.isDestroyed&&JO(e)&&("Range"===ZO(e).type&&function(t,e,n){if(t.isDestroyed||!JO(t))return;const r=t.view.posAtCoords({left:e,top:n})?.pos;"number"!=typeof r?t.commands.focus("end"):t.chain().focus().setTextSelection(r).run()}(e,t,n))},measure(t){if(!e.isDestroyed&&JO(e))return lN(e,t,n,pm(r,t))},onCompositionStateChange(t){if(e.isDestroyed)return()=>{};const n=e.view.dom,r=()=>t(!0),o=()=>t(!1);return n.addEventListener("compositionstart",r),n.addEventListener("compositionend",o),()=>{n.removeEventListener("compositionstart",r),n.removeEventListener("compositionend",o),t(!1)}}}}var BN=vC.extend({inclusive:!1,renderHTML({HTMLAttributes:t}){const{href:e,target:n,rel:r,...o}=t;return["span",LS(o,{"data-rich-text-link-href":e,style:"text-decoration-line: underline;"}),0]}}),zN=[DO.configure({bold:!1,italic:!1,link:!1,strike:!1,underline:!1}),xI.extend({keepOnSplit:!0}),SI.extend({keepOnSplit:!0}),PC.extend({keepOnSplit:!0}),RC.extend({keepOnSplit:!0}),TC,EC,CC,AC,OC,NC,MC.configure({types:["paragraph"],alignments:["left","center","right"]}),LC.configure({className:"land-rich-text-selection"}),BN.configure({autolink:!0,defaultProtocol:"https",openOnClick:!1,protocols:["mailto","land"],HTMLAttributes:{target:"_blank",rel:"noopener noreferrer",class:"land-rich-text-link"}})];function FN({landEditor:t,shape:e,fontCatalog:n,initialRichText:r,className:o,editorStyle:i,formattingToolbar:s,onTiptapEditorChange:a,onReady:c,onDispose:d,onRichTextChange:u}){const p=k(null),h=X(e.props.backgroundColor)?null:q(e.props.backgroundColor),f=h&&r.content.length>0?function(t,e){const n=YO(t.content,(t,n)=>{if("text"!==t.type||!t.text||n.insideCodeBlock||t.marks?.some(t=>"code"===t.type))return t;const r=t.marks??[],o=r.findIndex(t=>"textStyle"===t.type);if(o<0)return{...t,marks:[...r,{type:"textStyle",attrs:{backgroundColor:e}}]};const i=r[o]?.attrs?.backgroundColor;return"string"==typeof i&&i.length>0?t:{...t,marks:r.map((t,n)=>n===o?{...t,attrs:{...t.attrs,backgroundColor:e}}:t)}});return n.changed?Af({...t,content:n.nodes}):t}(r,h):r,m=g(r=>{const o=p.current;if(o?.editor===r)return o.controller;const i=DN({shapeId:e.id,editor:r,fontCatalog:n,landEditor:t});return p.current={editor:r,controller:i},i},[n,t,e.id]),y=aI({extensions:zN,content:f,autofocus:!1,editable:!0,immediatelyRender:!0,shouldRerenderOnTransaction:!1,editorProps:{attributes:{"data-ui":"rich-text-editor",class:"land-text-editor__content",dir:"auto"},handleKeyDown:(e,n)=>(n.stopPropagation(),!n.isComposing&&("Escape"===n.key?(n.preventDefault(),t.editing.cancel("user"),!0):!("Enter"!==n.key||!n.metaKey&&!n.ctrlKey)&&(n.preventDefault(),t.editing.complete("user"),!0)))},onUpdate:({editor:t})=>{const e=m(t);u({editor:t,controller:e,richText:e.getValue()})}},[e.id]);return w(()=>{if(!y||y.isDestroyed)return;const n=m(y),r={shapeId:e.id,editor:y,controller:n,formatting:n.formatting},o={shapeId:e.id,formatting:n.formatting},i=!1===s?()=>{}:zO(t,n.formatting);return c(r),a?.(o),()=>{i(),p.current?.editor===y&&(p.current=null),d(r),a?.(null)}},[m,s,t,d,c,a,e.id,y]),l(tI,{editor:y,className:o,style:i})}function jN({editor:t,controller:e,shapeId:n,request:r,onApplied:o,attempt:i=0}){if(!e.isDestroyed())if(e.isConnected())!function({editor:t,controller:e,shapeId:n,request:r,onApplied:o}){if(e.isDestroyed())return;if(e.focus(),!r||r.shapeId!==n)return e.focusEnd(),void o?.(r);if("selectAll"===r.entryMode)return window.requestAnimationFrame(()=>{!e.isDestroyed()&&e.isConnected()&&e.focusSelectAll()}),t.editing.consumeEntryRequest(r.id),void o?.(r);if("placeCaret"===r.entryMode&&r.caretPagePoint)return e.focusAtPagePoint(t,r.caretPagePoint),t.editing.consumeEntryRequest(r.id),void o?.(r);e.focusEnd(),t.editing.consumeEntryRequest(r.id),o?.(r)}({editor:t,controller:e,shapeId:n,request:r,onApplied:o});else{if(i>=4)return;window.requestAnimationFrame(()=>{jN({editor:t,controller:e,shapeId:n,request:r,onApplied:o,attempt:i+1})})}}function WN({editor:t,shape:e,tiptapEditor:n,richTextController:r,latestShapeRef:o,fontCatalog:i}){const s=k(e.props.richText),a=k(!1),l=k(null),c=g(({controller:n,richText:r})=>{if(a.current||!n.isConnected())return;const c=Af(r);s.current=c,em(t,e.id,c,n.measure(o.current)??cN(c,o.current,i,pm(t,o.current)),"user"),function(t,e,n,r){null!==r.current&&window.clearTimeout(r.current),r.current=window.setTimeout(()=>{r.current=null,yN(t,e,n.current)},0)}(t,n,o,l)},[t,i,o,e.id]);return w(()=>()=>{null!==l.current&&(window.clearTimeout(l.current),l.current=null)},[]),b(()=>{n&&r&&!n.isDestroyed&&r.isConnected()&&yN(t,r,e)},[t,r,e,n]),w(()=>{if(!n||!r||!r.isConnected())return;const t=e.props.richText;t!==s.current&&(JSON.stringify(s.current)!==JSON.stringify(t)?(a.current=!0,r.setValue(t),s.current=t,a.current=!1):s.current=t)},[r,e.props.richText,n]),w(()=>{if(r)return r.onCompositionStateChange(e=>{t.editing.setComposition(e,"system")})},[t,r]),w(()=>{if(!r||!r.isConnected())return;let n=!1;return Mm(e.props.font,i).then(()=>{!n&&r.isConnected()&&yN(t,r,o.current)}),()=>{n=!0}},[t,i,o,r,e.props.font]),c}function HN({editor:t,href:e,openExternal:n}){Pf({href:e,openExternal:n,openInternal(e){t.viewport.centerOnShape(e,{source:"user",animation:{durationMs:240}})&&t.commands.setSelectedShapeIds([e],{source:"user"})}})}function _N({shapeId:n,operationKind:r,fontCatalog:o,formattingToolbar:i,openLink:s=()=>{},onTiptapEditorChange:a}){const c=t(),d=e(c.shapes.getSignal(n)),u=e(c.state.shapeEditing).session;return Gf(d)&&u?.shapeId===d.id?l(UN,{shape:d,session:u,fontCatalog:o,formattingToolbar:i,openLink:s,onTiptapEditorChange:a},`${d.id}:${r}`):null}function UN({shape:n,session:r,fontCatalog:o,formattingToolbar:i,openLink:s,onTiptapEditorChange:a}){const c=t(),d=k(n.props.richText),u=function(t){const e=k(t);return w(()=>{e.current=t},[t]),e}(n),p=e(c.state.shapeEditingEntryRequest),h=k(null),[f,m]=S(null),[y,x]=S(null),b=g(({editor:t,controller:e})=>{m(t.isDestroyed?null:t),x(e)},[]),P=g(({editor:t,controller:e})=>{m(e=>e===t?null:e),x(t=>t===e?null:t)},[]),M=WN({editor:c,shape:n,tiptapEditor:f,richTextController:y,latestShapeRef:u,fontCatalog:o}),I=g(()=>{f&&function(t,e){!(!e||t.isDestroyed||t.state.doc.textContent.length>0||t.getAttributes("textStyle").backgroundColor===e)&&t.commands.setBackgroundColor(e)}(f,X(n.props.backgroundColor)?null:q(n.props.backgroundColor))},[n.props.backgroundColor,f]);!function({editor:t,shapeId:e,session:n,tiptapEditor:r,richTextController:o,entryRequest:i,consumedEntryRequestIdRef:s,onEntryFocusApplied:a}){const l=k(null),c=k(null);w(()=>{if(!o||o.isDestroyed()||!o.isConnected())return;let t=!1,e=null,n=0;const r=()=>{t||o.isDestroyed()||null===s.current&&(o.isFocused()||(o.focus(),n+=1,o.isFocused()||n>=4||(e=window.setTimeout(r,16))))},i=window.requestAnimationFrame(()=>{r()});return()=>{t=!0,window.cancelAnimationFrame(i),null!==e&&window.clearTimeout(e)}},[s,o,e]),w(()=>{r&&!r.isDestroyed&&o&&null===s.current&&c.current!==n.operationKind&&(c.current=n.operationKind,window.setTimeout(()=>{jN({editor:t,controller:o,shapeId:e,request:{id:-1,shapeId:n.shapeId,entryMode:n.entryMode,caretPagePoint:n.caretPagePoint},onApplied:a})},0))},[s,t,o,n.caretPagePoint,n.entryMode,n.operationKind,n.shapeId,e,r,a]),w(()=>{r&&!r.isDestroyed&&o&&i&&i.shapeId===e&&s.current!==i.id&&jN({editor:t,controller:o,shapeId:e,request:i,onApplied(t){t&&(s.current=t.id),a?.()}})},[s,t,i,o,e,r,a]),w(()=>{if(!r||!o||r.isDestroyed||!o.isConnected())return;const e=o;"selectAll"===n.entryMode&&window.requestAnimationFrame(()=>{"Range"!==e.getSelectionSnapshot().type&&e.focusSelectAll()});const i=l.current,s=n.caretPagePoint;if("placeCaret"===n.entryMode&&s&&(i?.operationKind!==n.operationKind||i.entryMode!==n.entryMode)){l.current={operationKind:n.operationKind,entryMode:n.entryMode};const r={x:s.x,y:s.y};window.requestAnimationFrame(()=>{jN({editor:t,controller:e,shapeId:n.shapeId,request:{id:-1,shapeId:n.shapeId,entryMode:"placeCaret",caretPagePoint:r},onApplied:a})})}},[t,n.caretPagePoint,n.entryMode,n.operationKind,n.shapeId,o,r,a])}({editor:c,shapeId:n.id,session:r,tiptapEditor:f,richTextController:y,entryRequest:p,consumedEntryRequestIdRef:h,onEntryFocusApplied:I});const T=function({editor:t,shapeId:e,richTextController:n}){const r=k(null);return{onPointerDownCapture:g(o=>{if(0!==o.button||1!==o.detail||!n||n.isDestroyed())return void(r.current=null);const i=t.state.shapeEditingSession.get();i&&i.shapeId===e&&!i.isComposing&&"Range"===n.getSelectionSnapshot().type?r.current={pointerId:o.pointerId,clientX:o.clientX,clientY:o.clientY,moved:!1}:r.current=null},[t,n,e]),onPointerMoveCapture:g(t=>{const e=r.current;if(!e||e.pointerId!==t.pointerId)return;const n=t.clientX-e.clientX,o=t.clientY-e.clientY;n*n+o*o>=16&&(e.moved=!0)},[]),onPointerUpCapture:g(o=>{const i=r.current;if(r.current=null,!i||i.pointerId!==o.pointerId||i.moved||!n||n.isDestroyed())return;const s=t.state.shapeEditingSession.get();if(!s||s.shapeId!==e||s.isComposing)return;const a=o.clientX,l=o.clientY;window.setTimeout(()=>{n.isDestroyed()||"Range"!==n.getSelectionSnapshot().type||n.collapseSelectionAtClientPoint(a,l)},0)},[t,n,e]),onPointerCancel:g(()=>{r.current=null},[])}}({editor:c,shapeId:n.id,richTextController:y}),C=function(t,e,n=0){return v(()=>({color:K(t.props.color),fontFamily:rN(t.props.font,e),fontSize:oN(t.props.size),lineHeight:`${iN(t.props.size)}px`,textAlign:aN(t.props.textAlign),pointerEvents:"auto",userSelect:"text",cursor:"text",boxSizing:"border-box",position:"absolute",inset:0,width:"100%",height:"100%",paddingInline:n}),[t.props.color,t.props.font,t.props.size,t.props.textAlign,e,n])}(n,o,im(pm(c,n),n.props.w)),E=g(t=>{if(!t.ctrlKey&&!t.metaKey)return;const e=function(t){const e=t.target;return e instanceof Element?e.closest("[data-rich-text-link-href]")?.getAttribute("data-rich-text-link-href")??null:null}(t.nativeEvent);e&&f&&!f.isDestroyed&&(t.preventDefault(),t.stopPropagation(),HN({editor:c,href:e,openExternal:s}))},[c,s,f]);
46
- return l("div",{"data-ui":"text-editing-box","data-shape-id":n.id,"data-mount-target-kind":"shape",onPointerDown:t=>{t.stopPropagation()},onClickCapture:E,onPointerDownCapture:T.onPointerDownCapture,onPointerMoveCapture:T.onPointerMoveCapture,onPointerUpCapture:T.onPointerUpCapture,onPointerCancel:T.onPointerCancel,onContextMenu:t=>{t.stopPropagation()},onDragStart:t=>{t.preventDefault()},style:C,children:l(FN,{landEditor:c,shape:n,fontCatalog:o,initialRichText:d.current,className:"land-text-editor__content",formattingToolbar:i,editorStyle:{height:"100%",minHeight:"100%"},onReady:b,onDispose:P,onTiptapEditorChange:a,onRichTextChange:M})})}function VN(t,n,r,o,i,s){const a=e(t.state.shapeEditing).session,c=a?.shapeId===n.id,d=a&&c?l(_N,{shapeId:a.shapeId,operationKind:a.operationKind,fontCatalog:r,formattingToolbar:o,openLink:i,onTiptapEditorChange:s},a.shapeId+":"+a.operationKind):null;return function({editor:t,shape:e,isEditingThisShape:n,fontCatalog:r}){b(()=>{if(n)return;xN(t,e,r);let o=!1;return Mm(e.props.font,r).then(()=>{if(o)return;const n=t.shapes.get(e.id);Gf(n)&&n.props.font===e.props.font&&xN(t,n,r)}),()=>{o=!0}},[t,r,n,e,e.props.autoSize,e.props.font,e.props.richText,e.props.scale,e.props.size,e.props.textAlign,e.props.w])}({editor:t,shape:n,isEditingThisShape:c,fontCatalog:r}),{hasEditingSession:null!==a,isEditingThisShape:c,editingHost:d}}var KN=p(null);function qN({children:t,presenter:e}){
47
- return l(KN.Provider,{value:e,children:t})}var XN=p({query:"",activeMatch:null});function YN({activeMatch:t,children:e,query:n}){const r=v(()=>({activeMatch:t,query:n}),[t,n]);
48
- return l(XN.Provider,{value:r,children:e})}function JN(t,e){if(0===e.length)return[];const n=[],r=Ef(t),o=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),"giu");for(const i of r.matchAll(o)){const t=i.index,e=i[0];void 0!==t&&0!==e.length&&n.push({from:t,to:t+e.length})}return n}var GN=new Set(["key_down","key_up","pointer_cancel","pointer_down","pointer_move","pointer_up"]),ZN={id:"land.text.dom-events",handle({event:t,name:e}){if(!GN.has(e))return"continue";const n=t.target;return n instanceof HTMLElement&&n.closest('[data-ui="text-editing-box"]')?"handled":"continue"},getCursor:({element:t})=>t?.closest('[data-ui="text-editing-box"]')?"text":void 0};function QN({fontCatalog:t=bm(),formattingToolbar:e,openLink:n=()=>{},onTiptapEditorChange:r}={}){return{id:"land.text.react",domEventGuards:[ZN],canvasComponents:[{id:"land.text.styles",component:tR},{id:"land.text.default-font-preload",component:function(){
49
- return l(eR,{fontCatalog:t})}}],shapeRenderers:[{type:"text",hoverComponent:rR,component:function(o){
50
- return l(nR,{...o,fontCatalog:t,formattingToolbar:e,openLink:n,onTiptapEditorChange:r})}}]}}function tR(){
51
- return l("style",{"data-land-plugin":"text",children:'\n.land-text-editor__content {\n width: 100%;\n height: 100%;\n min-height: 100%;\n outline: none;\n white-space: pre-wrap;\n overflow-wrap: break-word;\n}\n\n.land-text-editor__content p {\n margin: 0;\n}\n\n.land-text-editor__content ul,\n.land-text-editor__content ol {\n margin: 0;\n padding-inline-start: 1.5em;\n}\n\n.land-text-editor__content ul {\n list-style: disc;\n}\n\n.land-text-editor__content ol {\n list-style: decimal;\n}\n\n.land-text-editor__content blockquote {\n margin: 0;\n padding-inline-start: 0.75em;\n border-inline-start: 2px solid currentColor;\n}\n\n.land-text-editor__content .land-rich-text-selection {\n background: color-mix(\n in srgb,\n var(--land-selection, #2563eb) 24%,\n transparent\n );\n}\n\n.land-text-search-match {\n border-radius: 2px;\n background: var(--land-text-search-match, #fde68a);\n color: inherit;\n padding: 0;\n}\n\n.land-text-search-match[data-active="true"] {\n background: var(--land-text-search-match-active, #f59e0b);\n}\n'})}function eR({fontCatalog:t}){return w(()=>{Mm(ym,t)},[t]),null}function nR({shape:t,editor:n,fontCatalog:r,formattingToolbar:o,openLink:i,onTiptapEditorChange:s}){const[a,d]=S(null),u=k(null),p=e(n.state.selectedShapeIds),h=y(XN),f=v(()=>JN(t.props.richText,h.query),[t.props.richText,h.query]),m=h.activeMatch?.shapeId===t.id?h.activeMatch:null,x=y(KN),{hasEditingSession:b,isEditingThisShape:P,editingHost:M}=VN(n,t,r,o,i,s),I=im(pm(n,t),t.props.w),T=null!==x&&function({isEditing:t,isOnlySelected:e}){return!t&&!e}({isEditing:b,isOnlySelected:1===p.length&&p[0]===t.id}),C=a?Sf(a.href):null,E=null!==C&&void 0===n.shapes.get(C),A=g(()=>{null!==u.current&&(window.clearTimeout(u.current),u.current=null)},[]),O=g(()=>{A(),u.current=window.setTimeout(()=>{d(null),u.current=null},160)},[A]);return w(()=>()=>{A()},[A]),w(()=>{T||(A(),d(null))},[T,A]),c("div",{"data-editing-hidden":P?"true":void 0,style:{position:"relative",boxSizing:"border-box",width:t.props.w,minHeight:t.props.h,transform:`scale(${t.props.scale})`,transformOrigin:"top left",color:K(t.props.color),fontFamily:rN(t.props.font,r),fontSize:oN(t.props.size),lineHeight:`${iN(t.props.size)}px`,textAlign:aN(t.props.textAlign),whiteSpace:"pre-wrap",overflowWrap:"break-word",userSelect:"none",pointerEvents:"none"},children:[
52
- l("div",{style:{boxSizing:"border-box",opacity:P?0:void 0,paddingInline:I,width:"100%"},children:fm(t.props.richText,{linkHandlers:T?{onPointerEnter({href:t,element:e}){A(),d({anchorElement:e,href:t})},onPointerLeave(){O()}}:void 0,defaultBackgroundColor:X(t.props.backgroundColor)?void 0:K(t.props.backgroundColor),searchRanges:f,activeSearchRange:m})}),T&&a&&x?l(x,{anchorElement:a.anchorElement,href:a.href,kind:C?"internal":"external",unavailable:E,onOpen:()=>{HN({editor:n,href:a.href,openExternal:i})},onPopoverPointerEnter:A,onPopoverPointerLeave:O}):null,
53
- l("div",{"data-ui":"text-editor-host-slot","data-shape-id":t.id,"data-active":P?"true":"false","aria-hidden":"true",style:{position:"absolute",inset:0,pointerEvents:"none"},children:M})]})}function rR({strokeWidth:t}){
54
- return l("div",{"data-ui":"text-hover-outline",style:{boxShadow:`inset 0 0 0 ${t}px ${n}`,inset:0,position:"absolute"}})}var oR="text.create",iR=class extends Pt{constructor(t){super(t,"text"),this.initial="idle",this.addChild(new sR(t,this)),this.addChild(new aR(t,this))}},sR=class extends Pt{constructor(t,e){super(t,"idle",e)}onEnter(){this.editor.interaction.clearSelection()}onPointerDown(t){this.transition("pointing",{originPagePoint:t.pagePoint.clone(),originScreenPoint:t.screenPoint.clone(),shapeId:null})}},aR=class extends Pt{info=null;operation=null;isHandingOffOperation=!1;constructor(t,e){super(t,"pointing",e)}onEnter(t){this.info=t,this.operation=this.editor.operations.begin({kind:oR,label:"shape.create",source:"user",history:"record"})}onPointerMove(t){this.updateFixedWidthShape(t.pagePoint,t.screenPoint)}onPointerUp(t){if(!this.info)return void this.transition("idle");const e=null!==this.info.shapeId?this.editor.shapes.get(this.info.shapeId):this.createTextShape(t.pagePoint);if(!Gf(e))return this.cancelOperation(),void this.transition("idle");let n;nt(this.editor,e.id,{source:"user"}),this.editor.state.tool.get().isToolLocked||(this.isHandingOffOperation=!0,this.transition("idle"),this.editor.commands.setActiveTool("select",{source:"system"}));try{n=this.editor.editing.start({shapeId:e.id,entryMode:"focusEnd",operationKind:oR,reuseActiveOperation:!0,preserveInteraction:!0},"user")}catch(r){throw this.cancelOperation(),r}finally{this.isHandingOffOperation=!1}n?this.operation=null:this.cancelOperation(),this.editor.state.tool.get().isToolLocked&&this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.isHandingOffOperation||this.cancelOperation(),this.info=null}cancelOperation(){const t=this.operation;this.operation=null,t?.isActive&&t.cancel()}updateFixedWidthShape(t,e){if(!this.info)return;const n=function(t,e,n,r,o){const i=Math.abs(r.x-n.x);return n.dist(r)<4||i<8?null:{x:Math.min(t.x,e.x),y:t.y-o.h/2,props:{...lR(o),w:Math.max(16,Math.abs(e.x-t.x)),autoSize:!1}}}(this.info.originPagePoint,t,this.info.originScreenPoint,e,this.getDefaultTextProps());if(n){if(!this.info.shapeId){const t=this.createTextShapeAt(n);return void(this.info.shapeId=t.id)}this.editor.commands.updateShapes([{id:this.info.shapeId,x:n.x,y:n.y,props:{w:n.props.w,h:n.props.h,autoSize:!1}}],{source:"user"})}}createTextShape(t){return this.createTextShapeAt(function(t,e){return{x:t.x,y:t.y-e.h/2,props:lR(e)}}(t,this.getDefaultTextProps()))}createTextShapeAt({x:t,y:e,props:n}){const r=tm(this.editor,{x:t,y:e,props:n},"user");return this.editor.commands.setSelectedShapeIds([r.id],{source:"system"}),r}getDefaultTextProps(){return Qf(this.editor)}};function lR(t){return Zf(t)}var cR=["start","middle","end"];function dR(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function uR(t){return Math.max(.01,t.props.scale)}function pR(t){return t.props.w*uR(t)}function hR(t){return t.props.h*uR(t)}function fR(t){return new N(0,0,pR(t),hR(t))}function mR(t){return"left"===t||"right"===t}function gR(t,e){const n=function(t){return dt({localWidth:pR(t),localHeight:hR(t),scaleX:t.scaleX,scaleY:t.scaleY})}(t),r=e.selectionLocalBounds.w/Math.max(1,n.width),o=e.selectionLocalBounds.h/Math.max(1,n.height);switch(e.handleId){case"left":case"right":return r;case"top":case"bottom":return o;default:return Math.max(r,o)}}var yR=class extends St{type="text";getDefaultProps(){return{richText:Cf(""),w:16,h:sN(tN),autoSize:!0,scale:1,font:ym,size:tN,color:W("text-slate"),backgroundColor:H("transparent"),textAlign:"start"}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{richText:Af(e.richText),w:Math.max(1,dR(e.w,n.w)),h:Math.max(1,dR(e.h,n.h)),autoSize:"boolean"==typeof e.autoSize?e.autoSize:n.autoSize,scale:Math.max(.01,dR(e.scale,n.scale)),font:km(e.font)?e.font:n.font,size:nN(e.size,n.size),color:V(e.color,n.color),backgroundColor:V(e.backgroundColor,n.backgroundColor),textAlign:(r=e.textAlign,"string"==typeof r&&cR.includes(r)?e.textAlign:n.textAlign)};var r}getPositionedBounds(t){return function(t){return new N(t.x,t.y,pR(t),hR(t))}(t)}getLocalBounds(t){return fR(t)}getRenderBounds(t){return fR(t)}getExportBounds(t){return fR(t)}canSnap(t,e){return!e||(n=e.editor,r=t.id,dm(n,r)?.behavior.canSnap??null??!0);var n,r}canReceiveTerminalBinding(t,e){return!e||(n=e.editor,r=t.id,dm(n,r)?.behavior.canReceiveTerminalBinding??null??!0);var n,r}canEdit(t){return!0}contributesToSelectionFrame(t,e){return n=e.editor,r=t.id,dm(n,r)?.behavior.contributesToSelectionFrame??null??!0;var n,r}canUseSelectionResizeHandles(t,e){return e.editor.state.shapeEditingSession.get()?.shapeId!==t.id&&(n=e.editor,r=t.id,dm(n,r)?.behavior.canUseSelectionResizeHandles??null??!0);var n,r}canUseSelectionRotateHandle(t,e){return e.editor.state.shapeEditingSession.get()?.shapeId!==t.id&&(n=e.editor,r=t.id,dm(n,r)?.behavior.canUseSelectionRotateHandle??null??!0);var n,r}getSelectionTargetId(t,e){return function(t,e){const n=dm(t,e);return n?"owner"===n.behavior.selectionTarget?n.ownerId:e:null}(e.editor,t.id)??t.id}getHoverTargetId(t,e){return function(t,e){const n=dm(t,e);return n?"owner"===n.behavior.hoverTarget?n.ownerId:e:null}(e.editor,t.id)??t.id}getHoverDecorationTargetId(t,e){return function(t,e){const n=dm(t,e);return n?"owner"===n.behavior.hoverDecorationTarget?n.ownerId:e:null}(e.editor,t.id)??t.id}getTranslateTargetId(t,e){return function(t,e){const n=dm(t,e);return n?"owner"===n.behavior.translateTarget?n.ownerId:e:null}(e.editor,t.id)??t.id}resizeSelectionBounds(t,e){const n={};if(e.isOnlyResizeTarget&&mR(e.handleId)){const r=ut({width:e.selectionLocalBounds.w,height:e.selectionLocalBounds.h,scaleX:t.scaleX,scaleY:t.scaleY});n.w=Math.max(16,r.width/uR(t)),n.autoSize=!1}else n.scale=Math.max(.01,t.props.scale*gR(t,e));const r=n.scale??uR(t),o=(n.w??t.props.w)*r,i=t.props.h*r,s=dt({localWidth:o,localHeight:i,scaleX:t.scaleX,scaleY:t.scaleY}),a=function(t,e){return 0===e.selectionRotation?t.clone():O.RotWith(t,e.selectionRotationCenter,e.selectionRotation)}(pt({handleId:e.handleId,requestedBounds:e.selectionLocalBounds,actualWidth:s.width,actualHeight:s.height,scaleX:e.scaleX,scaleY:e.scaleY,isResizingFromCenter:e.isResizingFromCenter}).center,e),l=e.scaleX<0!=e.scaleY<0;return{id:t.id,x:a.x-o/2,y:a.y-i/2,rotation:l?2*e.selectionRotation-t.rotation:t.rotation,scaleX:e.scaleX<0?-t.scaleX:t.scaleX,scaleY:e.scaleY<0?-t.scaleY:t.scaleY,props:n}}getAllowedSelectionResizeModes(t,e){return e.isOnlyResizeTarget&&mR(e.handleId)?st:at}onEditEnd(t){if(!(Ef(t.props.richText).trim().length>0))return{deleteShapeIds:[t.id]}}},xR=class{fontCatalog;type="text";constructor(t){this.fontCatalog=t}toSvg(t,e){if(0===Ef(t.props.richText).trim().length)return null;const n=im(pm(e.editor,t),t.props.w);return{tag:"foreignObject",attrs:{x:0,y:0,width:t.props.w*t.props.scale,height:t.props.h*t.props.scale},children:[{tag:"div",attrs:{xmlns:"http://www.w3.org/1999/xhtml",dir:"auto",style:bR(t,e,this.fontCatalog,n)},children:(r=t.props.richText,o=X(t.props.backgroundColor)?void 0:e.resolveColor(t.props.backgroundColor),r.content.map(t=>wR(t,o)))}]};var r,o}};function wR(t,e){const n="codeBlock"===t.type?void 0:e,r=t.content?.map(t=>function(t,e){if(Of(t)){const n=function(t,e){const n=Rf(t.marks,e);return n?Df(n):void 0}(t,e);return n?{tag:"span",attrs:{style:n},children:[t.text]}:t.text}return"hardBreak"===t.type?{tag:"br"}:wR(t,e)}(t,n))??[];if("bulletList"===t.type||"orderedList"===t.type)return{tag:"bulletList"===t.type?"ul":"ol",attrs:{style:"bulletList"===t.type?"margin:0;padding-inline-start:1.5em;list-style-type:disc":"margin:0;padding-inline-start:1.5em;list-style-type:decimal"},children:r};if("listItem"===t.type)return{tag:"li",children:r};if("blockquote"===t.type)return{tag:"blockquote",attrs:{style:"margin:0;padding-inline-start:0.75em;border-inline-start:2px solid currentColor"},children:r};const o=Nf(t);return{tag:"p",attrs:{style:o?`margin:0;text-align:${o}`:"margin:0"},children:r.length>0?r:[{tag:"br"}]}}function bR(t,e,n,r){return[`color:${e.resolveColor(t.props.color)}`,`font-family:${rN(t.props.font,n)}`,`font-size:${oN(t.props.size)}px`,`line-height:${iN(t.props.size)}px`,`text-align:${aN(t.props.textAlign)}`,"white-space:pre-wrap","overflow-wrap:break-word","box-sizing:border-box",`padding-inline:${r}px`,`width:${t.props.w}px`,`height:${t.props.h}px`,`transform:scale(${t.props.scale})`,"transform-origin:top left"].join(";")}var vR=".label";function kR(t){return"binding"===t?.typeName&&"path-label"===t.type}function SR(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):e}var PR=class extends A{type=nm;getDefaultProps(){return{labelPosition:.5}}validateProps(t){const e=this.getDefaultProps();return{labelPosition:SR((t&&"object"==typeof t?t:{}).labelPosition,e.labelPosition)}}canBind(t,e,n){return this.canUseShapeCompanion(e,n,t)}canUseShapeCompanion(t,e,n){return Gf(e.fromShape)&&(!n||null!==IR(n,e.toShape))}getExclusiveBindingKey(t){return t.toId}onBindingCreate(t,e){return this.syncLabelPosition(t,e)}onBindingUpdate(t,e,n){return this.syncLabelPosition(t,n)}onBindingLoad(t,e){return this.syncLabelPosition(t,e)}getGeometryDependentShapeIds(t,e,n){return"to"===n.role?[e.fromId]:[]}getTargetShapeContentCutoutLocalPolygons(t,e,n){if(!Gf(n.fromShape)||!IR(t,n.toShape))return[];const r=t.shapes.computeLocalToPageTransform(n.toShape).tryInvert();if(!r)return[];const o=t.shapes.computeLocalBounds(n.fromShape),i=r.compose(t.shapes.computeLocalToPageTransform(n.fromShape));return[[new O(o.minX,o.minY),new O(o.maxX,o.minY),new O(o.maxX,o.maxY),new O(o.minX,o.maxY)].map(t=>i.applyToPoint(t))]}onAfterShapeChange(t,e,n){return this.syncLabelPosition(t,e)}onBeforeDeleteShape(t,e,n){return"from"===n.role?{deleteBindingIds:[e.id]}:{deleteShapeIds:[e.fromId],deleteBindingIds:[e.id]}}onBeforeDeleteBinding(t,e){return{deleteBindingIds:[e.id]}}getExportShapeIds(t,e){return[e.fromId]}getShapeCompanionRootId(t,e){return e===t.fromId?t.toId:null}getSelectionCompanionFrameGeometries(t,e,n){if(e.toId!==n.selectedShape.id)return[];if(!0!==function(t,e){return dm(t,e)?.behavior.showsCompanionFrameWhenOwnerSelected??null}(t,e.fromId))return[];const r=t.shapes.get(e.fromId),o=t.shapes.get(e.toId);if(!Gf(r)||!o||!IR(t,o))return[];const i=t.shapes.computeGeometry(r),s=t.shapes.computeLocalToPageTransform(r),a=Math.atan2(s.b,s.a);return[{bounds:N.FromPoints(i.outlineVertices.map(t=>O.RotWith(t,i.center,-a))),rotation:a,rotationCenter:i.center}]}syncLabelPosition(t,e){if(!kR(e))return;const n=t.shapes.get(e.fromId),r=t.shapes.get(e.toId);if(!Gf(n)||!r||!IR(t,r))return{deleteBindingIds:[e.id]};const o=function(t,e,n,r){const o=MR(t,e,n,r),i=n.parentId,s=`${n.index}${vR}`,a=!1,l=am(t,e,i,o);return l?e.x===l.x&&e.y===l.y&&e.rotation===l.rotation&&e.scaleX===l.scaleX&&e.scaleY===l.scaleY&&e.parentId===i&&e.index===s&&e.props.w===o.props.w&&e.props.autoSize===a?null:{id:e.id,...l,parentId:i,index:s,props:{w:o.props.w,autoSize:a}}:null}(t,n,r,e.props.labelPosition);return o?{shapes:[{...n,...o,props:{...n.props,...o.props}}]}:void 0}};function MR(t,e,n,r=.5){const o=IR(t,n),i=o?TR(t,e,o):{start:0,end:1},s=Math.min(i.end,Math.max(i.start,r)),a=o?.getPointAt(s)??t.shapes.computePageCenter(n),l=um(t,e,n,nm),c=Math.min(l.maxWidth,Math.max(l.minWidth,e.props.w));return{x:a.x-c*e.props.scale/2,y:a.y-e.props.h*e.props.scale/2,rotation:sm(t,n),props:{w:c}}}function IR(t,e){return t.shapes.getUtil(e).getLabelPathGeometry(e,{editor:t})}function TR(t,e,n){if(n.length<=1e-6)return{start:.5,end:.5};const r=t.shapes.getPageBounds(e.id);if(!r)return{start:0,end:1};const o=Math.hypot(r.w,r.h)/2,i=Math.min(.5,(o+8)/n.length);return{start:i,end:1-i}}var CR=".label";function ER(t){return"shape"===t?.typeName&&"geo"===t.type}function AR(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):e}var OR=class extends A{type=rm;getDefaultProps(){return{normalizedAnchor:{x:.5,y:.5},ownerBaseHeight:0}}validateProps(t){const e=this.getDefaultProps(),n=t&&"object"==typeof t?t:{},r=n.normalizedAnchor&&"object"==typeof n.normalizedAnchor?n.normalizedAnchor:e.normalizedAnchor;return{normalizedAnchor:{x:AR(r.x,e.normalizedAnchor.x),y:AR(r.y,e.normalizedAnchor.y)},ownerBaseHeight:NR(n.ownerBaseHeight,e.ownerBaseHeight)}}canBind(t,e,n){return this.canUseShapeCompanion(e,n)}canUseShapeCompanion(t,e){return Gf(e.fromShape)&&ER(e.toShape)}getExclusiveBindingKey(t){return t.toId}onBindingCreate(t,e){return this.syncLabelPosition(t,e)}onBindingUpdate(t,e,n){return this.syncLabelPosition(t,n,e.toId===n.toId?void 0:{role:"to"})}onBindingLoad(t,e){return this.syncLabelPosition(t,e)}getGeometryDependentShapeIds(t,e,n){return"from"===n.role?[e.toId]:[e.fromId]}onAfterShapeChange(t,e,n){return this.syncLabelPosition(t,e,n)}onBeforeDeleteShape(t,e,n){if("from"===n.role){const n=t.shapes.get(e.toId),r=n?LR(n,e):null;return{shapes:r?[r]:void 0,deleteBindingIds:[e.id]}}return{deleteShapeIds:[e.fromId],deleteBindingIds:[e.id]}}onBeforeDeleteBinding(t,e){const n=t.shapes.get(e.toId),r=n?LR(n,e):null;return{shapes:r?[r]:void 0,deleteBindingIds:[e.id]}}getExportShapeIds(t,e){return[e.fromId]}getShapeCompanionRootId(t,e){return e===t.fromId?t.toId:null}syncLabelPosition(t,e,n){if(r=e,"binding"!==r?.typeName||"geo-label"!==r.type)return;var r;const o=t.shapes.get(e.fromId),i=t.shapes.get(e.toId);if(!Gf(o)||!ER(i))return{deleteBindingIds:[e.id]};const s=function(t,e,n){const r=RR(e,"h")??1;return"to"===n?.role?r:t.props.ownerBaseHeight>0?t.props.ownerBaseHeight:r}(e,i,n),a=e.props.ownerBaseHeight===s?null:{...e,props:{...e.props,ownerBaseHeight:s}},l=function(t,e,n){const r=RR(t,"h");if(!r)return null;const o=Math.max(n,function(t){return Math.max(1,t.props.h*t.props.scale+32)}(e));return r===o?null:{...t,props:{...t.props,h:o}}}(i,o,s),c=function(t,e,n){const r=$R(t,e,n),o=n.parentId,i=`${n.index}${CR}`,s=!1,a=am(t,e,o,r);return a?e.x===a.x&&e.y===a.y&&e.rotation===a.rotation&&e.scaleX===a.scaleX&&e.scaleY===a.scaleY&&e.parentId===o&&e.index===i&&e.props.w===r.props.w&&e.props.autoSize===s?null:{id:e.id,...a,parentId:o,index:i,props:{w:r.props.w,autoSize:s}}:null}(t,o,l??i),d=[];return l&&d.push(l),c&&d.push({...o,...c,props:{...o.props,...c.props}}),d.length>0||a?{shapes:d.length>0?d:void 0,bindings:a?[a]:void 0}:void 0}};function NR(t,e){return"number"==typeof t&&Number.isFinite(t)&&t>0?t:e}function RR(t,e){const n=t.props[e];return"number"==typeof n&&Number.isFinite(n)?n:null}function LR(t,e){const n=RR(t,"h");return!n||e.props.ownerBaseHeight<=0||n===e.props.ownerBaseHeight?null:{...t,props:{...t.props,h:e.props.ownerBaseHeight}}}function $R(t,e,n){const r=t.shapes.computePageCenter(n),o=um(t,e,n,rm),i=Math.min(o.maxWidth,Math.max(o.minWidth,e.props.w)),s=t.shapes.computeLocalBounds(n),a=void 0===o.normalizedCenterX||.5===o.normalizedCenterX?r:t.shapes.computeLocalToPageTransform(n).applyToPoint(new O(s.minX+s.w*o.normalizedCenterX,s.center.y));return{x:a.x-i*e.props.scale/2,y:a.y-e.props.h*e.props.scale/2,rotation:sm(t,n),props:{w:i}}}var DR="text.edit",BR="path-label.create",zR="path-label.drag",FR="geo-label.edit",jR="geo-label.create",WR={propagation:"stop"};function HR(){let t=null,e=null;const n=()=>{t=null,e=null};return{id:"land.text.interactions",editorEvent:{handleEvent(r,o,i){if("cancel"!==o.type){if("select"===r.state.tool.get().activeToolId)if("pointer"!==o.type||"pointer_move"!==o.name||"dragging"!==r.inputs.state.get().dragPhase){if("pointer"===o.type&&"pointer_up"===o.name){const n=i.pointer?.clickCount??1;return function(t,e,n,r,o){if(!r||r.pointerId!==e.pointerId)return void o();if(o(),n>=2)return;const i=e.screenPoint.x-r.originScreenPoint.x,s=e.screenPoint.y-r.originScreenPoint.y;if(i*i+s*s>9)return;const a=t.shapes.get(r.shapeId);if(!a||!Gf(a)||!t.editing.canEditShape(a))return;t.editing.start({shapeId:a.id,entryMode:"placeCaret",caretPagePoint:e.pagePoint,operationKind:DR,preserveInteraction:!0},"user")}(r,o,n,t,()=>{t=null}),void function(t,e,n,r,o){if(!r||r.pointerId!==e.pointerId)return void o();if(o(),n>=2)return;const i=e.screenPoint.x-r.originScreenPoint.x,s=e.screenPoint.y-r.originScreenPoint.y;if(i*i+s*s>9)return;const a=t.shapes.get(r.shapeId),l=t.selection.getIds();if(!a||!VR(a)||a.isLocked||t.state.shapeEditingSession.get()||1!==l.length||l[0]!==a.id||lm(t,a.id,"geo-label"))return;const c=qR(t,a);c&&hm(t,c,{editOperationKind:FR,createOperationKind:jR,isExisting:!1,entryMode:"focusEnd"})}(r,o,n,e,()=>{e=null})}if("pointer"!==o.type||"pointer_cancel"!==o.name){if(r.tools.isInInitialState()){if("keyboard"===o.type&&"key_down"===o.name){if(r.state.shapeEditingSession.get())return;if("Enter"!==o.key||o.altKey||o.accelKey)return;const t=r.selection.getIds(),[e]=r.state.selectedShapes.get();if(1!==t.length||!e||!Gf(e)||!r.editing.canEditShape(e))return;return r.editing.start({shapeId:e.id,entryMode:"selectAll",operationKind:DR},"user"),WR}if("double_click"===o.type)return n(),function(t,e){const n=t.shapes.hitTest(e.pagePoint);if(!n)return!1;if(Gf(n))return!!t.editing.canEditShape(n)&&(t.editing.start({shapeId:n.id,entryMode:"selectAll",operationKind:DR},"user"),!0);return VR(n)?function(t,e){return!e.isLocked&&(UR(t,e.id),!0)}(t,n):!!IR(t,n)&&function(t,e,n){return!e.isLocked&&(_R(t,e.id,n),!0)}(t,n,e.pagePoint)}(r,o)?WR:void 0;if("pointer"===o.type&&"pointer_down"===o.name){n();const s=function(t,e,n,r){const o=t.shapes.hitTest(e.pagePoint);if(!o||!Gf(o)||!t.editing.canEditShape(o))return;const i=t.state.shapeEditingSession.get();if(i&&i.shapeId!==o.id)return t.editing.complete("user")?(t.editing.start({shapeId:o.id,entryMode:"placeCaret",caretPagePoint:e.pagePoint,operationKind:DR,preserveInteraction:!0},"user"),WR):WR;!i&&n<2&&function(t,e){const n=t.selection.getIds();if(1!==n.length)return!1;if(n[0]===e)return!0;const r=dm(t,e);return!!r&&r.behavior.canPlaceCaretWhenOwnerSelected&&n[0]===r.ownerId}(t,o.id)&&r({pointerId:e.pointerId,shapeId:o.id,originScreenPoint:{x:e.screenPoint.x,y:e.screenPoint.y}})}(r,o,i.pointer?.clickCount??1,e=>{t=e});return"stop"===s?.propagation||t?s:void function(t,e,n,r){const o=t.shapes.hitTest(e.pagePoint),i=t.selection.getIds();if(!o||!VR(o)||o.isLocked||t.state.shapeEditingSession.get()||e.shiftKey||e.altKey||e.accelKey||n>=2||1!==i.length||i[0]!==o.id||lm(t,o.id,"geo-label"))return;r({pointerId:e.pointerId,shapeId:o.id,originScreenPoint:{x:e.screenPoint.x,y:e.screenPoint.y}})}(r,o,i.pointer?.clickCount??1,t=>{e=t})}}}else n()}else n()}else n()}},shapePointer:{createSession:(t,e)=>function(t,e){if(e.event.shiftKey||e.event.accelKey||t.state.shapeEditingSession.get()||!Gf(e.shape))return null;const n=t.bindings.getFromShape(e.shape.id).find(kR);if(!n||n.toId!==e.selectionTargetId)return null;const r=t.shapes.get(n.toId),o=t.shapes.getPageBounds(e.shape.id);if(!r||!o||t.layers.isOrAncestorLocked(r.id)||!IR(t,r))return null;const i=o.center.sub(e.originPagePoint);return{shapeId:r.id,operationKind:zR,onDragStart({editor:t}){t.commands.setSelectedShapeIds([r.id],{source:"system"})},update({editor:t,pagePoint:e,source:r}){const o=t.bindings.get(n.id),s=t.shapes.get(n.fromId),a=t.shapes.get(n.toId);if(!kR(o)||!Gf(s)||!a)return"stop";const l=IR(t,a);if(!l)return"stop";const c=KR({editor:t,label:s,pathGeometry:l,pagePoint:e.add(i),hintPosition:o.props.labelPosition,snapToDefault:!0});return Math.abs(c-o.props.labelPosition)>1e-6&&t.commands.updateBinding({id:o.id,props:{labelPosition:c}},{source:r}),{status:"continue",finalPagePoint:l.getPointAt(c)}}}}(t,e)}}}function _R(t,e,n){const r=t.shapes.get(e);if(!r||r.isLocked)return!1;const o=IR(t,r);if(!o)return!1;const i=lm(t,r.id,nm),s=i??function(t,e,n){const r=IR(t,e);if(!r)return null;const o=XR(e,{...Qf(t),autoSize:!1,textAlign:"middle"}),i=r.getNearestPosition(n,{hintPosition:r.defaultPosition}),s=MR(t,o,e,i),a=cm(t,{bindingType:nm,owner:e,operationKind:BR,index:`${e.index}${vR}`,layout:s,bindingProps:{labelPosition:i}});if(!a)return null;const l=t.shapes.get(a.id),c=t.bindings.getFromShape(a.id).find(kR);if(!Gf(l)||!c)return a;const d=KR({editor:t,label:l,pathGeometry:r,pagePoint:n,hintPosition:i,snapToDefault:!1});Math.abs(d-i)>1e-6&&t.commands.updateBinding({id:c.id,props:{labelPosition:d}},{source:"user"});return a}(t,r,n??o.getPointAt(o.defaultPosition));return!!s&&(hm(t,s,{editOperationKind:"path-label.edit",createOperationKind:BR,isExisting:!!i}),!0)}function UR(t,e){const n=t.shapes.get(e);if(!n||!VR(n)||n.isLocked)return!1;const r=lm(t,n.id,rm),o=r??qR(t,n);return!!o&&(hm(t,o,{editOperationKind:FR,createOperationKind:jR,isExisting:!!r,entryMode:r?"selectAll":"focusEnd"}),!0)}function VR(t){return"geo"===t.type}function KR({editor:t,label:e,pathGeometry:n,pagePoint:r,hintPosition:o,snapToDefault:i}){let s=n.getNearestPosition(r,{hintPosition:o});if(i){const e=n.defaultPosition,r=n.getPointAt(e),o=n.getPointAt(s),i=Math.max(t.state.cameraZoom.get(),1e-4);o.dist(r)*i<=10&&(s=e)}const a=TR(t,e,n);return Math.min(a.end,Math.max(a.start,s))}function qR(t,e){const n=$R(t,XR(e,{...Qf(t),autoSize:!1,textAlign:"middle"}),e);return cm(t,{bindingType:rm,owner:e,operationKind:jR,index:`${e.index}${CR}`,layout:n,bindingProps:{normalizedAnchor:{x:.5,y:.5}}})}function XR(t,e){return{id:"shape:draft",typeName:"shape",scope:"document",type:"text",parentId:t.parentId,index:`${t.index}.label`,x:0,y:0,rotation:0,scaleX:1,scaleY:1,opacity:1,isHidden:!1,isLocked:!1,meta:{},props:e}}function YR({fontCatalog:t=bm()}={}){return{id:"land.text",shapeUtils:[new yR],shapeSvgExporters:[new xR(t)],bindingUtils:[new OR,new PR],interactionHandlers:[HR()],setup(t){t.tools.register("text",t=>new iR(t))}}}var JR=Ae("plugin-text.api");function GR({editor:t}){return function({editor:t}){return{create(e){const n=t.shapes.getDefaultProps("text"),[r]=t.commands.createShapes([{type:"text",x:e.x,y:e.y,meta:e.meta?{...e.meta}:void 0,props:{...n,w:e.w??n.w,h:e.h??n.h,font:e.font??n.font,color:e.color??n.color,size:e.size??n.size,textAlign:e.textAlign??n.textAlign,richText:Cf(e.text)}}],{source:"user"});return"text"===r?.type?{id:r.id,type:r.type}:null},startEditing(e){const n=e??t.selection.getIds()[0],r=n?t.shapes.get(n):null;return!(!r||"text"!==r.type||r.isLocked)&&(t.editing.start({shapeId:r.id,entryMode:"focusEnd"},"user"),!0)},startEditingGeoLabel(e){const n=t.selection.getIds(),r=e??(1===n.length?n[0]:void 0);return!!r&&UR(t,r)},startEditingPathLabel(e){const n=t.selection.getIds(),r=e??(1===n.length?n[0]:void 0);return!!r&&_R(t,r)},getBoundTextLabel(e){const n=lm(t,e,"geo-label")??lm(t,e,"path-label");return n&&Ef(n.props.richText).trim().length>0?{id:n.id,type:n.type}:null},getFormattingSnapshot:()=>function(t){return FO(t)?.getSnapshot()??null}(t),setSelectionStyle(e,n){const r=n?null:FO(t);if(r)return void 0!==e.color&&r.setColor(QR(e.color)),void 0!==e.backgroundColor&&r.setBackgroundColor(QR(e.backgroundColor)),void 0!==e.font&&r.setFont(e.font),void 0!==e.size&&r.setSize(e.size),void 0!==e.textAlign&&r.setTextAlign(e.textAlign),[r.shapeId];const o=ZR(t,n).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...e}}));return o.length>0&&t.commands.updateShapes(o.map(({id:t,props:e})=>({id:t,props:{...e}})),{source:"user"}),o.map(({id:t})=>t)},getInlineFormatState(e,n){const r=n?null:FO(t);if(r)return r.getSnapshot()?.[e]??!1;const o=ZR(t,n).map(t=>UO(t.props.richText,e));if(0===o.length)return!1;const i=o[0]??!1;return o.every(t=>t===i)?i:"mixed"},toggleInlineFormat(e,n){const r=n?null:FO(t);if(r)return r.toggle(e);const o=ZR(t,n).filter(t=>!t.isLocked),i=!o.every(t=>!0===UO(t.props.richText,e)),s=o.map(t=>({shape:t,richText:VO(t.props.richText,e,i)})).filter(({shape:t,richText:e})=>e!==t.props.richText);return 0!==s.length&&(t.commands.updateShapes(s.map(({shape:t,richText:e})=>({id:t.id,props:{richText:e}})),{source:"user"}),!0)},getBlockType(e){const n=e?null:FO(t);if(n)return n.getSnapshot()?.blockType??null;const r=ZR(t,e).map(t=>WO(t.props.richText));if(0===r.length)return null;const o=r[0]??null;return r.every(t=>t===o)?o:"mixed"},setBlockType(e,n){const r=n?null:FO(t);if(r)return r.setBlockType(e);const o=ZR(t,n).filter(t=>!t.isLocked).map(t=>({shape:t,richText:HO(t.props.richText,e)})).filter(({shape:t,richText:e})=>e!==t.props.richText);return 0!==o.length&&(t.commands.updateShapes(o.map(({shape:t,richText:e})=>({id:t.id,props:{richText:e}})),{source:"user"}),!0)},clearFormatting(){const e=FO(t);if(e)return e.clearFormatting();const n=t.state.selectedShapes.get().filter(Gf).filter(t=>!t.isLocked).map(t=>({shape:t,richText:qO(t.props.richText)})).filter(({shape:t,richText:e})=>e!==t.props.richText||!X(t.props.backgroundColor));return 0!==n.length&&(t.commands.updateShapes(n.map(({shape:t,richText:e})=>({id:t.id,props:{richText:e,backgroundColor:H("transparent")}})),{source:"user"}),!0)},getLinkHref(){const e=FO(t);if(e)return e.getSnapshot()?.linkHref??null;const n=t.state.selectedShapes.get().filter(Gf).map(t=>function(t){const e=[];if(XO(t.content,(t,n)=>{if("text"!==t.type||!t.text||n.insideCodeBlock||t.marks?.some(t=>"code"===t.type))return;const r=t.marks?.find(t=>"link"===t.type)?.attrs?.href;e.push("string"==typeof r&&r.length>0?r:null)}),0===e.length)return null;const n=e[0]??null;return e.every(t=>t===n)?n:"mixed"}(t.props.richText));if(0===n.length)return null;const r=n[0]??null;return n.every(t=>t===r)?r:"mixed"},setLink(e){const n=FO(t);if(n)return n.setLink(e);const r=null===e?null:wf(e);if(null!==e&&null===r)return!1;const o=t.state.selectedShapes.get().filter(Gf).filter(t=>!t.isLocked).map(t=>({shape:t,richText:KO(t.props.richText,r)})).filter(({shape:t,richText:e})=>e!==t.props.richText);return 0!==o.length&&(t.commands.updateShapes(o.map(({shape:t,richText:e})=>({id:t.id,props:{richText:e}})),{source:"user"}),!0)},getToolDefaults:()=>t.shapes.getDefaultProps("text"),setToolDefaults:e=>(t.shapes.updateDefaultProps("text",e),t.shapes.getDefaultProps("text"))}}({editor:t})}function ZR(t,e){if(e){const n=t.shapes.get(e);return Gf(n)?[n]:[]}return t.state.selectedShapes.get().filter(Gf)}function QR(t){const e=q(t);return"transparent"===e?null:e}function tL(t={}){const{fontCatalog:e,openLink:n,...r}=t,o={...wm(),...r},i=e??vm(o);return{id:"text",editor:YR({fontCatalog:i}),render:QN({fontCatalog:i,formattingToolbar:o.formattingToolbar,openLink:n,onTiptapEditorChange:o.onTiptapEditorChange}),api:JR,setup:({editor:t})=>({api:GR({editor:t})})}}var eL=tL();function nL(t){return{kind:"svg-inliner",id:"text.svg-inliner",async inline({exportedShapes:e,svg:n}){const r=e.filter(Gf),o=r.map(t=>Ef(t.props.richText)).join(""),i=new Set(r.map(t=>t.props.font)),s=[t.defaultFont,...t.fontsById.values()].filter(e=>function({definition:t,isDefault:e,svg:n,usedFontIds:r}){return!!t.source&&"system"!==t.source.kind&&(e&&r.has("default")||r.has(t.id)||n.includes(`font-family:${o=t.cssFamily,o.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}`));var o}({definition:e,isDefault:e===t.defaultFont,svg:n,usedFontIds:i})),a=(await Promise.all(s.map(t=>async function(t,e){const{source:n}=t;if(!n||"system"===n.kind)return"";if("stylesheet"===n.kind){const r=function(t,e){const n=lL(t);if(e.length>0&&"fonts.googleapis.com"===n.hostname&&!n.searchParams.has("text")){const t=Array.from(new Set(e)).join("");encodeURIComponent(t).length<=1500&&n.searchParams.set("text",t)}return n.href}(n.cssUrl,e),o=await sL(r,t.id);return iL(oL(await rL(await o.text(),o.url||r,t.id)),t.id)}return async function(t,e){const n="string"==typeof t.src?iL(oL(await rL(t.src,void 0,e)),e):`url("${await aL(new Blob([t.src],{type:"application/octet-stream"}),e)}")`,r=function(t){return t?[["ascent-override",t.ascentOverride],["descent-override",t.descentOverride],["font-display",t.display],["font-feature-settings",t.featureSettings],["line-gap-override",t.lineGapOverride],["font-stretch",t.stretch],["font-style",t.style],["unicode-range",t.unicodeRange],["font-weight",t.weight]].flatMap(([t,e])=>e?[`;${t}:${e}`]:[]).join(""):""}(t.descriptors);return`@font-face{font-family:${o=t.family,`"${o.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`};src:${n}${r}}`;var o}(n,t.id)}(t,o)))).filter(t=>t.length>0);return a.length>0?function(t,e){const n=t.match(/^<svg\b[^>]*>/u);if(!n)throw new Error("Could not embed font resources in the generated SVG.");const r=`<style type="text/css">${o=e,o.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}</style>`;var o;return`${n[0]}${r}${t.slice(n[0].length)}`}(n,a.join("\n")):n}}}async function rL(t,e,n){const r=Array.from(t.matchAll(/\burl\(\s*(["']?)(.*?)\1\s*\)/giu),t=>t[2]?.trim()).filter(t=>!!t),o=new Map;for(const i of new Set(r)){if(i.startsWith("data:")||i.startsWith("#"))continue;const t=lL(i,e).href,r=await aL(await(await sL(t,n)).blob(),n);o.set(i,r)}return t.replace(/\burl\(\s*(["']?)(.*?)\1\s*\)/giu,(t,e,n)=>{const r=o.get(n.trim());return r?`url(${e}${r}${e})`:t})}function oL(t){const e=String.raw`\blocal\(\s*(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|[^)]*)\s*\)`;return t.replace(new RegExp(`${e}\\s*,\\s*`,"giu"),"").replace(new RegExp(`\\s*,\\s*${e}`,"giu"),"").replace(new RegExp(e,"giu"),"")}function iL(t,e){if(!/\burl\(\s*["']?data:/iu.test(t))throw new Error(`Font resource "${e}" has no embeddable source.`);return t}async function sL(t,e){let n;try{n=await fetch(t)}catch(r){throw new Error(`Could not download font resource "${e}".`,{cause:r})}if(!n.ok)throw new Error(`Could not download font resource "${e}" (${n.status}).`);return n}async function aL(t,e){const n=await async function(t){const e=new Uint8Array(await t.arrayBuffer());let n="";for(let r=0;r<e.length;r+=32768)n+=String.fromCharCode(...e.subarray(r,r+32768));return`data:${t.type||"application/octet-stream"};base64,${btoa(n)}`}(t);if(!n)throw new Error(`Could not embed font resource "${e}".`);return n}function lL(t,e){try{return e?new URL(t,e):new URL(t,globalThis.location?.href)}catch(n){throw new Error(`Could not resolve font resource URL "${t}".`,{cause:n})}}function cL({fontCatalog:t}){return{id:"text.svg-export",requires:[eL],setup:()=>({exports:[nL(t)]})}}function dL(t){vf(t)&&window.open(t,"_blank","noopener,noreferrer")}function uL(t){return"text"===t?"文字生成":"图片生成"}function pL(t,e){if("text"===e){const n=t.shapes.getDefaultProps("text"),r=160,o=n.h;return{w:r,h:o,title:uL(e),contentProps:{...n,w:r,h:o,autoSize:!1,richText:Cf(""),textAlign:"middle"}}}const n=t.shapes.getDefaultProps("image");return{w:n.w,h:n.h,title:uL(e),contentProps:{...n,altText:""}}}function hL(t,e){if(t.state.readonly.get())return null;const n=t.shapes.get(e),r=gL(n);if(!n||!r||t.layers.isOrAncestorLocked(n.id)||t.shapes.isHidden(n.id)||Math.abs(Math.abs(n.scaleX)-1)>1e-8||Math.abs(Math.abs(n.scaleY)-1)>1e-8)return null;const o=t.shapes.computeLocalBounds(n);if(Math.abs(o.x)>1e-8||Math.abs(o.y)>1e-8)return null;const i=t.bindings.getToShape(n.id).filter(Fn).map(({id:t})=>t),s=t.operations.begin({kind:"flow.wrap-shape",label:"shape.wrap-flow-node",source:"user",history:"record"});try{const e=t.commands.createShapes([{type:"flow-node",parentId:n.parentId,index:n.index,x:n.x,y:n.y,rotation:n.rotation,scaleX:n.scaleX,scaleY:n.scaleY,opacity:n.opacity,props:{w:o.w,h:o.h,title:uL(r),kind:r}}],{source:"user",autoReparent:!1})[0];if(!mL(e))return s.cancel(),null;if(!t.commands.reparentShapes({ids:[n.id],parentId:e.id},{source:"user"}))return s.cancel(),null;t.commands.updateShapes([{id:n.id,opacity:1}],{source:"user"});for(const n of i)t.commands.updateBinding({id:n,toId:e.id},{source:"user"});return t.commands.setSelectedShapeIds([e.id],{source:"system"}),s.commit(),{nodeId:e.id,contentId:n.id}}catch(a){throw s.isActive&&s.cancel(),a}}function fL(t,e){if(t.state.readonly.get())return null;const n=t.shapes.get(e);if(!mL(n)||t.layers.isOrAncestorLocked(n.id)||t.layers.hasLockedDescendant(n.id)||t.shapes.isHidden(n.id))return null;const r=t.layers.getChildren(n.id);if(1!==r.length||!gL(r[0]))return null;const o=r[0],i=t.bindings.getToShape(n.id).filter(Fn).map(({id:t})=>t),s=t.operations.begin({kind:"flow.unwrap-node",label:"shape.unwrap-flow-node",source:"user",history:"record"});try{if(!t.commands.reparentShapes({ids:[o.id],parentId:n.parentId},{source:"user"}))return s.cancel(),null;t.commands.updateShapes([{id:o.id,index:n.index,opacity:o.opacity*n.opacity}],{source:"user"});for(const e of i)t.commands.updateBinding({id:e,toId:o.id},{source:"user"});return t.commands.deleteShapes([n.id],{source:"user"}),t.commands.setSelectedShapeIds([o.id],{source:"system"}),s.commit(),t.shapes.get(o.id)??null}catch(a){throw s.isActive&&s.cancel(),a}}function mL(t){return"flow-node"===t?.type}function gL(t){return"text"===t?.type||"image"===t?.type?t.type:null}var yL=Ae("plugin-flow.api");function xL({editor:t}){return{wrapShape(e){const n=hL(t,e);return n?{id:n.nodeId,type:"flow-node",contentId:n.contentId}:null},unwrapNode(e){const n=fL(t,e);return n?{id:n.id,type:n.type}:null}}}var wL=96;function bL(t,e,n){if(t.state.readonly.get())return null;const r=t.shapes.get(e.shape.id);if(!r||t.layers.isOrAncestorLocked(r.id)||t.shapes.isHidden(r.id))return null;const o=xt(t,r,e.port.id);if(!o)return null;const i=na(t,{shape:r,port:o},function(t,e,n,r){const o=pL(t,r),i=e.parentId,s=i.startsWith("shape:")?t.shapes.get(i):null,a=s?t.shapes.computeLocalToPageTransform(s):J.Identity(),l=a.tryInvert(),c=n.pageOutwardNormal.normalize(),d=new O(o.w/2,o.h/2),u=a.applyToPoint(d),p=a.applyToPoint(d.add(new O(o.w/2,0))),h=a.applyToPoint(d.add(new O(0,o.h/2))),f=Math.abs(vL(p.sub(u),c))+Math.abs(vL(h.sub(u),c)),m=n.pagePoint.add(c.mul(96+f)),g=l?.applyToPoint(m)??m;return{type:"flow-node",parentId:i,x:g.x-o.w/2,y:g.y-o.h/2,rotation:0,props:{w:o.w,h:o.h,title:o.title,kind:r}}}(t,r,o,n)),s=t.operations.begin({kind:`flow.create-${n}-node`,label:"shape.create",source:"user",history:"record"});try{const e=function(t,e,n){const r=pL(t,n),o=t.commands.createShapes([{...e,type:"flow-node",props:{w:r.w,h:r.h,title:r.title,kind:n,...e.props}}],{source:"user",autoReparent:!1})[0];if(!mL(o))return null;const i=t.commands.createShapes([{type:n,parentId:o.id,x:0,y:0,props:r.contentProps}],{source:"user",autoReparent:!1})[0];return i&&i.type===n?{nodeId:o.id,contentId:i.id}:null}(t,i,n);if(!e)return s.cancel(),null;const a=t.shapes.get(e.nodeId);if(!a||"flow-node"!==a.type)return s.cancel(),null;const l=ia(t,a,o);if(!l)return s.cancel(),null;const c=Oo(t,{start:Co(r.id,o),end:Co(a.id,l),props:{routing:"curved"},selectionAfter:[a.id]});return c?(s.commit(),{contentId:e.contentId,connectorId:c.id,nodeId:a.id}):(s.cancel(),null)}catch(a){throw s.isActive&&s.cancel(),a}}function vL(t,e){return t.x*e.x+t.y*e.y}var kL=34,SL=["text","image"];function PL(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.max(1,t):e}function ML(t,e){return SL.includes(t)?t:e}function IL(t){return/^\s*$/.test(t.props.title)?"text"===t.props.kind?"文字生成":"图片生成":t.props.title}function TL(t){return new N(0,-34,t.props.w,t.props.h+34)}var CL=class extends St{type="flow-node";getDefaultProps(){return{w:240,h:180,title:"",kind:"image"}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:PL(e.w,n.w),h:PL(e.h,n.h),title:"string"==typeof e.title?e.title:n.title,kind:ML(e.kind,n.kind)}}getLocalBounds(t){return new N(0,0,t.props.w,t.props.h)}getRenderBounds(t){return TL(t)}getPointHitTestBounds(t){const e=TL(t);return new N(e.x+t.x,e.y+t.y,e.w,e.h)}hitTest(t,e){return this.getPositionedBounds(t).containsPoint(e)||function(t){return new N(t.x,t.y-34,t.props.w,34)}(t).containsPoint(e)}hitTestBindingTarget(t,e){return this.getPositionedBounds(t).containsPoint(e)}canEdit(t){return!1}canReceiveTerminalBinding(t){return!0}canReceiveChildren(t){return!0}canReceiveChild(t,e){return"text"===e.type||"image"===e.type}canAutomaticallyReceiveChildren(t){return!1}getChildClipLocalBounds(t){return this.getLocalBounds(t)}isSelectionTransformContainer(t){return!0}shouldResizeDescendants(t){return!0}getResizeToFitDescendantsProps(t,e){return this.validateProps({...t.props,w:e.w,h:e.h})}},EL=184,AL=["left","right"],OL={id:"land.flow.dom-events",handle:({event:t})=>HL(t.target)?"handled":"continue",getCursor:({element:t})=>t?.closest("[data-flow-connector-port]")?"pointer":void 0};function NL(t={}){const e=new Set(t.visiblePortIds??AL);return{id:"land.flow.react",shapeRenderers:[{type:"flow-node",component:RL,foregroundComponent:LL}],canvasOverlays:[{id:"land.flow.connector-ports",order:110,component:()=>l($L,{visiblePortIds:e})}],domEventGuards:[OL]}}function RL(t){return null}function LL({editor:t,shape:e}){const n="text"===e.props.kind?wn:gn;
55
- return l("div",{style:{height:"100%",overflow:"visible",pointerEvents:"none",position:"relative",width:"100%"},children:l(o,{editor:t,shape:e,isEditing:!1,value:e.props.title,fallback:IL(e),bodyWidth:e.props.w,bodyHeight:e.props.h,renderHeight:34,operationKind:"flow-node.edit",editAriaLabel:"Flow node title",inputAriaLabel:"Flow node title",dataUi:{heading:"flow-node-canvas-heading",dragHandle:"flow-node-drag-handle",name:"flow-node-canvas-name",input:"flow-node-canvas-name-input"},onValueChange:n=>{t.commands.updateShapes([{id:e.id,props:{title:n}}],{source:"user"})},leading:l(n,{"data-ui":"flow-node-title-icon","data-flow-node-kind":e.props.kind,size:14,stroke:1.7}),editable:!1,showBackground:!1,showDragHandle:!1})})}var $L=m(function({visiblePortIds:n}){const r=t(),o=e(r.state.readonly),i=e(r.state.tool).activeToolId;e(r.state.selectedShapes);const s=e(r.state.shapeEditingSession),a=e(r.inputs.isSpacePressed),d=e(r.render.interaction.selectionTranslationActive),u=e(r.state.cameraZoom),[p,h]=S(null),f=Math.max(u,1e-4),m=ha(r),y="select"===i?m.visibleShapes.filter(t=>m.sourceShapeIds.has(t.id)):[],x=p?function(t,e,n,r){const o=e.find(t=>t.id===n.shapeId);if(!o)return null;const i=xt(t,o,n.portId);return i&&FL(i,r)?{shape:o,port:i}:null}(r,y,p,n):null,b=null!==x,v=null!==p&&null===x;w(()=>{v&&h(null)},[v]),w(()=>{if(!b)return;const t=t=>{HL(t.target)||h(null)},e=t=>{"Escape"===t.key&&h(null)};return document.addEventListener("pointerdown",t),document.addEventListener("keydown",e),()=>{document.removeEventListener("pointerdown",t),document.removeEventListener("keydown",e)}},[b]);const k=g(t=>{h(e=>e?.shapeId===t.shapeId&&e.portId===t.portId?null:t)},[]),P=g(t=>{x&&(bL(r,x,t),h(null))},[r,x]);return o||s||a||d||0===y.length?null:c("g",{"data-ui":"flow-connector-ports-overlay",children:[
56
- l("style",{children:_L}),y.flatMap(t=>yt(r,t).map(e=>{if(!FL(e,n))return null;const r={shapeId:t.id,portId:e.id};
57
- return l(DL,{isOpen:p?.shapeId===t.id&&p.portId===e.id,onToggle:()=>k(r),port:e,shape:t,zoom:f},`${t.id}:${e.id}`)})),x?l(BL,{onCreate:P,port:x.port,zoom:f}):null]})});function DL({isOpen:t,onToggle:e,port:n,shape:r,zoom:o}){const i=Gs(n,o),s=24;
58
- return l("foreignObject",{"data-flow-connector-port":"true","data-flow-connector-port-id":n.id,"data-flow-connector-port-shape-id":r.id,height:s/o,overflow:"visible",pointerEvents:"all",width:s/o,x:i.x-12/o,y:i.y-12/o,children:l("div",{style:{height:s,transform:`scale(${1/o})`,transformOrigin:"top left",width:s},children:l("button",{"aria-expanded":t,"aria-haspopup":"menu","aria-label":"新增节点","data-flow-port-button":"true","data-flow-ui":"true",onClick:e,onPointerDown:t=>{t.preventDefault(),t.stopPropagation()},style:UL,type:"button",children:l("span",{"data-flow-port-visual":"true",style:VL,children:l(xn,{"aria-hidden":"true","data-flow-port-plus-icon":"true",size:14,strokeWidth:2.5})})})})})}function BL({onCreate:n,port:r,zoom:o}){const i=t(),s=e(i.state.viewportScreenSize),a=function(t,e,n,r){const o=t.viewport.pageToScreen(new O(e.x,e.y)),i=EL,s=120,a=16,l=8,c=n.pageOutwardNormal;let d,u;if(Math.abs(c.x)>=Math.abs(c.y)){const t=c.x>=0?o.x+a:o.x-a-i,e=c.x>=0?o.x-a-i:o.x+a;d=jL(t,i,r.w,l)?t:e,u=o.y-s/2}else{const t=c.y>=0?o.y+a:o.y-a-s,e=c.y>=0?o.y-a-s:o.y+a;d=o.x-i/2,u=jL(t,s,r.h,l)?t:e}const p=t.viewport.screenToPage(new O(WL(d,i,r.w,l),WL(u,s,r.h,l)));return{x:p.x,y:p.y}}(i,Gs(r,o),r,s);
59
- return l("foreignObject",{"data-flow-node-menu":"true",height:120/o,overflow:"visible",pointerEvents:"all",width:EL/o,x:a.x,y:a.y,children:c("div",{"aria-label":"新增节点","data-flow-ui":"true",onPointerDown:t=>{t.stopPropagation()},role:"menu",style:{...KL,transform:`scale(${1/o})`},children:[
60
- l("div",{"data-flow-menu-title":"true",style:qL,children:"新增节点"}),
61
- l(zL,{icon:bn,label:"文字生成",onSelect:()=>n("text")}),
62
- l(zL,{icon:yn,label:"图片生成",onSelect:()=>n("image")})]})})}function zL({icon:t,label:e,onSelect:n}){
63
- return c("button",{"data-flow-menu-item":e,onClick:n,role:"menuitem",style:XL,type:"button",children:[l(t,{"aria-hidden":"true",size:16,strokeWidth:2}),l("span",{children:e})]})}function FL(t,e){return e.has(t.id)}function jL(t,e,n,r){return t>=r&&t+e<=n-r}function WL(t,e,n,r){return Math.min(Math.max(t,r),Math.max(r,n-e-r))}function HL(t){return t instanceof Element&&!!t.closest("[data-flow-ui]")}var _L='\n [data-flow-port-visual] {\n transition: transform 120ms ease, box-shadow 120ms ease;\n }\n [data-flow-port-button]:hover [data-flow-port-visual],\n [data-flow-port-button][aria-expanded="true"] [data-flow-port-visual],\n [data-flow-port-button]:focus-visible [data-flow-port-visual] {\n transform: scale(1.2);\n }\n [data-flow-port-button]:focus-visible [data-flow-port-visual] {\n box-shadow: 0 0 0 2px var(--popover, #ffffff), 0 0 0 4px var(--land-selection, #2563eb);\n }\n [data-flow-menu-item]:hover,\n [data-flow-menu-item]:focus-visible {\n background: rgba(37, 99, 235, 0.1) !important;\n }\n @media (prefers-reduced-motion: reduce) {\n [data-flow-port-visual] {\n transition: none;\n }\n }\n',UL={alignItems:"center",background:"transparent",border:0,cursor:"pointer",display:"flex",height:"100%",justifyContent:"center",outline:"none",padding:0,width:"100%"},VL={alignItems:"center",background:"var(--land-selection, #2563eb)",borderRadius:"999px",boxShadow:"0 1px 3px rgba(15, 23, 42, 0.24)",color:"#ffffff",display:"flex",height:20,justifyContent:"center",transformOrigin:"center",width:20},KL={background:"var(--popover, #ffffff)",border:"1px solid var(--border, #e2e8f0)",borderRadius:10,boxShadow:"0 12px 30px rgba(15, 23, 42, 0.16)",boxSizing:"border-box",color:"var(--popover-foreground, #0f172a)",display:"flex",flexDirection:"column",fontFamily:"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",gap:2,padding:6,transformOrigin:"top left",width:EL},qL={color:"var(--muted-foreground, #64748b)",fontSize:12,fontWeight:600,lineHeight:"18px",padding:"2px 8px 4px"},XL={alignItems:"center",background:"transparent",border:0,borderRadius:7,color:"inherit",cursor:"pointer",display:"flex",flexShrink:0,font:"inherit",fontSize:13,fontWeight:500,gap:9,height:34,outline:"none",padding:"0 8px",textAlign:"left",width:"100%"},YL=class{type="flow-node";toSvg(t,e){return{tag:"rect",attrs:{x:0,y:0,width:t.props.w,height:t.props.h,rx:8,ry:8,fill:"#ffffff"}}}toSvgForeground(t,e){return{tag:"g",children:[{tag:"rect",attrs:{x:.5,y:.5,width:Math.max(t.props.w-1,0),height:Math.max(t.props.h-1,0),rx:8,ry:8,fill:"none",stroke:"#94a3b8","stroke-width":1}},{tag:"text",attrs:{x:0,y:-8,fill:"#0f172a","font-family":"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif","font-size":12,"font-weight":400},children:[IL(t)]}]}}};function JL(){return{id:"land.flow",shapeUtils:[new CL],shapeSvgExporters:[new YL]}}function GL(t={}){const e=t.visiblePortIds?[...t.visiblePortIds]:void 0;return{id:"flow",requires:[fl,gh,eL],editor:JL(),render:NL({visiblePortIds:e}),api:yL,setup:({editor:t})=>({api:xL({editor:t})})}}var ZL=GL();function QL(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.max(1,t):e}var t$=class extends St{type="group";getGroupingShapeCreateInput({parentId:t,parentLocalBounds:e}){return{type:this.type,x:e.x,y:e.y,parentId:t,props:{w:e.w,h:e.h}}}getDefaultProps(){return{w:1,h:1}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:QL(e.w,n.w),h:QL(e.h,n.h)}}getLocalBounds(t){return new N(0,0,t.props.w,t.props.h)}hitTest(t,e){return!1}hitTestLineSegment(t,e){return!1}isSelectionTransformContainer(t){return!0}canUngroupChildren(t){return!0}shouldResizeDescendants(t){return!0}getResizeToFitDescendantsProps(t,e){return this.validateProps({...t.props,w:e.w,h:e.h})}getMinimumChildCount(t){return 2}contributesToExportBounds(t){return!1}canReceiveChildren(t){return!0}canAutomaticallyReceiveChildren(t){return!1}canBeDirectlyBrushSelected(t){return!1}},e$=class{type="group";toSvg(t){return{tag:"g"}}};function n$(){return{id:"land.group",shapeUtils:[new t$],shapeSvgExporters:[new e$]}}function r$(){return{id:"land.group.react",shapeRenderers:[{type:"group",component:o$,hoverComponent:s$}]}}function o$({editor:t,shape:n,isSelected:r}){const o=e(t.state.selectedShapeIds),i=t.layers.getDescendantIds(n.id),s=o.some(t=>i.includes(t));
64
- return l(i$,{shape:n,showSelectionBoundary:r||s})}function i$({shape:t,showSelectionBoundary:e=!1}){const{h:n,w:r}=t.props,o=K(H("#64748b"));
65
- return l("svg",{width:"100%",height:"100%",viewBox:`0 0 ${r} ${n}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:e?l("rect",{"data-ui":"group-selection-boundary",x:.5,y:.5,width:Math.max(r-1,0),height:Math.max(n-1,0),fill:"none",stroke:o,strokeDasharray:"4 4",strokeWidth:1,vectorEffect:"non-scaling-stroke"}):null})}function s$({shape:t,strokeWidth:e}){const{h:r,w:o}=t.props;
66
- return l("svg",{"data-ui":"group-hover-outline",width:"100%",height:"100%",viewBox:`0 0 ${o} ${r}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:l("rect",{x:0,y:0,width:o,height:r,fill:"none",stroke:n,strokeWidth:e,vectorEffect:"non-scaling-stroke"})})}var a$={id:"group",editor:n$(),render:r$()};function l$(t){return C(t)&&"html"===t.type}var c$="html.interact",d$={propagation:"stop"};function u$(t,e){const n=t.shapes.get(e);return!(!l$(n)||!t.editing.canEditShape(n))&&!!t.editing.start({shapeId:e,entryMode:"focusEnd",operationKind:c$},"user")}function p$(){return{id:"land.html.interactions",editorEvent:{handleEvent(t,e){if("select"===t.state.tool.get().activeToolId){if("keyboard"===e.type&&"key_down"===e.name&&"Enter"===e.key&&!e.altKey&&!e.accelKey&&!t.state.shapeEditingSession.get()){const e=t.selection.getIds();return 1===e.length&&u$(t,e[0])?d$:void 0}if("double_click"===e.type){const n=t.shapes.hitTest(e.pagePoint);if(n&&u$(t,n.id))return d$}}}}}}var h$=Ae("plugin-html.api");function f$({editor:t}){return{create(e){const n=t.shapes.getDefaultProps("html"),[r]=t.commands.createShapes([{type:"html",x:e.x,y:e.y,meta:e.meta?{...e.meta}:void 0,props:{...n,w:e.w??n.w,h:e.h??n.h,html:e.html,title:e.title??n.title}}],{source:"user"});return"html"===r?.type?{id:r.id,type:r.type}:null},update(e,n){const r=t.shapes.get(e);return!(!l$(r)||r.isLocked)&&(t.commands.updateShapes([{id:e,props:{...n}}],{source:"user"}),!0)},startInteracting:e=>u$(t,e)}}function m$(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.max(32,t):e}var g$=class extends St{type="html";getDefaultProps(){return{w:480,h:320,html:"",title:""}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:m$(e.w,n.w),h:m$(e.h,n.h),html:"string"==typeof e.html?e.html:n.html,title:"string"==typeof e.title?e.title:n.title}}getLocalBounds(t){return new N(0,0,t.props.w,t.props.h)}canEdit(t){return!0}canReceiveTerminalBinding(t){return!0}};function y$(t){return t.trim()||"Embedded HTML"}function x$(){return{id:"land.html",shapeUtils:[new g$],interactionHandlers:[p$()]}}var w$="allow-forms allow-pointer-lock allow-presentation allow-scripts";function b$(t={}){return{id:"land.html.react",shapeRenderers:[{type:"html",component:(n=t.sandbox??"allow-forms allow-pointer-lock allow-presentation allow-scripts",function({editor:t,shape:r,shapeEditingSession:o}){const i=k(null),s=e(t.state.readonly),a=s||o?.shapeId===r.id;return w(()=>{a&&!s&&i.current?.focus()},[a,s]),l("iframe",{ref:i,"data-ui":"html-shape-frame",loading:"lazy",referrerPolicy:"no-referrer",sandbox:n,srcDoc:r.props.html,tabIndex:a?0:-1,title:y$(r.props.title),style:{background:"#fff",border:0,display:"block",height:r.props.h,pointerEvents:a?"auto":"none",width:r.props.w}})}),hoverComponent:v$}]};var n}function v$({shape:t,strokeWidth:e}){
67
- return l("svg",{"aria-hidden":"true","data-ui":"html-hover-outline",width:"100%",height:"100%",viewBox:`0 0 ${t.props.w} ${t.props.h}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},children:l("rect",{x:0,y:0,width:t.props.w,height:t.props.h,fill:"none",stroke:n,strokeWidth:e,vectorEffect:"non-scaling-stroke"})})}function k$(t={}){return{id:"html",editor:x$(),render:b$(t),api:h$,setup:({editor:t})=>({api:f$({editor:t})})}}var S$=k$(),P$=G("plugin.laser.runtime");function M$(t){return t.runtime.require(P$)}function I$(t,e){const n=t.trail[t.trail.length-1];n&&n.dist2(e)<=1e-6||t.trail.push(e.clone())}function T$(t,e){M$(t).set(e.sessionId,e.trail)}var C$=class extends Pt{constructor(t){super(t,"laser"),this.initial="idle",this.addChild(new E$(t,this)),this.addChild(new A$(t,this)),this.addChild(new O$(t,this))}},E$=class extends Pt{constructor(t,e){super(t,"idle",e)}onPointerDown(t){0===t.button&&this.transition("pointing",function(t,e){const n={sessionId:M$(t).start(),originScreenPoint:e.screenPoint.clone(),trail:[e.pagePoint.clone()]};return T$(t,n),n}(this.editor,t))}},A$=class extends Pt{info=null;constructor(t,e){super(t,"pointing",e)}onEnter(t){this.info=t}onPointerMove(t){this.info&&function(t,e){return t.dist2(e)>=9}(this.info.originScreenPoint,t.screenPoint)&&(I$(this.info,t.pagePoint),T$(this.editor,this.info),this.transition("drawing",this.info))}onPointerUp(){this.info&&M$(this.editor).finish(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&M$(this.editor).finish(this.info.sessionId),this.transition("idle")}onExit(){this.info&&M$(this.editor).finish(this.info.sessionId),this.info=null}},O$=class extends Pt{info=null;constructor(t,e){super(t,"drawing",e)}onEnter(t){this.info=t}onPointerMove(t){this.info&&(I$(this.info,t.pagePoint),T$(this.editor,this.info))}onPointerUp(){this.info&&M$(this.editor).finish(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&M$(this.editor).finish(this.info.sessionId),this.transition("idle")}onExit(){this.info&&M$(this.editor).finish(this.info.sessionId),this.info=null}};function N$(){return{id:"land.laser.react",canvasOverlays:[{id:"land.laser.trail-overlay",component:R$}]}}var R$=m(function(){return e(M$(t()).activeSignal)?l(L$,{}):null}),L$=m(function(){const n=t(),r=M$(n),o=e(r.trailSignal),i=e(n.state.cameraZoom),s=Math.max(i,1e-4),a=function(){const[t,e]=S(()=>J$());return w(()=>{if("undefined"==typeof window)return;let t=0;const n=r=>{e(r),t=window.requestAnimationFrame(n)};return t=window.requestAnimationFrame(n),()=>{window.cancelAnimationFrame(t)}},[]),t}(),d=k({sessionId:0,samples:[],sourceLength:0}),u=Math.max(a,J$());let p,h=[];o&&(!function(t,e,n,r){e.sessionId!==t.sessionId&&(t.sessionId=e.sessionId,t.samples=[],t.sourceLength=0);const o=e.points;Z$(t,r),o.length<t.sourceLength&&(t.samples=[],t.sourceLength=0);if(o.length===t.sourceLength)return;const i=t.sourceLength,s=o.length-i,a=t.samples[t.samples.length-1]?.time??r-U$*s;for(let l=i;l<o.length;l++){const e=o[l],c=(l-i+1)/s;G$(t,{x:e.x,y:e.y},n,cD(a,r,c))}t.sourceLength=o.length,Z$(t,r)}(d.current,o,s,u),h=function(t,e){const n=Q$(t,e);return function(t,e){if(t.length<=1)return[...t];const n=.15+.85*(1-e),r=[t[0]];for(let o=1;o<t.length;o++)r.push(lD(r[r.length-1],t[o],n));return r}(n.length>z$?n.slice(-64):n,W$)}(d.current.samples,u),p=d.current.samples[d.current.samples.length-1]?.time);const f="ending"===o?.phase,m=0===h.length,g=f&&m?o.sessionId:null;if(w(()=>{null!==g&&r.clear(g)},[g,r]),!o||m)return null;const y=f&&void 0!==p?dD(1-(u-p)/Y$,0,1):1,x=(v=j$/s,0===(b=h).length||v<=0?null:1===b.length?pD(eD(b[0],v/2,_$))??"":pD(function(t){if(0===t.length)return[];if(1===t.length)return eD(t[0].point,Math.max(t[0].radius,.01),_$);const e=[],n=[];for(const a of t){const t=oD(a.direction);uD(e,sD(a.point,aD(t,a.radius))),uD(n,iD(a.point,aD(t,a.radius)))}const r=[];for(const a of e)uD(r,a);const o=t[t.length-1],i=oD(o.direction),s=function({center:t,direction:e,normal:n,radius:r}){if(r<=0)return[];const o=[];for(let i=1;i<H$;i++){const s=i/H$;o.push(iD(t,iD(aD(e,Math.sin(Math.PI*s)*r),aD(n,-Math.cos(Math.PI*s)*r))))}return o}({center:o.point,direction:o.direction,normal:i,radius:o.radius});for(const a of s)uD(r,a);for(let a=n.length-1;a>=0;a--)uD(r,n[a]);return r}(function(t,e){const n=function(t){const e=[0];for(let n=1;n<t.length;n++)e.push(e[n-1]+nD(t[n-1],t[n]));return e}(t),r=n[n.length-1]??0,o=Math.max(e,r);return t.map((r,i)=>{const s=n[i]??0,a=dD(s/o,0,1);return{point:r,direction:tD(t,i),radius:e/2*a,runningLength:s}})}(b,v))));var b,v;return x?c("g",{"data-ui":"laser-trail-overlay",style:{opacity:y},children:[l("path",{"data-ui":"laser-trail-glow",d:x,fill:D$,style:{filter:`blur(${B$/s}px)`}}),l("path",{"data-ui":"laser-trail-beam",d:x,fill:$$})]}):null}),$$="rgb(255, 38, 38)",D$="rgba(255, 48, 48, 0.55)",B$=4,z$=64,F$=1,j$=12,W$=.32,H$=8,_$=13,U$=16,V$=8,K$=600,q$=300,X$=1400,Y$=400;function J$(){return"undefined"==typeof performance?Date.now():performance.now()}function G$(t,e,n,r){const o=t.samples[t.samples.length-1];if(!o)return void t.samples.push({...e,time:r,velocity:0});const i=F$/n,s=nD(o,e);if(s<i)return void(t.samples[t.samples.length-1]={...o,...e,time:r});const a=s*n/Math.max(V$,r-o.time);t.samples.push({...e,time:r,velocity:cD(o.velocity,a,.68)})}function Z$(t,e){t.samples=Q$(t.samples,e)}function Q$(t,e){const n=t[t.length-1];if(!n)return[];const r=e-dD(K$+n.velocity*q$,K$,X$);if(n.time<r)return[];const o=t.findIndex(t=>t.time>=r);if(-1===o)return[];const i=t.slice(o),s=t[o-1],a=i[0];return s&&a.time>r?[(l=s,c=a,d=dD((r-s.time)/(a.time-s.time),0,1),{...lD(l,c,d),time:cD(l.time,c.time,d),velocity:cD(l.velocity,c.velocity,d)}),...i]:i;var l,c,d}function tD(t,e){if(t.length<=1)return{x:1,y:0};const n=t[e-1]??t[e],r=t[e+1]??t[e];return function(t){const e=Math.sqrt(t.x*t.x+t.y*t.y);return e<=0?{x:1,y:0}:{x:t.x/e,y:t.y/e}}(0===e?sD(r,t[e]):e===t.length-1?sD(t[e],n):sD(r,n))}function eD(t,e,n){const r=[];for(let o=0;o<n;o++){const i=2*Math.PI*o/n;r.push({x:t.x+Math.cos(i)*e,y:t.y+Math.sin(i)*e})}return r}function nD(t,e){return Math.sqrt(rD(t,e))}function rD(t,e){const n=t.x-e.x,r=t.y-e.y;return n*n+r*r}function oD(t){return{x:-t.y,y:t.x}}function iD(t,e){return{x:t.x+e.x,y:t.y+e.y}}function sD(t,e){return{x:t.x-e.x,y:t.y-e.y}}function aD(t,e){return{x:t.x*e,y:t.y*e}}function lD(t,e,n){return{x:cD(t.x,e.x,n),y:cD(t.y,e.y,n)}}function cD(t,e,n){return t+(e-t)*n}function dD(t,e,n){return Math.max(e,Math.min(n,t))}function uD(t,e){const n=t[t.length-1];!n||rD(n,e)>.04?t.push(e):t[t.length-1]=e}function pD(t){if(t.length<2)return null;if(2===t.length)return`M ${fD(t[0])} L ${fD(t[1])} Z`;const e=[`M ${fD(hD(t[0],t[1]))}`];for(let n=1;n<t.length;n++){const r=t[n],o=t[(n+1)%t.length];e.push(`Q ${fD(r)} ${fD(hD(r,o))}`)}return e.push("Z"),e.join(" ")}function hD(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}function fD(t){return`${mD(t.x)},${mD(t.y)}`}function mD(t){return Number.isInteger(t)?`${t}`:t.toFixed(3)}function gD(){return{id:"land.laser",setup(t){t.runtime.provide(P$,function(t){const{atom:e,computed:n}=t.signals,r=e("laser.trail",null);let o=1;return{trailSignal:r,activeSignal:n("laser.active",()=>null!==r.get()),start(){const t=o++;return r.set({sessionId:t,phase:"active",points:[]}),t},set(t,e){const n=r.get();n&&n.sessionId===t&&r.set({sessionId:t,phase:"active",points:e.map(t=>t.clone())})},finish(t){const e=r.get();e&&e.sessionId===t&&r.set({...e,phase:"ending"})},clear(t){r.get()?.sessionId===t&&r.set(null)}}}(t)),t.tools.register("laser",t=>new C$(t))}}}var yD={id:"laser",editor:gD(),render:N$()},xD="path.node",wD="path.control";function bD(t,e){return["node",t,e].map(encodeURIComponent).join("|")}function vD(t,e,n){return["control",n,t,e].map(encodeURIComponent).join("|")}function kD(t,e){const n=e.split("|").map(t=>{try{return decodeURIComponent(t)}catch{return""}});return"path.node"===t&&3===n.length&&"node"===n[0]?{type:xD,subpathId:n[1],nodeId:n[2]}:"path.control"!==t||4!==n.length||"control"!==n[0]||"in"!==n[1]&&"out"!==n[1]?null:{type:wD,handle:n[1],subpathId:n[2],nodeId:n[3]}}var SD=new WeakMap;function PD(t,e){e?SD.set(t,MD(e)):SD.delete(t)}function MD(t){return{...t,pagePoint:t.pagePoint.clone()}}var ID=["nonzero","evenodd"],TD=["corner","smooth","symmetric"];function CD(t){return C(t)&&"path"===t.type}function ED(t){return"string"==typeof t&&ID.includes(t)}function AD(t){return"string"==typeof t&&TD.includes(t)}function OD(){const n=t(),r=e(n.state.tool),o=e(n.state.shapeEditingSession),i=e(n.state.selectedShapes),s=e(n.state.camera);if(e(n.inputs.state),"select"!==r.activeToolId||!o)return null;const a=1===i.length?i[0]:null;if(!CD(a)||a.id!==o.shapeId)return null;const c=function(t){const e=SD.get(t);return e?MD(e):null}(n);if(!c||c.shapeId!==a.id)return null;const d=8/s.z,u=d/2,p=1.5/s.z;
68
- return l("g",{"data-ui":"path-edit-insert-preview",pointerEvents:"none",children:l("rect",{"data-ui":"path-edit-insert-preview-control-point",x:c.pagePoint.x-u,y:c.pagePoint.y-u,width:d,height:d,rx:2,ry:2,fill:"rgba(219, 234, 254, 0.72)",stroke:"var(--land-selection, #2563eb)",strokeDasharray:`${3/s.z} ${2/s.z}`,strokeWidth:p})})}function ND(t){return Number.isInteger(t)?`${t}`:`${Number(t.toFixed(2))}`}function RD(t){return new O(t.x,t.y)}function LD(t,e){const n=RD(e);if(!function(t,e){return!!t.out||!!e.in}(t,e))return`L ${ND(n.x)} ${ND(n.y)}`;const r=function(t){const e=RD(t);return t.out?e.add(new O(t.out.dx,t.out.dy)):e}(t),o=function(t){const e=RD(t);return t.in?e.add(new O(t.in.dx,t.in.dy)):e}(e);return["C",ND(r.x),ND(r.y),ND(o.x),ND(o.y),ND(n.x),ND(n.y)].join(" ")}function $D(t){const e=t.nodes[0];if(!e)return null;const n=[`M ${ND(e.x)} ${ND(e.y)}`];for(let r=1;r<t.nodes.length;r+=1){const e=t.nodes[r-1],o=t.nodes[r];e&&o&&n.push(LD(e,o))}if(t.closed&&t.nodes.length>1){const r=t.nodes[t.nodes.length-1];r&&n.push(LD(r,e)),n.push("Z")}return n.join(" ")}function DD(t){const e=t.map($D).filter(t=>null!==t);return e.length>0?e.join(" "):null}var BD=1e-6,zD=1/3,FD=Math.PI/8,jD=new WeakMap;function WD(t){return Number.isFinite(t)}function HD(t){return{dx:t.dx,dy:t.dy}}function _D(t){return{id:t.id,x:t.x,y:t.y,kind:t.kind,...t.in?{in:HD(t.in)}:null,...t.out?{out:HD(t.out)}:null}}function UD(t){return{id:t.id,closed:t.closed,nodes:t.nodes.map(_D)}}function VD(t){return t.map(UD)}function KD(t){return new O(t.x,t.y)}function qD(t){const e=KD(t);return t.in?e.add(new O(t.in.dx,t.in.dy)):e}function XD(t){const e=KD(t);return t.out?e.add(new O(t.out.dx,t.out.dy)):e}function YD(t,e,n,r,o){const i=1-o,s=i*i*i,a=3*i*i*o,l=3*i*o*o,c=o*o*o;return new O(t.x*s+e.x*a+n.x*l+r.x*c,t.y*s+e.y*a+n.y*l+r.y*c)}function JD(t,e,n){return new O(t.x+(e.x-t.x)*n,t.y+(e.y-t.y)*n)}function GD(t,e){return[KD(t),XD(t),qD(e),KD(e)]}function ZD(t,e){return!!t.out||!!e.in}function QD(t,e,n){return ZD(t,e)?YD(...GD(t,e),n):JD(KD(t),KD(e),n)}function tB(t,e,n){const r=KD(e),o=XD(e),i=qD(n),s=KD(n);if(e.out||n.in)for(let a=1;a<=18;a+=1)t.push(YD(r,o,i,s,a/18));else t.push(s)}function eB(t){const e=t.nodes[0];if(!e)return{id:t.id,closed:t.closed,points:[]};const n=[KD(e)];for(let r=1;r<t.nodes.length;r+=1){const e=t.nodes[r-1],o=t.nodes[r];e&&o&&tB(n,e,o)}if(t.closed&&t.nodes.length>1){const r=t.nodes[t.nodes.length-1];r&&tB(n,r,e)}return{id:t.id,closed:t.closed,points:n}}function nB(t){const e=t.props,n=jD.get(e);if(n)return n;const r=rB(t.props);return jD.set(e,r),r}function rB(t){const e=t.subpaths.map(eB),n=e.flatMap(t=>t.points),r=t.subpaths.flatMap(t=>t.nodes.flatMap(t=>[KD(t),...t.in?[qD(t)]:[],...t.out?[XD(t)]:[]])),o=r.length>0?N.FromPoints(r):new N(0,0,1,1),i=Math.max(t.strokeWidth/2,1),s=n.length>0?N.FromPoints(n).expand(i):o.expand(i),a=new N(s.x,s.y,Math.max(s.w,1),Math.max(s.h,1));return{path:DD(t.subpaths),pointBounds:o,localBounds:s,renderBounds:a,outlineVertices:n.map(t=>t.clone()),flattenedSubpaths:e}}function oB(t,e){return t.map(t=>({...t,nodes:t.nodes.map(t=>function(t,e){const n=e(KD(t)),r=t.in?e(qD(t)):null,o=t.out?e(XD(t)):null;return{...t,x:n.x,y:n.y,...r?{in:{dx:r.x-n.x,dy:r.y-n.y}}:{in:null},...o?{out:{dx:o.x-n.x,dy:o.y-n.y}}:{out:null}}}(t,e))}))}function iB(t,e){const n=rB({...e,subpaths:VD(t)}).pointBounds,r=Number.isFinite(n.x)?n.x:0,o=Number.isFinite(n.y)?n.y:0,i=function(t,e,n){return oB(t,t=>new O(t.x+e,t.y+n))}(t,-r,-o);return{x:r,y:o,subpaths:i,geometry:rB({...e,subpaths:i})}}function sB(t,e){return oB(t.props.subpaths,t=>e.applyToPoint(t))}function aB(t,e){return DD(sB(t,e))}function lB(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return{distanceSquared:t.dist2(e),t:0};const i=t.sub(e),s=Math.max(0,Math.min(1,(i.x*r.x+i.y*r.y)/o)),a=e.add(r.mul(s));return{distanceSquared:t.dist2(a),t:s}}function cB(t,e,n){return lB(t,e,n).distanceSquared}function dB(t,e,n){const r=n*n;let o=null;for(const i of t){if(i.nodes.length<2)continue;const t=i.closed?i.nodes.length:i.nodes.length-1;for(let n=0;n<t;n+=1){const t=i.nodes[n],s=i.nodes[(n+1)%i.nodes.length];if(!t||!s)continue;const a=ZD(t,s)?32:1;let l=KD(t);for(let n=1;n<=a;n+=1){const c=QD(t,s,n/a),d=lB(e,l,c),u=(n-1+d.t)/a;u>.02&&u<.98&&d.distanceSquared<=r&&(!o||d.distanceSquared<o.distanceSquared)&&(o={subpathId:i.id,startNodeId:t.id,endNodeId:s.id,t:u,point:QD(t,s,u),distanceSquared:d.distanceSquared}),l=c}}}return o?{subpathId:o.subpathId,startNodeId:o.startNodeId,endNodeId:o.endNodeId,t:o.t,point:o.point.clone(),distance:Math.sqrt(o.distanceSquared)}:null}function uB(t,e){return t.find(t=>t.id===e)??null}function pB(t,e,n){return uB(t,e)?.nodes.find(t=>t.id===n)??null}function hB(t,e,n,r){return t.map(t=>t.id!==e?UD(t):{...t,nodes:t.nodes.map(t=>t.id===n?r(_D(t)):_D(t))})}function fB(t,e,n){const r=wB(e);return 0===r.size?VD(t):t.map(t=>{const e=r.get(t.id);return e?{...t,nodes:t.nodes.map(t=>e.has(t.id)?n(_D(t)):_D(t))}:UD(t)})}function mB(t,e,n){return t.map(t=>{if(t.id!==e)return UD(t);const r=t.nodes.findIndex(t=>t.id===n),o=t.nodes[r];if(!o)return UD(t);const i=r>0?t.nodes[r-1]:t.closed?t.nodes[t.nodes.length-1]:null,s=r<t.nodes.length-1?t.nodes[r+1]:t.closed?t.nodes[0]:null,a=KD(o),l=function(t,e,n){const r=e?KD(e):null,o=n?KD(n):null;if(r&&o){const e=o.sub(r);if(e.len()<=BD)return null;const n=e.normalize();return function(t,e){const n=Math.abs(t.x*e.y-t.y*e.x),r=t.len()*e.len();return r<=BD||n/r<=.001}(r.sub(t),o.sub(t))?n.rot(FD):n}const i=o?o.sub(t):r?t.sub(r):null;return!i||i.len()<=BD?null:i.normalize().rot(FD)}(a,i,s),c=t.nodes.map(_D);return c[r]={..._D(o),kind:"smooth",in:i&&l?OB(l.mul(-a.dist(KD(i))*zD)):null,out:s&&l?OB(l.mul(a.dist(KD(s))*zD)):null},{...t,nodes:c}})}function gB(t,e,n){return hB(t,e,n,t=>({...t,kind:"corner",in:null,out:null}))}function yB(t,e,n){return null!==xB(t,e,n)}function xB(t,e,n,r=e.at(-1)??null){if(!function(t){const e=new Set;for(const n of t){if(!n.id||e.has(n.id))return!1;e.add(n.id);const t=new Set;for(const e of n.nodes){if(!e.id||t.has(e.id))return!1;t.add(e.id)}}return!0}(t))return null;const o=function(t){const e=new Set,n=[];for(const r of t){const t=JSON.stringify([r.subpathId,r.nodeId]);e.has(t)||(e.add(t),n.push({subpathId:r.subpathId,nodeId:r.nodeId}))}return n}(e);if(o.length<2)return null;let i;switch(n){case"merge":i=function(t,e){const n=bB(e);if(null!==n)return function(t,e,n){const r=t.findIndex(t=>t.id===e),o=t[r];if(!o)return null;const i=function(t,e){const n=e.map(e=>t.nodes.findIndex(t=>t.id===e.nodeId));if(n.some(t=>t<0))return null;const r=Array.from(new Set(n)).sort((t,e)=>t-e);if(r.length!==e.length)return null;if(!t.closed)return r.every((t,e)=>0===e||t===r[e-1]+1)?r:null;if(r.length===t.nodes.length)return r;const o=r.flatMap((e,n)=>{const o=r[(n+1)%r.length];return(e+1)%t.nodes.length===o?[]:[n]});if(1!==o.length)return null;const i=(o[0]+1)%r.length;return[...r.slice(i),...r.slice(0,i)]}(o,n);if(!i||i.length<2)return null;const s=new Set(i),a=i.map(t=>o.nodes[t]),l=i[0],c=a[0],d=a[a.length-1],u=a.reduce((t,e)=>t.add(KD(e)),O.Zero()).div(a.length),p={..._D(c),x:u.x,y:u.y,kind:"corner",in:TB(c.in,KD(c),u),out:TB(d.out,KD(d),u)},h=o.nodes.flatMap((t,e)=>s.has(e)?e===l?[p]:[]:[_D(t)]),f=o.closed&&h.length>=3;o.closed&&!f&&IB(h);return{subpaths:EB(t,r,[{...o,closed:f,nodes:h}]),selectedNodes:[{subpathId:e,nodeId:p.id}]}}(t,n,e);const r=vB(t,e);return r?function(t,e){const[n,r]=e,o=SB(n),i=PB(r),s=o[o.length-1],a=i[0],l=KD(s).add(KD(a)).div(2),c={..._D(s),x:l.x,y:l.y,kind:"corner",in:TB(s.in,KD(s),l),out:TB(a.out,KD(a),l)},{nodes:d}=CB(i.slice(1),new Set([...o.slice(0,-1).map(t=>t.id),c.id]),"merged"),u={...n.subpath,closed:!1,nodes:[...o.slice(0,-1),c,...d]};return{subpaths:AB(t,e,u),selectedNodes:[{subpathId:u.id,nodeId:c.id}]}}(t,r):null}(t,o);break;case"join":i=function(t,e){if(2!==e.length)return null;const n=bB(e);if(null!==n)return function(t,e,n){const r=t.findIndex(t=>t.id===e),o=t[r];if(!o||o.closed||o.nodes.length<3)return null;const i=new Set([o.nodes[0].id,o.nodes[o.nodes.length-1].id]);if(2!==n.length||n.some(t=>!i.has(t.nodeId)))return null;const s=o.nodes.map(_D);return s[0]={...s[0],kind:"corner",in:null},s[s.length-1]={...s[s.length-1],kind:"corner",out:null},{subpaths:EB(t,r,[{...o,closed:!0,nodes:s}]),selectedNodes:n.map(t=>({...t}))}}(t,n,e);const r=vB(t,e);return r?function(t,e){const[n,r]=e,o=SB(n),{nodes:i,nodeIdMap:s}=CB(PB(r),new Set(o.map(t=>t.id)),"joined"),a=o[o.length-1],l=i[0];o[o.length-1]={...a,kind:"corner",out:null},i[0]={...l,kind:"corner",in:null};const c={...n.subpath,closed:!1,nodes:[...o,...i]};return{subpaths:AB(t,e,c),selectedNodes:[{subpathId:c.id,nodeId:n.node.id},{subpathId:c.id,nodeId:s.get(r.node.id)??r.node.id}]}}(t,r):null}(t,o);break;case"separate":i=function(t,e){if(2!==e.length)return null;const n=bB(e);if(null===n)return null;const r=t.findIndex(t=>t.id===n),o=t[r];if(!o||o.nodes.length<2)return null;const i=function(t,e){const[n,r]=e.map(e=>t.nodes.findIndex(t=>t.id===e.nodeId));return void 0===n||void 0===r||n<0||r<0?-1:r===n+1?n:n===r+1?r:t.closed?n===t.nodes.length-1&&0===r?n:r===t.nodes.length-1&&0===n?r:-1:-1}(o,e);if(i<0)return null;if(o.closed){const n=[...o.nodes.slice(i+1).map(_D),...o.nodes.slice(0,i+1).map(_D)];return IB(n),{subpaths:EB(t,r,[{...o,closed:!1,nodes:n}]),selectedNodes:e.map(t=>({...t}))}}const s=o.nodes.slice(0,i+1).map(_D),a=o.nodes.slice(i+1).map(_D);IB(s),IB(a);const l=s.length>=2?{...o,closed:!1,nodes:s}:null,c=function(t,e){const n=new Set(t.map(t=>t.id));if(!n.has(e))return e;let r=2;for(;n.has(`${e}:${r}`);)r+=1;return`${e}:${r}`}(t,`${o.id}:split`),d=a.length>=2?{...o,id:c,closed:!1,nodes:a}:null,u=[l,d].filter(t=>null!==t),p=new Set(s.map(t=>t.id)),h=new Set(a.map(t=>t.id)),f=e.flatMap(t=>l&&p.has(t.nodeId)?[{subpathId:l.id,nodeId:t.nodeId}]:d&&h.has(t.nodeId)?[{subpathId:d.id,nodeId:t.nodeId}]:[]);return{subpaths:EB(t,r,u),selectedNodes:f}}(t,o)}if(!i)return null;const s=r?o.findIndex(t=>{return n=r,(e=t).subpathId===n.subpathId&&e.nodeId===n.nodeId;var e,n}):-1;return{...i,primaryNode:i.selectedNodes[s]??i.selectedNodes.at(-1)??null}}function wB(t){const e=new Map;for(const n of t){const t=e.get(n.subpathId)??new Set;t.add(n.nodeId),e.set(n.subpathId,t)}return e}function bB(t){const e=t[0];return e&&t.every(t=>t.subpathId===e.subpathId)?e.subpathId:null}function vB(t,e){if(2!==e.length)return null;const n=kB(t,e[0]),r=kB(t,e[1]);return n&&r&&n.subpathIndex!==r.subpathIndex?[n,r]:null}function kB(t,e){const n=t.findIndex(t=>t.id===e.subpathId),r=t[n];if(!r||r.closed)return null;const o=r.nodes.findIndex(t=>t.id===e.nodeId),i=r.nodes[o];return!i||0!==o&&o!==r.nodes.length-1?null:{subpath:r,subpathIndex:n,endpoint:0===o?"start":"end",node:i}}function SB(t){return"end"===t.endpoint?t.subpath.nodes.map(_D):MB(t.subpath.nodes)}function PB(t){return"start"===t.endpoint?t.subpath.nodes.map(_D):MB(t.subpath.nodes)}function MB(t){return[...t].reverse().map(t=>({..._D(t),in:t.out?HD(t.out):null,out:t.in?HD(t.in):null}))}function IB(t){0!==t.length&&(t[0]={...t[0],kind:"corner",in:null},t[t.length-1]={...t[t.length-1],kind:"corner",out:null})}function TB(t,e,n){return t?OB(e.add(new O(t.dx,t.dy)).sub(n)):null}function CB(t,e,n){const r=new Map;return{nodes:t.map(t=>{let o=t.id;if(e.has(o)){let r=1,i=`${o}:${n}`;for(;e.has(i);)r+=1,i=`${t.id}:${n}:${r}`;o=i}return e.add(o),r.set(t.id,o),{..._D(t),id:o}}),nodeIdMap:r}}function EB(t,e,n){return t.flatMap((t,r)=>r===e?n.map(UD):[UD(t)])}function AB(t,e,n){const r=Math.min(e[0].subpathIndex,e[1].subpathIndex),o=new Set([e[0].subpathIndex,e[1].subpathIndex]);return t.flatMap((t,e)=>e===r?[n]:o.has(e)?[]:[UD(t)])}function OB(t){return t.len2()<=1e-12?null:{dx:t.x,dy:t.y}}function NB(t,e,n){return t.map(t=>{if(t.id!==e.subpathId)return UD(t);const r=t.nodes.findIndex(t=>t.id===e.startNodeId);if(r<0)return UD(t);const o=(r+1)%t.nodes.length,i=t.nodes[r],s=t.nodes[o];if(!i||!s||s.id!==e.endNodeId)return UD(t);const a=function(t,e,n,r){if(!ZD(t,e)){const o=JD(KD(t),KD(e),n);return{start:_D(t),node:{id:r,x:o.x,y:o.y,kind:"corner"},end:_D(e)}}const[o,i,s,a]=GD(t,e),l=JD(o,i,n),c=JD(i,s,n),d=JD(s,a,n),u=JD(l,c,n),p=JD(c,d,n),h=JD(u,p,n);return{start:{..._D(t),out:OB(l.sub(o))},node:{id:r,x:h.x,y:h.y,kind:"smooth",in:OB(u.sub(h)),out:OB(p.sub(h))},end:{..._D(e),in:OB(d.sub(a))}}}(i,s,e.t,n),l=t.nodes.map(_D);return l[r]=a.start,l[o]=a.end,l.splice(r+1,0,a.node),{...t,nodes:l}})}var RB=new WeakMap;function LB(t){const e=RB.get(t);return e?function(t){return{shapeId:t.shapeId,nodes:t.nodes.map(t=>({...t})),primary:{...t.primary}}}(e):null}function $B(t){const e=RB.get(t);if(!e)return null;if(t.state.shapeEditingSession.get()?.shapeId!==e.shapeId)return null;const n=t.shapes.get(e.shapeId);if(!CD(n))return null;const r=e.nodes.flatMap(t=>{const e=uB(n.props.subpaths,t.subpathId)?.nodes.find(e=>e.id===t.nodeId);return e?[{ref:{...t},node:e}]:[]});if(0===r.length)return null;const o=r.some(({ref:t})=>HB(t,e.primary))?e.primary:r[r.length-1].ref;return{selection:{shapeId:n.id,nodes:r.map(({ref:t})=>({...t})),primary:{...o}},shape:n,entries:r}}function DB(t){const e=RB.get(t);RB.delete(t),t.state.shapeEditingSession.get()?.shapeId===e?.shapeId&&WB(t,null)}function BB(t,e,n,r){const o={subpathId:n,nodeId:r};zB(t,e,[o],o)}function zB(t,e,n,r=n.at(-1)??null){const o=function(t,e,n){const r=function(t){const e=new Set,n=[];for(const r of t){const t=JSON.stringify([r.subpathId,r.nodeId]);e.has(t)||(e.add(t),n.push({...r}))}return n}(e).filter(e=>null!==jB(t,e));if(0===r.length)return null;const o=(n&&r.find(t=>HB(t,n)))??r[r.length-1];return{shapeId:t.id,nodes:r,primary:{...o}}}(e,n,r);if(!o)return void DB(t);RB.set(t,o);const i=jB(e,o.primary);WB(t,i?t.shapes.computeLocalToPageTransform(e).applyToPoint(KD(i)):null)}function FB(t,e,n){return t.nodes.some(t=>t.subpathId===e&&t.nodeId===n)}function jB(t,e){return uB(t.props.subpaths,e.subpathId)?.nodes.find(t=>t.id===e.nodeId)??null}function WB(t,e){const n=t.state.shapeEditingSession.get();n&&t.session.update({shapeEditingSession:{...n,caretPagePoint:e?{x:e.x,y:e.y}:void 0}},"system")}function HB(t,e){return t.subpathId===e.subpathId&&t.nodeId===e.nodeId}var _B="land.path.draftSubpathId",UB="land.path.previewNodeId";function VB(t){const e=t.meta[_B],n=t.meta[UB];return{subpathId:"string"==typeof e?e:null,previewNodeId:"string"==typeof n?n:null}}function KB(t,e){const n=qB(t);return e.subpathId&&(n[_B]=e.subpathId),e.previewNodeId&&(n[UB]=e.previewNodeId),n}function qB(t){const e={...t};return delete e[_B],delete e[UB],e}var XB="var(--land-selection, #2563eb)",YB="rgba(255, 255, 255, 0.98)";function JB(){const n=t(),r=e(n.state.tool),o=e(n.inputs.state),i=e(n.state.selectedShapes),s=e(n.state.camera);if("path"!==r.activeToolId)return null;const a=1===i.length?i[0]:null,d=CD(a)?a:null,u=8/s.z,p=1.5/s.z,h=6/s.z,f=1/s.z,m=o.currentPagePoint;if(!d)return m?l(QB,{point:m,size:u,strokeWidth:p,variant:"candidate"}):null;const g=function(t,e){const n=VB(e);if(!n.subpathId)return null;const r=uB(sB(e,t.shapes.computeLocalToPageTransform(e)),n.subpathId);if(!r)return null;const o=n.previewNodeId?r.nodes.findIndex(t=>t.id===n.previewNodeId):-1,i=o>=0?r.nodes[o]??null:null,s=o>0?r.nodes[o-1]??null:null,a=s&&i?$D({id:`${r.id}:preview`,closed:!1,nodes:[s,i]}):null;return{closed:r.closed,committedNodes:r.nodes.filter(t=>t.id!==n.previewNodeId),previewNode:i,previewPath:a}}(n,d);if(!g)return m?l(QB,{point:m,size:u,strokeWidth:p,variant:"candidate"}):null;const y=g.previewNode?KD(g.previewNode):o.isPointing?null:m,x=y&&!g.committedNodes.some(t=>KD(t).dist2(y)<=.25/(s.z*s.z));
69
- return c("g",{"data-ui":"path-draft-overlay",pointerEvents:"none",children:[g.previewPath?l("path",{"data-ui":"path-draft-preview-segment",d:g.previewPath,fill:"none",stroke:XB,strokeWidth:Math.max(p,1/s.z),strokeDasharray:`${6/s.z} ${4/s.z}`,strokeLinecap:"round",strokeLinejoin:"round"}):null,x?l(QB,{point:y,size:u,strokeWidth:p,variant:"candidate"}):null,g.committedNodes.map((t,e)=>l(GB,{node:t,showIn:g.closed||e>0,size:h,strokeWidth:f},t.id)),g.committedNodes.map(t=>l(QB,{point:KD(t),size:u,strokeWidth:p,variant:"committed"},t.id))]})}function GB({node:t,showIn:e,size:n,strokeWidth:r}){const o=KD(t);
70
- return c(a,{children:[e&&t.in?l(ZB,{anchor:o,point:qD(t),size:n,strokeWidth:r,variant:"in"}):null,t.out?l(ZB,{anchor:o,point:XD(t),size:n,strokeWidth:r,variant:"out"}):null]})}function ZB({anchor:t,point:e,size:n,strokeWidth:r,variant:o}){const i=n/2;
71
- return c("g",{"data-ui":"path-draft-curve-handle","data-path-draft-curve-handle":o,children:[l("line",{"data-ui":"path-draft-control-line",x1:t.x,y1:t.y,x2:e.x,y2:e.y,stroke:"rgba(37, 99, 235, 0.44)",strokeWidth:r}),l("rect",{"data-ui":"path-draft-control-handle",x:e.x-i,y:e.y-i,width:n,height:n,fill:YB,stroke:XB,strokeWidth:r})]})}function QB({point:t,size:e,strokeWidth:n,variant:r}){const o=e/2;
72
- return l("rect",{"data-ui":"path-draft-control-point","data-path-draft-control-point":r,x:t.x-o,y:t.y-o,width:e,height:e,rx:2,ry:2,fill:"candidate"===r?"rgba(219, 234, 254, 0.98)":YB,stroke:XB,strokeWidth:n})}function tz({shape:t,shapeEditingSession:e=null,fill:n=t.props.fill,stroke:r=t.props.stroke,strokeWidth:o=t.props.strokeWidth}){const{renderBounds:i}=nB({props:{...t.props,strokeWidth:o}}),s=nz(t);if(!s)return null;const a=e?.shapeId===t.id;
73
- return c("svg",{width:"100%",height:"100%",viewBox:`${i.x} ${i.y} ${Math.max(i.w,1)} ${Math.max(i.h,1)}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[X(n)?null:l("path",{d:s,fill:K(n),fillRule:t.props.fillRule,clipRule:t.props.fillRule,stroke:"none"}),
74
- l("path",{d:s,fill:"none",stroke:K(r),strokeWidth:o,strokeLinecap:"round",strokeLinejoin:"round"}),a?l(rz,{shape:t}):null]})}function ez({shape:t,strokeWidth:e}){const{renderBounds:r}=nB(t),o=nz(t);return o?l("svg",{"data-ui":"path-hover-outline",width:"100%",height:"100%",viewBox:`${r.x} ${r.y} ${Math.max(r.w,1)} ${Math.max(r.h,1)}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:l("path",{d:o,fill:"none",stroke:n,strokeWidth:e,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:"non-scaling-stroke"})}):null}function nz(t){const e=function(t){return VB(t).previewNodeId}(t);return DD(function(t,e){return e?t.map(t=>({...t,nodes:t.nodes.filter(t=>t.id!==e).map(t=>({...t}))})).filter(t=>t.nodes.length>0):t.map(t=>({...t,nodes:t.nodes.map(t=>({...t}))}))}(t.props.subpaths,e))}function rz({shape:t}){
75
- return l(a,{children:t.props.subpaths.flatMap(t=>t.nodes.flatMap(e=>{const n=KD(e),r=[];if(e.in){const o=qD(e);r.push(l("line",{x1:n.x,y1:n.y,x2:o.x,y2:o.y,stroke:"rgba(37, 99, 235, 0.44)",strokeWidth:1,strokeDasharray:"4 3",vectorEffect:"non-scaling-stroke"},`${t.id}:${e.id}:in`))}if(e.out){const o=XD(e);r.push(l("line",{x1:n.x,y1:n.y,x2:o.x,y2:o.y,stroke:"rgba(37, 99, 235, 0.44)",strokeWidth:1,strokeDasharray:"4 3",vectorEffect:"non-scaling-stroke"},`${t.id}:${e.id}:out`))}return r}))})}function oz(){return{id:"land.path.react",canvasOverlays:[{id:"land.path.draft-overlay",component:JB,order:20},{id:"land.path.edit-insert-preview-overlay",component:OD,order:21}],shapeRenderers:[{type:"path",component:iz,hoverComponent:sz}],selectionCustomHandleRenderers:[{type:xD,component:az},{type:wD,component:lz}]}}function iz({shape:t,shapeEditingSession:e}){
76
- return l(tz,{shape:t,shapeEditingSession:e})}function sz({shape:t,strokeWidth:e}){
77
- return l(ez,{shape:t,strokeWidth:e})}function az({handle:t,strokeWidth:e}){const n=cz(t.type,t.id);
78
- return l("rect",{"data-selection-custom-handle":t.id,"data-selection-custom-handle-type":t.type,"data-selection-custom-handle-id":t.id,x:t.bounds.x,y:t.bounds.y,width:t.bounds.w,height:t.bounds.h,rx:2,ry:2,fill:n?"rgba(219, 234, 254, 0.98)":"rgba(255,255,255,0.98)",stroke:n?"rgba(29, 78, 216, 1)":"rgba(37, 99, 235, 0.94)",strokeWidth:n?1.5*e:e,style:{cursor:t.cursor??"grab",pointerEvents:"auto"}})}function lz({handle:t,strokeWidth:e}){const n=cz(t.type,t.id);
79
- return l("circle",{"data-selection-custom-handle":t.id,"data-selection-custom-handle-type":t.type,"data-selection-custom-handle-id":t.id,cx:t.point.x,cy:t.point.y,r:Math.max(t.bounds.w,t.bounds.h)/2,fill:n?"rgba(29, 78, 216, 1)":"rgba(37, 99, 235, 0.92)",stroke:"rgba(255,255,255,0.96)",strokeWidth:n?1.5*e:e,style:{cursor:t.cursor??"grab",pointerEvents:"auto"}})}function cz(n,r){const o=t();e(o.state.shapeEditingSession);const i=LB(o),s=kD(n,r);return!!i&&!!s&&FB(i,s.subpathId,s.nodeId)}var dz=class{editor;deactivateHistoryScope=null;session=null;subscribers=new Set;constructor(t){this.editor=t}start(t,e,n){const r=this.editor.shapes.get(e);if(!CD(r))return!1;if(this.session?.mode===t&&this.session.shapeId===e)return!0;this.clear();const o=[uz(this.editor,r,t)];this.session={mode:t,shapeId:e,snapshots:o,index:o.length-1,initialShapeSignature:pz(r),onApply:n?.onApply,onBoundaryUndo:n?.onBoundaryUndo};const i={getState:()=>this.getState(),subscribe:t=>this.subscribe(t),undo:()=>this.undo(),redo:()=>this.redo()};return this.deactivateHistoryScope=this.editor.history.activateScope(i),this.notify(),!0}record(t){const e=this.session,n=this.editor.shapes.get(t);if(!e||e.shapeId!==t||!CD(n))return!1;const r=uz(this.editor,n,e.mode);return e.snapshots[e.index]?.signature===r.signature?(e.snapshots[e.index]=r,!1):(e.snapshots=[...e.snapshots.slice(0,e.index+1),r],e.index=e.snapshots.length-1,this.notify(),!0)}replaceCurrent(t){const e=this.session,n=this.editor.shapes.get(t);if(!e||e.shapeId!==t||!CD(n))return!1;const r=uz(this.editor,n,e.mode),o=e.snapshots[e.index];return e.snapshots[e.index]=r,o?.signature!==r.signature&&(this.notify(),!0)}end(t,e){return this.session?.mode===t&&this.session.shapeId===e&&(this.clear(),!0)}hasNetChanges(t,e){const n=this.session,r=this.editor.shapes.get(e);return!(!n||n.mode!==t||n.shapeId!==e)&&(!CD(r)||n.initialShapeSignature!==pz(r))}undo(){const t=this.session;return!!t&&(t.index<=0?t.onBoundaryUndo?.()??!1:this.applySnapshot(t.index-1))}redo(){const t=this.session;return!(!t||t.index>=t.snapshots.length-1)&&this.applySnapshot(t.index+1)}applySnapshot(t){const e=this.session,n=e?.snapshots[t];if(!e||!n)return!1;const r=this.editor.shapes.get(e.shapeId);if(!CD(r))return this.clear(),!1;e.index=t;const o=LB(this.editor);this.editor.commands.updateShapes([{id:e.shapeId,..."create"===e.mode&&n.draftMeta?{meta:KB(r.meta,n.draftMeta)}:{},props:{subpaths:VD(n.subpaths)}}],{source:"user"});const i=this.editor.shapes.get(e.shapeId);CD(i)&&e.onApply?.(i);const s=n.selection??o;return s&&CD(i)&&this.editor.state.shapeEditingSession.get()?.shapeId===e.shapeId?zB(this.editor,i,s.nodes,s.primary):DB(this.editor),this.notify(),!0}getState(){const t=this.session?.index??0,e=(this.session?.snapshots.length??1)-1;return{canUndo:t+(this.session?.onBoundaryUndo?1:0)>0,canRedo:t<e}}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}clear(){(this.session||this.deactivateHistoryScope)&&(this.session=null,this.deactivateHistoryScope?.(),this.deactivateHistoryScope=null,this.notify())}notify(){for(const t of this.subscribers)t()}};function uz(t,e,n){const r=VD(e.props.subpaths),o="create"===n?VB(e):null;return{subpaths:r,draftMeta:o,selection:LB(t),signature:JSON.stringify({subpaths:r,draftMeta:o})}}function pz(t){return JSON.stringify(function(t){return{...t,meta:{...t.meta},props:{...t.props,fill:{...t.props.fill},stroke:{...t.props.stroke},subpaths:VD(t.props.subpaths)}}}(t))}var hz=new WeakMap;function fz(t){const e=hz.get(t);if(e)return e;const n=new dz(t);return hz.set(t,n),n}function mz(t,e,n,r){return fz(t).start(e,n,r)}function gz(t,e){return fz(t).record(e)}function yz(t,e,n){return fz(t).end(e,n)}var xz=new WeakMap;function wz(t){return xz.get(t)??!1}function bz(t){return function(t,e){const n=t.state.shapeEditingSession.get(),r=n?t.shapes.get(n.shapeId):null;return!(!n||!CD(r))&&(wz(t)===e||(xz.set(t,e),e||t.snaps.clearIndicators(),t.session.update({shapeEditingSession:{...n}},"system")),e)}(t,!wz(t))}function vz(t){xz.delete(t),t.snaps.clearIndicators()}function kz(t){let e=null;const n=Tt("path.editSnap.lifecycle",t.state.shapeEditingSession,()=>{const n=t.state.shapeEditingSession.get(),r=n?t.shapes.get(n.shapeId):null,o=CD(r)?r.id:null;if(o!==e){if(e){const n=function(t,e,n){return fz(t).hasNetChanges(e,n)}(t,"edit",e);yz(t,"edit",e),n||t.editing.cancelOperation()}e=o,DB(t),vz(t),o&&mz(t,"edit",o,{onBoundaryUndo:()=>{if(t.state.shapeEditingSession.get()?.shapeId!==o)return!1;const e=t.editing.complete("user");return e&&"select"!==t.state.tool.get().activeToolId&&t.commands.setActiveTool("select",{source:"system"}),e}})}});return()=>{n(),e&&yz(t,"edit",e),DB(t),vz(t)}}var Sz="path.edit",Pz=Math.PI/4,Mz={propagation:"stop"},Iz=1,Tz=new WeakMap,Cz=new WeakMap;function Ez(t){const e=t.state.shapeEditingSession.get();if(!e)return null;const n=t.shapes.get(e.shapeId);return CD(n)?n:null}function Az(t,e,n){return t.shapes.computeLocalToPageTransform(e).invert().applyToPoint(n)}function Oz(t){PD(t,null)}function Nz(t){Oz(t),DB(t)}function Rz(t){return t.shiftKey}function Lz(t){return JSON.stringify([t.subpathId,t.nodeId])}function $z(t,e){const n=Tz.get(t);if(!n)return;if(e.pointerId!==n.pointerId)return;const r=t.shapes.get(n.shapeId);if(!CD(r))return void Dz(t);if(!(n.isActive||(o=n.originScreenPoint,i=e.screenPoint,o.dist2(i)>=9)))return;var o,i;n.isActive=!0;const s=function(t,e){const n=Math.min(t.x,e.x),r=Math.min(t.y,e.y),o=Math.max(t.x,e.x),i=Math.max(t.y,e.y);return new N(n,r,o-n,i-r)}(n.originPagePoint,e.pagePoint),a=function(t,e,n){const r=t.shapes.computeLocalToPageTransform(e);return e.props.subpaths.flatMap(t=>t.nodes.flatMap(e=>{const o=r.applyToPoint(KD(e));return n.containsPoint(o)?[{subpathId:t.id,nodeId:e.id}]:[]}))}(t,r,s),l=Rz(e)?function(t,e){const n=new Map(t.map(t=>[Lz(t),{...t}]));for(const r of e){const t=Lz(r);n.has(t)?n.delete(t):n.set(t,{...r})}return Array.from(n.values())}(n.previousEntries,a):a;t.interaction.setBrushBox(s),zB(t,r,l,l.at(-1)??null)}function Dz(t){const e=Tz.get(t);if(!e)return;const n=t.shapes.get(e.shapeId);CD(n)&&t.state.shapeEditingSession.get()?.shapeId===e.shapeId?zB(t,n,e.previousEntries,e.previousPrimary):DB(t),Tz.delete(t),t.interaction.setBrushBox(null)}function Bz(t,e,n,r){const o=t.shapes.get(e);CD(o)&&zB(t,o,n,r)}function zz(t){return t.filter(t=>t.nodes.length>=2)}function Fz(t,e){t.editing.complete("user"),t.shapes.get(e.id)&&t.operations.run({kind:"path.shape-delete",label:"shape.delete",source:"user",history:"record"},()=>{t.commands.deleteShapes([e.id],{source:"user"})})}function jz(t,e,n){const r=zz(function(t,e){const n=wB(e);return 0===n.size?VD(t):t.map(t=>{const e=n.get(t.id);if(!e)return UD(t);const r=t.nodes.filter(t=>!e.has(t.id)).map(_D),o=t.closed&&r.length>=3;return t.closed&&!o&&IB(r),{...t,closed:o,nodes:r}}).filter(t=>t.nodes.length>0)}(e.props.subpaths,n));0!==r.length?(t.commands.updateShapes([{id:e.id,props:{subpaths:r}}],{source:"user"}),DB(t),gz(t,e.id)):Fz(t,e)}function Wz(t,e){const n=$B(t);if(!n||n.shape.isLocked)return!1;const{shape:r,selection:o}=n,i=xB(r.props.subpaths,o.nodes,e,o.primary);if(!i)return!1;const s=zz(i.subpaths);return 0===s.length?(Fz(t,r),!0):(t.operations.run({kind:"path.node-operation",label:"shape.edit",source:"user",history:"record"},()=>{t.commands.updateShapes([{id:r.id,props:{subpaths:s}}],{source:"user"}),Bz(t,r.id,i.selectedNodes,i.primaryNode)}),gz(t,r.id),!0)}function Hz(t,e){const n=$B(t);if(!n||n.shape.isLocked)return!1;const{shape:r,selection:o}=n,i=function(t,e,n){const r=t.shapes.computeLocalToPageTransform(e).invert(),o=r.applyToPoint(new O(0,0));return r.applyToPoint(n).sub(o)}(t,r,e),s=fB(r.props.subpaths,o.nodes,t=>Kz(t,i));return t.operations.run({kind:"path.node-nudge",label:"shape.edit",source:"user",history:"record"},()=>{t.commands.updateShapes([{id:r.id,props:{subpaths:s}}],{source:"user"}),Bz(t,r.id,o.nodes,o.primary)}),gz(t,r.id),!0}function _z(t,e,n){const r=Ez(t);if(r&&t.tools.isInInitialState()&&("Enter"===e.key||"Escape"===e.key)&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.accelKey)return t.editing.complete("user");if(!(r||"Enter"!==e.key||e.altKey||e.ctrlKey||e.metaKey||e.accelKey))return function(t){if(t.state.shapeEditingSession.get()||"select"!==t.state.tool.get().activeToolId||!t.tools.isInInitialState())return!1;const e=t.selection.getIds(),[n]=t.state.selectedShapes.get();return!(1!==e.length||!CD(n)||!t.editing.canEditShape(n)||(Nz(t),vz(t),!t.editing.start({shapeId:n.id,operationKind:Sz,entryMode:"focusEnd"},"user")))}(t);if(r&&e.accelKey&&"z"===e.key.toLowerCase()&&!e.altKey)return e.shiftKey?t.history.redo():t.history.undo();if(e.accelKey&&("'"===e.key||"Quote"===e.code)&&r&&!r.isLocked)return bz(t),t.inputs.state.get().isPointing&&t.tools.dispatch(e,n),!0;if(e.accelKey&&"j"===e.key.toLowerCase()&&!e.altKey&&r&&!r.isLocked)return Wz(t,"merge");const o=function(t){if(t.altKey||t.ctrlKey||t.metaKey||t.accelKey)return null;const e=t.shiftKey?10:1;switch(t.key){case"ArrowLeft":return new O(-e,0);case"ArrowRight":return new O(e,0);case"ArrowUp":return new O(0,-e);case"ArrowDown":return new O(0,e);default:return null}}(e);if(o)return Hz(t,o);if(e.altKey||e.ctrlKey||e.metaKey||e.accelKey)return!1;const i=$B(t);if(!i||i.shape.isLocked)return!1;const s=e.key.toLowerCase();return"backspace"===s||"delete"===s?(jz(t,i.shape,i.selection.nodes),!0):"c"===s?function(t,e,n){const r=n.filter(t=>{const n=pB(e.props.subpaths,t.subpathId,t.nodeId);return!!n&&!n.in&&!n.out});if(0===r.length)return!1;const o=r.reduce((t,e)=>mB(t,e.subpathId,e.nodeId),e.props.subpaths);return t.commands.updateShapes([{id:e.id,props:{subpaths:o}}],{source:"user"}),Bz(t,e.id,n,n.at(-1)??null),gz(t,e.id),!0}(t,i.shape,i.selection.nodes):"x"===s?(function(t,e,n){const r=n.reduce((t,e)=>gB(t,e.subpathId,e.nodeId),e.props.subpaths);t.commands.updateShapes([{id:e.id,props:{subpaths:r}}],{source:"user"}),Bz(t,e.id,n,n.at(-1)??null),gz(t,e.id)}(t,i.shape,i.selection.nodes),!0):"j"===s?Wz(t,"join"):"k"===s&&Wz(t,"separate")}function Uz(t,e,n){const r=n?t.len():e?.len()??t.len();if(0===r)return null;const o=t.normalize().mul(-r);return{dx:o.x,dy:o.y}}function Vz(t,e){const n=e.sub(t),r=n.len();if(0===r)return e.clone();const o=Math.round(Math.atan2(n.y,n.x)/Pz)*Pz;return t.add(new O(Math.cos(o)*r,Math.sin(o)*r))}function Kz(t,e){return{...t,x:t.x+e.x,y:t.y+e.y}}function qz(){return{createSession(t,{handle:e,shape:n,originPagePoint:r}){if(!CD(n)||"custom"!==e.kind)return null;const o=kD(e.type,e.id);if(!o)return null;if(t.state.shapeEditingSession.get()?.shapeId!==n.id)return null;const i=Cz.get(t),s="path.node"===o.type&&i?.shapeId===n.id&&i.nodeId===o.nodeId;s&&Cz.delete(t);const a=n,l=pB(a.props.subpaths,o.subpathId,o.nodeId),c=Az(t,a,r),d=$B(t),u=d?.selection.shapeId===n.id?d.selection.nodes.map(t=>({...t})):[],p=d?.selection.shapeId===n.id?{...d.selection.primary}:null,h={subpathId:o.subpathId,nodeId:o.nodeId},f=!!d&&d.selection.shapeId===n.id&&FB(d.selection,o.subpathId,o.nodeId),m="path.node"===o.type&&f,g="path.node"===o.type&&t.inputs.state.get().shiftKey,y=g&&!m?[...d?.selection.shapeId===n.id?d.selection.nodes:[],h]:null;y?zB(t,n,y,h):t.inputs.state.get().shiftKey||f||BB(t,n,o.subpathId,o.nodeId);const x="path.node"===o.type&&(y||m)?y??d.selection.nodes:[h],w=t.shapes.computeLocalToPageTransform(a),b=l?w.applyToPoint(KD(l)):r,v=e.point.sub(r),k="path.node"===o.type?x.flatMap(t=>{const e=pB(a.props.subpaths,t.subpathId,t.nodeId);return e?[w.applyToPoint(KD(e))]:[]}):[e.point],S=(k.length>0?k:[e.point]).map(t=>t.sub(r)),P=function(t,e,n){const r=new Set(n.map(Lz)),o=t.shapes.computeLocalToPageTransform(e);return{points:e.props.subpaths.flatMap(t=>t.nodes.flatMap(n=>{const i={subpathId:t.id,nodeId:n.id};return r.has(Lz(i))?[]:[{id:`${e.id}:${t.id}:${n.id}`,nodeId:e.id,point:o.applyToPoint(KD(n)),kind:"custom"}]})),outlines:[]}}(t,a,"path.node"===o.type?x:[]);return{shapeId:n.id,operationKind:"path.handle",onClick:g&&m?({editor:t})=>{const e=t.shapes.get(n.id);CD(e)&&function(t,e,n,r){const o=LB(t);if(!o||o.shapeId!==e.id)return void BB(t,e,n,r);const i={subpathId:n,nodeId:r},s=FB(o,n,r),a=s?o.nodes.filter(t=>!HB(t,i)):[...o.nodes,i];zB(t,e,a,s?a.at(-1)??null:i)}(t,e,o.subpathId,o.nodeId)}:void 0,onCancel({editor:t,reason:e}){if("pointer_cancel"!==e&&"escape"!==e)return;const r=t.shapes.get(n.id);CD(r)&&t.state.shapeEditingSession.get()?.shapeId===n.id&&(0!==u.length?zB(t,r,u,p):DB(t))},onComplete({editor:t}){s?function(t,e){fz(t).replaceCurrent(e)}(t,n.id):gz(t,n.id)},update({editor:t,pagePoint:e,accelKey:i,source:s}){if(!CD(t.shapes.get(n.id)))return"stop";const d=t.inputs.state.get(),u=d.shiftKey?"path.node"===o.type?Vz(r,e):Vz(b,e.add(v)).sub(v):e,p=wz(t)&&!i&&!d.shiftKey&&P.points.length>0,h=p?t.snaps.snapHandle({mode:"align",pagePoint:u,sourcePointOffsets:S,snapshot:P,threshold:10/t.state.camera.get().z}):null;p||t.snaps.clearIndicators();const f=h?.snappedPagePoint??u,m=Az(t,a,"path.node"===o.type?f:f.add(v)),g="path.node"===o.type?l?fB(a.props.subpaths,x,t=>Kz(t,m.sub(c))):VD(a.props.subpaths):hB(a.props.subpaths,o.subpathId,o.nodeId,t=>function(t,e,n,r){const o=KD(t),i=r.altKey?{...t,kind:"corner"}:{...t},s=n.sub(o);return"in"===e?(i.in={dx:s.x,dy:s.y},r.altKey||"corner"===t.kind||(i.out=Uz(s,t.out?XD(t).sub(o):null,"symmetric"===t.kind))):(i.out={dx:s.x,dy:s.y},r.altKey||"corner"===t.kind||(i.in=Uz(s,t.in?qD(t).sub(o):null,"symmetric"===t.kind))),i}(t,o.handle,m,{altKey:d.altKey}));if(t.commands.updateShapes([{id:n.id,props:{subpaths:g}}],{source:s}),"path.node"===o.type){const e=t.shapes.get(n.id);CD(e)&&zB(t,e,x,{subpathId:o.subpathId,nodeId:o.nodeId})}return"continue"}}}}}function Xz(){return{id:"land.path.interactions",editorEvent:{handleEvent(t,e,n){if("pointer"===e.type&&"pointer_move"===e.name&&Tz.get(t)?.pointerId===e.pointerId)return Oz(t),$z(t,e),Mz;if("pointer"===e.type&&"pointer_up"===e.name&&(Cz.delete(t),Oz(t),Tz.get(t)?.pointerId===e.pointerId))return function(t,e){const n=Tz.get(t);n&&(n.isActive?$z(t,e):Rz(e)||DB(t),Tz.delete(t),t.interaction.setBrushBox(null))}(t,e),Mz;if("pointer"===e.type&&"pointer_cancel"===e.name&&(Cz.delete(t),Oz(t),Tz.get(t)?.pointerId===e.pointerId))return Dz(t),Mz;if("double_click"===e.type&&!e.shiftKey&&!e.altKey&&!e.accelKey){Nz(t);const n=t.shapes.hitTest(e.pagePoint);if(CD(n))return vz(t),t.editing.start({shapeId:n.id,operationKind:Sz,entryMode:"focusEnd"},"user"),Mz}if("cancel"===e.type)return Cz.delete(t),Tz.has(t)?(Dz(t),Mz):"command"===e.reason?void Oz(t):"escape"===e.reason&&t.tools.isInInitialState()&&Ez(t)&&t.editing.complete("user")?Mz:void Nz(t);if("keyboard"===e.type&&"key_down"===e.name)return _z(t,e,n)?Mz:void 0;if("pointer"!==e.type||"pointer_move"!==e.name){if("pointer"===e.type&&"pointer_down"===e.name&&0===e.button&&e.altKey){Oz(t);const n=Ez(t);if(!n)return;const r=t.selection.hitTestHandle(e.pagePoint);if("custom"===r?.kind&&"path.node"===r.type){const e=kD(r.type,r.id);if("path.node"===e?.type){const r=$B(t);return jz(t,n,r?.selection.shapeId===n.id&&FB(r.selection,e.subpathId,e.nodeId)?r.selection.nodes:[{subpathId:e.subpathId,nodeId:e.nodeId}]),Mz}}}if("pointer"===e.type&&"pointer_down"===e.name&&0===e.button&&!e.altKey){Oz(t);const n=Ez(t);if(!n)return;const r=t.selection.hitTestHandle(e.pagePoint);if("custom"===r?.kind)return void(kD(r.type,r.id)||DB(t));const o=Az(t,n,e.pagePoint),i=dB(n.props.subpaths,o,7/t.state.camera.get().z);if(!i)return function(t,e,n){const r=$B(t);Tz.set(t,{shapeId:e.id,pointerId:n.pointerId,originPagePoint:n.pagePoint.clone(),originScreenPoint:n.screenPoint.clone(),previousEntries:r?.selection.shapeId===e.id?r.selection.nodes.map(t=>({...t})):[],previousPrimary:r?.selection.shapeId===e.id?{...r.selection.primary}:null,isActive:!1})}(t,n,e),Mz;const s=`insert-node:${Iz+=1}`;return t.operations.run({kind:"path.insert-node",label:"shape.edit",source:"user",history:"record"},()=>{const e=NB(n.props.subpaths,i,s);t.commands.updateShapes([{id:n.id,props:{subpaths:e}}],{source:"user"});const r=t.shapes.get(n.id);CD(r)&&BB(t,r,i.subpathId,s)}),gz(t,n.id),void Cz.set(t,{shapeId:n.id,nodeId:s})}}else"mouse"!==e.pointerType||0!==e.buttons||e.altKey?Oz(t):function(t,e){const n=Ez(t);if(!n||"select"!==t.state.tool.get().activeToolId||!t.tools.isInInitialState())return void Oz(t);if("custom"===t.selection.hitTestHandle(e.pagePoint)?.kind)return void Oz(t);const r=Az(t,n,e.pagePoint),o=dB(n.props.subpaths,r,7/t.state.camera.get().z);if(!o)return void Oz(t);const i=t.shapes.computeLocalToPageTransform(n);PD(t,{shapeId:n.id,subpathId:o.subpathId,startNodeId:o.startNodeId,endNodeId:o.endNodeId,t:o.t,pagePoint:i.applyToPoint(o.point)})}(t,e)}},selectionHandle:qz()}}function Yz(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function Jz(t){if(!t||"object"!=typeof t)return null;const e=t,n=Yz(e.dx,NaN),r=Yz(e.dy,NaN);return Number.isFinite(n)&&Number.isFinite(r)?e.dx===n&&e.dy===r?t:{dx:n,dy:r}:null}function Gz(t,e,n){if(!t||"object"!=typeof t)return null;const r=t,o=new Set,i=Array.isArray(r.nodes)?r.nodes.map((t,e)=>function(t,e,n){if(!t||"object"!=typeof t)return null;const r=t,o=Yz(r.x,NaN),i=Yz(r.y,NaN);return Number.isFinite(o)&&Number.isFinite(i)?{id:Qz("string"==typeof r.id&&r.id.length>0?r.id:`node:${e}`,n),x:o,y:i,kind:AD(r.kind)?r.kind:"corner",in:Jz(r.in),out:Jz(r.out)}:null}(t,e,o)).filter(t=>null!==t):[];return 0===i.length?null:{id:Qz("string"==typeof r.id&&r.id.length>0?r.id:`subpath:${e}`,n),closed:"boolean"==typeof r.closed&&r.closed,nodes:i}}function Zz(t,e){if(!Array.isArray(t))return e;const n=new Set,r=t.map((t,e)=>Gz(t,e,n)).filter(t=>null!==t);return r.length>0?r:e}function Qz(t,e){if(!e.has(t))return e.add(t),t;let n=2;for(;e.has(`${t}:${n}`);)n+=1;const r=`${t}:${n}`;return e.add(r),r}function tF(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist2(e);const i=t.sub(e),s=Math.max(0,Math.min(1,(i.x*r.x+i.y*r.y)/o));return t.dist2(e.add(r.mul(s)))}var eF=class extends St{type="path";getDefaultProps(){return{subpaths:[{id:"subpath:default",closed:!1,nodes:[{id:"node:0",x:0,y:0,kind:"corner"},{id:"node:1",x:96,y:0,kind:"corner"}]}],fill:H("transparent"),stroke:W("stroke-slate"),strokeWidth:3,fillRule:"nonzero"}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{subpaths:(r=Zz(e.subpaths,n.subpaths),r.map(t=>({...t,nodes:t.nodes.filter(t=>WD(t.x)&&WD(t.y))})).filter(t=>t.nodes.length>0).map(UD)),fill:V(e.fill,n.fill),stroke:V(e.stroke,n.stroke),strokeWidth:Math.max(1,Yz(e.strokeWidth,n.strokeWidth)),fillRule:ED(e.fillRule)?e.fillRule:n.fillRule};var r}getPositionedBounds(t){const e=nB(t).localBounds;return new N(t.x+e.x,t.y+e.y,e.w,e.h)}getLocalBounds(t){return nB(t).localBounds}getRenderBounds(t){return nB(t).renderBounds}getExportBounds(t){return this.getRenderBounds(t)}getSelectionResizeLocalBounds(t){return nB(t).pointBounds}resizeSelectionBounds(t,e){const n=sB(t,this.getLocalTransform(t)).map(t=>({...t,nodes:t.nodes.map(t=>rF(t,t=>function(t,e){return 0===e.selectionRotation?t:O.RotWith(t,e.selectionRotationCenter,-e.selectionRotation)}(t,e)))})),r=iB(function(t,e){const n=nB(t).pointBounds,r=0===n.w?1:e.w/Math.max(n.w,1e-6),o=0===n.h?1:e.h/Math.max(n.h,1e-6);return oB(t.props.subpaths,t=>new O(0===n.w?e.center.x:e.x+(t.x-n.x)*r,0===n.h?e.center.y:e.y+(t.y-n.y)*o))}({...t,x:0,y:0,rotation:0,scaleX:1,scaleY:1,props:{...t.props,subpaths:n}},e.selectionLocalBounds).map(t=>({...t,nodes:t.nodes.map(t=>rF(t,t=>function(t,e){return 0===e.selectionRotation?t:O.RotWith(t,e.selectionRotationCenter,e.selectionRotation)}(t,e)))})),t.props);return{id:t.id,x:r.x,y:r.y,rotation:0,scaleX:1,scaleY:1,props:{subpaths:r.subpaths}}}getPositionedOutlineVertices(t){return nB(t).outlineVertices.map(e=>new O(t.x+e.x,t.y+e.y))}getTerminalBindingOutlines(t){return nB(t).flattenedSubpaths.filter(t=>t.points.length>0).map(e=>({points:e.points.map(e=>new O(t.x+e.x,t.y+e.y)),closed:e.closed}))}resolveBindingPoint(t,e){const n=e.editor.shapes.computePositionedToPageTransform(t),r=n.tryInvert();if(!r)return e.rawPagePoint;const o=r.applyToPoint(e.rawPagePoint),i=r.applyToPoint(e.oppositePagePoint),s=i.sub(o);let a=Number.POSITIVE_INFINITY;for(const l of this.getTerminalBindingOutlines(t)){const t=l.closed?l.points.length:Math.max(0,l.points.length-1);for(let e=0;e<t;e+=1){const t=l.points[e],n=l.points[(e+1)%l.points.length];if(!t||!n)continue;const r=nF(o,i,t,n);null!==r&&r>1e-6&&r<a&&(a=r)}}return Number.isFinite(a)?n.applyToPoint(o.add(s.mul(a))):e.rawPagePoint}getHandleSnapGeometry(t){return{points:t.props.subpaths.flatMap(t=>t.nodes.flatMap(t=>[{point:KD(t),kind:"custom"},...t.in?[{point:qD(t),kind:"custom"}]:[],...t.out?[{point:XD(t),kind:"custom"}]:[]])),outline:nB(t).outlineVertices}}canReceiveTerminalBinding(t){return!0}canEdit(t){return!0}canUseSelectionResizeHandles(t,e){return e.editor.state.shapeEditingSession.get()?.shapeId!==t.id}canUseSelectionRotateHandle(t,e){return e.editor.state.shapeEditingSession.get()?.shapeId!==t.id}getSelectionHandleAnchors(t,e){const n={terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};if(!e.isOnlySelected)return n;const r=e.editor.state.shapeEditingSession.get();if(!r||r.shapeId!==t.id)return n;const o=e.editor.shapes.computeLocalToPageTransform(t);return{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:t.props.subpaths.flatMap(t=>t.nodes.flatMap(e=>{const n=[{kind:"custom",type:xD,id:bD(t.id,e.id),point:o.applyToPoint(KD(e)),cursor:"grab"}];return e.in&&n.push({kind:"custom",type:wD,id:vD(t.id,e.id,"in"),point:o.applyToPoint(qD(e)),cursor:"grab"}),e.out&&n.push({kind:"custom",type:wD,id:vD(t.id,e.id,"out"),point:o.applyToPoint(XD(e)),cursor:"grab"}),n}))}}getSelectionOverlayInfo(t,e){const n=e.editor.state.shapeEditingSession.get();return n&&n.shapeId===t.id?{usesSelectionPathOverlay:!0,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:aB(t,e.editor.shapes.computeLocalToPageTransform(t)),pathStyle:null,bindingSegments:[]}:{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,pathStyle:null,bindingSegments:[]}}hitTest(t,e,n){const r=new O(e.x-t.x,e.y-t.y),o=nB(t);return!X(t.props.fill)&&function(t,e,n){let r=0,o=0;for(const i of t)if(i.closed&&!(i.points.length<3))for(let t=0;t<i.points.length;t+=1){const n=i.points[t],s=i.points[(t+1)%i.points.length];n&&s&&(n.y<=e.y&&s.y>e.y||n.y>e.y&&s.y<=e.y)&&n.x+(e.y-n.y)/(s.y-n.y)*(s.x-n.x)>e.x&&(o+=1,r+=s.y>n.y?1:-1)}return"evenodd"===n?o%2==1:0!==r}(o.flattenedSubpaths,r,t.props.fillRule)||function(t,e,n){const r=n*n;for(const o of t)for(let t=1;t<o.points.length;t+=1){const n=o.points[t-1],i=o.points[t];if(n&&i&&cB(e,n,i)<=r)return!0}return!1}(o.flattenedSubpaths,r,t.props.strokeWidth/2+6)}hitTestLineSegment(t,e){const n=new O(e.positionedStart.x-t.x,e.positionedStart.y-t.y),r=new O(e.positionedEnd.x-t.x,e.positionedEnd.y-t.y),o=e.positionedMargin+t.props.strokeWidth/2;return nB(t).flattenedSubpaths.some(t=>function(t,e,n,r){const o=r*r;for(let i=1;i<n.length;i+=1){const r=n[i-1],s=n[i];if(r&&s&&(tF(r,t,e)<=o||tF(s,t,e)<=o||tF(t,r,s)<=o||tF(e,r,s)<=o))return!0}return!1}(n,r,t.points,o))}isWrappedByBrush(t,e){const n=e.pageOutlineVertices;return 0===n.length?!!e.pageBounds&&e.brushBounds.containsBox(e.pageBounds):n.every(t=>e.brushBounds.containsPoint(t))}canSelectByBrush(t,e){return e.isWrapping?this.isWrappedByBrush(t,e):e.pageBounds?.intersects(e.brushBounds)??!1}onEditEnd(t){if(t.props.subpaths.every(t=>t.nodes.length<2))return{deleteShapeIds:[t.id]}}};function nF(t,e,n,r){const o=e.sub(t),i=r.sub(n),s=o.x*i.y-o.y*i.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(t),l=(a.x*i.y-a.y*i.x)/s,c=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&c>=0&&c<=1?l:null}function rF(t,e){const n=e(KD(t)),r=t.in?e(qD(t)):null,o=t.out?e(XD(t)):null;return{..._D(t),x:n.x,y:n.y,in:r?{dx:r.x-n.x,dy:r.y-n.y}:null,out:o?{dx:o.x-n.x,dy:o.y-n.y}:null}}var oF=Math.PI/4,iF=1,sF=1;function aF(){return`node:${iF+=1}`}function lF(t,e,n){return t.shapes.computeLocalToPageTransform(e).invert().applyToPoint(n)}function cF(t,e,n,r){const o=(uB(e.props.subpaths,n)?.nodes.filter(t=>t.id!==r))?.at(-1);return o?t.shapes.computeLocalToPageTransform(e).applyToPoint(new O(o.x,o.y)):null}function dF(t,e){const n=e.sub(t),r=n.len();if(0===r)return e.clone();const o=Math.round(Math.atan2(n.y,n.x)/oF)*oF;return t.add(new O(Math.cos(o)*r,Math.sin(o)*r))}function uF(t,e,n,r,o){const i=function(t,e,n){const r=uB(e.props.subpaths,n)?.nodes[0];return r?t.shapes.computeLocalToPageTransform(e).applyToPoint(new O(r.x,r.y)):null}(t,e,n),s=uB(e.props.subpaths,n),a=s?.nodes.filter(t=>t.id!==r).length??0;return!(!i||!s||a<3)&&i.dist(o)<=10/t.state.camera.get().z}function pF(t,e){return e.previewNodeId?t.map(t=>t.id===e.subpathId?{...t,nodes:t.nodes.filter(t=>t.id!==e.previewNodeId)}:t):VD(t)}function hF(t,e){return uB(t.props.subpaths,e.subpathId)?.nodes.filter(t=>t.id!==e.previewNodeId).length??0}var fF=class extends Pt{draft=null;operation=null;constructor(t){super(t,"path"),this.initial="idle",this.addChild(new mF(t,this)),this.addChild(new gF(t,this))}onEnter(){this.editor.interaction.clearSelection()}onExit(){this.draft&&(this.canFinishDraft()?this.finishDraft({switchToSelect:!1}):this.cancelDraft())}isInInitialState(){return!this.hasDraft()&&super.isInInitialState()}startOrExtend(t,e,n){if(!this.draft){this.operation=this.editor.operations.begin({kind:"path.create",label:"shape.create",source:"user",history:"record"});const n=this.editor.shapes.getDefaultProps("path"),r=`subpath:${sF+=1}`,o=aF(),i={id:o,x:0,y:0,kind:"corner"},[s]=this.editor.commands.createShapes([{type:"path",x:t.x,y:t.y,meta:KB({},{subpathId:r,previewNodeId:null}),props:{...n,subpaths:[{id:r,closed:!1,nodes:[i]}]}}],{source:"user",autoReparent:!1});if(!CD(s))throw this.cancelOperation(),new Error("Failed to create path shape");return this.editor.commands.setSelectedShapeIds([s.id],{source:"system"}),this.draft={shapeId:s.id,subpathId:r,lastNodeId:o,createdShape:!0,previewNodeId:null},mz(this.editor,"create",s.id,{onBoundaryUndo:()=>this.draft?.shapeId===s.id&&(this.cancelDraft(),this.editor.commands.setActiveTool("select",{source:"system"}),!0),onApply:t=>{const e=this.draft;if(!e||e.shapeId!==t.id)return;const n=uB(t.props.subpaths,e.subpathId);this.draft={...e,lastNodeId:n?.nodes.at(-1)?.id??e.lastNodeId,previewNodeId:null}}}),{shapeId:s.id,subpathId:r,nodeId:o,originPagePoint:t.clone(),originScreenPoint:e.clone(),startNode:_D(i),finishOnPointerUp:!1}}const r=this.editor.shapes.get(this.draft.shapeId);if(!CD(r))return this.cancelDraft(),null;const o=n.shiftKey?cF(this.editor,r,this.draft.subpathId,this.draft.previewNodeId)??t:t,i=n.shiftKey?dF(o,t):t;if(uF(this.editor,r,this.draft.subpathId,this.draft.previewNodeId,t)){const n=this.draft,o=uB(r.props.subpaths,n.subpathId)?.nodes.find(t=>t.id!==n.previewNodeId);return o?(this.editor.commands.updateShapes([{id:r.id,meta:KB(r.meta,{subpathId:n.subpathId,previewNodeId:null}),props:{subpaths:pF(r.props.subpaths,n).map(t=>t.id===n.subpathId?{...t,closed:!0}:t)}}],{source:"user"}),this.draft={...n,previewNodeId:null},{shapeId:r.id,subpathId:n.subpathId,nodeId:o.id,originPagePoint:t.clone(),originScreenPoint:e.clone(),startNode:_D(o),finishOnPointerUp:!0}):null}const s=lF(this.editor,r,i),a=this.draft.previewNodeId??aF(),l=r.props.subpaths.map(t=>t.id===this.draft?.subpathId?this.draft.previewNodeId?{...t,nodes:t.nodes.map(t=>t.id===this.draft?.previewNodeId?{id:a,x:s.x,y:s.y,kind:"corner"}:t)}:{...t,nodes:[...t.nodes,{id:a,x:s.x,y:s.y,kind:"corner"}]}:t);return this.editor.commands.updateShapes([{id:r.id,meta:KB(r.meta,{subpathId:this.draft.subpathId,previewNodeId:null}),props:{subpaths:l}}],{source:"user"}),this.draft={...this.draft,lastNodeId:a,previewNodeId:null},{shapeId:r.id,subpathId:this.draft.subpathId,nodeId:a,originPagePoint:t.clone(),originScreenPoint:e.clone(),startNode:{id:a,x:s.x,y:s.y,kind:"corner"},finishOnPointerUp:!1}}updateNodeDrag(t,e,n,r){const o=this.editor.shapes.get(t.shapeId);if(!CD(o))return;const i=r.shiftKey?dF(t.originPagePoint,e):e,s=lF(this.editor,o,t.originPagePoint),a=lF(this.editor,o,i),l=t.originScreenPoint.dist(n)>=3,c=hB(o.props.subpaths,t.subpathId,t.nodeId,()=>l?function(t,e,n){return{...t,kind:n.altKey?"smooth":"symmetric",in:{dx:-e.x,dy:-e.y},out:{dx:e.x,dy:e.y}}}(t.startNode,a.sub(s),r):_D(t.startNode));this.editor.commands.updateShapes([{id:o.id,meta:KB(o.meta,{subpathId:t.subpathId,previewNodeId:this.draft?.previewNodeId??null}),props:{subpaths:c}}],{source:"user"})}updatePreview(t,e){if(!this.draft)return;const n=this.editor.shapes.get(this.draft.shapeId);if(!CD(n)||hF(n,this.draft)<1)return;const r=e.shiftKey?cF(this.editor,n,this.draft.subpathId,this.draft.previewNodeId):null,o=r?dF(r,t):t,i=lF(this.editor,n,o),s=this.draft.previewNodeId??aF(),a=n.props.subpaths.map(t=>t.id!==this.draft?.subpathId?t:this.draft.previewNodeId?{...t,nodes:t.nodes.map(t=>t.id===this.draft?.previewNodeId?{id:s,x:i.x,y:i.y,kind:"corner"}:t)}:{...t,nodes:[...t.nodes,{id:s,x:i.x,y:i.y,kind:"corner"}]});this.editor.commands.updateShapes([{id:n.id,meta:KB(n.meta,{subpathId:this.draft.subpathId,previewNodeId:s}),props:{subpaths:a}}],{source:"user"}),this.draft={...this.draft,previewNodeId:s}}canFinishDraft(){if(!this.draft)return!1;const t=this.editor.shapes.get(this.draft.shapeId);return!!CD(t)&&hF(t,this.draft)>=2}finishDraft(t={}){if(!this.draft)return;const e=t.switchToSelect??!0,n=this.editor.shapes.get(this.draft.shapeId);if(CD(n)){const t=pF(n.props.subpaths,this.draft),e=iB(sB({...n,props:{...n.props,subpaths:t}},this.editor.shapes.computeLocalToPageTransform(n)),n.props);this.editor.commands.updateShapes([{id:n.id,x:e.x,y:e.y,rotation:0,scaleX:1,scaleY:1,meta:qB(n.meta),props:{subpaths:e.subpaths}}],{source:"user"}),this.draft.createdShape&&nt(this.editor,n.id,{source:"user"})}yz(this.editor,"create",this.draft.shapeId),this.commitOperation(),this.draft=null,e&&!this.editor.state.tool.get().isToolLocked&&this.editor.commands.setActiveTool("select",{source:"system"})}finishDraftAndEdit(){const t=this.draft?.shapeId;if(t){if(!this.canFinishDraft())return this.cancelDraft(),void(this.editor.state.tool.get().isToolLocked||this.editor.commands.setActiveTool("select",{source:"system"}));this.finishDraft({switchToSelect:!1}),CD(this.editor.shapes.get(t))&&(this.editor.commands.setActiveTool("select",{source:"system"}),this.editor.editing.start({shapeId:t,operationKind:"path.edit",entryMode:"focusEnd"},"user"))}}cancelDraft(){this.draft&&(yz(this.editor,"create",this.draft.shapeId),this.cancelOperation(),this.draft=null)}hasDraft(){return null!==this.draft}commitOperation(){const t=this.operation;this.operation=null,t?.commit()}cancelOperation(){const t=this.operation;this.operation=null,t?.isActive&&t.cancel()}},mF=class extends Pt{tool;constructor(t,e){super(t,"idle",e),this.tool=e}onPointerDown(t){if(0!==t.button)return;const e=this.tool.startOrExtend(t.pagePoint,t.screenPoint,{altKey:t.altKey,shiftKey:t.shiftKey});e&&this.transition("dragging_node",e)}onPointerMove(t){this.tool.updatePreview(t.pagePoint,{shiftKey:t.shiftKey})}onKeyDown(t){("Enter"===t.key&&this.tool.hasDraft()||"Escape"===t.key&&this.tool.hasDraft())&&this.tool.finishDraftAndEdit()}onCancel(t){"escape"===t.reason&&this.tool.hasDraft()&&this.tool.finishDraftAndEdit()}},gF=class extends Pt{tool;info=null;constructor(t,e){super(t,"dragging_node",e),this.tool=e}onEnter(t){this.info=t}onPointerMove(t){this.info&&this.tool.updateNodeDrag(this.info,t.pagePoint,t.screenPoint,{altKey:t.altKey,shiftKey:t.shiftKey})}onPointerUp(t){const e=this.info;e&&(this.tool.updateNodeDrag(e,t.pagePoint,t.screenPoint,{altKey:t.altKey,shiftKey:t.shiftKey}),gz(this.editor,e.shapeId)),this.transition("idle"),e?.finishOnPointerUp&&this.tool.finishDraft()}onCancel(){this.tool.cancelDraft(),this.transition("idle")}onExit(){this.info=null}},yF=class{type="path";toSvg(t,e){const n=nB(t);return n.path?{tag:"path",attrs:{d:n.path,fill:X(t.props.fill)?"none":e.resolveColor(t.props.fill),"fill-rule":t.props.fillRule,"clip-rule":t.props.fillRule,stroke:e.resolveColor(t.props.stroke),"stroke-width":t.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round"}}:null}};function xF(){return{id:"land.path",shapeUtils:[new eF],shapeSvgExporters:[new yF],interactionHandlers:[Xz()],setup(t){const e=kz(t);return t.tools.register("path",t=>new fF(t)),e}}}var wF=T((t,e)=>{var n,r;n=t,r=function(){function t(t,e){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!((o=(o=s.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=e.call(t,s)}catch(a){i=[6,a],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}var e=function(t,e){this.next=null,this.key=t,this.data=e,this.left=null,this.right=null};function n(t,e){return t>e?1:t<e?-1:0}function r(t,n,r){for(var o=new e(null,null),i=o,s=o;;){var a=r(t,n.key);if(a<0){if(null===n.left)break;if(r(t,n.left.key)<0){var l=n.left;if(n.left=l.right,l.right=n,null===(n=l).left)break}s.left=n,s=n,n=n.left}else{if(!(a>0))break;if(null===n.right)break;if(r(t,n.right.key)>0&&(l=n.right,n.right=l.left,l.left=n,null===(n=l).right))break;i.right=n,i=n,n=n.right}}return i.right=n.left,s.left=n.right,n.left=o.right,n.right=o.left,n}function o(t,n,o,i){var s=new e(t,n);if(null===o)return s.left=s.right=null,s;var a=i(t,(o=r(t,o,i)).key);return a<0?(s.left=o.left,s.right=o,o.left=null):a>=0&&(s.right=o.right,s.left=o,o.right=null),s}function i(t,e,n){var o=null,i=null;if(e){var s=n((e=r(t,e,n)).key,t);0===s?(o=e.left,i=e.right):s<0?(i=e.right,e.right=null,o=e):(o=e.left,e.left=null,i=e)}return{left:o,right:i}}function s(t,e,n,r,o){if(t){r(e+(n?"└── ":"├── ")+o(t)+"\n");var i=e+(n?" ":"│ ");t.left&&s(t.left,i,!1,r,o),t.right&&s(t.right,i,!0,r,o)}}var a=function(){function a(t){void 0===t&&(t=n),this._root=null,this._size=0,this._comparator=t}return a.prototype.insert=function(t,e){return this._size++,this._root=o(t,e,this._root,this._comparator)},a.prototype.add=function(t,n){var o=new e(t,n);null===this._root&&(o.left=o.right=null,this._size++,this._root=o);var i=this._comparator,s=r(t,this._root,i),a=i(t,s.key);return 0===a?this._root=s:(a<0?(o.left=s.left,o.right=s,s.left=null):a>0&&(o.right=s.right,o.left=s,s.right=null),this._size++,this._root=o),this._root},a.prototype.remove=function(t){this._root=this._remove(t,this._root,this._comparator)},a.prototype._remove=function(t,e,n){var o;return null===e?null:0===n(t,(e=r(t,e,n)).key)?(null===e.left?o=e.right:(o=r(t,e.left,n)).right=e.right,this._size--,o):e},a.prototype.pop=function(){var t=this._root;if(t){for(;t.left;)t=t.left;return this._root=r(t.key,this._root,this._comparator),this._root=this._remove(t.key,this._root,this._comparator),{key:t.key,data:t.data}}return null},a.prototype.findStatic=function(t){for(var e=this._root,n=this._comparator;e;){var r=n(t,e.key);if(0===r)return e;e=r<0?e.left:e.right}return null},a.prototype.find=function(t){return this._root&&(this._root=r(t,this._root,this._comparator),0!==this._comparator(t,this._root.key))?null:this._root},a.prototype.contains=function(t){for(var e=this._root,n=this._comparator;e;){var r=n(t,e.key);if(0===r)return!0;e=r<0?e.left:e.right}return!1},a.prototype.forEach=function(t,e){for(var n=this._root,r=[],o=!1;!o;)null!==n?(r.push(n),n=n.left):0!==r.length?(n=r.pop(),t.call(e,n),n=n.right):o=!0;return this},a.prototype.range=function(t,e,n,r){for(var o=[],i=this._comparator,s=this._root;0!==o.length||s;)if(s)o.push(s),s=s.left;else{if(i((s=o.pop()).key,e)>0)break;if(i(s.key,t)>=0&&n.call(r,s))return this;s=s.right}return this},a.prototype.keys=function(){var t=[];return this.forEach(function(e){var n=e.key;return t.push(n)}),t},a.prototype.values=function(){var t=[];return this.forEach(function(e){var n=e.data;return t.push(n)}),t},a.prototype.min=function(){return this._root?this.minNode(this._root).key:null},a.prototype.max=function(){return this._root?this.maxNode(this._root).key:null},a.prototype.minNode=function(t){if(void 0===t&&(t=this._root),t)for(;t.left;)t=t.left;return t},a.prototype.maxNode=function(t){if(void 0===t&&(t=this._root),t)for(;t.right;)t=t.right;return t},a.prototype.at=function(t){for(var e=this._root,n=!1,r=0,o=[];!n;)if(e)o.push(e),e=e.left;else if(o.length>0){if(e=o.pop(),r===t)return e;r++,e=e.right}else n=!0;return null},a.prototype.next=function(t){var e=this._root,n=null;if(t.right){for(n=t.right;n.left;)n=n.left;return n}for(var r=this._comparator;e;){var o=r(t.key,e.key);if(0===o)break;o<0?(n=e,e=e.left):e=e.right}return n},a.prototype.prev=function(t){var e=this._root,n=null;if(null!==t.left){for(n=t.left;n.right;)n=n.right;return n}for(var r=this._comparator;e;){var o=r(t.key,e.key);if(0===o)break;o<0?e=e.left:(n=e,e=e.right)}return n},a.prototype.clear=function(){return this._root=null,this._size=0,this},a.prototype.toList=function(){return function(t){for(var n=t,r=[],o=!1,i=new e(null,null),s=i;!o;)n?(r.push(n),n=n.left):r.length>0?n=(n=s=s.next=r.pop()).right:o=!0;return s.next=null,i.next}(this._root)},a.prototype.load=function(t,n,r){void 0===n&&(n=[]),void 0===r&&(r=!1);var o=t.length,i=this._comparator;if(r&&d(t,n,0,o-1,i),null===this._root)this._root=l(t,n,0,o),this._size=o;else{var s=function(t,n,r){for(var o=new e(null,null),i=o,s=t,a=n;null!==s&&null!==a;)r(s.key,a.key)<0?(i.next=s,s=s.next):(i.next=a,a=a.next),i=i.next;return null!==s?i.next=s:null!==a&&(i.next=a),o.next}(this.toList(),function(t,n){for(var r=new e(null,null),o=r,i=0;i<t.length;i++)o=o.next=new e(t[i],n[i]);return o.next=null,r.next}(t,n),i);o=this._size+o,this._root=c({head:s},0,o)}return this},a.prototype.isEmpty=function(){return null===this._root},Object.defineProperty(a.prototype,"size",{get:function(){return this._size},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"root",{get:function(){return this._root},enumerable:!0,configurable:!0}),a.prototype.toString=function(t){void 0===t&&(t=function(t){return String(t.key)});var e=[];return s(this._root,"",!0,function(t){return e.push(t)},t),e.join("")},a.prototype.update=function(t,e,n){var s=this._comparator,a=i(t,this._root,s),l=a.left,c=a.right;s(t,e)<0?c=o(e,n,c,s):l=o(e,n,l,s),this._root=function(t,e,n){return null===e?t:(null===t||((e=r(t.key,e,n)).left=t),e)}(l,c,s)},a.prototype.split=function(t){return i(t,this._root,this._comparator)},a.prototype[Symbol.iterator]=function(){var e,n,r;return t(this,function(t){switch(t.label){case 0:e=this._root,n=[],r=!1,t.label=1;case 1:return r?[3,6]:null===e?[3,2]:(n.push(e),e=e.left,[3,5]);case 2:return 0===n.length?[3,4]:[4,e=n.pop()];case 3:return t.sent(),e=e.right,[3,5];case 4:r=!0,t.label=5;case 5:return[3,1];case 6:return[2]}})},a}();function l(t,n,r,o){var i=o-r;if(i>0){var s=r+Math.floor(i/2),a=t[s],c=n[s],d=new e(a,c);return d.left=l(t,n,r,s),d.right=l(t,n,s+1,o),d}return null}function c(t,e,n){var r=n-e;if(r>0){var o=e+Math.floor(r/2),i=c(t,e,o),s=t.head;return s.left=i,t.head=t.head.next,s.right=c(t,o+1,n),s}return null}function d(t,e,n,r,o){if(!(n>=r)){for(var i=t[n+r>>1],s=n-1,a=r+1;;){do{s++}while(o(t[s],i)<0);do{a--}while(o(t[a],i)>0);if(s>=a)break;var l=t[s];t[s]=t[a],t[a]=l,l=e[s],e[s]=e[a],e[a]=l}d(t,e,n,a,o),d(t,e,a+1,r,o)}}const u=(t,e)=>t.ll.x<=e.x&&e.x<=t.ur.x&&t.ll.y<=e.y&&e.y<=t.ur.y,p=(t,e)=>{if(e.ur.x<t.ll.x||t.ur.x<e.ll.x||e.ur.y<t.ll.y||t.ur.y<e.ll.y)return null;const n=t.ll.x<e.ll.x?e.ll.x:t.ll.x,r=t.ur.x<e.ur.x?t.ur.x:e.ur.x;return{ll:{x:n,y:t.ll.y<e.ll.y?e.ll.y:t.ll.y},ur:{x:r,y:t.ur.y<e.ur.y?t.ur.y:e.ur.y}}};let h=Number.EPSILON;void 0===h&&(h=Math.pow(2,-52));const f=h*h,m=(t,e)=>{if(-h<t&&t<h&&-h<e&&e<h)return 0;const n=t-e;return n*n<f*t*e?0:t<e?-1:1};class g{constructor(){this.tree=new a,this.round(0)}round(t){const e=this.tree.add(t),n=this.tree.prev(e);if(null!==n&&0===m(e.key,n.key))return this.tree.remove(t),n.key;const r=this.tree.next(e);return null!==r&&0===m(e.key,r.key)?(this.tree.remove(t),r.key):t}}const y=new class{constructor(){this.reset()}reset(){this.xRounder=new g,this.yRounder=new g}round(t,e){return{x:this.xRounder.round(t),y:this.yRounder.round(e)}}},x=134217729;function w(t,e,n,r,o){let i,s,a,l,c=e[0],d=r[0],u=0,p=0;d>c==d>-c?(i=c,c=e[++u]):(i=d,d=r[++p]);let h=0;if(u<t&&p<n)for(d>c==d>-c?(s=c+i,a=i-(s-c),c=e[++u]):(s=d+i,a=i-(s-d),d=r[++p]),i=s,0!==a&&(o[h++]=a);u<t&&p<n;)d>c==d>-c?(s=i+c,l=s-i,a=i-(s-l)+(c-l),c=e[++u]):(s=i+d,l=s-i,a=i-(s-l)+(d-l),d=r[++p]),i=s,0!==a&&(o[h++]=a);for(;u<t;)s=i+c,l=s-i,a=i-(s-l)+(c-l),c=e[++u],i=s,0!==a&&(o[h++]=a);for(;p<n;)s=i+d,l=s-i,a=i-(s-l)+(d-l),d=r[++p],i=s,0!==a&&(o[h++]=a);return 0===i&&0!==h||(o[h++]=i),h}function b(t){return new Float64Array(t)}const v=b(4),k=b(8),S=b(12),P=b(16),M=b(4);function I(t,e,n,r,o,i){const s=(e-i)*(n-o),a=(t-o)*(r-i),l=s-a,c=Math.abs(s+a);return Math.abs(l)>=33306690738754716e-32*c?l:-function(t,e,n,r,o,i,s){let a,l,c,d,u,p,h,f,m,g,y,b,I,T,C,E,A,O;const N=t-o,R=n-o,L=e-i,$=r-i;T=N*$,p=x*N,h=p-(p-N),f=N-h,p=x*$,m=p-(p-$),g=$-m,C=f*g-(T-h*m-f*m-h*g),E=L*R,p=x*L,h=p-(p-L),f=L-h,p=x*R,m=p-(p-R),g=R-m,A=f*g-(E-h*m-f*m-h*g),y=C-A,u=C-y,v[0]=C-(y+u)+(u-A),b=T+y,u=b-T,I=T-(b-u)+(y-u),y=I-E,u=I-y,v[1]=I-(y+u)+(u-E),O=b+y,u=O-b,v[2]=b-(O-u)+(y-u),v[3]=O;let D=function(t,e){let n=e[0];for(let r=1;r<t;r++)n+=e[r];return n}(4,v),B=22204460492503146e-32*s;if(D>=B||-D>=B)return D;if(u=t-N,a=t-(N+u)+(u-o),u=n-R,c=n-(R+u)+(u-o),u=e-L,l=e-(L+u)+(u-i),u=r-$,d=r-($+u)+(u-i),0===a&&0===l&&0===c&&0===d)return D;if(B=11093356479670487e-47*s+33306690738754706e-32*Math.abs(D),D+=N*d+$*a-(L*c+R*l),D>=B||-D>=B)return D;T=a*$,p=x*a,h=p-(p-a),f=a-h,p=x*$,m=p-(p-$),g=$-m,C=f*g-(T-h*m-f*m-h*g),E=l*R,p=x*l,h=p-(p-l),f=l-h,p=x*R,m=p-(p-R),g=R-m,A=f*g-(E-h*m-f*m-h*g),y=C-A,u=C-y,M[0]=C-(y+u)+(u-A),b=T+y,u=b-T,I=T-(b-u)+(y-u),y=I-E,u=I-y,M[1]=I-(y+u)+(u-E),O=b+y,u=O-b,M[2]=b-(O-u)+(y-u),M[3]=O;const z=w(4,v,4,M,k);T=N*d,p=x*N,h=p-(p-N),f=N-h,p=x*d,m=p-(p-d),g=d-m,C=f*g-(T-h*m-f*m-h*g),E=L*c,p=x*L,h=p-(p-L),f=L-h,p=x*c,m=p-(p-c),g=c-m,A=f*g-(E-h*m-f*m-h*g),y=C-A,u=C-y,M[0]=C-(y+u)+(u-A),b=T+y,u=b-T,I=T-(b-u)+(y-u),y=I-E,u=I-y,M[1]=I-(y+u)+(u-E),O=b+y,u=O-b,M[2]=b-(O-u)+(y-u),M[3]=O;const F=w(z,k,4,M,S);return T=a*d,p=x*a,h=p-(p-a),f=a-h,p=x*d,m=p-(p-d),g=d-m,C=f*g-(T-h*m-f*m-h*g),E=l*c,p=x*l,h=p-(p-l),f=l-h,p=x*c,m=p-(p-c),g=c-m,A=f*g-(E-h*m-f*m-h*g),y=C-A,u=C-y,M[0]=C-(y+u)+(u-A),b=T+y,u=b-T,I=T-(b-u)+(y-u),y=I-E,u=I-y,M[1]=I-(y+u)+(u-E),O=b+y,u=O-b,M[2]=b-(O-u)+(y-u),M[3]=O,P[w(F,S,4,M,P)-1]}(t,e,n,r,o,i,c)}const T=(t,e)=>t.x*e.y-t.y*e.x,C=(t,e)=>t.x*e.x+t.y*e.y,E=(t,e,n)=>{const r=I(t.x,t.y,e.x,e.y,n.x,n.y);return r>0?-1:r<0?1:0},A=t=>Math.sqrt(C(t,t)),O=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},o={x:n.x-t.x,y:n.y-t.y};return T(o,r)/A(o)/A(r)},N=(t,e,n)=>{const r={x:e.x-t.x,y:e.y-t.y},o={x:n.x-t.x,y:n.y-t.y};return C(o,r)/A(o)/A(r)},R=(t,e,n)=>0===e.y?null:{x:t.x+e.x/e.y*(n-t.y),y:n},L=(t,e,n)=>0===e.x?null:{x:n,y:t.y+e.y/e.x*(n-t.x)};class ${static compare(t,e){const n=$.comparePoints(t.point,e.point);return 0!==n?n:(t.point!==e.point&&t.link(e),t.isLeft!==e.isLeft?t.isLeft?1:-1:B.compare(t.segment,e.segment))}static comparePoints(t,e){return t.x<e.x?-1:t.x>e.x?1:t.y<e.y?-1:t.y>e.y?1:0}constructor(t,e){void 0===t.events?t.events=[this]:t.events.push(this),this.point=t,this.isLeft=e}link(t){if(t.point===this.point)throw new Error("Tried to link already linked events");const e=t.point.events;for(let n=0,r=e.length;n<r;n++){const t=e[n];this.point.events.push(t),t.point=this.point}this.checkForConsuming()}checkForConsuming(){const t=this.point.events.length;for(let e=0;e<t;e++){const n=this.point.events[e];if(void 0===n.segment.consumedBy)for(let r=e+1;r<t;r++){const t=this.point.events[r];void 0===t.consumedBy&&n.otherSE.point.events===t.otherSE.point.events&&n.segment.consume(t.segment)}}}getAvailableLinkedEvents(){const t=[];for(let e=0,n=this.point.events.length;e<n;e++){const n=this.point.events[e];n!==this&&!n.segment.ringOut&&n.segment.isInResult()&&t.push(n)}return t}getLeftmostComparator(t){const e=new Map,n=n=>{const r=n.otherSE;e.set(n,{sine:O(this.point,t.point,r.point),cosine:N(this.point,t.point,r.point)})};return(t,r)=>{e.has(t)||n(t),e.has(r)||n(r);const{sine:o,cosine:i}=e.get(t),{sine:s,cosine:a}=e.get(r);return o>=0&&s>=0?i<a?1:i>a?-1:0:o<0&&s<0?i<a?-1:i>a?1:0:s<o?-1:s>o?1:0}}}let D=0;class B{static compare(t,e){const n=t.leftSE.point.x,r=e.leftSE.point.x,o=t.rightSE.point.x,i=e.rightSE.point.x;if(i<n)return 1;if(o<r)return-1;const s=t.leftSE.point.y,a=e.leftSE.point.y,l=t.rightSE.point.y,c=e.rightSE.point.y;if(n<r){if(a<s&&a<l)return 1;if(a>s&&a>l)return-1;const n=t.comparePoint(e.leftSE.point);if(n<0)return 1;if(n>0)return-1;const r=e.comparePoint(t.rightSE.point);return 0!==r?r:-1}if(n>r){if(s<a&&s<c)return-1;if(s>a&&s>c)return 1;const n=e.comparePoint(t.leftSE.point);if(0!==n)return n;const r=t.comparePoint(e.rightSE.point);return r<0?1:r>0?-1:1}if(s<a)return-1;if(s>a)return 1;if(o<i){const n=e.comparePoint(t.rightSE.point);if(0!==n)return n}if(o>i){const n=t.comparePoint(e.rightSE.point);if(n<0)return 1;if(n>0)return-1}if(o!==i){const t=l-s,e=o-n,d=c-a,u=i-r;if(t>e&&d<u)return 1;if(t<e&&d>u)return-1}return o>i?1:o<i||l<c?-1:l>c?1:t.id<e.id?-1:t.id>e.id?1:0}constructor(t,e,n,r){this.id=++D,this.leftSE=t,t.segment=this,t.otherSE=e,this.rightSE=e,e.segment=this,e.otherSE=t,this.rings=n,this.windings=r}static fromRing(t,e,n){let r,o,i;const s=$.comparePoints(t,e);if(s<0)r=t,o=e,i=1;else{if(!(s>0))throw new Error(`Tried to create degenerate segment at [${t.x}, ${t.y}]`);r=e,o=t,i=-1}return new B(new $(r,!0),new $(o,!1),[n],[i])}replaceRightSE(t){this.rightSE=t,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const t=this.leftSE.point.y,e=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:t<e?t:e},ur:{x:this.rightSE.point.x,y:t>e?t:e}}}vector(){return{x:this.rightSE.point.x-this.leftSE.point.x,y:this.rightSE.point.y-this.leftSE.point.y}}isAnEndpoint(t){return t.x===this.leftSE.point.x&&t.y===this.leftSE.point.y||t.x===this.rightSE.point.x&&t.y===this.rightSE.point.y}comparePoint(t){if(this.isAnEndpoint(t))return 0;const e=this.leftSE.point,n=this.rightSE.point,r=this.vector();if(e.x===n.x)return t.x===e.x?0:t.x<e.x?1:-1;const o=(t.y-e.y)/r.y,i=e.x+o*r.x;if(t.x===i)return 0;const s=(t.x-e.x)/r.x,a=e.y+s*r.y;return t.y===a?0:t.y<a?-1:1}getIntersection(t){const e=this.bbox(),n=t.bbox(),r=p(e,n);if(null===r)return null;const o=this.leftSE.point,i=this.rightSE.point,s=t.leftSE.point,a=t.rightSE.point,l=u(e,s)&&0===this.comparePoint(s),c=u(n,o)&&0===t.comparePoint(o),d=u(e,a)&&0===this.comparePoint(a),h=u(n,i)&&0===t.comparePoint(i);if(c&&l)return h&&!d?i:!h&&d?a:null;if(c)return d&&o.x===a.x&&o.y===a.y?null:o;if(l)return h&&i.x===s.x&&i.y===s.y?null:s;if(h&&d)return null;if(h)return i;if(d)return a;const f=((t,e,n,r)=>{if(0===e.x)return L(n,r,t.x);if(0===r.x)return L(t,e,n.x);if(0===e.y)return R(n,r,t.y);if(0===r.y)return R(t,e,n.y);const o=T(e,r);if(0==o)return null;const i={x:n.x-t.x,y:n.y-t.y},s=T(i,e)/o,a=T(i,r)/o;return{x:(t.x+a*e.x+(n.x+s*r.x))/2,y:(t.y+a*e.y+(n.y+s*r.y))/2}})(o,this.vector(),s,t.vector());return null===f?null:u(r,f)?y.round(f.x,f.y):null}split(t){const e=[],n=void 0!==t.events,r=new $(t,!0),o=new $(t,!1),i=this.rightSE;this.replaceRightSE(o),e.push(o),e.push(r);const s=new B(r,i,this.rings.slice(),this.windings.slice());return $.comparePoints(s.leftSE.point,s.rightSE.point)>0&&s.swapEvents(),$.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(r.checkForConsuming(),o.checkForConsuming()),e}swapEvents(){const t=this.rightSE;this.rightSE=this.leftSE,this.leftSE=t,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let e=0,n=this.windings.length;e<n;e++)this.windings[e]*=-1}consume(t){let e=this,n=t;for(;e.consumedBy;)e=e.consumedBy;for(;n.consumedBy;)n=n.consumedBy;const r=B.compare(e,n);if(0!==r){if(r>0){const t=e;e=n,n=t}if(e.prev===n){const t=e;e=n,n=t}for(let t=0,r=n.rings.length;t<r;t++){const r=n.rings[t],o=n.windings[t],i=e.rings.indexOf(r);-1===i?(e.rings.push(r),e.windings.push(o)):e.windings[i]+=o}n.rings=null,n.windings=null,n.consumedBy=e,n.leftSE.consumedBy=e.leftSE,n.rightSE.consumedBy=e.rightSE}}prevInResult(){return void 0!==this._prevInResult||(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null),this._prevInResult}beforeState(){if(void 0!==this._beforeState)return this._beforeState;if(this.prev){const t=this.prev.consumedBy||this.prev;this._beforeState=t.afterState()}else this._beforeState={rings:[],windings:[],multiPolys:[]};return this._beforeState}afterState(){if(void 0!==this._afterState)return this._afterState;const t=this.beforeState();this._afterState={rings:t.rings.slice(0),windings:t.windings.slice(0),multiPolys:[]};const e=this._afterState.rings,n=this._afterState.windings,r=this._afterState.multiPolys;for(let s=0,a=this.rings.length;s<a;s++){const t=this.rings[s],r=this.windings[s],o=e.indexOf(t);-1===o?(e.push(t),n.push(r)):n[o]+=r}const o=[],i=[];for(let s=0,a=e.length;s<a;s++){if(0===n[s])continue;const t=e[s],r=t.poly;if(-1===i.indexOf(r))if(t.isExterior)o.push(r);else{-1===i.indexOf(r)&&i.push(r);const e=o.indexOf(t.poly);-1!==e&&o.splice(e,1)}}for(let s=0,a=o.length;s<a;s++){const t=o[s].multiPoly;-1===r.indexOf(t)&&r.push(t)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(void 0!==this._isInResult)return this._isInResult;const t=this.beforeState().multiPolys,e=this.afterState().multiPolys;switch(q.type){case"union":{const n=0===t.length,r=0===e.length;this._isInResult=n!==r;break}case"intersection":{let n,r;t.length<e.length?(n=t.length,r=e.length):(n=e.length,r=t.length),this._isInResult=r===q.numMultiPolys&&n<r;break}case"xor":{const n=Math.abs(t.length-e.length);this._isInResult=n%2==1;break}case"difference":{const n=t=>1===t.length&&t[0].isSubject;this._isInResult=n(t)!==n(e);break}default:throw new Error(`Unrecognized operation type found ${q.type}`)}return this._isInResult}}class z{constructor(t,e,n){if(!Array.isArray(t)||0===t.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=e,this.isExterior=n,this.segments=[],"number"!=typeof t[0][0]||"number"!=typeof t[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const r=y.round(t[0][0],t[0][1]);this.bbox={ll:{x:r.x,y:r.y},ur:{x:r.x,y:r.y}};let o=r;for(let i=1,s=t.length;i<s;i++){if("number"!=typeof t[i][0]||"number"!=typeof t[i][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");let e=y.round(t[i][0],t[i][1]);e.x===o.x&&e.y===o.y||(this.segments.push(B.fromRing(o,e,this)),e.x<this.bbox.ll.x&&(this.bbox.ll.x=e.x),e.y<this.bbox.ll.y&&(this.bbox.ll.y=e.y),e.x>this.bbox.ur.x&&(this.bbox.ur.x=e.x),e.y>this.bbox.ur.y&&(this.bbox.ur.y=e.y),o=e)}r.x===o.x&&r.y===o.y||this.segments.push(B.fromRing(o,r,this))}getSweepEvents(){const t=[];for(let e=0,n=this.segments.length;e<n;e++){const n=this.segments[e];t.push(n.leftSE),t.push(n.rightSE)}return t}}class F{constructor(t,e){if(!Array.isArray(t))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new z(t[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let n=1,r=t.length;n<r;n++){const e=new z(t[n],this,!1);e.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=e.bbox.ll.x),e.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=e.bbox.ll.y),e.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=e.bbox.ur.x),e.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=e.bbox.ur.y),this.interiorRings.push(e)}this.multiPoly=e}getSweepEvents(){const t=this.exteriorRing.getSweepEvents();for(let e=0,n=this.interiorRings.length;e<n;e++){const n=this.interiorRings[e].getSweepEvents();for(let e=0,r=n.length;e<r;e++)t.push(n[e])}return t}}class j{constructor(t,e){if(!Array.isArray(t))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{"number"==typeof t[0][0][0]&&(t=[t])}catch(n){}this.polys=[],this.bbox={ll:{x:Number.POSITIVE_INFINITY,y:Number.POSITIVE_INFINITY},ur:{x:Number.NEGATIVE_INFINITY,y:Number.NEGATIVE_INFINITY}};for(let r=0,o=t.length;r<o;r++){const e=new F(t[r],this);e.bbox.ll.x<this.bbox.ll.x&&(this.bbox.ll.x=e.bbox.ll.x),e.bbox.ll.y<this.bbox.ll.y&&(this.bbox.ll.y=e.bbox.ll.y),e.bbox.ur.x>this.bbox.ur.x&&(this.bbox.ur.x=e.bbox.ur.x),e.bbox.ur.y>this.bbox.ur.y&&(this.bbox.ur.y=e.bbox.ur.y),this.polys.push(e)}this.isSubject=e}getSweepEvents(){const t=[];for(let e=0,n=this.polys.length;e<n;e++){const n=this.polys[e].getSweepEvents();for(let e=0,r=n.length;e<r;e++)t.push(n[e])}return t}}class W{static factory(t){const e=[];for(let n=0,r=t.length;n<r;n++){const r=t[n];if(!r.isInResult()||r.ringOut)continue;let o=null,i=r.leftSE,s=r.rightSE;const a=[i],l=i.point,c=[];for(;o=i,i=s,a.push(i),i.point!==l;)for(;;){const t=i.getAvailableLinkedEvents();if(0===t.length){const t=a[0].point,e=a[a.length-1].point;throw new Error(`Unable to complete output ring starting at [${t.x}, ${t.y}]. Last matching segment found ends at [${e.x}, ${e.y}].`)}if(1===t.length){s=t[0].otherSE;break}let n=null;for(let e=0,o=c.length;e<o;e++)if(c[e].point===i.point){n=e;break}if(null!==n){const t=c.splice(n)[0],r=a.splice(t.index);r.unshift(r[0].otherSE),e.push(new W(r.reverse()));continue}c.push({index:a.length,point:i.point});const r=i.getLeftmostComparator(o);s=t.sort(r)[0].otherSE;break}e.push(new W(a))}return e}constructor(t){this.events=t;for(let e=0,n=t.length;e<n;e++)t[e].segment.ringOut=this;this.poly=null}getGeom(){let t=this.events[0].point;const e=[t];for(let l=1,c=this.events.length-1;l<c;l++){const n=this.events[l].point,r=this.events[l+1].point;0!==E(n,t,r)&&(e.push(n),t=n)}if(1===e.length)return null;const n=e[0],r=e[1];0===E(n,t,r)&&e.shift(),e.push(e[0]);const o=this.isExteriorRing()?1:-1,i=this.isExteriorRing()?0:e.length-1,s=this.isExteriorRing()?e.length:-1,a=[];for(let l=i;l!=s;l+=o)a.push([e[l].x,e[l].y]);return a}isExteriorRing(){if(void 0===this._isExteriorRing){const t=this.enclosingRing();this._isExteriorRing=!t||!t.isExteriorRing()}return this._isExteriorRing}enclosingRing(){return void 0===this._enclosingRing&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){let t=this.events[0];for(let r=1,o=this.events.length;r<o;r++){const e=this.events[r];$.compare(t,e)>0&&(t=e)}let e=t.segment.prevInResult(),n=e?e.prevInResult():null;for(;;){if(!e)return null;if(!n)return e.ringOut;if(n.ringOut!==e.ringOut)return n.ringOut.enclosingRing()!==e.ringOut?e.ringOut:e.ringOut.enclosingRing();e=n.prevInResult(),n=e?e.prevInResult():null}}}class H{constructor(t){this.exteriorRing=t,t.poly=this,this.interiorRings=[]}addInterior(t){this.interiorRings.push(t),t.poly=this}getGeom(){const t=[this.exteriorRing.getGeom()];if(null===t[0])return null;for(let e=0,n=this.interiorRings.length;e<n;e++){const n=this.interiorRings[e].getGeom();null!==n&&t.push(n)}return t}}class _{constructor(t){this.rings=t,this.polys=this._composePolys(t)}getGeom(){const t=[];for(let e=0,n=this.polys.length;e<n;e++){const n=this.polys[e].getGeom();null!==n&&t.push(n)}return t}_composePolys(t){const e=[];for(let n=0,r=t.length;n<r;n++){const r=t[n];if(!r.poly)if(r.isExteriorRing())e.push(new H(r));else{const t=r.enclosingRing();t.poly||e.push(new H(t)),t.poly.addInterior(r)}}return e}}class U{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:B.compare;this.queue=t,this.tree=new a(e),this.segments=[]}process(t){const e=t.segment,n=[];if(t.consumedBy)return t.isLeft?this.queue.remove(t.otherSE):this.tree.remove(e),n;const r=t.isLeft?this.tree.add(e):this.tree.find(e);if(!r)throw new Error(`Unable to find segment #${e.id} [${e.leftSE.point.x}, ${e.leftSE.point.y}] -> [${e.rightSE.point.x}, ${e.rightSE.point.y}] in SweepLine tree.`);let o,i,s=r,a=r;for(;void 0===o;)s=this.tree.prev(s),null===s?o=null:void 0===s.key.consumedBy&&(o=s.key);for(;void 0===i;)a=this.tree.next(a),null===a?i=null:void 0===a.key.consumedBy&&(i=a.key);if(t.isLeft){let r=null;if(o){const t=o.getIntersection(e);if(null!==t&&(e.isAnEndpoint(t)||(r=t),!o.isAnEndpoint(t))){const e=this._splitSafely(o,t);for(let t=0,r=e.length;t<r;t++)n.push(e[t])}}let s=null;if(i){const t=i.getIntersection(e);if(null!==t&&(e.isAnEndpoint(t)||(s=t),!i.isAnEndpoint(t))){const e=this._splitSafely(i,t);for(let t=0,r=e.length;t<r;t++)n.push(e[t])}}if(null!==r||null!==s){let t=null;t=null===r?s:null===s||$.comparePoints(r,s)<=0?r:s,this.queue.remove(e.rightSE),n.push(e.rightSE);const o=e.split(t);for(let e=0,r=o.length;e<r;e++)n.push(o[e])}n.length>0?(this.tree.remove(e),n.push(t)):(this.segments.push(e),e.prev=o)}else{if(o&&i){const t=o.getIntersection(i);if(null!==t){if(!o.isAnEndpoint(t)){const e=this._splitSafely(o,t);for(let t=0,r=e.length;t<r;t++)n.push(e[t])}if(!i.isAnEndpoint(t)){const e=this._splitSafely(i,t);for(let t=0,r=e.length;t<r;t++)n.push(e[t])}}}this.tree.remove(e)}return n}_splitSafely(t,e){this.tree.remove(t);const n=t.rightSE;this.queue.remove(n);const r=t.split(e);return r.push(n),void 0===t.consumedBy&&this.tree.add(t),r}}const V="undefined"!=typeof process&&process.env.POLYGON_CLIPPING_MAX_QUEUE_SIZE||1e6,K="undefined"!=typeof process&&process.env.POLYGON_CLIPPING_MAX_SWEEPLINE_SEGMENTS||1e6,q=new class{run(t,e,n){q.type=t,y.reset();const r=[new j(e,!0)];for(let a=0,c=n.length;a<c;a++)r.push(new j(n[a],!1));if(q.numMultiPolys=r.length,"difference"===q.type){const t=r[0];let e=1;for(;e<r.length;)null!==p(r[e].bbox,t.bbox)?e++:r.splice(e,1)}if("intersection"===q.type)for(let a=0,c=r.length;a<c;a++){const t=r[a];for(let e=a+1,n=r.length;e<n;e++)if(null===p(t.bbox,r[e].bbox))return[]}const o=new a($.compare);for(let a=0,c=r.length;a<c;a++){const t=r[a].getSweepEvents();for(let e=0,n=t.length;e<n;e++)if(o.insert(t[e]),o.size>V)throw new Error("Infinite loop when putting segment endpoints in a priority queue (queue size too big).")}const i=new U(o);let s=o.size,l=o.pop();for(;l;){const t=l.key;if(o.size===s){const e=t.segment;throw new Error(`Unable to pop() ${t.isLeft?"left":"right"} SweepEvent [${t.point.x}, ${t.point.y}] from segment #${e.id} [${e.leftSE.point.x}, ${e.leftSE.point.y}] -> [${e.rightSE.point.x}, ${e.rightSE.point.y}] from queue.`)}if(o.size>V)throw new Error("Infinite loop when passing sweep line over endpoints (queue size too big).");if(i.segments.length>K)throw new Error("Infinite loop when passing sweep line over endpoints (too many sweep line segments).");const e=i.process(t);for(let n=0,r=e.length;n<r;n++){const t=e[n];void 0===t.consumedBy&&o.insert(t)}s=o.size,l=o.pop()}return y.reset(),new _(W.factory(i.segments)).getGeom()}};return{union:function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return q.run("union",t,n)},intersection:function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return q.run("intersection",t,n)},xor:function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return q.run("xor",t,n)},difference:function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return q.run("difference",t,n)}}},"object"==typeof t&&void 0!==e?e.exports=r():"function"==typeof define&&define.amd?define(r):(n="undefined"!=typeof globalThis?globalThis:n||self).polygonClipping=r()}),bF=wF(),vF=1,kF=1;function SF(t,e){return Math.abs(t[0]-e[0])<1e-6&&Math.abs(t[1]-e[1])<1e-6}function PF(t){return sB(t.shape,t.localToPage).filter(t=>t.closed&&t.nodes.length>=3).map(t=>function(t){const e=[];for(const n of t){const t=[n.x,n.y],r=e[e.length-1];r&&SF(r,t)||e.push(t)}return e.length>1&&SF(e[0],e[e.length-1])&&e.pop(),e.length>=3?e:null}(eB(t).points)).filter(t=>null!==t).map(t=>[t])}function MF(t){const e=t.length>1&&SF(t[0],t[t.length-1])?t.slice(0,-1):t;return e.length<3?null:{id:`boolean-subpath:${vF+=1}`,closed:!0,nodes:e.map(([t,e])=>({id:`boolean-node:${kF+=1}`,x:t,y:e,kind:"corner"}))}}function IF(t,e){const n=e.map(PF).filter(t=>t.length>0);return 0===n.length?[]:function(t,e){const[n,...r]=e;if(!n)return[];if(0===r.length)return n;switch(t){case"union":return(0,bF.union)(n,...r);case"subtract":return(0,bF.difference)(n,...r);case"intersect":return(0,bF.intersection)(n,...r);case"xor":return(0,bF.xor)(n,...r)}}(t,n).flatMap(t=>t).map(MF).filter(t=>null!==t)}var TF=Ae("plugin-path.api");function CF({editor:t}){return function({editor:t}){return{getSelectionStyle:()=>function(t){const e=t.state.selectedShapes.get().filter(CD);return 0===e.length?null:{fill:$F(e.map(t=>t.props.fill)),stroke:$F(e.map(t=>t.props.stroke)),strokeWidth:LF(e.map(t=>t.props.strokeWidth))}}(t),setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(CD).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)},getToolDefaults:()=>t.shapes.getDefaultProps("path"),setToolDefaults:e=>(t.shapes.updateDefaultProps("path",e),t.shapes.getDefaultProps("path")),canBeginEdit:()=>null!==EF(t),beginEdit(){const e=EF(t);return!!e&&(DB(t),vz(t),t.editing.start({shapeId:e.id,operationKind:"path.edit",entryMode:"focusEnd"},"user"),!0)},isEditing:()=>null!==AF(t),completeEdit:()=>!!AF(t)&&(t.editing.complete("user"),!0),isNodeSnapEnabled:()=>wz(t),canToggleNodeSnap:()=>{const e=AF(t);return!!e&&!e.isLocked},toggleNodeSnap(){const e=AF(t);return!(!e||e.isLocked)&&(bz(t),!0)},canDeleteSelectedNodes:()=>OF(t,()=>!0),deleteSelectedNodes(){const e=$B(t);return!(!e||e.shape.isLocked)&&(jz(t,e.shape,e.selection.nodes),!0)},canMakeSelectedNodesCurve:()=>OF(t,t=>t.entries.some(({node:t})=>!t.in&&!t.out)),makeSelectedNodesCurve:()=>NF(t,"make-curve"),canRemoveSelectedNodeHandles:()=>OF(t,t=>t.entries.some(({node:t})=>!!t.in||!!t.out)),removeSelectedNodeHandles:()=>NF(t,"remove-handles"),canRunSelectedNodeOperation:e=>OF(t,t=>yB(t.shape.props.subpaths,t.selection.nodes,e)),runSelectedNodeOperation(e){const n=$B(t);return!(!n||n.shape.isLocked||!yB(n.shape.props.subpaths,n.selection.nodes,e))&&(Wz(t,e),!0)},canRunBooleanOperation:()=>RF(t).length>=2,runBooleanOperation:e=>function(t,e){const n=RF(t),r=n[0];if(!r||n.length<2)return null;const o=function(t,e,n){const r=IF(t,e);return 0===r.length?null:iB(r,{...n,fillRule:"evenodd"})}(e,n.map(e=>({shape:e,localToPage:t.shapes.computeLocalToPageTransform(e)})),{fill:r.props.fill,stroke:r.props.stroke,strokeWidth:r.props.strokeWidth});if(!o)return null;let i=null;return t.operations.run({kind:`path.boolean.${e}`,label:"shape.boolean",source:"user",history:"record"},()=>{const[e]=t.commands.createShapes([{type:"path",x:o.x,y:o.y,parentId:r.parentId,props:{...r.props,subpaths:o.subpaths,fillRule:"evenodd"}}],{source:"user"});t.commands.deleteShapes(n.map(t=>t.id),{source:"user"}),e&&(i=e.id,t.commands.setSelectedShapeIds([e.id],{source:"system"}))}),i}(t,e)}}({editor:t})}function EF(t){const e=t.state.selectedShapes.get(),n=1===e.length?e[0]:null;return CD(n)&&!n.isLocked?n:null}function AF(t){const e=t.state.shapeEditingSession.get(),n=e?t.shapes.get(e.shapeId):null;return CD(n)?n:null}function OF(t,e){const n=$B(t);return!!n&&!n.shape.isLocked&&e(n)}function NF(t,e){const n=$B(t);if(!n||n.shape.isLocked)return!1;const r="make-curve"===e?n.entries.filter(({node:t})=>!t.in&&!t.out).reduce((t,{ref:e})=>mB(t,e.subpathId,e.nodeId),n.shape.props.subpaths):n.selection.nodes.reduce((t,e)=>gB(t,e.subpathId,e.nodeId),n.shape.props.subpaths);t.commands.updateShapes([{id:n.shape.id,props:{subpaths:r}}],{source:"user"});const o=t.shapes.get(n.shape.id);return CD(o)&&zB(t,o,n.selection.nodes,n.selection.primary),gz(t,n.shape.id),!0}function RF(t){return t.state.selectedShapes.get().filter(CD).filter(t=>!t.isLocked&&!t.isHidden)}function LF(t){const[e,...n]=t;return void 0!==e&&n.every(t=>t===e)?e:null}function $F(t){const[e,...n]=t;return void 0!==e&&n.every(t=>Y(e,t))?e:null}var DF={id:"path",editor:xF(),render:oz(),api:TF,setup:({editor:t})=>({api:CF({editor:t})})},BF=Ae("canvas-kit.clipboard");function zF({clipboard:t,editor:e,tasks:n}){return function({clipboard:t,editor:e,tasks:n}){return{hasContent:()=>null!==t.getMemoryPayload(),copy:()=>n.run(async n=>{const r=e.selection.createClipboardPayload();return r?(await t.write(r),n.throwIfAborted(),r):null}),cut:()=>n.run(async n=>{const r=e.selection.createClipboardPayload();return!!r&&(await t.write(r),n.throwIfAborted(),e.selection.delete("user"),!0)}),paste:(r={})=>n.run(async n=>{const o=await t.read();return n.throwIfAborted(),!!o&&(e.selection.pasteClipboardPayload({payload:o,pagePoint:r.pagePoint?FF(r.pagePoint):e.state.viewportPageBounds.get()?.center??void 0,source:"user"}),!0)})}}({clipboard:t,editor:e,tasks:n})}function FF(t){return new O(t.x,t.y)}function jF(){let t=null;const e=new Set;return{value:{async write(n){t=n;for(const t of e)t()},read:async()=>t,getMemoryPayload:()=>t,subscribe:t=>(e.add(t),()=>e.delete(t))},dispose(){e.clear(),t=null}}}function WF(t={}){return{id:"canvas-kit.clipboard-runtime",api:BF,setup({editor:e,tasks:n}){const r=t.createClipboard?.()??jF();try{return{api:zF({clipboard:r.value,editor:e,tasks:n}),dispose:()=>r.dispose?.()}}catch(o){throw Promise.resolve(r.dispose?.()).catch(()=>{}),o}}}}var HF=WF();function _F(t){return new Promise((e,n)=>{const r=new FileReader;r.addEventListener("load",()=>{e("string"==typeof r.result?r.result:null)}),r.addEventListener("error",()=>{n(r.error)}),r.readAsDataURL(t)})}async function UF({assetInliners:t=[],editor:e,padding:n=16,resolveThemeColor:r,shapeIds:o}){e.exports.repairIntegrity(o);const i=Array.from(e.shapeSvgExporters.values(),t=>t.type).sort();let s,a=e.exports.getIntegrityReport(o);try{s=await async function({assetInliners:t,editor:e,padding:n,resolveThemeColor:r,shapeIds:o}){const i=3;for(let a=0;a<i;a+=1){const i=e.store.getRevision();try{for(const n of t)await(n.prepare?.({editor:e,requestedShapeIds:o}))}catch(s){if(e.store.getRevision()!==i)continue;throw s}if(e.store.getRevision()!==i)continue;const a=e.exports.getSvgString(o,{padding:n,resolveThemeColor:r}),l=a?.exportedShapeIds.flatMap(t=>{const n=e.shapes.get(t);return n?[n]:[]})??[];if(e.store.getRevision()===i)return{exportedShapes:l,result:a}}throw new Error("The document changed repeatedly during SVG export.")}({assetInliners:t,editor:e,padding:n,resolveThemeColor:r,shapeIds:o})}catch(p){return a=e.exports.getIntegrityReport(o),VF({cause:p,integrity:a,supportedShapeTypes:i})}a=e.exports.getIntegrityReport(o);const l=function({integrity:t,supportedShapeTypes:e}){const n=function(t){const e=Object.entries(t).filter(t=>"number"==typeof t[1]);return 0===e.length?"none":e.map(([t,e])=>`${t} ${e}`).join(", ")}(function(t){const e={};for(const n of t.issues)e[n.kind]=(e[n.kind]??0)+1;return e}(t));return 0===t.fatalIssueCount&&0===t.issues.length?{tone:"success",title:"SVG export ready",details:`${t.requestedShapeIds.length} shape(s) ready. Issues: ${n}.`,integrity:t,supportedShapeTypes:e}:t.canExport?{tone:"warning",title:"SVG export repaired",details:`${t.requestedShapeIds.length} shape(s) exportable. Issues: ${n}.`,integrity:t,supportedShapeTypes:e}:{tone:"error",title:"SVG export blocked",details:`Fatal export issue(s): ${n}.`,integrity:t,supportedShapeTypes:e}}({integrity:a,supportedShapeTypes:i}),{exportedShapes:c,result:d}=s;if(!d)return{status:{...l,tone:"error",title:"SVG export blocked",details:`${l.details} No exportable SVG content was produced.`},svg:null,width:null,height:null,exportedShapeIds:[],skippedShapes:[]};let u=d.svg;try{for(const n of t)u=await n.inline({editor:e,exportedShapes:c,exportedShapeIds:d.exportedShapeIds,svg:u});!function(t){const e=new Set,n=/<([a-z][\w:-]*)\b([^>]*)>/giu,r=/<style\b[^>]*>([\s\S]*?)<\/style>/giu,o=/\burl\(\s*(["']?)(.*?)\1\s*\)/giu,i=Array.from(t.matchAll(n));for(const a of i){const t=YF(a[1]??""),n=GF(a[2]??"");for(const r of JF(t)){const t=n.get(r)?.trim();if(!t)continue;const o="srcset"===r?ZF(t):[t];for(const n of o)QF(n)||e.add(n)}}const s=[...i.map(t=>t[0]),...Array.from(t.matchAll(r),t=>t[1]??"")];for(const a of s){for(const t of a.matchAll(o)){const n=t[2]?.trim();n&&!QF(n)&&e.add(n)}/@import\b/iu.test(a)&&e.add("CSS @import"),/\blocal\(/iu.test(a)&&e.add("CSS local() font source")}if(e.size>0)throw new Error(`${e.size} external SVG resource(s) remain after embedding.`)}(u)}catch(p){return VF({cause:p,exportedShapeIds:d.exportedShapeIds,integrity:a,skippedShapes:d.skippedShapes,supportedShapeTypes:i})}return{status:l,svg:u,width:d.width,height:d.height,exportedShapeIds:d.exportedShapeIds,skippedShapes:d.skippedShapes}}function VF({cause:t,exportedShapeIds:e=[],integrity:n,skippedShapes:r=[],supportedShapeTypes:o}){return{status:{tone:"error",title:"SVG export blocked",details:`Resource embedding failed: ${t instanceof Error&&t.message.trim().length>0?t.message:"An SVG resource could not be embedded."}`,integrity:n,supportedShapeTypes:o},svg:null,width:null,height:null,exportedShapeIds:e,skippedShapes:r}}var KF={audio:["src"],embed:["src"],iframe:["src"],img:["src","srcset"],input:["src"],object:["data"],script:["src"],source:["src","srcset"],track:["src"],video:["poster","src"]},qF=["href","xlink:href"],XF=new Set(["a","area"]);function YF(t){return(t.split(":").pop()??t).toLowerCase()}function JF(t){const e=KF[t]??[];return XF.has(t)?e:[...qF,...e]}function GF(t){const e=new Map;for(const n of t.matchAll(/([^\s=/>]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/gu)){const t=n[1]?.toLowerCase(),r=n[2]??n[3]??n[4];t&&void 0!==r&&e.set(t,r)}return e}function ZF(t){const e=[];let n=0;for(;n<t.length;){for(;n<t.length&&(","===t[n]||/\s/u.test(t[n]??""));)n+=1;if(n>=t.length)break;const r="data:"===t.slice(n,n+5).toLowerCase(),o=n;for(;n<t.length&&!/\s/u.test(t[n]??"")&&(r||","!==t[n]);)n+=1;let i=t.slice(o,n);const s=r&&i.endsWith(",");if(s&&(i=i.replace(/,+$/u,"")),i&&e.push(i),!s)for(;n<t.length&&","!==t[n];)n+=1}return e}function QF(t){return t.startsWith("#")||/^data:/iu.test(t)}var tj=16384,ej=67108864;async function nj({background:t,pixelRatio:e=2,...n}){const r=await UF(n);if(!r.svg||null===r.width||null===r.height)return{status:"error"===r.status.tone?oj(r.status):{...r.status,tone:"error",title:"PNG export blocked",details:`${r.status.details} No exportable SVG content was produced.`},blob:null,width:null,height:null,exportedShapeIds:r.exportedShapeIds,skippedShapes:r.skippedShapes};try{const n=await async function({background:t,height:e,pixelRatio:n,svg:r,width:o}){const i=Math.ceil(o*n),s=Math.ceil(e*n);if(function({height:t,pixelRatio:e,sourceHeight:n,sourceWidth:r,width:o}){if(!Number.isFinite(e)||e<=0||!Number.isFinite(r)||r<=0||!Number.isFinite(n)||n<=0)throw new Error("PNG dimensions and pixel ratio must be positive numbers.");if(o>tj||t>tj||o*t>ej)throw new Error(`PNG dimensions ${o}×${t} exceed the browser export limit.`)}({height:s,pixelRatio:n,sourceHeight:e,sourceWidth:o,width:i}),"undefined"==typeof document||"undefined"==typeof Image||"undefined"==typeof FileReader)throw new Error("PNG export requires a browser environment.");const a=await _F(new Blob([r],{type:"image/svg+xml;charset=utf-8"}));if(!a)throw new Error("The exported SVG could not be encoded as a data URL.");const l=await(d=a,new Promise((t,e)=>{const n=new Image;n.onload=()=>t(n),n.onerror=()=>e(new Error("The exported SVG could not be decoded.")),n.src=d})),c=document.createElement("canvas");var d;c.width=i,c.height=s;const u=c.getContext("2d");if(!u)throw new Error("A 2D canvas context is unavailable.");t&&(u.fillStyle=t,u.fillRect(0,0,i,s));return u.drawImage(l,0,0,i,s),{blob:await rj(c),width:i,height:s}}({background:t,height:r.height,pixelRatio:e,svg:r.svg,width:r.width});return{status:oj(r.status,`${n.width}×${n.height} px.`),blob:n.blob,width:n.width,height:n.height,exportedShapeIds:r.exportedShapeIds,skippedShapes:r.skippedShapes}}catch(o){const t=o instanceof Error&&o.message.trim().length>0?o.message:"The SVG could not be rasterized.";return{status:{...r.status,tone:"error",title:"PNG export blocked",details:`Rasterization failed: ${t}`},blob:null,width:null,height:null,exportedShapeIds:r.exportedShapeIds,skippedShapes:r.skippedShapes}}}function rj(t){return new Promise((e,n)=>{t.toBlob(t=>{t?e(t):n(new Error("The browser did not produce a PNG blob."))},"image/png")})}function oj(t,e){return{...t,title:"success"===t.tone?"PNG export ready":"warning"===t.tone?"PNG export repaired":"PNG export blocked",details:e?`${t.details} ${e}`:t.details}}async function ij(t,e){return(await t.export("svg",{...dj(e),options:e})).result}async function sj(t,e){return(await t.export("png",{...dj(e),options:e})).result}function aj(){return{kind:"provider",id:"canvas-kit.export.svg",format:"svg",label:"SVG",mimeType:"image/svg+xml;charset=utf-8",fileExtension:"svg",async export({editor:t,options:e,shapeIds:n},r){const o=e??{},i=await UF({assetInliners:[cj(n,r.inlineSvg)],editor:t,padding:o.padding,resolveThemeColor:o.appearance?.resolveThemeColor,shapeIds:n});return{data:i.svg,result:i,status:i.status}}}}function lj(){return{kind:"provider",id:"canvas-kit.export.png",format:"png",label:"PNG",mimeType:"image/png",fileExtension:"png",async export({editor:t,options:e,shapeIds:n},r){const o=e??{},i=await nj({assetInliners:[cj(n,r.inlineSvg)],background:o.background,editor:t,padding:o.padding,pixelRatio:o.pixelRatio,resolveThemeColor:o.appearance?.resolveThemeColor,shapeIds:n});return{data:i.blob,result:i,status:i.status}}}}function cj(t,e){return{inline:n=>e({...n,requestedShapeIds:t})}}function dj(t){return t.scope?{scope:t.scope}:{shapeIds:t.shapeIds}}function uj(){return{id:"canvas-kit.export",setup:()=>({exports:[aj(),lj()]})}}function pj(t,e=0){return Math.max(0,"number"==typeof t&&Number.isFinite(t)?t:e)}function hj({cornerRadius:t,h:e,w:n}){return Math.min(pj(t),Math.max(0,n)/2,Math.max(0,e)/2)}function fj(t){return E(t)&&"video"===t.type}function mj(t){return C(t)&&"video"===t.type}var gj=Ae("plugin-video.api");function yj({editor:t}){return{getSelectionState(){if(1!==t.selection.getIds().length)return null;const[e]=t.state.selectedShapes.get();return mj(e)?{shapeId:e.id,cornerRadius:pj(e.props.cornerRadius),loop:e.props.loop}:null},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(mj).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...void 0===e.cornerRadius?{}:{cornerRadius:pj(e.cornerRadius)},...void 0===e.loop?{}:{loop:e.loop}}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)}}}function xj(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}var wj=class extends St{type="video";getDefaultProps(){return{w:320,h:180,assetId:null,name:"",loop:!1,cornerRadius:0}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Math.max(64,xj(e.w,n.w)),h:Math.max(36,xj(e.h,n.h)),assetId:(r=e.assetId,"string"==typeof r&&r.startsWith("asset:")?e.assetId:null),name:"string"==typeof e.name?e.name:"",loop:!0===e.loop,cornerRadius:pj(e.cornerRadius)};var r}getLocalBounds(t){return new N(0,0,t.props.w,t.props.h)}getRenderBounds(t){return Sj(t)}getExportBounds(t){return this.getLocalBounds(t)}getPointHitTestBounds(t){const e=Sj(t);return new N(e.x+t.x,e.y+t.y,e.w,e.h)}canEdit(t){return!0}hitTest(t,e){return this.getPointHitTestBounds(t).containsPoint(e)}hitTestBindingTarget(t,e){return this.getPositionedBounds(t).containsPoint(e)}canReceiveTerminalBinding(t){return!0}getAllowedSelectionResizeModes(t,e){return at}},bj="Video",vj=34;function kj(t){return/^\s*$/.test(t)?bj:t}function Sj(t){return new N(0,-34,t.props.w,t.props.h+34)}function Pj(){return{id:"land.video",shapeUtils:[new wj]}}var Mj='[data-ui="video-shape-player"]',Ij=new Set(["key_down","key_up","pointer_cancel","pointer_down","pointer_move","pointer_up"]),Tj=["Inter","ui-sans-serif","system-ui","-apple-system","BlinkMacSystemFont","'Segoe UI'","sans-serif"].join(", "),Cj={id:"land.video.player.dom-events",handle({event:t,name:e}){if(!Ij.has(e))return"continue";const n=t.target;return n instanceof Element&&n.closest(Mj)?"handled":"continue"},getCursor:({element:t})=>t?.closest(Mj)?"default":void 0},Ej=i({id:"land.video.name.dom-events",selector:'[data-ui="video-canvas-name"]'});function Aj(){return{id:"land.video.react",domEventGuards:[Cj,Ej],shapeRenderers:[{type:"video",component:Oj,hoverComponent:Nj}]}}function Oj({editor:t,isSelected:e,shape:n,shapeEditingSession:r}){const{assetId:o,h:i,loop:s,name:a,w:d}=n.props,u=o?t.assets.resolveUrl(o):null,p=r?.shapeId===n.id;
80
- return c("div",{style:{height:"100%",overflow:"visible",pointerEvents:"none",position:"relative",width:"100%"},children:[l("div",{"data-ui":"video-shape",style:{background:"#000",borderRadius:hj(n.props),display:"block",height:i,left:0,overflow:"hidden",pointerEvents:"none",position:"absolute",top:34,width:d},children:u?l("video",{"aria-label":kj(a),controls:e,"data-ui":"video-shape-player",draggable:!1,loop:s,playsInline:!0,preload:"metadata",src:u,style:{display:"block",height:i,objectFit:"contain",pointerEvents:e?"auto":"none",userSelect:"none",width:d}}):l("div",{"data-ui":"video-shape-missing-asset",style:{alignItems:"center",background:"#0f172a",border:"1px solid #334155",boxSizing:"border-box",color:"#cbd5e1",display:"flex",fontFamily:Tj,fontSize:12,height:i,justifyContent:"center",overflow:"hidden",width:d},children:"Missing video"})}),l(Rj,{editor:t,shape:n,isEditing:p})]})}function Nj({shape:t,strokeWidth:e}){const r=Sj(t);
81
- return l("svg",{"aria-hidden":"true","data-ui":"video-hover-outline",width:"100%",height:"100%",viewBox:`${r.x} ${r.y} ${r.w} ${r.h}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},children:l("rect",{x:0,y:0,width:t.props.w,height:t.props.h,rx:hj(t.props),ry:hj(t.props),fill:"none",stroke:n,strokeWidth:e,vectorEffect:"non-scaling-stroke"})})}function Rj({editor:t,shape:e,isEditing:n}){
82
- return l(o,{editor:t,shape:e,isEditing:n,value:e.props.name,fallback:kj(""),bodyWidth:e.props.w,bodyHeight:e.props.h,renderHeight:34,operationKind:"video.edit",editAriaLabel:"Edit video name",inputAriaLabel:"Video name",dataUi:{heading:"video-canvas-heading",dragHandle:"video-drag-handle",name:"video-canvas-name",input:"video-canvas-name-input"},onValueChange:n=>{t.commands.updateShapes([{id:e.id,props:{name:n}}],{source:"user"})}})}var Lj={id:"video",editor:Pj(),render:Aj(),api:gj,setup:({editor:t})=>({api:yj({editor:t})})},$j=Ae("video.host-api"),Dj="blobs",Bj=null;function zj(){return"undefined"==typeof indexedDB?Promise.resolve(null):(Bj||(Bj=new Promise((t,e)=>{const n=indexedDB.open("land.plugin-video",1);n.addEventListener("upgradeneeded",()=>{n.result.objectStoreNames.contains(Dj)||n.result.createObjectStore(Dj)}),n.addEventListener("success",()=>{const e=n.result;e.addEventListener("versionchange",()=>{e.close(),Bj=null}),t(e)}),n.addEventListener("error",()=>{Bj=null,e(n.error)})})),Bj)}var Fj="video-blob:";function jj(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?`${Fj}${crypto.randomUUID()}`:`${Fj}${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}async function Wj(t){if("undefined"==typeof indexedDB)throw new Error("IndexedDB is not available for video storage.");const e=jj();return await async function(t,e){const n=await zj();n&&await new Promise((r,o)=>{const i=n.transaction(Dj,"readwrite");i.addEventListener("complete",()=>r()),i.addEventListener("abort",()=>o(i.error)),i.addEventListener("error",()=>o(i.error)),i.objectStore(Dj).put(e,t)})}(e,t),{storageKey:e}}async function Hj(t){const e=await async function(t){const e=await zj();return e?new Promise((n,r)=>{const o=e.transaction(Dj,"readonly").objectStore(Dj).get(t);o.addEventListener("success",()=>n(o.result??null)),o.addEventListener("error",()=>r(o.error))}):null}(t);return e instanceof Blob?e:null}async function _j(t){await async function(t){const e=await zj();e&&await new Promise((n,r)=>{const o=e.transaction(Dj,"readwrite");o.addEventListener("complete",()=>n()),o.addEventListener("abort",()=>r(o.error)),o.addEventListener("error",()=>r(o.error)),o.objectStore(Dj).delete(t)})}(t)}async function Uj(){return(await async function(){const t=await zj();return t?new Promise((e,n)=>{const r=t.transaction(Dj,"readonly").objectStore(Dj).getAllKeys();r.addEventListener("success",()=>e([...r.result])),r.addEventListener("error",()=>n(r.error))}):null}())?.map(String)??[]}function Vj(t,e){const n=t.assets.get(e);return fj(n)&&"local"===n.props.source.kind&&n.props.source.storageKey||null}function Kj(t,e){const n=t.assets.get(e);return fj(n)&&"remote"===n.props.source.kind&&n.props.source.url||null}function qj(t){const e=new Set;for(const n of t.assets.getAll())fj(n)&&"local"===n.props.source.kind&&n.props.source.storageKey&&e.add(n.props.source.storageKey);return e}async function Xj({editor:t,objectUrls:e}){const n=qj(t),r=await Uj(),o=[];for(const i of r)n.has(i)||(e?.release(i),await _j(i),o.push(i));return o}function Yj(){const t=new Map,e=new Map;let n=0,r=!1;const o=async(o,i={})=>{if(i.signal?.throwIfAborted(),r)return null;const s=t.get(o);if(s)return s;const a=e.get(o);if(a)return a;const l=n,c=Hj(o).then(e=>{if(i.signal?.throwIfAborted(),!e||r||l!==n)return null;const s=URL.createObjectURL(e);return t.set(o,s),s}).finally(()=>{e.delete(o)});return e.set(o,c),c};return{async preloadForEditor(t,e={}){e.signal?.throwIfAborted(),await Promise.all(Array.from(qj(t)).map(t=>o(t,e)))},preload:o,resolve:e=>t.get(e)??null,resolveAssetUrl(e,n){const r=Kj(e,n);if(r)return r;const o=Vj(e,n);return o?t.get(o)??null:null},release(n){const r=t.get(n);r&&(URL.revokeObjectURL(r),t.delete(n)),e.delete(n)},releaseAll(){r=!0,n+=1;for(const e of t.values())URL.revokeObjectURL(e);t.clear(),e.clear()}}}async function Jj(t,{signal:e}){if("url"===t.type)return{...await Gj(t.url,{signal:e}),name:t.name||rW(t.url)||"Video",source:{kind:"remote",url:t.url},mimeType:null};const n="file"===t.type?t.file:t.blob;if(!tW(n))throw new Error("The selected file is not a video.");const r=URL.createObjectURL(n),o=await Gj(r,{signal:e}).finally(()=>URL.revokeObjectURL(r));e.throwIfAborted();const{storageKey:i}=await Wj(n);try{e.throwIfAborted()}catch(s){throw await _j(i),s}return{...o,name:"file"===t.type?t.file.name||"Video":t.name||"Video",source:{kind:"local",storageKey:i},mimeType:"file"===t.type?t.file.type||"video/mp4":t.mimeType||t.blob.type||"video/mp4",fileSize:n.size}}function Gj(t,{signal:e}={}){return e?.throwIfAborted(),new Promise((n,r)=>{const o=document.createElement("video"),i=()=>{o.removeEventListener("loadedmetadata",s),o.removeEventListener("error",a),e?.removeEventListener("abort",l),o.removeAttribute("src"),o.load()},s=()=>{const t=o.videoWidth||320,e=o.videoHeight||180,r=Number.isFinite(o.duration)&&o.duration>=0?o.duration:null;i(),n({width:t,height:e,duration:r})},a=()=>{i(),r(new Error("Could not decode video metadata."))},l=()=>{i(),r(e?.reason??new Error("Video metadata decoding aborted."))};o.preload="metadata",o.addEventListener("loadedmetadata",s),o.addEventListener("error",a),e?.addEventListener("abort",l,{once:!0}),o.src=t,o.load(),e?.aborted&&l()})}function Zj({height:t,width:e}){const n=e>0&&Number.isFinite(e)?e:320,r=t>0&&Number.isFinite(t)?t:180,o=Math.min(1,480/Math.max(n,r));return{w:Math.max(64,Math.round(n*o)),h:Math.max(36,Math.round(r*o))}}function Qj(t){for(const e of t)if(e.type.startsWith("video/"))return e;return null}function tW(t){return!t.type||t.type.startsWith("video/")}function eW({filename:t,url:e}){const n=document.createElement("a");n.href=e,n.download=t,n.click()}async function nW({blob:t,filename:e}){const n=URL.createObjectURL(t);try{eW({filename:e,url:n})}finally{window.setTimeout(()=>URL.revokeObjectURL(n),0)}}function rW(t){try{const e=new URL(t).pathname.split("/").filter(Boolean).at(-1);return e?decodeURIComponent(e):null}catch{return null}}var oW=1;function iW(t,e){return t.commands.createAsset({type:"video",props:{w:e.width,h:e.height,duration:e.duration,name:e.name,source:e.source,mimeType:e.mimeType,fileSize:e.fileSize}},{source:"user"})}async function sW({editor:t,objectUrls:e,pagePoint:n,signal:r,size:o,source:i}){return aW({editor:t,input:await Jj(i,{signal:r}),objectUrls:e,pagePoint:n,signal:r,size:o})}async function aW({editor:t,input:e,objectUrls:n,pagePoint:r,signal:o,size:i}){const s="local"===e.source.kind?e.source.storageKey:null;try{s&&await n.preload(s,{signal:o}),o.throwIfAborted()}catch(l){throw await dW({objectUrls:n,storageKey:s}),l}let a=null;try{const o=iW(t,e);a=o.id;const l=function(t){return!t||!Number.isFinite(t.w)||!Number.isFinite(t.h)||t.w<=0||t.h<=0?null:{w:Math.max(64,t.w),h:Math.max(36,t.h)}}(i)??Zj({width:o.props.w,height:o.props.h}),c=t.state.viewportPageBounds.get(),d=r??c?.center??t.viewport.screenToPage(new O(360,240)),[u]=t.commands.createShapes([{type:"video",x:Math.round(d.x-l.w/2),y:Math.round(d.y-l.h/2),props:{...l,assetId:o.id,name:e.name}}],{source:"user"});return u?(t.commands.setSelectedShapeIds([u.id],{source:"user"}),u.id):(t.commands.deleteAsset(o.id,{source:"system"}),a=null,await dW({objectUrls:n,storageKey:s}),null)}catch(l){throw a&&t.commands.deleteAsset(a,{source:"system"}),await dW({objectUrls:n,storageKey:s}),l}}async function lW({editor:t,file:e,objectUrls:n,signal:r}){if(!tW(e))return!1;const[o]=t.state.selectedShapes.get();return!(1!==t.selection.getIds().length||!mj(o)||o.isLocked)&&async function({editor:t,input:e,objectUrls:n,shape:r,signal:o}){const i=r.props.assetId,s="local"===e.source.kind?e.source.storageKey:null;try{o.throwIfAborted(),s&&await n.preload(s,{signal:o}),o.throwIfAborted()}catch(a){throw await dW({objectUrls:n,storageKey:s}),a}try{const o=t.shapes.get(r.id);if(!mj(o)||o.isLocked||o.props.assetId!==i)return await dW({objectUrls:n,storageKey:s}),!1;const l=t.operations.begin({kind:`video.asset.replace:${r.id}:${oW++}`,label:"video.asset.replace",source:"user",history:"record"});try{const n=iW(t,e);return t.commands.updateShapes([{id:r.id,props:{assetId:n.id,name:e.name}}],{source:"user"}),i&&!function(t,e){return t.snapshots.getDocument().records.some(t=>"shape"===t.typeName&&t.props.assetId===e)}(t,i)&&t.commands.deleteAsset(i,{source:"user"}),l.commit(),!0}catch(a){throw l.isActive&&l.cancel(),a}}catch(a){throw await dW({objectUrls:n,storageKey:s}),a}}({editor:t,input:await Jj({type:"file",file:e},{signal:r}),objectUrls:n,shape:o,signal:r})}async function cW({editor:t,objectUrls:e,onError:n}){if(1!==t.selection.getIds().length)return;const[r]=t.state.selectedShapes.get();if(!mj(r)||!r.props.assetId)return;const o=t.assets.get(r.props.assetId);if(!fj(o))return;const i=o.props.name||"land-video";if("remote"===o.props.source.kind)return void(await async function({filename:t,onError:e,url:n}){try{const e=await fetch(n);if(!e.ok)throw new Error(`Could not download video URL (${e.status}).`);await nW({blob:await e.blob(),filename:t})}catch(r){e?.(new Error("Could not download remote video; opening URL instead.",{cause:r})),function(t){const e=document.createElement("a");e.href=t,e.rel="noreferrer",e.target="_blank",e.click()}(n)}}({filename:i,onError:n,url:o.props.source.url}));const s=o.props.source.storageKey,a=await Hj(s);if(a)return void(await nW({blob:a,filename:i}));const l=e.resolve(s);l&&eW({filename:i,url:l})}async function dW({objectUrls:t,storageKey:e}){e&&(t.release(e),await _j(e))}function uW({editor:t,onError:e,tasks:n,videoAssetService:r}){let o;const i=pW(t=>o.insert({source:{type:"file",file:t}}),e),s=pW(t=>o.replaceSelection({file:t}),e);return o={openInsertFilePicker(){i.open()},openReplaceFilePicker(){s.open()},insert:({pagePoint:e,size:o,source:i})=>n.run(async n=>{n.throwIfAborted();const s=await sW({editor:t,objectUrls:r.objectUrls,pagePoint:e,signal:n,size:o,source:i});return n.throwIfAborted(),s}),replaceSelection:({file:e})=>n.run(async n=>{if(!e.type.startsWith("video/"))return!1;const[o]=t.state.selectedShapes.get();if(!mj(o)||o.isLocked)return!1;const i=await lW({editor:t,file:e,objectUrls:r.objectUrls,signal:n});return n.throwIfAborted(),i}),downloadSelectionOriginal:()=>n.run(async n=>{await cW({editor:t,objectUrls:r.objectUrls,onError:e}),n.throwIfAborted()})},{value:o,dispose(){i.dispose(),s.dispose()}}}function pW(t,e){let n=null,r=!1;return{open(){if(!r){if(!globalThis.document)throw new Error("Video file selection requires a browser document.");n??=function(){const n=document.createElement("input");return n.type="file",n.accept="video/*",n.hidden=!0,n.onchange=()=>{const o=n.files?.[0]??null;n.value="",o&&!r&&t(o).catch(t=>{e?.(new Error("Video file selection failed.",{cause:t}))})},n}(),n.click()}},dispose(){r=!0,n&&(n.onchange=null),n=null}}}function hW(){const t=Yj();return{value:{objectUrls:t,async cleanupAfterRestore(e,{signal:n}){n.throwIfAborted(),await Xj({editor:e,objectUrls:t}),n.throwIfAborted()},preloadForEditor:(e,{signal:n})=>t.preloadForEditor(e,{signal:n}),resolveAssetUrl:(e,n)=>t.resolveAssetUrl(e,n)},dispose(){t.releaseAll()}}}function fW(t={}){return{id:"video.host",requires:[Lj],api:$j,setup({editor:e,tasks:n}){const r=(t.createAssetService??hW)();let o=null;try{const i=uW({editor:e,onError:t.onError,tasks:n,videoAssetService:r.value});return o=i.dispose,{api:i.value,imports:[{id:"video.host-import",order:100,acceptsPreview:t=>t.fileTypes.some(t=>t.startsWith("video/"))||t.dataTypes.some(t=>{const e=t.toLowerCase();return"files"===e||"text/uri-list"===e}),accepts:t=>null!==Qj(t.files)||(t.urls?.some(mW)??!1),async import(t){const e=Qj(t.files),n=t.urls?.find(mW);return(e||n)&&await i.value.insert({source:e?{type:"file",file:e}:{type:"url",url:n},pagePoint:t.pagePoint})?"handled":"ignored"}}],assetResolvers:[{id:"video.host.asset-resolver",resolve:t=>r.value.resolveAssetUrl(e,t),preload:({signal:t})=>r.value.preloadForEditor(e,{signal:t}),cleanupAfterRestore:({signal:t})=>r.value.cleanupAfterRestore(e,{signal:t})}],dispose(){o?.(),r.dispose()}}}catch(i){throw o?.(),r.dispose(),i}}}}function mW(t){return t.startsWith("data:video/")||/\.(?:m4v|mov|mp4|ogv|webm)(?:[?#].*)?$/i.test(t)}function gW({toolIds:t,shortcutOverrides:e}){return I([...t.map(yW),{id:"standard.history.undo",shortcut:{key:"z",accelKey:!0},isEnabled:t=>wW(t)&&t.history.state.getSnapshot().canUndo,run:t=>{t.history.undo()}},{id:"standard.history.redo",shortcut:{key:"z",accelKey:!0,shiftKey:!0},isEnabled:t=>wW(t)&&t.history.state.getSnapshot().canRedo,run:t=>{t.history.redo()}},{id:"standard.selection.select-all",shortcut:{key:"a",accelKey:!0},isEnabled:t=>t.pages.state.getSnapshot().currentPageShapeIds.length>0,run:t=>t.selection.selectAll()},{id:"standard.selection.duplicate",shortcut:{key:"d",accelKey:!0},isEnabled:t=>wW(t)&&bW(t),run:t=>{t.selection.duplicate()}},{id:"standard.selection.delete",shortcut:["Backspace","Delete"],isEnabled:t=>wW(t)&&bW(t),run:t=>t.selection.delete()},{id:"standard.layer.move-selection-backward",shortcut:{key:"ArrowDown",altKey:!0},isEnabled:t=>wW(t)&&vW(t).canMoveBackward,run:t=>{t.layers.move(t.selection.state.getSnapshot().ids,"backward")}},{id:"standard.layer.move-selection-forward",shortcut:{key:"ArrowUp",altKey:!0},isEnabled:t=>wW(t)&&vW(t).canMoveForward,run:t=>{t.layers.move(t.selection.state.getSnapshot().ids,"forward")}},{id:"standard.clipboard.copy",shortcut:{key:"c",accelKey:!0},isEnabled:bW,run:async t=>{await(t.api(BF)?.copy())}},{id:"standard.clipboard.cut",shortcut:{key:"x",accelKey:!0},isEnabled:t=>wW(t)&&bW(t),run:async t=>{await(t.api(BF)?.cut())}},{id:"standard.clipboard.paste",shortcut:{key:"v",accelKey:!0},isEnabled:t=>wW(t)&&(t.api(BF)?.hasContent()??!1),run:async t=>{await(t.api(BF)?.paste())}},{id:"standard.view.zoom-in",shortcut:{key:"="},isEnabled:()=>!0,run:t=>t.viewport.zoomIn()},{id:"standard.view.zoom-out",shortcut:{key:"-"},isEnabled:()=>!0,run:t=>t.viewport.zoomOut()},{id:"standard.view.reset-zoom",shortcut:{key:"0",accelKey:!0},isEnabled:()=>!0,run:t=>t.viewport.resetZoom()}],e)}function yW(t){return{id:`standard.tool.${t}`,shortcut:kW(t),isEnabled:e=>wW(e)||xW.has(t),run:e=>e.tools.setCurrent(t)}}var xW=new Set(["select","hand","laser"]);function wW(t){return!t.document.readonlyState.getSnapshot()}function bW(t){return t.selection.state.getSnapshot().ids.length>0}function vW(t){return t.layers.getActionState(t.selection.state.getSnapshot().ids)}function kW(t){const e=SW[t];return e?{key:e}:void 0}var SW={select:"v",hand:"h",rectangle:"r",ellipse:"o",rhombus:"d",triangle:"3",pentagon:"5",hexagon:"6",star:"8",draw:"p",arrow:"a",eraser:"e",laser:"l",path:"b",text:"t",frame:"f"};function PW(t={}){const e=!1!==t.geo&&!1!==t.connector,n=e&&!1!==t.flow&&!1!==t.image&&!1!==t.text,r="object"==typeof t.connector?hl(t.connector):fl,o="object"==typeof t.flow?GL(t.flow):ZL,i="object"==typeof t.text?{...wm(),...t.text}:wm(),s=vm(i),a=tL({...i,fontCatalog:s}),l=!1===t.image?null:mf({onError:t.onError}),c=!1===t.video?null:fW({onError:t.onError}),d=["select","hand",...!1===t.geo?[]:qo,...!1===t.draw?[]:["draw"],...!1===t.arrow?[]:["arrow"],...e?["connector"]:[],...!1===t.eraser?[]:["eraser"],...!1===t.laser?[]:["laser"],...!1===t.path?[]:["path"],...!1===t.text?[]:["text"],...!1===t.frame?[]:["frame"]];return{plugins:[...!1===t.geo?[]:[Js],...!1===t.draw?[]:[Qc],...!1===t.arrow?[]:[pn],...e?[r]:[],...!1===t.eraser?[]:[iu],...!1===t.laser?[]:[yD],...!1===t.path?[]:[DF],...!1===t.html?[]:[S$],...l?[gh,l]:[],...c?[Lj,c]:[],...!1===t.text?[]:[a,cL({fontCatalog:s})],...n?[o]:[],...!1===t.frame?[]:[Eu],...!1===t.group?[]:[a$],HF,uj()],actions:gW({toolIds:d,shortcutOverrides:t.shortcutOverrides})}}export{ne as ARROW_STROKE_STYLES,pn as Arrow,Ee as ArrowBindingUtil,gi as ArrowLeftTool,yi as ArrowRightTool,on as ArrowShapeSvgExporter,Ve as ArrowShapeUtil,Ze as ArrowTool,ci as BurstTool,vr as CONNECTOR_ARROW_TERMINAL_PADDING,An as CONNECTOR_CLICK_DRAG_THRESHOLD_SCREEN,wo as CONNECTOR_CURVE_INSERT_HANDLE_TYPE,xo as CONNECTOR_CURVE_WAYPOINT_HANDLE_TYPE,Bn as CONNECTOR_DASH_ARRAY,En as CONNECTOR_LINE_HIT_RADIUS_SCREEN,kn as CONNECTOR_ORTHOGONAL_OBSTACLE_CLEARANCE_PAGE,bo as CONNECTOR_ORTHOGONAL_SEGMENT_HANDLE_TYPE,Nn as CONNECTOR_ORTHOGONAL_SEGMENT_SNAP_SCREEN,vn as CONNECTOR_ORTHOGONAL_STUB_PAGE,On as CONNECTOR_ORTHOGONAL_TERMINAL_SNAP_SCREEN,Tn as CONNECTOR_PORT_HIT_RADIUS_SCREEN,Mn as CONNECTOR_PORT_HOVER_GAP_SCREEN,In as CONNECTOR_PORT_HOVER_ICON_SCREEN,Pn as CONNECTOR_PORT_HOVER_RADIUS_SCREEN,Cn as CONNECTOR_PORT_VISUAL_OFFSET_SCREEN,Sn as CONNECTOR_PORT_VISUAL_RADIUS_SCREEN,Ln as CONNECTOR_QUICK_CONNECT_CROSS_AXIS_PAGE,Rn as CONNECTOR_QUICK_CONNECT_DISTANCE_PAGE,Dn as CONNECTOR_QUICK_CREATE_CROSS_GAP_PAGE,$n as CONNECTOR_QUICK_CREATE_GAP_PAGE,fl as Connector,Na as ConnectorBindingUtil,sl as ConnectorShapeSvgExporter,tl as ConnectorShapeUtil,il as ConnectorTool,w$ as DEFAULT_HTML_IFRAME_SANDBOX,mp as DEFAULT_IMAGE_SMUDGE_BRUSH_COLOR,fp as DEFAULT_IMAGE_SMUDGE_BRUSH_SIZE,ym as DEFAULT_TEXT_FONT,HF as DefaultClipboardRuntimePlugin,Qc as Draw,Xc as DrawShapeSvg,Kc as DrawShapeSvgExporter,Vc as DrawShapeUtil,Sc as DrawTool,ii as EllipseTool,iu as Eraser,xd as EraserTool,wL as FLOW_NODE_GAP_PAGE,kL as FLOW_NODE_TITLE_RENDER_HEIGHT,ZL as Flow,CL as FlowNodeShapeUtil,YL as FlowNodeSvgExporter,Eu as Frame,bu as FrameShapeSvgExporter,uu as FrameShapeUtil,yu as FrameTool,qo as GEO_SHAPE_KINDS,Xo as GEO_STROKE_STYLES,Js as Geo,Ws as GeoShapeSvgExporter,Fs as GeoShapeUtil,a$ as Group,e$ as GroupShapeSvgExporter,t$ as GroupShapeUtil,xm as HOST_TEXT_FONT,c$ as HTML_INTERACTION_OPERATION_KIND,hi as HexagonTool,S$ as Html,g$ as HtmlShapeUtil,Ru as IMAGE_CROP_ASPECT_RATIO_PRESETS,yp as IMAGE_SMUDGE_BRUSH_SIZE_MAX,gp as IMAGE_SMUDGE_BRUSH_SIZE_MIN,gh as Image,Hp as ImageShapeSvgExporter,Wp as ImageShapeUtil,yD as Laser,C$ as LaserTool,si as MessageCircleTool,wD as PATH_CONTROL_HANDLE_TYPE,ID as PATH_FILL_RULES,xD as PATH_NODE_HANDLE_TYPE,TD as PATH_NODE_KINDS,DF as Path,yF as PathShapeSvgExporter,eF as PathShapeUtil,fF as PathTool,pi as PentagonTool,oi as RectangleTool,di as RhombusTool,fi as StarTool,li as SummaryLeftTool,ai as SummaryTool,QO as TEXT_SIZE_PRESETS,eL as Text,qN as TextLinkPopoverPresenterProvider,YN as TextSearchHighlightProvider,mi as TrapezoidTool,ui as TriangleTool,bj as VIDEO_NAME_FALLBACK,vj as VIDEO_NAME_RENDER_HEIGHT,Lj as Video,wj as VideoShapeUtil,Re as arrowApiToken,Ep as cancelImageSmudgeSession,Op as cancelImageSmudgeSessionIfActive,BF as canvasClipboardApiToken,oa as chooseFacingPort,ia as chooseOpposingPort,Nh as cleanupUnreferencedImageBlobs,Xj as cleanupUnreferencedVideoBlobs,zp as cloneImageSmudgeStrokes,Oo as commitConnectorCreation,Ap as completeImageSmudgeSession,tf as confirmImageSmudgeSession,cl as connectorApiToken,Oe as createArrow,ln as createArrowCanvasRenderPlugin,sn as createArrowEditorPlugin,rn as createArrowInteractionHandler,nn as createArrowSelectionHandleInteractionHandler,kf as createCanvasShapeLinkHref,WF as createClipboardRuntimePlugin,Co as createConnectorBoundEndpoint,ga as createConnectorCanvasRenderPlugin,ko as createConnectorCurveInsertHandleId,vo as createConnectorCurveWaypointHandleId,al as createConnectorEditorPlugin,So as createConnectorOrthogonalSegmentHandleId,hl as createConnectorPlugin,Dr as createConnectorTerminalOffsetMapper,uj as createDefaultCanvasExportPlugin,sa as createDefaultConnectorQuickCreateNodeFactory,bm as createDefaultTextFontCatalog,wm as createDefaultTextPluginOptions,Jc as createDrawCanvasRenderPlugin,qc as createDrawEditorPlugin,Sd as createEraserCanvasRenderPlugin,ou as createEraserEditorPlugin,NL as createFlowCanvasRenderPlugin,JL as createFlowEditorPlugin,bL as createFlowNodeFromPort,GL as createFlowPlugin,Pu as createFrameCanvasRenderPlugin,vu as createFrameEditorPlugin,Us as createGeoCanvasRenderPlugin,Hs as createGeoEditorPlugin,r$ as createGroupCanvasRenderPlugin,n$ as createGroupEditorPlugin,b$ as createHtmlCanvasRenderPlugin,x$ as createHtmlEditorPlugin,p$ as createHtmlInteractionHandler,k$ as createHtmlPlugin,f$ as createHtmlPluginApi,eh as createImageCanvasRenderPlugin,cp as createImageCropInteractionHandler,lp as createImageCropSelectionHandleInteractionHandler,Zp as createImageEditorPlugin,lf as createImageHostApi,mf as createImageHostPlugin,Rh as createImageObjectUrlStore,Up as createImageSmudgeInteractionHandler,Sh as createImageStorageKey,df as createImageSvgAssetInliner,N$ as createLaserCanvasRenderPlugin,gD as createLaserEditorPlugin,Lh as createLocalImageAssetService,hW as createLocalVideoAssetService,jF as createMemoryCanvasClipboard,oz as createPathCanvasRenderPlugin,vD as createPathControlHandleId,xF as createPathEditorPlugin,bD as createPathNodeHandleId,lj as createPngExportFormatProvider,Cf as createRichTextFromPlainText,gW as createStandardCanvasActions,PW as createStandardCanvasKitProfile,aj as createSvgExportFormatProvider,QN as createTextCanvasRenderPlugin,YR as createTextEditorPlugin,vm as createTextFontCatalog,tL as createTextPlugin,cL as createTextSvgExportPlugin,Aj as createVideoCanvasRenderPlugin,Pj as createVideoEditorPlugin,uW as createVideoHostApi,fW as createVideoHostPlugin,Yj as createVideoObjectUrlStore,jj as createVideoStorageKey,Gj as decodeVideoMetadata,Th as deleteImageBlob,_j as deleteVideoBlob,Xh as downloadSelectedImageOriginal,cW as downloadSelectedVideoOriginal,Nc as drawApiToken,sj as exportCanvasPng,ij as exportCanvasSvg,nj as exportEditorPng,UF as exportEditorSvg,ra as findQuickConnectTargets,JN as findRichTextSearchMatches,Zj as fitVideoSize,bc as flipDrawShapeInSelectionBounds,yL as flowApiToken,pu as frameApiToken,xi as geoApiToken,Rp as getActiveImageSmudgeSession,Ch as getAllImageBlobStorageKeys,Uj as getAllVideoBlobStorageKeys,Et as getArrowBindingAnchorPagePoint,Rt as getArrowTerminalPagePoint,na as getBalancedConnectorBranchNodeInput,Pr as getConnectorArrowGlyphLength,Sr as getConnectorArrowLength,kr as getConnectorArrowMagnification,Ao as getConnectorCreationInvalidReason,Wr as getConnectorInfo,Ir as getConnectorMarkerPath,Mr as getConnectorMarkerRefX,Ho as getConnectorParentId,ha as getConnectorPortInteractionState,Tr as getConnectorSegmentPoint,Gs as getConnectorVisualPortPoint,uL as getDefaultFlowNodeTitle,kc as getDrawShapeDiagnostics,yc as getDrawShapeParentPoints,xc as getDrawShapeParentSegments,ad as getEraserRuntime,jh as getFirstImageFile,Qj as getFirstVideoFile,IL as getFlowNodeDisplayTitle,TL as getFlowNodeRenderBounds,y$ as getHtmlDisplayTitle,Ju as getImageCropModeOperationKind,Hu as getImageCropRectOrDefault,Mp as getImageSmudgeModeOperationKind,M$ as getLaserRuntime,Eh as getLocalImageAssetStorageKey,Vj as getLocalVideoAssetStorageKey,Qs as getNearestConnectorPortAtPoint,Ef as getPlainTextFromRichText,Oh as getReferencedImageStorageKeys,qj as getReferencedVideoStorageKeys,Ah as getRemoteImageAssetUrl,Kj as getRemoteVideoAssetUrl,jr as getResolvedConnectorLocalInfo,Br as getResolvedConnectorPageInfo,kj as getVideoDisplayName,Sj as getVideoRenderBounds,fa as getVisibleConnectorSourcePortAtPoint,jo as hasDirectedConnector,h$ as htmlApiToken,dh as imageApiToken,yh as imageHostApiToken,Vh as insertImageIntoEditor,aW as insertPreparedVideoIntoEditor,sW as insertVideoIntoEditor,od as interpolateDrawShapeRecords,bf as isAllowedRichTextLinkHref,ie as isArrowBindingRecord,oe as isArrowShapeRecord,re as isArrowStrokeStyle,Fn as isConnectorBindingRecord,zn as isConnectorShapeRecord,Oc as isDrawShapeRecord,vf as isExternalRichTextLinkHref,mL as isFlowNodeShape,Jo as isGeoShapeKind,Yo as isGeoShapeRecord,Go as isGeoStrokeStyle,l$ as isHtmlShapeRecord,op as isImageAssetRecord,ip as isImageShapeRecord,Ip as isImageSmudgeModeForShape,ED as isPathFillRule,AD as isPathNodeKind,CD as isPathShapeRecord,Gf as isTextShapeRecord,fj as isVideoAssetRecord,tW as isVideoBlob,mj as isVideoShapeRecord,wf as normalizeRichTextLinkHref,dL as openBrowserRichTextLink,Pf as openRichTextLink,Sf as parseCanvasShapeLinkHref,Po as parseConnectorIndexedHandleId,Mo as parseConnectorOrthogonalSegmentHandleId,kD as parsePathHandle,TF as pathApiToken,Jj as prepareVideoAssetInput,ta as quickConnectFromPort,_F as readBlobAsDataUrl,Mh as readImageBlob,Ih as readImageBlobAsDataUrl,Hj as readVideoBlob,$p as redoImageSmudgeStroke,Dp as registerImageSmudgeConfirmHandler,qh as replaceSelectedImageFromFile,lW as replaceSelectedVideoFromFile,Bp as requestImageSmudgeConfirm,At as resolveArrowBindingPagePoint,qe as resolveArrowTerminalBindingAtPoint,Xe as resolveArrowTerminalBindingAtStartPoint,Ye as resolveArrowTerminalBindingForArrow,Eo as resolveConnectorDraftEndpoint,_o as resolveConnectorDraftParentId,Ro as setConnectorTerminalPagePoint,Cp as startImageSmudgeSession,u$ as startInteractingWithHtmlShape,JR as textApiToken,Lp as undoImageSmudgeStroke,fL as unwrapFlowNode,Np as updateImageSmudgeBrush,em as updateTextShapeRichText,Af as validateRichTextDocument,gj as videoApiToken,$j as videoHostApiToken,hL as wrapShapeAsFlowNode,Ph as writeImageBlob,Wj as writeVideoBlob};
1
+ import{getCanvasSurfaceElementForNode as t,getCanvasSurfaceScreenPoint as e,useEditor as n,useValue as r}from"@yuzhouu/canvas-kit/plugin-runtime";import{SHAPE_HOVER_STROKE as o,SHAPE_HOVER_STROKE_WIDTH as i,ShapeHeadingControl as s,createShapeHeadingDomEventGuard as a,useCanvasRenderers as l}from"@yuzhouu/canvas-kit/plugin-runtime";import{Fragment as c,jsx as d,jsxs as u}from"react/jsx-runtime";import{createContext as p,createElement as h,forwardRef as f,memo as g,useCallback as m,useContext as y,useEffect as x,useLayoutEffect as w,useMemo as b,useRef as v,useState as k,useSyncExternalStore as P}from"react";import{EditorContent as S,useEditor as I}from"@tiptap/react";import{Extension as M,Mark as T,Node as C,callOrReturn as A,canInsertNode as E,combineTransactionSteps as L,createStyleTag as B,findChildrenInRange as R,getAttributes as $,getChangedRanges as N,getExtensionField as z,getMarksBetween as O,getNodeAtPosition as W,getNodeType as H,getRenderedAttributes as D,getStyleProperty as F,isAtEndOfNode as j,isAtStartOfNode as U,isNodeActive as X,isNodeEmpty as Y,isNodeSelection as K,markInputRule as _,markPasteRule as q,mergeAttributes as V,nodeInputRule as G,parseIndentedBlocks as J,renderNestedMarkdownContent as Z,textblockTypeInputRule as Q,wrappingInputRule as tt}from"@tiptap/core";import{jsx as et}from"@tiptap/core/jsx-runtime";import{NodeSelection as nt,Plugin as rt,PluginKey as ot,Selection as it,TextSelection as st}from"@tiptap/pm/state";import{Decoration as at,DecorationSet as lt}from"@tiptap/pm/view";import{Fragment as ct}from"@tiptap/pm/model";import{dropCursor as dt}from"@tiptap/pm/dropcursor";import{gapCursor as ut}from"@tiptap/pm/gapcursor";import{history as pt,redo as ht,undo as ft}from"@tiptap/pm/history";import gt from"polygon-clipping";import{applyCanvasActionShortcutOverrides as mt}from"@yuzhouu/canvas-kit";function yt(t){return!!t&&"shape"===t.typeName}function xt(t){return!!t&&"asset"===t.typeName}var wt=class{},bt=class t{x;y;constructor(t,e){this.x=t,this.y=e}add(e){return new t(this.x+e.x,this.y+e.y)}sub(e){return new t(this.x-e.x,this.y-e.y)}mul(e){return new t(this.x*e,this.y*e)}div(e){return new t(this.x/e,this.y/e)}len2(){return this.x*this.x+this.y*this.y}len(){return Math.sqrt(this.len2())}dist2(t){const e=this.x-t.x,n=this.y-t.y;return e*e+n*n}dist(t){return Math.sqrt(this.dist2(t))}rot(e){const n=Math.cos(e),r=Math.sin(e);return new t(this.x*n-this.y*r,this.x*r+this.y*n)}per(){return new t(-this.y,this.x)}normalize(){const e=this.len();return 0===e?new t(0,0):this.div(e)}equals(t){return this.x===t.x&&this.y===t.y}clone(){return new t(this.x,this.y)}static From(e,n){return new t(e,n)}static Zero(){return new t(0,0)}static Med(e,n){return new t((e.x+n.x)/2,(e.y+n.y)/2)}static Lrp(e,n,r){return new t(e.x+(n.x-e.x)*r,e.y+(n.y-e.y)*r)}static Dist(t,e){return t.dist(e)}static Dist2(t,e){return t.dist2(e)}static Angle(t,e){return Math.atan2(e.y-t.y,e.x-t.x)}static Nudge(t,e,n){const r=e.sub(t),o=r.len();return 0===o?t.clone():t.add(r.mul(n/o))}static RotWith(e,n,r){const o=e.x-n.x,i=e.y-n.y,s=Math.cos(r),a=Math.sin(r);return new t(n.x+o*s-i*a,n.y+o*a+i*s)}static IsNaN(t){return isNaN(t.x)||isNaN(t.y)}},vt=class t{x;y;w;h;constructor(t,e,n,r){this.x=t,this.y=e,this.w=n,this.h=r}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 bt(this.x+this.w/2,this.y+this.h/2)}containsPoint(t){return t.x>=this.minX&&t.x<=this.maxX&&t.y>=this.minY&&t.y<=this.maxY}containsBox(t){return t.minX>=this.minX&&t.maxX<=this.maxX&&t.minY>=this.minY&&t.maxY<=this.maxY}intersects(t){return this.minX<t.maxX&&this.maxX>t.minX&&this.minY<t.maxY&&this.maxY>t.minY}expand(e){return new t(this.x-e,this.y-e,this.w+2*e,this.h+2*e)}clone(){return new t(this.x,this.y,this.w,this.h)}static FromPoints(e){let n=1/0,r=1/0,o=-1/0,i=-1/0;for(const t of e)n=Math.min(n,t.x),r=Math.min(r,t.y),o=Math.max(o,t.x),i=Math.max(i,t.y);return new t(n,r,o-n,i-r)}};function kt(t,e,n){const r=e.sub(t),o=n.sub(t),i=r.x*r.x+r.y*r.y;if(0===i)return t;const s=Math.max(0,Math.min(1,(o.x*r.x+o.y*r.y)/i));return new bt(t.x+r.x*s,t.y+r.y*s)}function Pt(t,e,n){return t.dist(kt(e,n,t))}function St(t,e,n,r){const o=e.sub(t),i=r.sub(n),s=o.x*i.y-o.y*i.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(t),l=(a.x*i.y-a.y*i.x)/s,c=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&c>=0&&c<=1}function It(t,e,n,r){return St(t,e,n,r)?0:Math.min(Pt(t,n,r),Pt(e,n,r),Pt(n,t,e),Pt(r,t,e))}function Mt(t,e){if(!function(t){return t.length>=3&&t.every(t=>Number.isFinite(t.x)&&Number.isFinite(t.y))}(e))return!1;let n=!1;for(let r=0;r<e.length;r+=1){const o=e[r],i=e[(r+e.length-1)%e.length];if(Pt(t,i,o)<=1e-8)return!0;o.y>t.y!=i.y>t.y&&t.x<(i.x-o.x)*(t.y-o.y)/(i.y-o.y)+o.x&&(n=!n)}return n}var Tt=["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"],Ct=Object.fromEntries(Tt.map(t=>[t,`--land-shape-${t}`])),At={"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"};function Et(t){return{kind:"theme",slot:t}}function Lt(t){return{kind:"custom",value:t}}function Bt(t){return function(t){return!!t&&"object"==typeof t&&"theme"===t.kind&&Tt.includes(t.slot)}(t)||function(t){return!!t&&"object"==typeof t&&"custom"===t.kind&&"string"==typeof t.value}(t)}function Rt(t){return Ct[t]}function $t(t,e){return Bt(t)?t:e}function Nt(t){return"custom"===t.kind?t.value:`var(${Rt(t.slot)}, ${At[t.slot]})`}function zt(t,e){if("custom"===t.kind)return t.value;const n=Rt(t.slot),r=At[t.slot];return e?.(n,r)??r}function Ot(t){if("custom"!==t.kind)return!1;const e=t.value.trim().toLowerCase();return"transparent"===e||/^#[0-9a-f]{6}00$/.test(e)}function Wt(t,e){return t===e||!(!t||!e)&&(t.kind===e.kind&&("theme"===t.kind?t.slot===e.slot:t.value===e.value))}var Ht=class t{a;b;c;d;e;f;constructor(t,e,n,r,o,i){this.a=t,this.b=e,this.c=n,this.d=r,this.e=o,this.f=i}static Identity(){return new t(1,0,0,1,0,0)}static Translate(e,n){return new t(1,0,0,1,e,n)}static Rotate(e){const n=Math.cos(e),r=Math.sin(e);return new t(n,r,-r,n,0,0)}static Scale(e,n){return new t(e,0,0,n,0,0)}compose(e){return new t(this.a*e.a+this.c*e.b,this.b*e.a+this.d*e.b,this.a*e.c+this.c*e.d,this.b*e.c+this.d*e.d,this.a*e.e+this.c*e.f+this.e,this.b*e.e+this.d*e.f+this.f)}applyToPoint(t){return new bt(this.a*t.x+this.c*t.y+this.e,this.b*t.x+this.d*t.y+this.f)}determinant(){return this.a*this.d-this.b*this.c}getMaximumLinearScale(){const t=this.a*this.a+this.b*this.b+this.c*this.c+this.d*this.d,e=this.determinant(),n=Math.max(0,t*t-4*e*e);return Math.sqrt((t+Math.sqrt(n))/2)}tryInvert(e=0){const n=this.determinant(),r=Number.isFinite(e)?Math.max(0,e):0;if(!Number.isFinite(n)||Math.abs(n)<=r)return null;const o=1/n;return new t(this.d*o,-this.b*o,-this.c*o,this.a*o,(this.c*this.f-this.d*this.e)*o,(this.b*this.e-this.a*this.f)*o)}invert(){return this.tryInvert()??t.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(e,n,r,o=1,i=1){const s=t.Translate(e,n),a=0===r?t.Identity():t.Rotate(r),l=1===o&&1===i?t.Identity():t.Scale(o,i);return s.compose(a).compose(l)}};function Dt(t){return{id:t}}function Ft(t){return void 0!==t&&t<0?-1:1}function jt(t,e){if(void 0===e)return t;const n=2*Math.PI;return t+Math.round((e-t)/n)*n}function Ut(t,e){const n=2*Math.PI,r=((t-e+Math.PI)%n+n)%n-Math.PI;return Math.abs(r)}function Xt(t,e,n={}){if(!function(t){return[t.a,t.b,t.c,t.d,t.e,t.f].every(Number.isFinite)}(t)||![e.x,e.y,e.w,e.h].every(Number.isFinite))return null;const r=Number.isFinite(n.epsilon)?Math.max(0,n.epsilon??0):1e-8,o=Math.hypot(t.a,t.b),i=Math.hypot(t.c,t.d),s=t.determinant(),a=({rotation:n,scaleX:r,scaleY:o})=>{const i=e.center,s=t.applyToPoint(i),a={x:s.x-i.x,y:s.y-i.y,rotation:n,scaleX:r,scaleY:o};return Object.values(a).every(Number.isFinite)?a:null},l=r*Math.max(1,o,i),c=o<=l,d=i<=l;if(c||d){if(c&&d)return a({rotation:n.preferredRotation??0,scaleX:0,scaleY:0});if(c){const e=i*Ft(n.preferredScaleYSign);return a({rotation:jt(Math.atan2(-t.c/e,t.d/e),n.preferredRotation),scaleX:0,scaleY:e})}const e=o*Ft(n.preferredScaleXSign);return a({rotation:jt(Math.atan2(t.b/e,t.a/e),n.preferredRotation),scaleX:e,scaleY:0})}if(Math.abs(t.a*t.c+t.b*t.d)/(o*i)>r)return null;if(Math.abs(s)<=r*o*i)return null;const u=Math.atan2(t.b,t.a),p=o,h=i*(s<0?-1:1),f=[{rotation:jt(u,n.preferredRotation),scaleX:p,scaleY:h},{rotation:jt(u+Math.PI,n.preferredRotation),scaleX:-p,scaleY:-h}],g=Ft(n.preferredScaleXSign),m=Ft(n.preferredScaleYSign),y=t=>{let e=0;return void 0!==n.preferredScaleXSign&&Ft(t.scaleX)===g&&(e+=1),void 0!==n.preferredScaleYSign&&Ft(t.scaleY)===m&&(e+=1),{signMatches:e,rotationDistance:void 0===n.preferredRotation?0:Ut(t.rotation,n.preferredRotation)}},x=y(f[0]),w=y(f[1]),b=w.signMatches>x.signMatches||w.signMatches===x.signMatches&&w.rotationDistance<x.rotationDistance?f[1]:f[0];return a({rotation:b.rotation,scaleX:b.scaleX,scaleY:b.scaleY})}new bt(24,24);function Yt(t,e,n){const r=t.shapes.get(e);if(!r)return;const o=t.layers.getContainingParentIdForShape(r);o&&o!==r.parentId&&t.commands.reparentShapes({ids:[e],parentId:o},n)}var Kt=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],_t=["top_left","top_right","bottom_right","bottom_left"],qt=["free","aspect_ratio_locked"],Vt=["free"],Gt=["aspect_ratio_locked"];function Jt(t,e){return 0===e.rotation?t.clone():bt.RotWith(t,e.rotationCenter,e.rotation)}function Zt({axis:t,bounds:e,point:n}){return"horizontal"===t?new bt(e.minX+e.maxX-n.x,n.y):new bt(n.x,e.minY+e.maxY-n.y)}function Qt({localWidth:t,localHeight:e,scaleX:n,scaleY:r}){return{width:Math.abs(n)*t,height:Math.abs(r)*e}}function te({width:t,height:e,scaleX:n,scaleY:r}){const o=Math.abs(n),i=Math.abs(r);return{width:0===o?t:t/o,height:0===i?e:e/i}}function ee({requestedBounds:t,handleId:e,actualWidth:n,actualHeight:r,scaleX:o,scaleY:i,isResizingFromCenter:s}){return new vt(s?t.center.x-n/2:function(t){return"top_left"===t||"left"===t||"bottom_left"===t}(e)?o<0?t.minX:t.maxX-n:function(t){return"top_right"===t||"right"===t||"bottom_right"===t}(e)?o<0?t.maxX-n:t.minX:t.center.x-n/2,s?t.center.y-r/2:function(t){return"top_left"===t||"top"===t||"top_right"===t}(e)?i<0?t.minY:t.maxY-r:function(t){return"bottom_left"===t||"bottom"===t||"bottom_right"===t}(e)?i<0?t.maxY-r:t.minY:t.center.y-r/2,n,r)}function ne({outputBounds:t,cutoutLocalPolygons:e,localToOutput:n}){const r=e.filter(t=>t.length>=3);return 0===r.length?null:[re((o=t.expand(100),[new bt(o.minX,o.minY),new bt(o.maxX,o.minY),new bt(o.maxX,o.maxY),new bt(o.minX,o.maxY)])),...r.map(t=>re(t,n))].join(" ");var o}function re(t,e){const n=e?t.map(t=>e.applyToPoint(t)):t,r=n[0];return r?[`M ${oe(r.x)} ${oe(r.y)}`,...n.slice(1).map(t=>`L ${oe(t.x)} ${oe(t.y)}`),"Z"].join(" "):""}function oe(t){return Number.isFinite(t)?Number(t.toFixed(3)).toString():"0"}var ie=[{id:"top",normalizedAnchor:{x:.5,y:0},outwardNormal:{x:0,y:-1}},{id:"right",normalizedAnchor:{x:1,y:.5},outwardNormal:{x:1,y:0}},{id:"bottom",normalizedAnchor:{x:.5,y:1},outwardNormal:{x:0,y:1}},{id:"left",normalizedAnchor:{x:0,y:.5},outwardNormal:{x:-1,y:0}}];function se(t,e){return t.shapes.getUtil(e).getTerminalBindingPorts(e,{editor:t}).flatMap(n=>{const r=le(t,e,n);return r?[r]:[]})}function ae(t,e,n){const r=t.shapes.getUtil(e).getTerminalBindingPorts(e,{editor:t}).find(t=>t.id===n);return r?le(t,e,r):null}function le(t,e,n){const r=t.shapes.getUtil(e),o=r.getLocalBounds(e),i=t.shapes.computeLocalToPageTransform(e),s=function(t,e){const n=t.determinant();return!Number.isFinite(n)||Math.abs(n)<1e-12?bt.Zero():new bt((t.d*e.x-t.b*e.y)/n,(-t.c*e.x+t.a*e.y)/n).normalize()}(i,new bt(n.outwardNormal.x,n.outwardNormal.y));if(s.len2()<1e-12)return null;const a=new bt(o.x+o.w*n.normalizedAnchor.x,o.y+o.h*n.normalizedAnchor.y),l=i.applyToPoint(a),c=Math.max(64,o.w*i.getMaximumLinearScale(),o.h*i.getMaximumLinearScale()),d=r.resolveBindingPoint(e,{editor:t,rawPagePoint:l.add(s.mul(c)),oppositePagePoint:l.sub(s.mul(c))});return{id:n.id,normalizedAnchor:{...n.normalizedAnchor},pagePoint:d,pageOutwardNormal:s}}function ce(t){return[new bt(t.minX,t.minY),new bt(t.maxX,t.minY),new bt(t.maxX,t.maxY),new bt(t.minX,t.maxY)]}function de(t,e,n,r){const o=e.sub(t),i=r.sub(n),s=o.x*i.y-o.y*i.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(t),l=(a.x*i.y-a.y*i.x)/s,c=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&c>=0&&c<=1?l:null}function ue(t,e,n){const r=t[e];return"number"==typeof r&&Number.isFinite(r)?r:n}var pe=class{getPositionedBounds(t){const e=this.getLocalBounds(t);return new vt(e.x+t.x,e.y+t.y,e.w,e.h)}getRenderBounds(t){return this.getLocalBounds(t)}getPointHitTestBounds(t,e){return this.getPositionedBounds(t)}getExportBounds(t){return this.getRenderBounds(t)}getChildClipLocalBounds(t){return null}getChildClipLocalPolygons(t){const e=this.getChildClipLocalBounds(t);return e?[ce(e)]:null}getChildExportClipLocalBounds(t){return this.getChildClipLocalBounds(t)}getChildExportClipLocalPolygons(t){const e=this.getChildExportClipLocalBounds(t);return e?[ce(e)]:null}getSelectionResizeLocalBounds(t){return this.getLocalBounds(t)}resizeSelectionBounds(t,e){const n=this.getSelectionResizeLocalBounds(t);if(0!==n.x||0!==n.y)throw new Error(`Shape util "${this.type}" must implement resizeSelectionBounds for non-origin local bounds`);const r=te({width:e.selectionLocalBounds.w,height:e.selectionLocalBounds.h,scaleX:t.scaleX,scaleY:t.scaleY}),o=e.scaleX<0!=e.scaleY<0?2*e.selectionRotation-t.rotation:t.rotation,i=this.validateProps({...t.props,w:r.width,h:r.height}),s=ue(i,"w",r.width),a=ue(i,"h",r.height),l=Qt({localWidth:s,localHeight:a,scaleX:t.scaleX,scaleY:t.scaleY}),c=Jt(ee({requestedBounds:e.selectionLocalBounds,handleId:e.handleId,actualWidth:l.width,actualHeight:l.height,scaleX:e.scaleX,scaleY:e.scaleY,isResizingFromCenter:e.isResizingFromCenter}).center,{rotation:e.selectionRotation,rotationCenter:e.selectionRotationCenter});return{id:t.id,x:c.x-s/2,y:c.y-a/2,rotation:o,scaleX:e.scaleX<0?-t.scaleX:t.scaleX,scaleY:e.scaleY<0?-t.scaleY:t.scaleY,props:i}}getAllowedSelectionResizeModes(t,e){return qt}getSelectionResizeHandleIds(t,e){return Kt}flipSelectionBounds(t,e){const n=this.getSelectionPagePoints(t);if(n){const r=n.map(t=>{const n=0===e.selectionRotation?t.clone():bt.RotWith(t,e.selectionRotationCenter,-e.selectionRotation),r=Zt({axis:e.axis,bounds:e.selectionBounds,point:n});return 0===e.selectionRotation?r:bt.RotWith(r,e.selectionRotationCenter,e.selectionRotation)}),o=this.getSelectionPageMiddlePoint(t),i=o?(()=>{const t=0===e.selectionRotation?o.clone():bt.RotWith(o,e.selectionRotationCenter,-e.selectionRotation),n=Zt({axis:e.axis,bounds:e.selectionBounds,point:t});return 0===e.selectionRotation?n:bt.RotWith(n,e.selectionRotationCenter,e.selectionRotation)})():void 0;return this.updateSelectionPagePoints(t,{pagePoints:[r[0],r[1]],pageMiddlePoint:i})}const r=this.getSelectionResizeLocalBounds(t),o=0===e.selectionRotation?e.selectionLocalBounds.center:bt.RotWith(e.selectionLocalBounds.center,e.selectionRotationCenter,e.selectionRotation);return{id:t.id,x:o.x-r.center.x,y:o.y-r.center.y,rotation:2*e.selectionRotation-t.rotation,scaleX:"horizontal"===e.axis?-t.scaleX:t.scaleX,scaleY:"vertical"===e.axis?-t.scaleY:t.scaleY}}updateSelectionPagePoints(t,e){throw new Error(`Shape util "${this.type}" must implement updateSelectionPagePoints before selection can transform point-defined geometry`)}getSelectionPagePoints(t){return null}getSelectionPageMiddlePoint(t){return null}contributesToSelectionFrame(t,e){return!0}canParticipateInSelectionResize(t,e){return!0}canParticipateInSelectionFlip(t,e){return this.canParticipateInSelectionResize(t,e)}canParticipateInSelectionRotation(t,e){return!0}canUseSelectionResizeHandles(t,e){return this.canParticipateInSelectionResize(t,e)}canUseSelectionRotateHandle(t,e){return this.canParticipateInSelectionRotation(t,e)}canParticipateInSelectionTranslation(t,e){return!0}getSelectionTargetId(t,e){return t.id}getHoverTargetId(t,e){return t.id}getHoverDecorationTargetId(t,e){return t.id}getTranslateTargetId(t,e){return t.id}isSelectionTransformContainer(t){return!1}shouldRotateDescendants(t){return this.isSelectionTransformContainer(t)}shouldResizeDescendants(t){return!1}getResizeToFitDescendantsProps(t,e){return null}getMinimumChildCount(t){return 0}contributesToExportBounds(t){return!0}canUngroupChildren(t){return!1}getGroupingShapeCreateInput(t){return null}canStartTranslateFromSelectionBounds(t,e){return!0}canSnap(t,e){return!0}canSnapChildrenToSelf(t){return!1}getBoundsSnapGeometry(t){return{}}getHandleSnapGeometry(t){return{outline:ce(this.getLocalBounds(t))}}getPositionedOutlineVertices(t){const e=this.getPositionedBounds(t);return[new bt(e.minX,e.minY),new bt(e.maxX,e.minY),new bt(e.maxX,e.maxY),new bt(e.minX,e.maxY)]}getSelectionFramePositionedOutlineVertices(t,e){return null}getSelectionHandleAnchors(t,e){return{terminalHandleAnchors:[],middleHandleAnchors:[]}}getSelectionOverlayInfo(t,e){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,pathStyle:null,bindingSegments:[]}}getLabelPathGeometry(t,e){return null}isWrappedByBrush(t,e){return 0===e.pageOutlineVertices.length?!!e.pageBounds&&e.brushBounds.containsBox(e.pageBounds):e.pageOutlineVertices.every(t=>e.brushBounds.containsPoint(t))}canSelectByBrush(t,e){return!e.isWrapping||this.isWrappedByBrush(t,e)}getLocalTransform(t){const e=this.getLocalBounds(t).center;return Ht.Translate(t.x+e.x,t.y+e.y).compose(Ht.Rotate(t.rotation)).compose(Ht.Scale(t.scaleX,t.scaleY)).compose(Ht.Translate(-e.x,-e.y))}getPositionedTransform(t){const e=this.getLocalBounds(t).center,n=new bt(t.x+e.x,t.y+e.y);return Ht.Translate(n.x,n.y).compose(Ht.Rotate(t.rotation)).compose(Ht.Scale(t.scaleX,t.scaleY)).compose(Ht.Translate(-n.x,-n.y))}canEdit(t){return!1}canReceiveChildren(t){return!1}getChildTransformPolicy(t){return"isometry"}canReceiveChild(t,e){return this.canReceiveChildren(t)}isChildVisible(t,e,n){return!0}getChildPlacementMeta(t,e,n){return e.meta}canAutomaticallyReceiveChildren(t){return this.canReceiveChildren(t)}canBeDirectlyBrushSelected(t){return!0}canReceiveTerminalBinding(t,e){return!1}canUseTerminalBindingPortHandles(t,e){return this.canReceiveTerminalBinding(t,e)}getTerminalBindingPorts(t,e){return this.canReceiveTerminalBinding(t,e)?ie:[]}getTerminalBindingOutlines(t,e){return this.canReceiveTerminalBinding(t,e)?[{points:this.getPositionedOutlineVertices(t),closed:!0}]:[]}canCopyToClipboard(t,e){return!0}onEditEnd(t,e){}hitTest(t,e,n){return this.getPositionedBounds(t).containsPoint(e)}hitTestBindingTarget(t,e,n){return this.hitTest(t,e,n)}hitTestLineSegment(t,e){return function(t,e,n){if(n.containsPoint(t)||n.containsPoint(e))return!0;const r=ce(n);for(let o=0;o<r.length;o+=1){const n=r[o],i=r[(o+1)%r.length];if(n&&i&&null!==de(t,e,n,i))return!0}return!1}(e.positionedStart,e.positionedEnd,this.getPositionedBounds(t).expand(e.positionedMargin))}resolveBindingPoint(t,e){this.getPositionedBounds(t);const n=e.editor.shapes.computePositionedToPageTransform(t),r=n.tryInvert();if(!r)return e.rawPagePoint;const o=function(t,e,n){if(n.length<2)return null;let r=Number.POSITIVE_INFINITY;const o=e.sub(t);for(let i=0;i<n.length;i+=1){const o=n[i],s=n[(i+1)%n.length]??n[0];if(!o||!s)continue;const a=de(t,e,o,s);null===a||a<=1e-6||a>=r||(r=a)}return Number.isFinite(r)?t.add(o.mul(r)):null}(r.applyToPoint(e.rawPagePoint),r.applyToPoint(e.oppositePagePoint),this.getPositionedOutlineVertices(t));return o?n.applyToPoint(o):e.rawPagePoint}},he=class{editor;id;parent;children=new Map;currentChild=null;initial=null;constructor(t,e,n){this.editor=t,this.id=e,this.parent=n}addChild(t){this.children.set(t.id,t)}enter(t){if(this.onEnter(t),!this.initial)return;const e=this.children.get(this.initial);if(!e)throw new Error(`Missing child state "${this.initial}" on "${this.id}"`);this.currentChild=e,e.enter(t)}exit(t){this.currentChild&&(this.currentChild.exit(t),this.currentChild=null),this.onExit(t)}transition(t,e){if(!this.parent){const n=this.children.get(t);if(!n)throw new Error(`Missing root child state "${t}" on tool "${this.id}"`);if(this.currentChild===n)return;return this.currentChild?.exit(e),this.currentChild=n,void n.enter(e)}this.parent.transition(t,e)}isInInitialState(){return!this.currentChild||!!this.initial&&(this.currentChild.id===this.initial&&this.currentChild.isInInitialState())}dispatch(t,e){if(this.currentChild)return this.currentChild.dispatch(t,e);switch(t.type){case"pointer":return this.handlePointerEvent(t,e);case"keyboard":return this.handleKeyboardEvent(t,e);case"wheel":return this.onWheel(t,e);case"tick":return this.onTick(t,e);case"cancel":return this.onCancel(t,e)}}onEnter(t){}onExit(t){}onPointerDown(t,e){}onPointerMove(t,e){}onPointerUp(t,e){}onCancel(t,e){}onKeyDown(t,e){}onKeyUp(t,e){}onWheel(t,e){}onTick(t,e){}handlePointerEvent(t,e){switch(t.name){case"pointer_down":return this.onPointerDown(t,e);case"pointer_move":return this.onPointerMove(t,e);case"pointer_up":return this.onPointerUp(t,e);case"pointer_cancel":return this.onCancel({type:"cancel",reason:"pointer_cancel"},e)}}handleKeyboardEvent(t,e){return"key_down"===t.name?this.onKeyDown(t,e):this.onKeyUp(t,e)}};function fe(t){return Math.min(1,Math.max(0,(96-t)/96))}function ge(t,e,n){if(e.w<=0||e.h<=0||n<=0)return bt.Zero();const r=Math.min(n,32),o=fe(t.x),i=fe(e.w-t.x),s=fe(t.y),a=1.25*(i-o)*r,l=1.25*(fe(e.h-t.y)-s)*r;return 0===a&&0===l?bt.Zero():new bt(a,l)}Math.PI,Math.PI,Math.PI;function me(t,e,n,r={}){let o=!0;return e.graph.effect(t,()=>{e.get(),o&&!1===r.fireImmediately?o=!1:(o=!1,n())})}function ye(t){return Math.max(0,Math.min(1,t))}function xe(t,e,n){return t.shapes.computePositionedToPageTransform(e).applyToPoint(function(t,e,n){const r=t.shapes.computePositionedBounds(e);return new bt(r.minX+r.w*n.x,r.minY+r.h*n.y)}(t,e,n))}function we(t,e,n,r){return function(t,e,n,r){return t.shapes.getUtil(e).resolveBindingPoint(e,{editor:t,rawPagePoint:n,oppositePagePoint:r})}(t,e,xe(t,e,n),r)}var be=2*Math.PI;function ve(t,e){const n="start"===e?t.props.start:t.props.end;return function(t,e){if(0===t.rotation&&1===t.scaleX&&1===t.scaleY)return e;const n=new bt(t.x+t.props.w/2,t.y+t.props.h/2),r=e.sub(n),o=new bt(r.x*t.scaleX,r.y*t.scaleY);return n.add(o.rot(t.rotation))}(t,new bt(t.x+n.x,t.y+n.y))}function ke(t,e,n){const r="start"===n?e.props.start:e.props.end;return t.shapes.computeLocalToPageTransform(e).applyToPoint(new bt(r.x,r.y))}function Pe(t){return"start"===t?"end":"start"}function Se(t,e,n,r){const o=t.shapes.computeLocalToPageTransform(e).tryInvert();if(!o)return null;const i=Me(o.applyToPoint(n),o.applyToPoint(r)),s=t.shapes.getUtil(e),a={...e,props:{...e.props,w:i.w,h:i.h,start:i.start,end:i.end}},l=Xt(s.getLocalTransform(e).compose(Ht.Translate(i.x,i.y)),s.getLocalBounds(a),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY});return l?{...a,...l}:null}function Ie(t,e,n,r){return Se(t,e,"start"===n?r:ke(t,e,"start"),"end"===n?r:ke(t,e,"end"))}function Me(t,e){const n=$e(t.x,e.x),r=$e(t.y,e.y);return{x:n.origin,y:r.origin,w:n.size,h:r.size,start:{x:n.startOffset,y:r.startOffset},end:{x:n.endOffset,y:r.endOffset}}}function Te(t){return Oe(new bt(t.props.start.x,t.props.start.y).add(new bt(t.x,t.y)),new bt(t.props.end.x,t.props.end.y).add(new bt(t.x,t.y)),t.props.bend)}function Ce(t){return Oe(new bt(t.props.start.x,t.props.start.y),new bt(t.props.end.x,t.props.end.y),t.props.bend)}function Ae(t,e,n){const r=bt.Med(t,e),o=e.sub(t);if(o.len()<1e-6)return 0;const i=o.per().normalize();return-Xe(n.sub(r),i)}function Ee(t){const e="curved"===t.type&&t.path.includes(" A "),n=e?null:function(t){const e=[];let n=0;for(let r=1;r<t.length;r+=1){const o=t[r-1].dist(t[r]);e.push(o),n+=o}return{length:n,segmentLengths:e}}(t.points),r=e?t.arc.length:n?.length??0,o=n?Le(t.points,n,t.middle,.5):.5;return{length:r,defaultPosition:.5,getPointAt(r){const i=Re(r);return e?Fe(t.start.point,t.end.point,t.arc,i):function(t,e,n){const r=t[0]??bt.Zero();if(!e||e.length<=1e-6)return r.clone();const o=e.length*n;let i=0;for(let s=0;s<e.segmentLengths.length;s+=1){const n=e.segmentLengths[s];if(o<=i+n||s===e.segmentLengths.length-1){const e=t[s],r=t[s+1],a=n<=1e-6?0:(o-i)/n;return e.add(r.sub(e).mul(Re(a)))}i+=n}return(t[t.length-1]??r).clone()}(t.points,n,Be(i,o))},getNearestPosition:(r,i)=>e?function(t,e,n=.5){const r=e.sub(t.arc.center);if(r.len2()<=1e-12)return Re(n);const o=t.arc.center.add(r.normalize().mul(t.arc.radius)),i=De(t.start.point,t.end.point,t.arc);if(Math.abs(i)<=1e-6)return Re(n);const s=De(t.start.point,o,t.arc);if(Math.abs(s)<=Math.abs(i)+1e-6)return Re(s/i);const a=e.dist2(t.start.point),l=e.dist2(t.end.point);return Math.abs(a-l)<=1e-8?n<=.5?0:1:a<l?0:1}(t,r,i?.hintPosition):function(t,e){const n=Re(t),r=Re(e);return n<=r?r<=1e-6?.5:n/r*.5:1-r<=1e-6?.5:.5+(n-r)/(1-r)*.5}(Le(t.points,n,r,Be(i?.hintPosition??.5,o)),o)}}function Le(t,e,n,r=.5){if(!e||e.length<=1e-6)return Re(r);let o=0,i=Re(r),s=1/0;for(let a=0;a<e.segmentLengths.length;a+=1){const l=t[a],c=t[a+1],d=e.segmentLengths[a],u=c.sub(l),p=d<=1e-6?0:Re(Xe(n.sub(l),u)/u.len2()),h=l.add(u.mul(p)),f=(o+d*p)/e.length,g=h.dist2(n),m=g<s-1e-8,y=Math.abs(g-s)<=1e-8&&Math.abs(f-r)<Math.abs(i-r);(m||y)&&(s=g,i=f),o+=d}return Re(i)}function Be(t,e){const n=Re(t),r=Re(e);return n<=.5?r*n*2:r+(1-r)*(n-.5)*2}function Re(t){return Math.max(0,Math.min(1,t))}function $e(t,e){const n=Math.min(t,e),r=Math.max(t,e);return Math.abs(r-n)<1e-6?{origin:n-.5,size:1,startOffset:.5,endOffset:.5}:{origin:n,size:r-n,startOffset:t-n,endOffset:e-n}}function Ne(t){return Number.isFinite(t)?Number(t.toFixed(3)).toString():"0"}function ze(t,e=0){return function(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}(t,e)}function Oe(t,e,n){const r=ze(n,0),o=function(t,e,n){const r=bt.Med(t,e),o=e.sub(t),i=o.len()?o.per().normalize():new bt(0,-1);return r.add(i.mul(-n))}(t,e,r),i=function(t,e,n){const r=function(t,e,n){const r=-2*(t.x*(e.y-n.y)-t.y*(e.x-n.x)+e.x*n.y-n.x*e.y);if(Math.abs(r)<1e-6)return null;const o=((t.x*t.x+t.y*t.y)*(n.y-e.y)+(e.x*e.x+e.y*e.y)*(t.y-n.y)+(n.x*n.x+n.y*n.y)*(e.y-t.y))/r,i=((t.x*t.x+t.y*t.y)*(e.x-n.x)+(e.x*e.x+e.y*e.y)*(n.x-t.x)+(n.x*n.x+n.y*n.y)*(t.x-e.x))/r;return Number.isFinite(o)&&Number.isFinite(i)?new bt(o,i):null}(t,e,n);if(!r)return null;const o=r.dist(t);if(o<1e-6)return null;const i=(a=t,l=e,c=n,(c.x-a.x)*(l.y-a.y)-(l.x-a.x)*(c.y-a.y)<0?1:0),s=function(t,e,n){const r=t.dist(n),o=n.dist(e),i=e.dist(t);if(o<1e-6||i<1e-6)return 0;const s=(o*o+i*i-r*r)/(2*o*i);return 2*Math.acos(Math.max(-1,Math.min(1,s)))}(t,e,n);var a,l,c;if(!Number.isFinite(s))return null;const d=Math.PI>s?1:0,u=(be-s)*(i?1:-1);return{center:r,radius:o,largeArcFlag:d,sweepFlag:i,size:u,length:Math.abs(u*o)}}(t,o,e),s=Math.abs(r)<1e-6||null===i||0===i.length||!Number.isFinite(i.length)||!Number.isFinite(i.radius),a=s?[t,e]:He(t,e,i,24),l=s||null===i?`M ${Ne(t.x)} ${Ne(t.y)} L ${Ne(e.x)} ${Ne(e.y)}`:`M ${Ne(t.x)} ${Ne(t.y)} A ${Ne(i.radius)} ${Ne(i.radius)} 0 ${i.largeArcFlag} ${i.sweepFlag} ${Ne(e.x)} ${Ne(e.y)}`,c={start:{terminal:"start",point:t,handle:t},end:{terminal:"end",point:e,handle:e},middle:o,bend:r,points:a,bounds:vt.FromPoints(a),path:l};return s?{type:"straight",...c,arc:null}:{type:"curved",...c,arc:i}}function We({start:t,end:e,middle:n,bend:r,arc:o,startHandle:i=t,endHandle:s=e}){const a=De(t,e,o);if(Math.abs(a)<1e-6||!Number.isFinite(a)||!Number.isFinite(o.radius)||o.radius<1e-6){const o=Oe(t,e,0);return{...o,start:{...o.start,handle:i},end:{...o.end,handle:s},middle:n,bend:r}}const l={center:o.center,radius:o.radius,largeArcFlag:Math.abs(a)>Math.PI?1:0,sweepFlag:o.sweepFlag,size:a,length:Math.abs(a*o.radius)},c=He(t,e,l,24),d=`M ${Ne(t.x)} ${Ne(t.y)} A ${Ne(l.radius)} ${Ne(l.radius)} 0 ${l.largeArcFlag} ${l.sweepFlag} ${Ne(e.x)} ${Ne(e.y)}`;return{type:"curved",start:{terminal:"start",point:t,handle:i},end:{terminal:"end",point:e,handle:s},middle:n,arc:l,bend:r,points:c,bounds:vt.FromPoints(c),path:d}}function He(t,e,n,r){const o=[],i=bt.Angle(n.center,t),s=De(t,e,n);for(let a=0;a<=r;a++){const t=a/r;o.push(je(n.center,n.radius,i+s*t))}return o}function De(t,e,n){return function(t,e,n){const r=e-t;return n?(r%be+be)%be:-((t-e)%be+be)%be}(bt.Angle(n.center,t),bt.Angle(n.center,e),n.sweepFlag)}function Fe(t,e,n,r){const o=bt.Angle(n.center,t),i=De(t,e,n);return je(n.center,n.radius,o+i*r)}function je(t,e,n){return t.add(new bt(Math.cos(n)*e,Math.sin(n)*e))}function Ue(t,e,n){const r=n.sub(e),o=r.x*r.x+r.y*r.y;if(0===o)return t.dist(e);const i=t.sub(e),s=Math.max(0,Math.min(1,Xe(i,r)/o)),a=e.add(r.mul(s));return t.dist(a)}function Xe(t,e){return t.x*e.x+t.y*e.y}var Ye=["solid","dashed","dotted"];function Ke(t){return"string"==typeof t&&Ye.includes(t)}function _e(t){return!!t&&"shape"===t.typeName&&"arrow"===t.type}function qe(t){return!!t&&"binding"===t.typeName&&"arrow"===t.type}function Ve(t,e,n){return t.bindings.getFromShape(e.id).find(t=>qe(t)&&t.props.terminal===n)??null}function Ge(t,e,n){const r=ke(t,e,n),o=Ve(t,e,n);if(!o)return{terminal:n,binding:null,target:null,handlePagePoint:r,boundaryPagePoint:r,isArcBoundaryPoint:!0};const i=t.shapes.get(o.toId);return!i||_e(i)?{terminal:n,binding:o,target:null,handlePagePoint:r,boundaryPagePoint:r,isArcBoundaryPoint:!0}:{terminal:n,binding:o,target:i,handlePagePoint:xe(t,i,o.props.normalizedAnchor),boundaryPagePoint:r,isArcBoundaryPoint:!1}}function Je(t,e){const n=Ge(t,e,"start"),r=Ge(t,e,"end"),o=en(t,e,n.handlePagePoint,r.handlePagePoint);return"curved"===o.type&&(an(t,n,o,"start"),an(t,r,o,"end")),{info:nn(o,n,r),fullInfo:o,bindingSegments:[ln(n,o),ln(r,o)].filter(t=>null!==t)}}function Ze(t,e){if(!Ve(t,e,"start")&&!Ve(t,e,"end"))return Ce(e);const n=t.shapes.computeLocalToPageTransform(e).tryInvert();return n?function(t,e,n){const r=tn(e.info,n);if("curved"!==e.info.type)return r;const o=Oe(n.applyToPoint(e.fullInfo.start.point),n.applyToPoint(e.fullInfo.end.point),t.props.bend);if("curved"!==o.type)return r;const i=n.applyToPoint(e.info.start.point),s=n.applyToPoint(e.info.end.point),a=function(t,e,n){const r=e.sub(t);if(r.len2()<1e-12)return null;const o=bt.Med(t,e),i=r.per().normalize(),s=n.sub(o),a=s.x*i.x+s.y*i.y;return o.add(i.mul(a))}(i,s,o.arc.center);if(!a)return r;const l={center:a,radius:a.dist(i),sweepFlag:o.arc.sweepFlag},c=Fe(i,s,l,.5);return We({start:i,end:s,middle:c,bend:Ae(i,s,c),arc:l,startHandle:n.applyToPoint(e.info.start.handle),endHandle:n.applyToPoint(e.info.end.handle)})}(e,Je(t,e),n):Oe(new bt(e.props.start.x,e.props.start.y),new bt(e.props.end.x,e.props.end.y),e.props.bend)}function Qe(t,e,n){return{...t,start:{...t.start,handle:e},end:{...t.end,handle:n}}}function tn(t,e){const n=t=>e.applyToPoint(t),r=n(t.start.point),o=n(t.end.point),i=n(t.middle),s=t.points.map(n),a=s.map((t,e)=>`${0===e?"M":"L"} ${sn(t.x)} ${sn(t.y)}`).join(" "),l={start:{...t.start,point:r,handle:n(t.start.handle)},end:{...t.end,point:o,handle:n(t.end.handle)},middle:i,bend:Ae(r,o,i),points:s,bounds:vt.FromPoints(s),path:a};if("straight"===t.type)return{...t,...l};const c=n(t.arc.center),d={...t.arc,center:c,radius:c.dist(r),sweepFlag:e.determinant()<0?1===t.arc.sweepFlag?0:1:t.arc.sweepFlag};return function(t){const e=Math.hypot(t.a,t.b),n=Math.hypot(t.c,t.d),r=Math.max(1,e,n);return Math.abs(e-n)<=1e-8*r&&Math.abs(t.a*t.c+t.b*t.d)<=1e-8*r*r}(e)?We({start:r,end:o,middle:i,bend:l.bend,arc:d,startHandle:l.start.handle,endHandle:l.end.handle}):{...t,...l,arc:d}}function en(t,e,n,r){const o=t.shapes.computeLocalToPageTransform(e),i=o.tryInvert();return i?tn(Oe(i.applyToPoint(n),i.applyToPoint(r),e.props.bend),o):Oe(n,r,e.props.bend)}function nn(t,e,n){if(e.boundaryPagePoint.dist2(t.start.point)<1e-10&&n.boundaryPagePoint.dist2(t.end.point)<1e-10)return Qe(t,e.handlePagePoint,n.handlePagePoint);if("straight"===t.type)return Qe(Oe(e.boundaryPagePoint,n.boundaryPagePoint,0),e.handlePagePoint,n.handlePagePoint);if(t.path.includes(" A "))return We({start:e.boundaryPagePoint,end:n.boundaryPagePoint,middle:Fe(e.boundaryPagePoint,n.boundaryPagePoint,t.arc,.5),bend:t.bend,arc:t.arc,startHandle:e.handlePagePoint,endHandle:n.handlePagePoint});const r=rn(t.points,e.boundaryPagePoint),o=rn(t.points,n.boundaryPagePoint),i=[e.boundaryPagePoint];for(let a=Math.floor(r)+1;a<=Math.floor(o);a+=1){const e=t.points[a];e&&a<o&&i.push(e)}i.push(n.boundaryPagePoint);const s=function(t){if(0===t.length)return bt.Zero();const e=[];let n=0;for(let o=0;o<t.length-1;o+=1){const r=t[o].dist(t[o+1]);e.push(r),n+=r}let r=n/2;for(let o=0;o<e.length;o+=1){const n=e[o];if(r<=n){const e=t[o];return e.add(t[o+1].sub(e).mul(0===n?0:r/n))}r-=n}return t[t.length-1]}(i);return{...t,start:{...t.start,point:e.boundaryPagePoint,handle:e.handlePagePoint},end:{...t.end,point:n.boundaryPagePoint,handle:n.handlePagePoint},middle:s,points:i,bounds:vt.FromPoints(i),path:on(i),bend:Ae(e.boundaryPagePoint,n.boundaryPagePoint,s)}}function rn(t,e){let n=0,r=1/0;for(let o=0;o<t.length-1;o+=1){const i=t[o],s=t[o+1].sub(i),a=s.len2(),l=0===a?0:Math.max(0,Math.min(1,((e.x-i.x)*s.x+(e.y-i.y)*s.y)/a)),c=i.add(s.mul(l)).dist2(e);c<r&&(r=c,n=o+l)}return n}function on(t){return t.map((t,e)=>`${0===e?"M":"L"} ${sn(t.x)} ${sn(t.y)}`).join(" ")}function sn(t){return Number(t.toFixed(3)).toString()}function an(t,e,n,r){if(!e.target)return void(e.isArcBoundaryPoint=!0);const o=un(t.shapes.getPageOutlineVertices(e.target.id),n,r);o?(e.boundaryPagePoint=o,e.isArcBoundaryPoint=!0):e.isArcBoundaryPoint=!1}function ln(t,e){if(!t.binding)return null;const n=function(t,e){return{terminal:t.terminal,anchorPagePoint:t.handlePagePoint,boundaryPagePoint:t.boundaryPagePoint,guidePath:"curved"===e.type&&t.isArcBoundaryPoint?dn(t.terminal,t.handlePagePoint,t.boundaryPagePoint,e):null}}(t,e);return{terminal:n.terminal,anchorPagePoint:n.anchorPagePoint,boundaryPagePoint:n.boundaryPagePoint,guidePath:n.guidePath}}function cn(t,{arrow:e,terminal:n,target:r,anchorPagePoint:o,fallbackBoundaryPagePoint:i}){const s=function(t,e,n){return Ge(t,e,n).handlePagePoint}(t,e,Pe(n)),a=en(t,e,"start"===n?o:s,"end"===n?o:s);if("curved"!==a.type)return{terminal:n,anchorPagePoint:o,boundaryPagePoint:i,guidePath:null};const l=un(t.shapes.getPageOutlineVertices(r.id),a,n);return l?{terminal:n,anchorPagePoint:o,boundaryPagePoint:l,guidePath:dn(n,o,l,a)}:{terminal:n,anchorPagePoint:o,boundaryPagePoint:i,guidePath:null}}function dn(t,e,n,r){if(r.path.includes(" A "))return function({terminal:t,handlePagePoint:e,boundaryPagePoint:n,fullInfo:r}){if(e.dist(n)<1e-6)return null;const o="start"===t?r.arc.sweepFlag:function(t){return t?0:1}(r.arc.sweepFlag),i={center:r.arc.center,radius:r.arc.radius,sweepFlag:o};return We({start:e,end:n,middle:Fe(e,n,i,.5),bend:r.bend,arc:i}).path}({terminal:t,handlePagePoint:e,boundaryPagePoint:n,fullInfo:r});const o=rn(r.points,n),i=[e];if("start"===t)for(let s=1;s<=Math.floor(o);s+=1){const t=r.points[s];t&&s<o&&i.push(t)}else for(let s=r.points.length-2;s>=Math.ceil(o);s-=1){const t=r.points[s];t&&s>o&&i.push(t)}return i.push(n),on(i)}function un(t,e,n){const r=[];for(let o=0;o<e.points.length-1;o+=1){const n=e.points[o],i=e.points[o+1];for(let e=0;e<t.length;e+=1){const s=t[e],a=t[(e+1)%t.length];if(!s||!a)continue;const l=pn(n,i,s,a);l&&r.push({point:l.point,position:o+l.t})}}return 0===r.length?null:(r.sort((t,e)=>t.position-e.position),"start"===n?r[0].point:r[r.length-1].point)}function pn(t,e,n,r){const o=e.sub(t),i=r.sub(n),s=o.x*i.y-o.y*i.x;if(Math.abs(s)<1e-9)return null;const a=n.sub(t),l=(a.x*i.y-a.y*i.x)/s,c=(a.x*o.y-a.y*o.x)/s;return l<-1e-9||l>1.000000001||c<-1e-9||c>1.000000001?null:{point:t.add(o.mul(Math.max(0,Math.min(1,l)))),t:Math.max(0,Math.min(1,l))}}function hn(t,e){const n=t.shapes.getPageBounds(e.id)??t.shapes.computePageBounds(e);return n.w*n.h}function fn(t,e){return t.shapes.getUtil(e).canReceiveChildren(e)}function gn(t,e){return!(!e||_e(e))&&t.shapes.getUtil(e).canReceiveTerminalBinding(e,{editor:t})}function mn(t,e,n){const r=fn(t,e),o=fn(t,n);if(r!==o)return r?1:-1;if(r&&o){const r=hn(t,e)-hn(t,n);if(Math.abs(r)>1e-6)return r}return 0}function yn(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function xn(t){if(t)return{shapes:[t]}}var wn=class extends wt{type="arrow";getDefaultProps(){return{terminal:"start",normalizedAnchor:{x:.5,y:.5}}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps(),r=e.normalizedAnchor&&"object"==typeof e.normalizedAnchor?e.normalizedAnchor:n.normalizedAnchor;return{terminal:"end"===e.terminal?"end":n.terminal,normalizedAnchor:{x:Math.min(1,Math.max(0,yn(r.x,n.normalizedAnchor.x))),y:Math.min(1,Math.max(0,yn(r.y,n.normalizedAnchor.y)))}}}canBind(t,e,n){return _e(n.fromShape)&&gn(t,n.toShape)}getExclusiveBindingKey(t){return`${t.fromId}:${t.props.terminal}`}onBindingCreate(t,e){return xn(this.syncArrowTerminal(t,e))}onBindingUpdate(t,e,n){return xn(this.syncArrowTerminal(t,n))}onBindingLoad(t,e){return xn(this.syncArrowTerminal(t,e))}getGeometryDependentShapeIds(t,e,n){return"to"===n.role?[e.fromId]:[]}onAfterShapeChange(t,e,n){return xn(this.syncArrowTerminal(t,e))}onBeforeDeleteShape(t,e,n){if("from"===n.role)return{deleteBindingIds:[e.id]};const r=t.shapes.get(e.fromId);if(!_e(r))return{deleteBindingIds:[e.id]};const o=this.resolveTerminalPagePoint(t,e);return{shapes:[o?Ie(t,r,e.props.terminal,o)??r:r],deleteBindingIds:[e.id]}}onBeforeDeleteBinding(t,e){const n=t.shapes.get(e.fromId);if(!_e(n))return{deleteBindingIds:[e.id]};const r=this.resolveTerminalPagePoint(t,e);return{shapes:[r?Ie(t,n,e.props.terminal,r)??n:n],deleteBindingIds:[e.id]}}syncArrowTerminal(t,e){if(!qe(e))return null;const n=t.shapes.get(e.fromId);if(!_e(n))return null;const r=this.resolveTerminalPagePoint(t,e);return r?ke(t,n,e.props.terminal).dist(r)<1e-6?null:Ie(t,n,e.props.terminal,r):null}resolveTerminalPagePoint(t,e){if(!qe(e))return null;const n=t.shapes.get(e.fromId),r=t.shapes.get(e.toId);if(!_e(n)||!r||_e(r))return null;const o=ke(t,n,Pe(e.props.terminal)),i=we(t,r,e.props.normalizedAnchor,o);return cn(t,{arrow:n,terminal:e.props.terminal,target:r,anchorPagePoint:xe(t,r,e.props.normalizedAnchor),fallbackBoundaryPagePoint:i}).boundaryPagePoint}};function bn(t){return Object.freeze({id:t,kind:"api"})}function vn(t,e,n="user"){if(e.parentId?.startsWith("shape:")){const n=t.shapes.get(e.parentId);if(!n||!t.shapes.computeLocalToPageTransform(n).tryInvert())throw new Error("Cannot create an arrow inside a singular parent transform")}const[r]=t.commands.createShapes([{type:"arrow",x:e.startPagePoint.x,y:e.startPagePoint.y,parentId:e.parentId,props:e.props,meta:e.meta}],{source:n,autoReparent:!1});if(!_e(r))throw new Error("Failed to create arrow shape");const o=Se(t,r,e.startPagePoint,e.endPagePoint);if(!o)throw new Error("Cannot create an arrow inside a singular parent transform");t.commands.updateShapes([{id:r.id,x:o.x,y:o.y,rotation:o.rotation,scaleX:o.scaleX,scaleY:o.scaleY,props:{...o.props}}],{source:n}),e.startBinding&&t.commands.createBinding({type:"arrow",fromId:o.id,toId:e.startBinding.targetShapeId,props:{terminal:"start",normalizedAnchor:e.startBinding.normalizedAnchor}},{source:n}),e.endBinding&&t.commands.createBinding({type:"arrow",fromId:o.id,toId:e.endBinding.targetShapeId,props:{terminal:"end",normalizedAnchor:e.endBinding.normalizedAnchor}},{source:n});const i=t.shapes.get(o.id);if(!_e(i))throw new Error("Failed to create arrow shape");return i}function kn(t,e,n,r,o="user"){if(!e)return t.interaction.setBindingPreview(r.preview),null;let i=null;return i=function(t,e,n){const r=t.shapes.get(e.shapeId);if(!_e(r))return null;const o=Ie(t,r,e.terminal,e.pagePoint);if(!o)return null;t.commands.updateShapes([{id:r.id,x:o.x,y:o.y,rotation:o.rotation,scaleX:o.scaleX,scaleY:o.scaleY,props:{...o.props}}],{source:n});const i=t.bindings.getFromShape(r.id).find(t=>qe(t)&&t.props.terminal===e.terminal)??null;e.binding?qe(i)?t.commands.updateBinding({id:i.id,toId:e.binding.targetShapeId,props:{terminal:e.terminal,normalizedAnchor:e.binding.normalizedAnchor}},{source:n}):(i&&t.commands.deleteBinding(i.id,{source:n}),t.commands.createBinding({type:"arrow",fromId:r.id,toId:e.binding.targetShapeId,props:{terminal:e.terminal,normalizedAnchor:e.binding.normalizedAnchor}},{source:n})):i&&(t.commands.deleteBinding(i.id,{source:n}),t.commands.updateShapes([{id:r.id,x:o.x,y:o.y,rotation:o.rotation,scaleX:o.scaleX,scaleY:o.scaleY,props:{...o.props}}],{source:n}));const s=t.shapes.get(r.id);return _e(s)?s:o}(t,{shapeId:e,terminal:n,pagePoint:r.pagePoint,binding:r.binding},o),t.interaction.setBindingPreview(r.preview),i}var Pn=bn("plugin-arrow.api");function Sn({editor:t}){return function({editor:t}){return{create(e){const n=t.shapes.getDefaultProps("arrow"),r=vn(t,{startPagePoint:new bt(e.start.x,e.start.y),endPagePoint:new bt(e.end.x,e.end.y),startBinding:e.startBinding?{targetShapeId:e.startBinding.targetShapeId,normalizedAnchor:e.startBinding.normalizedAnchor}:null,endBinding:e.endBinding?{targetShapeId:e.endBinding.targetShapeId,normalizedAnchor:e.endBinding.normalizedAnchor}:null,meta:e.meta?{...e.meta}:void 0,props:{...n,bend:e.bend??n.bend,stroke:e.stroke??n.stroke,strokeStyle:e.strokeStyle??n.strokeStyle,strokeWidth:e.strokeWidth??n.strokeWidth,headStart:e.headStart??n.headStart,headEnd:e.headEnd??n.headEnd}});return{id:r.id,type:r.type}},getSelectionStyle(){const e=t.state.selectedShapes.get().filter(_e);return 0===e.length?null:{stroke:In(e.map(t=>t.props.stroke)),strokeStyle:In(e.map(t=>t.props.strokeStyle)),strokeWidth:In(e.map(t=>t.props.strokeWidth)),headStart:In(e.map(t=>t.props.headStart)),headEnd:In(e.map(t=>t.props.headEnd))}},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(_e).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)},getToolDefaults:()=>t.shapes.getDefaultProps("arrow"),setToolDefaults:e=>(t.shapes.updateDefaultProps("arrow",e),t.shapes.getDefaultProps("arrow"))}}({editor:t})}function In(t){const[e,...n]=t;return void 0!==e&&n.every(t=>t===e)?e:null}function Mn(t,e){const n=[];return"arrow"===e.headStart&&n.push(Cn(t,"start",e.strokeWidth)),"arrow"===e.headEnd&&n.push(Cn(t,"end",e.strokeWidth)),{path:n.length>0?n.map(Tn).join(" "):null,points:n.flat()}}function Tn([t,e,n]){return[`M ${An(t.x)} ${An(t.y)}`,`L ${An(e.x)} ${An(e.y)}`,`L ${An(n.x)} ${An(n.y)}`].join(" ")}function Cn(t,e,n){const r=t[e].point,o=function(t,e){if("curved"===t.type){const n=t[e].point.sub(t.arc.center).per().mul(1===t.arc.sweepFlag?1:-1).normalize();if(n.len2()>0)return n}const n=t.end.point.sub(t.start.point).normalize();return n.len2()>0?n:new bt(1,0)}(t,e),i=3.45*n*("start"===e?1:-1),s=o.per().mul(2*n),a=r.add(o.mul(i));return[a.sub(s),r,a.add(s)]}function An(t){return Number.isFinite(t)?Number(t.toFixed(3)).toString():"0"}function En(t,e){switch(t){case"dashed":return`${4*e} ${2*e}`;case"dotted":return"0 "+2*e;default:return}}function Ln(t,e){const n=t&&"object"==typeof t?t:void 0;return{x:Bn(n?.x,e.x),y:Bn(n?.y,e.y)}}function Bn(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function Rn(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist(e);const i=t.sub(e),s=Math.max(0,Math.min(1,(i.x*r.x+i.y*r.y)/o));return t.dist(e.add(r.mul(s)))}function $n(t,e,n,r){return function(t,e,n,r){const o=e.sub(t),i=r.sub(n),s=o.x*i.y-o.y*i.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(t),l=(a.x*i.y-a.y*i.x)/s,c=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&c>=0&&c<=1}(t,e,n,r)?0:Math.min(Rn(t,n,r),Rn(e,n,r),Rn(n,t,e),Rn(r,t,e))}var Nn=class extends pe{type="arrow";getDefaultProps(){return{w:160,h:48,start:{x:8,y:24},end:{x:152,y:24},bend:0,stroke:Et("stroke-slate"),strokeStyle:"solid",strokeWidth:2,headStart:"none",headEnd:"arrow"}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Math.max(1,Bn(e.w,n.w)),h:Math.max(1,Bn(e.h,n.h)),start:Ln(e.start,n.start),end:Ln(e.end,n.end),bend:Bn(e.bend,n.bend),stroke:$t(e.stroke,n.stroke),strokeStyle:Ke(e.strokeStyle)?e.strokeStyle:n.strokeStyle,strokeWidth:Math.max(1,Bn(e.strokeWidth,n.strokeWidth)),headStart:"arrow"===e.headStart?"arrow":"none",headEnd:"none"===e.headEnd?"none":"arrow"}}getPositionedBounds(t){const e=Te(t),n=Math.max(6,.5*t.props.strokeWidth+4);return e.bounds.expand(n)}getPointHitTestBounds(t,e){const n=Math.max(8,t.props.strokeWidth+4);if(!e?.editor)return Te(t).bounds.expand(n);const r=Je(e.editor,t).info,o=e.editor.shapes.computePositionedToPageTransform(t).tryInvert();if(!o||0===r.points.length)return Te(t).bounds.expand(n);const i=n*Math.sqrt(o.a*o.a+o.b*o.b+o.c*o.c+o.d*o.d);return vt.FromPoints(r.points.map(t=>o.applyToPoint(t))).expand(i)}getLocalBounds(t){return new vt(0,0,t.props.w,t.props.h)}getExportBounds(t){const e=Ce(t),n=Math.max(6,.5*t.props.strokeWidth+4);return e.bounds.expand(n)}updateSelectionPagePoints(t,e){const n=this.getSelectionPageMiddlePoint(t);if(e.pageMiddlePoint&&n){const r=this.getSelectionPagePoints(t),o=function(t,e){const n=t[1].sub(t[0]),r=t[2].sub(t[0]),o=n.x*r.y-n.y*r.x;if(Math.abs(o)<1e-9)return null;const i=new Ht(r.y/o,-n.y/o,-r.x/o,n.x/o,0,0),s=e[1].sub(e[0]),a=e[2].sub(e[0]),l=new Ht(s.x,s.y,a.x,a.y,0,0).compose(i);return new Ht(l.a,l.b,l.c,l.d,e[0].x-l.a*t[0].x-l.c*t[0].y,e[0].y-l.b*t[0].x-l.d*t[0].y)}([r[0],r[1],n],[e.pagePoints[0],e.pagePoints[1],e.pageMiddlePoint]);if(o){const e=Xt(o.compose(this.getLocalTransform(t)),this.getLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});if(e)return{id:t.id,...e}}}const r=function(t,e,n){const r=Me(e,n);return{...t,x:r.x,y:r.y,rotation:0,scaleX:1,scaleY:1,props:{...t.props,w:r.w,h:r.h,start:r.start,end:r.end,bend:t.props.bend}}}(t,e.pagePoints[0],e.pagePoints[1]);return{id:t.id,x:r.x,y:r.y,rotation:r.rotation,scaleX:r.scaleX,scaleY:r.scaleY,props:{w:r.props.w,h:r.props.h,start:r.props.start,end:r.props.end,bend:e.pageMiddlePoint?Ae(e.pagePoints[0],e.pagePoints[1],e.pageMiddlePoint):r.props.bend}}}isWrappedByBrush(t,e){return e.pageOutlineVertices.every(t=>e.brushBounds.containsPoint(t))}getSelectionPagePoints(t){return[ve(t,"start"),ve(t,"end")]}getSelectionPageMiddlePoint(t){return this.getLocalTransform(t).applyToPoint(Ce(t).middle)}contributesToSelectionFrame(t,e){return e.editor.selection.getIds().length>1}canUseSelectionResizeHandles(t,e){return e.editor.selection.getIds().length>1}canUseSelectionRotateHandle(t,e){return e.editor.selection.getIds().length>1}canStartTranslateFromSelectionBounds(t,e){return e.editor.selection.getIds().length>1}getSelectionHandleAnchors(t,e){if(!e.isOnlySelected)return{terminalHandleAnchors:[],middleHandleAnchors:[]};const n=Je(e.editor,t).info;return{terminalHandleAnchors:[{kind:"binding_terminal",terminal:"start",point:n.start.handle},{kind:"binding_terminal",terminal:"end",point:n.end.handle}],middleHandleAnchors:n.middle?[{kind:"binding_middle",point:n.middle}]:[]}}getSelectionOverlayInfo(t,e){const n=Je(e.editor,t),r=n.info,o=Ze(e.editor,t),i=Mn(o,t.props),s=e.editor.shapes.computeLocalToPageTransform(t);return{usesSelectionPathOverlay:!0,startPagePoint:r.start.point,endPagePoint:r.end.point,middlePagePoint:r.middle,path:r.path,pathStyle:{localPath:o.path,localDecorationPaths:i.path?[i.path]:[],localBounds:vt.FromPoints([...o.points,...i.points]),localToPage:s,strokeWidth:t.props.strokeWidth,strokeDasharray:En(t.props.strokeStyle,t.props.strokeWidth)},pageClipPath:ne({outputBounds:r.bounds,cutoutLocalPolygons:e.editor.shapes.getContentCutoutLocalPolygonsSignal(t.id).get(),localToOutput:s}),bindingSegments:n.bindingSegments}}getLabelPathGeometry(t,e){return Ee(Je(e.editor,t).info)}hitTest(t,e,n){return function(t,e){let n=1/0;for(let r=0;r<t.points.length-1;r++)n=Math.min(n,Ue(e,t.points[r],t.points[r+1]));return Number.isFinite(n)?n:e.dist(t.start.point)}(n?.editor?Je(n.editor,t).info:Te(t),n?.pagePoint??e)<=Math.max(8,t.props.strokeWidth+4)}hitTestLineSegment(t,e){const n=e.editor?Je(e.editor,t).info:Te(t),r=Math.max(8,t.props.strokeWidth+4,e.editor?e.pageMargin:e.positionedMargin),o=e.editor?e.pageStart:e.positionedStart,i=e.editor?e.pageEnd:e.positionedEnd;if(1===n.points.length)return Rn(n.points[0],o,i)<=r;for(let s=0;s<n.points.length-1;s+=1){const t=n.points[s],e=n.points[s+1];if(t&&e&&$n(o,i,t,e)<=r)return!0}return!1}};function zn(t,e,n,r){const o=function(t,e){let n=null;for(const r of e)(!n||mn(t,r,n)<0)&&(n=r);return n}(t,t.shapes.hitTestPoint(e,{hitTest:"bindingTarget",filter:e=>e.id!==r?.excludeShapeId&&gn(t,e)}));if(!o)return null;const i=function(t,e,n){const r=t.shapes.computePositionedToPageTransform(e).tryInvert(),o=t.shapes.computePositionedBounds(e);if(!r)return{x:.5,y:.5};const i=r.applyToPoint(n),s=o.w<=1e-6?.5:(i.x-o.minX)/o.w,a=o.h<=1e-6?.5:(i.y-o.minY)/o.h;return{x:ye(s),y:ye(a)}}(t,o,e);return{targetShape:o,normalizedAnchor:i,resolvedPagePoint:we(t,o,i,n),rawPagePoint:e.clone()}}function On(t,{terminal:e,rawPagePoint:n,oppositePagePoint:r,excludeShapeId:o,ignoreTargets:i=!1}){if(i)return{pagePoint:n.clone(),binding:null,preview:null};const s=zn(t,n,r,{excludeShapeId:o});return{pagePoint:s?.resolvedPagePoint??n.clone(),binding:Dn(s),preview:Fn(e,s)}}function Wn(t,{terminal:e,rawPagePoint:n,ignoreTargets:r=!1}){return On(t,{terminal:e,rawPagePoint:n,oppositePagePoint:n.add(new bt(1,0)),ignoreTargets:r})}function Hn(t,{arrow:e,terminal:n,rawPagePoint:r,ignoreTargets:o=!1}){const i=On(t,{terminal:n,rawPagePoint:r,oppositePagePoint:ke(t,e,Pe(n)),excludeShapeId:e.id,ignoreTargets:o});if(!i.preview)return i;const s=function(t,{arrow:e,terminal:n,rawPagePoint:r,preview:o}){const i=t.shapes.get(o.targetShapeId);if(!i||_e(i))return o;const s=cn(t,{arrow:e,terminal:n,target:i,anchorPagePoint:r,fallbackBoundaryPagePoint:o.resolvedPagePoint});return{...o,resolvedPagePoint:s.boundaryPagePoint,guidePath:s.guidePath}}(t,{arrow:e,terminal:n,rawPagePoint:r,preview:i.preview});return{...i,pagePoint:s.resolvedPagePoint,preview:s}}function Dn(t){return t?{targetShapeId:t.targetShape.id,normalizedAnchor:t.normalizedAnchor}:null}function Fn(t,e){return e?{terminal:t,targetShapeId:e.targetShape.id,rawPagePoint:e.rawPagePoint,resolvedPagePoint:e.resolvedPagePoint}:null}var jn=class extends he{constructor(t){super(t,"arrow"),this.initial="idle",this.addChild(new Un(t,this)),this.addChild(new Xn(t,this))}},Un=class extends he{constructor(t,e){super(t,"idle",e)}onEnter(){this.editor.interaction.clearSelection()}onPointerDown(t){const e=this.editor.shapes.getDefaultProps("arrow"),n=Wn(this.editor,{terminal:"start",rawPagePoint:t.pagePoint,ignoreTargets:t.accelKey});this.transition("creating",{startPagePoint:n.pagePoint,startScreenPoint:t.screenPoint.clone(),currentPagePoint:n.pagePoint.clone(),shapeId:null,startBinding:n.binding,props:e})}},Xn=class extends he{info=null;operation=null;isClickCreating=!1;constructor(t,e){super(t,"creating",e)}onEnter(t){if(this.info=t,this.isClickCreating=!1,!this.info)return;this.operation=this.editor.operations.begin({kind:"arrow.create",label:"shape.create",source:"user",history:"record"});const e=vn(this.editor,{startPagePoint:this.info.startPagePoint,endPagePoint:this.info.startPagePoint,startBinding:this.info.startBinding,props:{stroke:this.info.props.stroke,strokeStyle:this.info.props.strokeStyle,strokeWidth:this.info.props.strokeWidth,headStart:this.info.props.headStart,headEnd:this.info.props.headEnd}},"user");this.info.shapeId=e.id,this.editor.commands.setSelectedShapeIds([e.id],{source:"system"}),this.editor.interaction.setBindingPreview(null),this.updateCreationBindingGuides(e)}onPointerDown(t){this.isClickCreating&&this.updateShape(t.pagePoint)}onPointerMove(t){this.updateShape(t.pagePoint)}onTick(t){if(!this.info)return;const e=this.editor.inputs.state.get();if("dragging"!==e.dragPhase||!e.currentPagePoint||!e.currentScreenPoint)return;const n=ge(e.currentScreenPoint,this.editor.state.viewportScreenSize.get(),t.elapsed);0===n.x&&0===n.y||(this.editor.viewport.pan(n),this.updateShape(this.editor.viewport.screenToPage(e.currentScreenPoint)))}onPointerUp(t){if(this.info)return this.updateShape(t.pagePoint),this.info.shapeId?this.info.startScreenPoint.dist(t.screenPoint)<10?this.isClickCreating?(this.cancelOperation(),this.transition("idle"),{clickSequence:"break"}):void(this.isClickCreating=!0):(Yt(this.editor,this.info.shapeId,{source:"user"}),this.commitOperation(),this.editor.state.tool.get().isToolLocked?(this.transition("idle"),{clickSequence:"break"}):(this.editor.commands.setActiveTool("select",{source:"system"}),{clickSequence:"break"})):(this.cancelOperation(),void this.transition("idle"));this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.cancelOperation(),this.editor.interaction.setTerminalBindingGuides(null),this.info=null,this.isClickCreating=!1}commitOperation(){const t=this.operation;this.operation=null,t?.commit()}cancelOperation(){const t=this.operation;this.operation=null,t?.isActive&&t.cancel()}updateShape(t){if(!this.info)return;this.info.currentPagePoint=t.clone();const e=this.info.shapeId,n=e?this.editor.shapes.get(e):null,r=_e(n)?Hn(this.editor,{arrow:n,terminal:"end",rawPagePoint:t,ignoreTargets:this.editor.inputs.state.get().accelKey}):On(this.editor,{terminal:"end",rawPagePoint:t,oppositePagePoint:this.info.startPagePoint,ignoreTargets:this.editor.inputs.state.get().accelKey}),o=this.info.startBinding&&r.binding?.targetShapeId===this.info.startBinding.targetShapeId?{pagePoint:t,binding:null,preview:null}:r,i=kn(this.editor,e,"end",o,"user")??(e?this.editor.shapes.get(e):null);this.updateCreationBindingGuides(_e(i)?i:null)}updateCreationBindingGuides(t){if(!t)return void this.editor.interaction.setTerminalBindingGuides(null);const e=new Map(this.editor.bindings.getFromShape(t.id).filter(qe).map(t=>[t.props.terminal,t.toId])),n=Je(this.editor,t).bindingSegments.map(n=>({...n,ownerShapeId:t.id,targetShapeId:e.get(n.terminal)??null}));this.editor.interaction.setTerminalBindingGuides(n)}};function Yn({shapeId:t}){return{shapeId:t,operationKind:"select.binding_middle_drag",update({editor:e,pagePoint:n,accelKey:r,source:o}){const i=e.shapes.get(t);if(!_e(i))return"stop";const s=function(t,e){return{start:Ge(t,e,"start").handlePagePoint,end:Ge(t,e,"end").handlePagePoint}}(e,i),a=Ae(s.start,s.end,n),l=e.shapes.computeLocalToPageTransform(i).tryInvert();if(!l)return"stop";const c=Ae(l.applyToPoint(s.start),l.applyToPoint(s.end),l.applyToPoint(n)),d=0===function({bend:t,bypassSnap:e,zoom:n}){return e?t:Math.abs(t)*n<=6?0:t}({bend:a,bypassSnap:r,zoom:e.state.cameraZoom.get()})?0:c;return e.commands.updateShapes([{id:i.id,props:{bend:d}}],{source:o}),"continue"}}}function Kn(){return{createSession:(t,{handle:e,shape:n})=>_e(n)?"binding_terminal"===e.kind?function({handle:t,shapeId:e,terminal:n}){return{shapeId:e,operationKind:"select.binding_terminal_drag",handleSnapMode:"point",handleSnapContext:{shapeId:e,handle:t},shouldClearBindingPreviewOnExit:!0,update({editor:t,pagePoint:r,accelKey:o,source:i}){const s=t.shapes.get(e);if(!_e(s))return{status:"stop",finalPagePoint:null};const a=Hn(t,{arrow:s,terminal:n,rawPagePoint:r,ignoreTargets:o}),l=kn(t,s.id,n,a,i);return{status:"continue",finalPagePoint:l?ke(t,l,n):a.pagePoint}}}}({handle:e,shapeId:n.id,terminal:e.terminal}):"binding_middle"===e.kind?Yn({shapeId:n.id}):null:null}}function _n(){return{id:"land.arrow.interactions",selectionHandle:Kn()}}var qn=class{type="arrow";toSvg(t,e){const n=e.resolveColor(t.props.stroke),r=Ze(e.editor,t),o=ne({outputBounds:r.bounds,cutoutLocalPolygons:e.editor.shapes.getContentCutoutLocalPolygonsSignal(t.id).get()}),i=o?e.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"path",attrs:{d:o,"clip-rule":"evenodd","fill-rule":"evenodd"}}]}):void 0,s="arrow"===t.props.headStart?`url(#${e.addDef(Gn("start",n))})`:void 0,a="arrow"===t.props.headEnd?`url(#${e.addDef(Gn("end",n))})`:void 0;return{tag:"path",attrs:{d:r.path,fill:"none",stroke:n,"stroke-width":t.props.strokeWidth,"stroke-dasharray":En(t.props.strokeStyle,t.props.strokeWidth),"stroke-linecap":"round","stroke-linejoin":"round","marker-start":s,"marker-end":a,"clip-path":i?`url(#${i})`:void 0}}}};function Vn(){return{id:"land.arrow",shapeUtils:[new Nn],shapeSvgExporters:[new qn],bindingUtils:[new wn],interactionHandlers:[_n()],setup(t){t.bindings.setTerminalResolver(On),t.tools.register("arrow",t=>new jn(t))}}}function Gn(t,e){return{tag:"marker",attrs:{markerWidth:12,markerHeight:12,viewBox:"0 0 24 24",refX:"start"===t?2:22,refY:12,orient:"auto",markerUnits:"strokeWidth"},children:[{tag:"path",attrs:{d:"start"===t?"M8.9,8 L2,12 L8.9,16":"M15.1,8 L22,12 L15.1,16",fill:"none",stroke:e,"stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"}}]}}function Jn(){return{id:"land.arrow.react",shapeRenderers:[{type:"arrow",component:Zn,hoverComponent:Qn}]}}function Zn({shape:t,editor:e}){
2
+ return d(tr,{shape:t,editor:e,idPrefix:"arrow",stroke:Nt(t.props.stroke),strokeWidth:t.props.strokeWidth})}function Qn({shape:t,editor:e,strokeWidth:n}){
3
+ return d(tr,{dataUi:"arrow-hover-outline",shape:t,editor:e,idPrefix:"arrow-hover",stroke:o,strokeWidth:n,vectorEffect:"non-scaling-stroke"})}function tr({dataUi:t,editor:e,idPrefix:n,shape:o,stroke:i,strokeWidth:s,vectorEffect:a}){const l=`${n}-content-clip-${o.id.replace(/[^a-zA-Z0-9_-]/g,"-")}`,c=Ze(e,o),p=Mn(c,o.props),h=r(e.shapes.getContentCutoutLocalPolygonsSignal(o.id)),f=ne({outputBounds:c.bounds,cutoutLocalPolygons:h});
4
+ return u("svg",{"data-ui":t,width:"100%",height:"100%",viewBox:`0 0 ${o.props.w} ${o.props.h}`,overflow:"visible",children:[f?d("defs",{children:d("clipPath",{id:l,clipPathUnits:"userSpaceOnUse",children:d("path",{d:f,clipRule:"evenodd",fillRule:"evenodd"})})}):null,u("g",{clipPath:f?`url(#${l})`:void 0,children:[d("path",{"data-arrow-path":"body",d:c.path,fill:"none",stroke:i,strokeWidth:s,strokeDasharray:En(o.props.strokeStyle,s),strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:a}),p.path?d("path",{"data-arrow-path":"heads",d:p.path,fill:"none",stroke:i,strokeWidth:s,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:a}):null]})]})}var er={id:"arrow",editor:Vn(),render:Jn(),api:Pn,setup:({editor:t})=>({api:Sn({editor:t})})},nr={outline:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},filled:{xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none"}},rr=(t,e,n,r)=>{const o=f(({color:n="currentColor",size:o=24,stroke:i=2,title:s,className:a,children:l,...c},d)=>h("svg",{ref:d,...nr[t],width:o,height:o,className:["tabler-icon",`tabler-icon-${e}`,a].join(" "),..."filled"===t?{fill:n}:{strokeWidth:i,stroke:n},...c},[s&&h("title",{key:"svg-title"},s),...r.map(([t,e])=>h(t,e)),...Array.isArray(l)?l:[l]]));return o.displayName=`${n}`,o},or=rr("outline","arrow-right","ArrowRight",[["path",{d:"M5 12l14 0",key:"svg-0"}],["path",{d:"M13 18l6 -6",key:"svg-1"}],["path",{d:"M13 6l6 6",key:"svg-2"}]]),ir=rr("outline","photo-scan","PhotoScan",[["path",{d:"M15 8h.01",key:"svg-0"}],["path",{d:"M6 13l2.644 -2.644a1.21 1.21 0 0 1 1.712 0l3.644 3.644",key:"svg-1"}],["path",{d:"M13 13l1.644 -1.644a1.21 1.21 0 0 1 1.712 0l1.644 1.644",key:"svg-2"}],["path",{d:"M3 7v-2a2 2 0 0 1 2 -2h2",key:"svg-3"}],["path",{d:"M3 17v2a2 2 0 0 0 2 2h2",key:"svg-4"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"svg-5"}],["path",{d:"M17 21h2a2 2 0 0 0 2 -2v-2",key:"svg-6"}]]),sr=rr("outline","photo","Photo",[["path",{d:"M15 8h.01",key:"svg-0"}],["path",{d:"M3 6a3 3 0 0 1 3 -3h12a3 3 0 0 1 3 3v12a3 3 0 0 1 -3 3h-12a3 3 0 0 1 -3 -3v-12",key:"svg-1"}],["path",{d:"M3 16l5 -5c.928 -.893 2.072 -.893 3 0l5 5",key:"svg-2"}],["path",{d:"M14 14l1 -1c.928 -.893 2.072 -.893 3 0l3 3",key:"svg-3"}]]),ar=rr("outline","plus","Plus",[["path",{d:"M12 5l0 14",key:"svg-0"}],["path",{d:"M5 12l14 0",key:"svg-1"}]]),lr=rr("outline","text-scan-ai","TextScanAi",[["path",{d:"M8 12h4.5",key:"svg-0"}],["path",{d:"M8 8h6",key:"svg-1"}],["path",{d:"M8 16h2",key:"svg-2"}],["path",{d:"M3 7v-2a2 2 0 0 1 2 -2h2",key:"svg-3"}],["path",{d:"M3 17v2a2 2 0 0 0 2 2h2",key:"svg-4"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"svg-5"}],["path",{d:"M14 21v-4a2 2 0 1 1 4 0v4",key:"svg-6"}],["path",{d:"M14 19h4",key:"svg-7"}],["path",{d:"M21 15v6",key:"svg-8"}]]),cr=rr("outline","typography","Typography",[["path",{d:"M4 20l3 0",key:"svg-0"}],["path",{d:"M14 20l7 0",key:"svg-1"}],["path",{d:"M6.9 15l6.9 0",key:"svg-2"}],["path",{d:"M10.2 6.3l5.8 13.7",key:"svg-3"}],["path",{d:"M5 20l6 -16l2 0l7 16",key:"svg-4"}]]),dr=36,ur=36,pr=4,hr=12,fr=8,gr=15,mr=12,yr=20,xr=12,wr=10,br=8,vr=8,kr=320,Pr=160,Sr=96,Ir=48,Mr="8 6";function Tr(t){return yt(t)&&"connector"===t.type}function Cr(t){return function(t){return!!t&&"binding"===t.typeName}(t)&&"connector"===t.type}function Ar(t,e){let n=null,r=null;for(const o of t.bindings.getFromShape(e))Cr(o)&&("start"===o.props.terminal?n=o:r=o);return{start:n,end:r}}function Er(t,e){return t.bindings.getFromShape(e).filter(Cr)}var Lr=.001;function Br(t,e){const n=Rr(t),r=Rr(e);let o;if(n&&(n.needsWinding=Xr(n,e.point)),r&&(r.needsWinding=Xr(r,t.point)),n||r)if(n&&r){if(void 0!==t.obstacleId&&t.obstacleId===e.obstacleId)return o=function(t,e,n,r){const o=Qr(t.bounds,e.bounds),i=Math.max(36,36),s=new vt(o.minX-i,o.minY-i,o.w+2*i,o.h+2*i),a=$r(t,s),l=$r(e,s);return function(t,e){const n=t.filter(t=>!function(t,e){for(let n=1;n<t.length;n+=1){const r=t[n-1],o=t[n];if(Math.abs(r.y-o.y)<Lr){if(r.y>e.minY+Lr&&r.y<e.maxY-Lr&&Math.max(r.x,o.x)>e.minX+Lr&&Math.min(r.x,o.x)<e.maxX-Lr)return!0}else if(r.x>e.minX+Lr&&r.x<e.maxX-Lr&&Math.max(r.y,o.y)>e.minY+Lr&&Math.min(r.y,o.y)<e.maxY-Lr)return!0}return!1}(t,e)&&!function(t){for(let e=1;e<t.length;e+=1)for(let n=e+2;n<t.length;n+=1)if(Ur(t[e-1],t[e],t[n-1],t[n]))return!0;return!1}(t));return[...n.length>0?n:t].sort(Wr)[0]}([to([n,...Nr(a,t.side,l,e.side,s),r]),to([n,...Nr(l,e.side,a,t.side,s).reverse(),r])],o)}(n,r,t.point,e.point),to(o);o=n.needsWinding&&r.needsWinding?Kr(n,r,t.point,e.point):n.needsWinding?Yr(n,r,t.point,e.point):r.needsWinding?Yr(r,n,e.point,t.point).reverse():function(t,e,n,r){if(qr(n,r))return[n,r];if(t.axis===e.axis){if("horizontal"===t.axis){const o=(t.point.x+e.point.x)/2;return[n,new bt(o,n.y),new bt(o,r.y),r]}const o=(t.point.y+e.point.y)/2;return[n,new bt(n.x,o),new bt(r.x,o),r]}return"horizontal"===t.axis?[n,new bt(r.x,n.y),r]:[n,new bt(n.x,r.y),r]}(n,r,t.point,e.point)}else{const i=n??r,s=n?t.point:e.point,a=n?e.point:t.point;o=i.needsWinding?function(t,e,n){const{bounds:r,neighborPoint:o}=t;if("horizontal"===t.axis){if(n.y<r.minY||n.y>r.maxY)return[e,o,new bt(o.x,n.y),n];const t=n.y+e.y>r.minY+r.maxY?r.maxY+36:r.minY-36;return[e,o,new bt(o.x,t),new bt(n.x,t),n]}if(n.x<r.minX||n.x>r.maxX)return[e,o,new bt(n.x,o.y),n];const i=n.x+e.x>r.minX+r.maxX?r.maxX+36:r.minX-36;return[e,o,new bt(i,o.y),new bt(i,n.y),n]}(i,s,a):function(t,e,n){if(qr(e,n))return[e,n];const r=n.sub(e);if("horizontal"===t.axis){if(Math.abs(r.x)<=Math.abs(r.y))return[e,new bt(n.x,e.y),n];const t=e.x+r.x/2;return[e,new bt(t,e.y),new bt(t,n.y),n]}if(Math.abs(r.x)>Math.abs(r.y))return[e,new bt(e.x,n.y),n];const o=e.y+r.y/2;return[e,new bt(e.x,o),new bt(n.x,o),n]}(i,s,a),n||o.reverse()}else o=function(t,e){if(qr(t,e))return[t,e];const n=e.sub(t);if(Math.abs(n.x)>Math.abs(n.y)){const r=t.x+n.x/2;return[t,new bt(r,t.y),new bt(r,e.y),e]}const r=t.y+n.y/2;return[t,new bt(t.x,r),new bt(e.x,r),e]}(t.point,e.point);return to(o)}function Rr(t){if(!t.obstacleBounds)return null;const e=function(t){return Math.abs(t.x)>=Math.abs(t.y)?"horizontal":"vertical"}(t.direction),n=function(t,e){return"horizontal"===e?new bt(t.x>=0?1:-1,0):new bt(0,t.y>=0?1:-1)}(t.direction,e);return{point:t.point,neighborPoint:t.point.add(n.mul(36)),bounds:t.obstacleBounds,axis:e,side:_r(n,e),needsWinding:!1}}function $r(t,e){switch(t.side){case"top":return new bt(t.point.x,e.minY);case"right":return new bt(e.maxX,t.point.y);case"bottom":return new bt(t.point.x,e.maxY);case"left":return new bt(e.minX,t.point.y)}}function Nr(t,e,n,r,o){const i=2*(o.w+o.h);if(i<=Lr)return[t,n];const s=zr(t,e,o),a=Or(zr(n,r,o)-s,i),l=[t],c=[{position:0,point:new bt(o.minX,o.minY)},{position:o.w,point:new bt(o.maxX,o.minY)},{position:o.w+o.h,point:new bt(o.maxX,o.maxY)},{position:2*o.w+o.h,point:new bt(o.minX,o.maxY)}].map(t=>({...t,travel:Or(t.position-s,i)})).filter(t=>t.travel>Lr&&t.travel<a-Lr).sort((t,e)=>t.travel-e.travel);return l.push(...c.map(t=>t.point)),l.push(n),l}function zr(t,e,n){switch(e){case"top":return t.x-n.minX;case"right":return n.w+t.y-n.minY;case"bottom":return n.w+n.h+n.maxX-t.x;case"left":return 2*n.w+n.h+n.maxY-t.y}}function Or(t,e){return(t%e+e)%e}function Wr(t,e){const n=Hr(t)-Hr(e);if(0!==n)return n;const r=Dr(t)-Dr(e);return Math.abs(r)>Lr?r:jr(Fr(t),Fr(e))}function Hr(t){let e=0;for(let n=1;n<t.length-1;n+=1){const r=t[n].sub(t[n-1]),o=t[n+1].sub(t[n]);Math.abs(r.x*o.y-r.y*o.x)>Lr&&(e+=1)}return e}function Dr(t){let e=0;for(let n=1;n<t.length;n+=1){const r=t[n-1],o=t[n];e+=Math.abs(o.x-r.x)+Math.abs(o.y-r.y)}return e}function Fr(t){const e=t.flatMap(t=>[t.x,t.y]),n=[...t].reverse().flatMap(t=>[t.x,t.y]);return jr(e,n)<=0?e:n}function jr(t,e){const n=Math.min(t.length,e.length);for(let r=0;r<n;r+=1){const n=t[r]-e[r];if(Math.abs(n)>Lr)return n}return t.length-e.length}function Ur(t,e,n,r){const o=Math.abs(t.y-e.y)<Lr,i=Math.abs(n.y-r.y)<Lr;if(o&&i)return Math.abs(t.y-n.y)<Lr&&Math.max(Math.min(t.x,e.x),Math.min(n.x,r.x))<=Math.min(Math.max(t.x,e.x),Math.max(n.x,r.x))+Lr;if(!o&&!i)return Math.abs(t.x-n.x)<Lr&&Math.max(Math.min(t.y,e.y),Math.min(n.y,r.y))<=Math.min(Math.max(t.y,e.y),Math.max(n.y,r.y))+Lr;const s=o?t:n,a=o?e:r,l=o?n:t,c=o?r:e;return l.x>=Math.min(s.x,a.x)-Lr&&l.x<=Math.max(s.x,a.x)+Lr&&s.y>=Math.min(l.y,c.y)-Lr&&s.y<=Math.max(l.y,c.y)+Lr}function Xr(t,e){return!function(t,e){return t.x>=e.minX&&t.x<=e.maxX&&t.y>=e.minY&&t.y<=e.maxY}(e,t.bounds)&&(n=t.neighborPoint.sub(t.point),r=e.sub(t.point),n.x*r.x+n.y*r.y<=0);var n,r}function Yr(t,e,n,r){const o=t.neighborPoint,i=Qr(t.bounds,e.bounds);if("horizontal"===t.axis){if("horizontal"===e.axis&&function(t,e){return t.y<e.minY||t.y>e.maxY}(r,t.bounds))return[n,o,new bt(o.x,r.y),r];if("horizontal"===e.axis){const i=r.y+n.y>t.bounds.minY+t.bounds.maxY?t.bounds.maxY+36:t.bounds.minY-36,s=Jr(t.bounds,e.bounds);return[n,o,new bt(o.x,i),new bt(s,i),new bt(s,r.y),r]}if(Gr(t.bounds,e.bounds)){const i=Zr(t.bounds,e.bounds);return[n,o,new bt(o.x,i),new bt(r.x,i),r]}const s=e.neighborPoint.y>r.y?i.maxY+36:i.minY-36;return[n,o,new bt(o.x,s),new bt(r.x,s),r]}if("horizontal"===e.axis&&function(t,e){return t.x<e.minX||t.x>e.maxX}(r,t.bounds))return[n,o,new bt(r.x,o.y),r];if("vertical"===e.axis){if(Vr(t.bounds,e.bounds)){const i=Jr(t.bounds,e.bounds);return[n,o,new bt(i,o.y),new bt(i,r.y),r]}const s=e.neighborPoint.x>r.x?i.maxX+36:i.minX-36;return[n,o,new bt(s,o.y),new bt(s,r.y),r]}const s=r.x+n.x>t.bounds.minX+t.bounds.maxX?t.bounds.maxX+36:t.bounds.minX-36,a=Zr(t.bounds,e.bounds);return[n,o,new bt(s,o.y),new bt(s,a),new bt(r.x,a),r]}function Kr(t,e,n,r){const o=t.neighborPoint,i=e.neighborPoint,s=Qr(t.bounds,e.bounds);if("horizontal"===t.axis&&"horizontal"===e.axis){if(Math.abs(n.x-r.x)<Lr&&Math.abs(o.x-i.x)<Lr)return[n,o,i,r];let a,l,c;return Gr(t.bounds,e.bounds)?(a=o.x,l=i.x,c=Zr(t.bounds,e.bounds)):o.x>n.x?(a=s.maxX+36,l=s.minX-36,c=s.minY-36):(a=s.minX-36,l=s.maxX+36,c=s.maxY+36),[n,new bt(a,n.y),new bt(a,c),new bt(l,c),new bt(l,r.y),r]}if(t.axis!==e.axis){if("horizontal"===t.axis){const t=o.x>n.x?s.maxX+36:s.minX-36,e=i.y>r.y?s.maxY+36:s.minY-36;return[n,new bt(t,n.y),new bt(t,e),new bt(r.x,e),r]}return Kr(e,t,r,n).reverse()}if(Math.abs(n.y-r.y)<Lr&&Math.abs(o.y-i.y)<Lr)return[n,o,i,r];let a,l,c;return Vr(t.bounds,e.bounds)?(a=o.y,l=i.y,c=Jr(t.bounds,e.bounds)):o.y>n.y?(a=s.maxY+36,l=s.minY-36,c=s.maxX+36):(a=s.minY-36,l=s.maxY+36,c=s.minX-36),[n,new bt(n.x,a),new bt(c,a),new bt(c,l),new bt(r.x,l),r]}function _r(t,e){return"horizontal"===e?t.x>=0?"right":"left":t.y>=0?"bottom":"top"}function qr(t,e){return Math.abs(t.x-e.x)<Lr||Math.abs(t.y-e.y)<Lr}function Vr(t,e){return t.maxX<=e.minX||e.maxX<=t.minX}function Gr(t,e){return t.maxY<=e.minY||e.maxY<=t.minY}function Jr(t,e){return e.minX>=t.maxX?t.maxX+(e.minX-t.maxX)/2:e.maxX+(t.minX-e.maxX)/2}function Zr(t,e){return e.minY>=t.maxY?t.maxY+(e.minY-t.maxY)/2:e.maxY+(t.minY-e.maxY)/2}function Qr(t,e){const n=Math.min(t.minX,e.minX),r=Math.min(t.minY,e.minY),o=Math.max(t.maxX,e.maxX),i=Math.max(t.maxY,e.maxY);return new vt(n,r,o-n,i-r)}function to(t){const e=[];for(const n of t){const t=e[e.length-1];if(t&&t.dist(n)<Lr)continue;const r=e[e.length-2];r&&t&&(Math.abs(r.x-t.x)<Lr&&Math.abs(t.x-n.x)<Lr||Math.abs(r.y-t.y)<Lr&&Math.abs(t.y-n.y)<Lr)?e[e.length-1]=n:e.push(n)}return e}var eo="border:";function no(t,e){const n=t.shapes.computePositionedToPageTransform(e);return t.shapes.getUtil(e).getTerminalBindingOutlines(e,{editor:t}).map(t=>({points:t.points.map(t=>n.applyToPoint(t)),closed:t.closed})).filter(t=>t.points.length>0)}function ro(t,e,n,r){const o=ao(t,e,n);if(!o)return null;const i=function(t,e){return[...t].sort((t,n)=>t.pagePoint.dist(e)-n.pagePoint.dist(e)||t.id.localeCompare(n.id))[0]??null}(se(t,e),o.point),s=i?ao(t,e,i.pagePoint):null;if(i&&s&&s.distance<=1e-4&&i.pagePoint.dist(o.point)<=r)return{port:i,borderDistance:o.distance};const a=function(t,e,n){const r=t.shapes.computePositionedToPageTransform(e).tryInvert(),o=t.shapes.computePositionedBounds(e);if(!r)return{x:.5,y:.5};const i=r.applyToPoint(n);return{x:co(o.w<=1e-6?.5:(i.x-o.minX)/o.w),y:co(o.h<=1e-6?.5:(i.y-o.minY)/o.h)}}(t,e,o.point);return{port:{id:lo(a),normalizedAnchor:a,pagePoint:o.point,pageOutwardNormal:o.outwardNormal},borderDistance:o.distance}}function oo(t,e,n){if(!n.normalizedAnchor||!n.portId.startsWith(eo))return ae(t,e,n.portId);const r=ao(t,e,function(t,e,n){const r=t.shapes.computePositionedBounds(e);return t.shapes.computePositionedToPageTransform(e).applyToPoint(new bt(r.minX+r.w*n.x,r.minY+r.h*n.y))}(t,e,n.normalizedAnchor));return r?{id:n.portId,normalizedAnchor:{...n.normalizedAnchor},pagePoint:r.point,pageOutwardNormal:r.outwardNormal}:null}function io(t){return t.id.startsWith(eo)?{kind:"border",normalizedAnchor:{...t.normalizedAnchor}}:{kind:"port",portId:t.id}}function so(t,e){return{terminal:t,portId:e.id,...e.id.startsWith(eo)?{normalizedAnchor:{...e.normalizedAnchor}}:{}}}function ao(t,e,n){const r=no(t,e);if(0===r.length)return null;const o=t.shapes.getPageCenter(e.id)??n;let i=null,s=0;for(const a of r){if(1===a.points.length){const t=a.points[0],e=t.sub(o).normalize(),r={point:t.clone(),outwardNormal:e.len2()>0?e:new bt(1,0),distance:t.dist(n),index:s};(!i||r.distance<i.distance)&&(i=r),s+=1;continue}const t=a.closed?a.points.length:a.points.length-1;for(let e=0;e<t;e+=1){const t=a.points[e],r=a.points[(e+1)%a.points.length];if(!t||!r)continue;const l=kt(t,r,n),c=l.dist(n),d=r.sub(t);if(d.len2()<=1e-12)continue;let u=new bt(-d.y,d.x).normalize();const p=l.sub(o);u.x*p.x+u.y*p.y<0&&(u=u.mul(-1)),(!i||c<i.distance||c===i.distance&&s<i.index)&&(i={point:l,outwardNormal:u,distance:c,index:s}),s+=1}}return i}function lo(t){return`${eo}${t.x.toFixed(6)}:${t.y.toFixed(6)}`}function co(t){return Math.max(0,Math.min(1,t))}var uo=3;function po(t){return 3.5+(Math.max(0,t)<=1?2:0)}function ho(t){const e=Math.max(0,t);return e*po(e)}function fo(t){const e=Math.max(0,t);return e*(po(e)-.5)}function go(t,e,n=1){return("start"===t?2:22)+2*("start"===t?1:-1)*po(e)*Math.max(0,n)}function mo(t,e,n=1){const r="start"===t?2:22,o="start"===t?1:-1,i=2*(po(e)-.5)*Math.max(0,n),s=r+o*i;return`M${s},${12-i} L${r},12 L${s},${12+i} M${go(t,e,n)},12 L${r},12`}function yo(t,e){const n=Math.max(0,Math.min(1,e)),r=1-n;return"line"===t.type?t.start.add(t.end.sub(t.start).mul(n)):"quadratic"===t.type?t.start.mul(r*r).add(t.control.mul(2*r*n)).add(t.end.mul(n*n)):t.start.mul(r*r*r).add(t.control1.mul(3*r*r*n)).add(t.control2.mul(3*r*n*n)).add(t.end.mul(n*n*n))}function xo(t){const e=function(t){const e=[];let n=null,r=0;return t.forEach((t,o)=>{const i="cubic"===t.type?32:"quadratic"===t.type?16:1;for(let s=0;s<=i;s+=1){const a=s/i,l=yo(t,a);n&&(r+=n.dist(l)),e.push({point:l,distance:r,segmentIndex:o,segmentPosition:a}),n=l}}),e}(t.segments),n=e[e.length-1]?.distance??0;return{length:n,defaultPosition:.5,getPointAt:r=>function(t,e,n,r){const o=e[0];if(!o)return t.startPagePoint.clone();if(n<=Io)return o.point.clone();const i=n*r;for(let s=1;s<e.length;s+=1){const n=e[s-1],r=e[s];if(r.distance<i)continue;const o=r.distance-n.distance;if(o<=Io)continue;const a=Math.max(0,Math.min(1,(i-n.distance)/o));if(n.segmentIndex!==r.segmentIndex)return n.point.add(r.point.sub(n.point).mul(a));const l=t.segments[n.segmentIndex];return l?yo(l,n.segmentPosition+(r.segmentPosition-n.segmentPosition)*a):n.point.add(r.point.sub(n.point).mul(a))}return e[e.length-1].point.clone()}(t,e,n,ko(r)),getNearestPosition:(r,o)=>function(t,e,n,r,o){const i=ko(o);if(n<=Io)return i;let s=i,a=1/0;for(let l=1;l<e.length;l+=1){const o=e[l-1],c=e[l],d=c.point.sub(o.point),u=d.len2();if(u<=Io*Io)continue;const p=Math.max(0,Math.min(1,Vo(r.sub(o.point),d)/u)),h=o.segmentIndex===c.segmentIndex?t.segments[o.segmentIndex]:null,f=h?wo(h,r,o.segmentPosition,c.segmentPosition,p):0,g=h?(f-o.segmentPosition)/Math.max(Io,c.segmentPosition-o.segmentPosition):p,m=h?yo(h,f):o.point.add(d.mul(p)),y=(o.distance+(c.distance-o.distance)*g)/n,x=m.dist2(r),w=x<a-1e-8,b=Math.abs(x-a)<=1e-8&&Math.abs(y-i)<Math.abs(s-i);(w||b)&&(a=x,s=y)}return ko(s)}(t,e,n,r,o?.hintPosition??.5)}}function wo(t,e,n,r,o){if("line"===t.type)return n+(r-n)*o;let i=n+(r-n)*o;for(let s=0;s<8;s+=1){const o=yo(t,i),s=bo(t,i),a=o.sub(e),l=s.len2()+Vo(a,vo(t,i));if(Math.abs(l)<=Io)break;const c=Math.max(n,Math.min(r,i-Vo(a,s)/l));if(Math.abs(c-i)<=1e-10){i=c;break}i=c}return[n,i,r].reduce((n,r)=>yo(t,r).dist2(e)<yo(t,n).dist2(e)?r:n,i)}function bo(t,e){const n=1-e;return"quadratic"===t.type?t.control.sub(t.start).mul(2*n).add(t.end.sub(t.control).mul(2*e)):t.control1.sub(t.start).mul(3*n*n).add(t.control2.sub(t.control1).mul(6*n*e)).add(t.end.sub(t.control2).mul(3*e*e))}function vo(t,e){if("quadratic"===t.type)return t.end.sub(t.control.mul(2)).add(t.start).mul(2);const n=1-e;return t.control2.sub(t.control1.mul(2)).add(t.start).mul(6*n).add(t.end.sub(t.control2.mul(2)).add(t.control1).mul(6*e))}function ko(t){return Math.max(0,Math.min(1,t))}var Po=new WeakMap,So=.4,Io=1e-6;function Mo(t){const e=t.tryInvert();return e?({point:n,direction:r,along:o,perpendicular:i})=>{const s=e.applyToPoint(n),a=Qo(e,n,r);if(a.len()<=Io)return Fo({point:n,direction:r,along:o,perpendicular:i});const l=new bt(-a.y,a.x),c=a.mul(o).add(l.mul(i));return t.applyToPoint(s.add(c)).sub(n)}:Fo}function To(t,e){const n=Ar(t,e.id),r=n.start?t.shapes.get(n.start.toId):null,o=n.end?t.shapes.get(n.end.toId):null,i=r&&n.start?oo(t,r,n.start.props):null,s=o&&n.end?oo(t,o,n.end.props):null,a=t.shapes.computeLocalToPageTransform(e),l=r?t.shapes.getPageBounds(r.id)??void 0:void 0,c=o?t.shapes.getPageBounds(o.id)??void 0:void 0,d=i&&n.start?n.start.toId:void 0,u=s&&n.end?n.end.toId:void 0,p=function({transform:t,startPoint:e,startNormal:n,startObstacleId:r,startObstacleBounds:o,endPoint:i,endNormal:s,endObstacleId:a,endObstacleBounds:l}){return[t.a,t.b,t.c,t.d,t.e,t.f,...Co(e),...Co(n),r??"",...Ao(o),...Co(i),...Co(s),a??"",...Ao(l)]}({transform:a,startPoint:i?.pagePoint,startNormal:i?.pageOutwardNormal,startObstacleId:d,startObstacleBounds:l,endPoint:s?.pagePoint,endNormal:s?.pageOutwardNormal,endObstacleId:u,endObstacleBounds:c}),h=Po.get(e);if(h&&function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return!1;return!0}(h.signature,p))return h.info;const f=e.props.curveWaypoints.map(t=>a.applyToPoint(new bt(t.x,t.y))),g=e.props.orthogonalBends.map(t=>a.applyToPoint(new bt(t.x,t.y))),m=a.applyToPoint(new bt(e.props.start.x,e.props.start.y)),y=a.applyToPoint(new bt(e.props.end.x,e.props.end.y)),x=i?.pagePoint??m,w=s?.pagePoint??y,b=w.sub(x).normalize(),v=x.sub(w).normalize(),k=Lo({start:i?{point:i.pagePoint,outwardNormal:i.pageOutwardNormal,obstacleId:d,obstacleBounds:l}:{point:x,outwardNormal:b.len()>Io?b:new bt(1,0)},end:s?{point:s.pagePoint,outwardNormal:s.pageOutwardNormal,obstacleId:u,obstacleBounds:c}:{point:w,outwardNormal:v.len()>Io?v:new bt(-1,0)},routing:e.props.routing,cornerRadius:e.props.cornerRadius,headStart:e.props.headStart,headEnd:e.props.headEnd,strokeWidth:e.props.strokeWidth,terminalOffsetMapper:Mo(a),curveWaypoints:f,orthogonalBends:g});return Po.set(e,{signature:p,info:k}),k}function Co(t){return t?[1,t.x,t.y]:[0,0,0]}function Ao(t){return t?[1,t.x,t.y,t.w,t.h]:[0,0,0,0,0]}function Eo(t,e){const n=To(t,e),r=t.shapes.computeLocalToPageTransform(e).tryInvert();return r?Jo(n,r):n}function Lo({start:t,end:e,routing:n,cornerRadius:r,headStart:o="none",headEnd:i="none",strokeWidth:s=2,terminalOffsetMapper:a=Fo,curveWaypoints:l=[],orthogonalBends:c=[]}){return"curved"===n?function(t,e,n,r){const o=[t.point,...n.map(t=>t.clone()),e.point],i=function(t,e,n){const r=function(t,e,n){if(t.length<2)return[];const r=t.map(t=>({point:t,incoming:bt.Zero(),outgoing:bt.Zero()}));if(r[0].outgoing=Yo(e,t[1]),r[r.length-1].incoming=Yo(n,t[t.length-2]),t.length>2){const e=function(t){const e=[];for(let n=0;n<t.length-1;n+=1){let r=t[n],o=t[n+1];r<o?o=r+(o-r)/2:r=o+(r-o)/2,e.push([r*So,o*So])}return e}(t.slice(1).map((e,n)=>e.dist(t[n])));for(let t=1;t<r.length-1;t+=1){const n=r[t],o=Ko(n.point,r[t-1].point,r[t+1].point),i=r[t-1].point.sub(n.point),s=Go(o.bisector,i)*Go(o.bisector,o.normal)>0?1:-1,[a,l]=e[t-1];n.incoming=o.normal.mul(s*a),n.outgoing=o.normal.mul(-s*l)}for(let t=1;t<r.length-1;t+=1){const n=r[t-1],o=r[t],i=r[t+1],s=Ko(o.point,n.point.add(n.outgoing),i.point.add(i.incoming)),a=o.point.add(s.normal),l=o.point.sub(s.normal),c=a.dist(n.point)+l.dist(i.point)<a.dist(i.point)+l.dist(n.point)?1:-1,[d,u]=e[t-1];o.incoming=s.normal.mul(c*d),o.outgoing=s.normal.mul(-c*u)}}return r.slice(1).map((t,e)=>{const n=r[e];return{type:"cubic",start:n.point,control1:n.point.add(n.outgoing),control2:t.point.add(t.incoming),end:t.point}})}(t,e,n);if(2!==t.length||1!==r.length)return r;const o=r[0],i=o.end.sub(o.start),s=i.len();if(s<=Io)return r;const a=i.normalize(),l=Math.abs(Go(a,o.control1.sub(o.start))),c=Math.abs(Go(a,o.control2.sub(o.start)));if(l>Io||c>Io)return r;const d=(Math.abs(i.x)>Math.abs(i.y)?new bt(Math.sign(i.x),0):new bt(0,Math.sign(i.y))).mul(s*So);return[{...o,control1:o.start.add(d),control2:o.end.sub(d)}]}(o,t,e),s=i[0],a=i[i.length-1],l=(u=i,p=$o(t,s?Uo(s):jo(t,e.point),r.headStart,r),h=$o(e,a?Xo(a).mul(-1):jo(e,t.point),r.headEnd,r),u.length<=1?Bo(u[0]?No(u[0]):0,p,h):{start:Ro(No(u[0]),p),end:Ro(No(u[u.length-1]),h)}),c=Wo(t,s?Uo(s):jo(t,e.point),r.headStart,r.strokeWidth,r.terminalOffsetMapper,l.start),d=Wo(e,a?Xo(a).mul(-1):jo(e,t.point),r.headEnd,r.strokeWidth,r.terminalOffsetMapper,l.end);var u,p,h;return Ho({start:t,end:e,segments:i.map((n,r,o)=>{const i=0===r?c.routePoint.sub(t.point):bt.Zero(),s=r===o.length-1?d.routePoint.sub(e.point):bt.Zero();return{...n,start:n.start.add(i),control1:n.control1.add(i),control2:n.control2.add(s),end:n.end.add(s)}}),markerSegments:[...c.markerSegments,...d.markerSegments],startArrowScale:l.start,endArrowScale:l.end,routePoints:o})}(t,e,l,{headStart:o,headEnd:i,strokeWidth:s,terminalOffsetMapper:a}):"orthogonal"===n?function(t,e,n,r,o){const i=oi(t.outwardNormal),s=oi(e.outwardNormal),a=function(t,e,n,r,o){return Oo([...Oo(t,e,n)].reverse(),r,o).reverse()}(function(t,e,n,r,o){if(0===o.length)return null;const i=o.map(t=>t.clone()),s=i[0],a=i[i.length-1];if(!s||!a)return null;0!==n.x?s.y=t.y:s.x=t.x;0!==r.x?a.y=e.y:a.x=e.x;const l=ri([t,...i,e]);if(l.length<2)return null;for(let c=1;c<l.length;c+=1){const t=l[c-1],e=l[c];if(t.x!==e.x&&t.y!==e.y)return null}return l}(t.point,e.point,i,s,r)??Br({...t,direction:i},{...e,direction:s}),t,i,e,s),l=zo(a,t,"start",i),c=zo(a,e,"end",s),d=(f=a,g=$o(t,l,o.headStart,o),m=$o(e,c,o.headEnd,o),f.length<=2?Bo(f[0]?.dist(f[f.length-1])??0,g,m):{start:Ro(f[0].dist(f[1]),g),end:Ro(f[f.length-2].dist(f[f.length-1]),m)}),u=Wo(t,l,o.headStart,o.strokeWidth,o.terminalOffsetMapper,d.start),p=Wo(e,c,o.headEnd,o.strokeWidth,o.terminalOffsetMapper,d.end),h=a.map(t=>t.clone());var f,g,m;h.length>0&&(h[0]=u.routePoint,h[h.length-1]=p.routePoint);return Ho({start:t,end:e,segments:ni(h,n).segments,markerSegments:[...u.markerSegments,...p.markerSegments],startArrowScale:d.start,endArrowScale:d.end,routePoints:a,startTangent:l,endTangent:c.mul(-1)})}(t,e,r,c,{headStart:o,headEnd:i,strokeWidth:s,terminalOffsetMapper:a}):function(t,e,n){const r=e.point.sub(t.point).normalize(),o=r.len()>Io?r:jo(t,e.point),i=r.len()>Io?r.mul(-1):jo(e,t.point),s=Bo(t.point.dist(e.point),$o(t,o,n.headStart,n),$o(e,i,n.headEnd,n)),a=Wo(t,o,n.headStart,n.strokeWidth,n.terminalOffsetMapper,s.start),l=Wo(e,i,n.headEnd,n.strokeWidth,n.terminalOffsetMapper,s.end);return Ho({start:t,end:e,segments:[{type:"line",start:a.routePoint,end:l.routePoint}],markerSegments:[...a.markerSegments,...l.markerSegments],startArrowScale:s.start,endArrowScale:s.end,routePoints:[t.point,e.point]})}(t,e,{headStart:o,headEnd:i,strokeWidth:s,terminalOffsetMapper:a})}function Bo(t,e,n){const r=e+n;if(r<=Io)return{start:0,end:0};const o=Math.min(1,Math.max(0,t-.01)/r);return{start:e>0?o:0,end:n>0?o:0}}function Ro(t,e){return e<=Io?0:Math.min(1,Math.max(0,t-.01)/e)}function $o(t,e,n,r){return"arrow"!==n?0:r.terminalOffsetMapper({point:t.point,direction:e,along:3+ho(r.strokeWidth),perpendicular:0}).len()}function No(t){const e=Do(t,"cubic"===t.type?16:"quadratic"===t.type?8:1);return e.slice(1).reduce((t,n,r)=>t+n.dist(e[r]),0)}function zo(t,e,n,r){if(e.obstacleBounds||t.length<2)return r;const o="start"===n?t[1].sub(t[0]):t[t.length-2].sub(t[t.length-1]);return o.len()>Io?oi(o):r}function Oo(t,e,n){if(!e.obstacleBounds||t.length<2)return[...t];const r=t[0],o=t[1],i=o.sub(r);if(i.len()<=Io)return[...t];if(Math.abs(Go(i,n))<=Io&&i.x*n.x+i.y*n.y>0)return[...t];const s=e.point.add(n.mul(36)),a=0!==n.x?new bt(s.x,o.y):new bt(o.x,s.y);return ri([e.point,s,a,...t.slice(1)])}function Wo(t,e,n,r,o,i){if("arrow"!==n||i<=0)return{tipPoint:t.point,routePoint:t.point,markerSegments:[]};const s=e.normalize().len()>Io?e.normalize():jo(t,t.point),a=(e,n=0)=>o({point:t.point,direction:s,along:e,perpendicular:n}),l=t.point.add(a(3*i)),c=t.point.add(a((3+ho(r))*i)),d=fo(r)*i,u=3*i;return{tipPoint:l,routePoint:c,markerSegments:[{type:"line",start:t.point.add(a(u+d,d)),end:l},{type:"line",start:l,end:t.point.add(a(u+d,-d))},{type:"line",start:c,end:l}]}}function Ho({start:t,end:e,segments:n,markerSegments:r,startArrowScale:o,endArrowScale:i,routePoints:s,startTangent:a,endTangent:l}){const c=[];n.forEach((t,e)=>{const n="cubic"===t.type?function(t,e,n,r,o){const i=[];for(let s=0;s<=o;s+=1){const a=s/o,l=1-a;i.push(t.mul(l*l*l).add(e.mul(3*l*l*a)).add(n.mul(3*l*a*a)).add(r.mul(a*a*a)))}return i}(t.start,t.control1,t.control2,t.end,16):"quadratic"===t.type?Do(t,8):[t.start,t.end];c.push(...0===e?n:n.slice(1))});const d=n[0],u=n[n.length-1],p=[...Zo(n),...r.flatMap(t=>[t.start,t.end]),t.point,e.point];return{path:ti(n),startPagePoint:t.point,endPagePoint:e.point,startTangent:a??(d?Uo(d):e.point.sub(t.point).normalize()),endTangent:l??(u?Xo(u):e.point.sub(t.point).normalize()),startArrowScale:o,endArrowScale:i,pageBounds:vt.FromPoints(p),segments:n,markerSegments:r,points:c,routePoints:s}}function Do(t,e){return Array.from({length:e+1},(n,r)=>yo(t,r/e))}function Fo({direction:t,along:e,perpendicular:n}){const r=t.normalize(),o=new bt(-r.y,r.x);return r.mul(e).add(o.mul(n))}function jo(t,e){const n=t.outwardNormal.normalize();return n.len()>Io?n:e.sub(t.point).normalize()}function Uo(t){return"line"===t.type?t.end.sub(t.start).normalize():("cubic"===t.type?t.control1:t.control).sub(t.start).normalize()}function Xo(t){return"line"===t.type?t.end.sub(t.start).normalize():t.end.sub("cubic"===t.type?t.control2:t.control).normalize()}function Yo(t,e){const n=e.sub(t.point).normalize(),r=t.outwardNormal.normalize(),o=r.len()>Io?r:n,i=e.sub(t.point),s=Math.abs(Vo(i,o)),a=i.len();if(a<Io)return bt.Zero();const l=s<.001?Math.min(150,a):Math.min(Math.max(s,100),a);return o.mul(l*So)}function Ko(t,e,n){const r=e.dist(t),o=t.dist(n);if(r<Io||o<Io)return{normal:bt.Zero(),bisector:bt.Zero()};const i=r/(r+o),s=e.add(n.sub(e).mul(i)),a=t.sub(s),l=a.len();if(l<Io)return{normal:bt.Zero(),bisector:bt.Zero()};const c=a.div(l);return{normal:new bt(-c.y,c.x),bisector:a}}function _o(t){const e=[];for(const n of t){const t=new Set([0,1]);for(const e of qo(n.start.x,n.control1.x,n.control2.x,n.end.x))t.add(e);for(const e of qo(n.start.y,n.control1.y,n.control2.y,n.end.y))t.add(e);for(const r of t)e.push(yo(n,r))}return e}function qo(t,e,n,r){const o=3*(3*e-t-3*n+r),i=2*(3*t-6*e+3*n),s=-3*t+3*e;if(Math.abs(o)<Io){if(Math.abs(i)<Io)return[];const t=-s/i;return t>0&&t<1?[t]:[]}const a=i*i-4*o*s;if(a<0)return[];const l=Math.sqrt(a);return[(-i+l)/(2*o),(-i-l)/(2*o)].filter(t=>t>0&&t<1)}function Vo(t,e){return t.x*e.x+t.y*e.y}function Go(t,e){return t.x*e.y-t.y*e.x}function Jo(t,e){const n=t=>e.applyToPoint(t),r=t.segments.map(t=>"line"===t.type?{type:"line",start:n(t.start),end:n(t.end)}:"quadratic"===t.type?{type:"quadratic",start:n(t.start),control:n(t.control),end:n(t.end)}:{type:"cubic",start:n(t.start),control1:n(t.control1),control2:n(t.control2),end:n(t.end)}),o=t.markerSegments.map(t=>({type:"line",start:n(t.start),end:n(t.end)})),i=t.points.map(n),s=n(t.startPagePoint),a=n(t.endPagePoint),l=[...Zo(r),...o.flatMap(t=>[t.start,t.end]),s,a];return{...t,path:ti(r),startPagePoint:s,endPagePoint:a,startTangent:Qo(e,t.startPagePoint,t.startTangent),endTangent:Qo(e,t.endPagePoint,t.endTangent),pageBounds:vt.FromPoints(l.length>0?l:i),segments:r,markerSegments:o,points:i,routePoints:t.routePoints.map(n)}}function Zo(t){const e=[];for(const n of t)"cubic"===n.type?e.push(..._o([n])):"quadratic"===n.type?e.push(n.start,n.control,n.end):e.push(n.start,n.end);return e}function Qo(t,e,n){return t.applyToPoint(e.add(n)).sub(t.applyToPoint(e)).normalize()}function ti(t){const e=t[0];if(!e)return"";const n=[`M ${ii(e.start)}`];for(const r of t)n.push("line"===r.type?`L ${ii(r.end)}`:"quadratic"===r.type?`Q ${ii(r.control)} ${ii(r.end)}`:`C ${ii(r.control1)} ${ii(r.control2)} ${ii(r.end)}`);return n.join(" ")}function ei(t){const e=[];for(let n=0;n<t.length;n+=1){const r=t[n],o=t[n+1];o&&r.end.equals(o.start)?(e.push(`M ${ii(r.start)} L ${ii(r.end)} L ${ii(o.end)}`),n+=1):e.push(`M ${ii(r.start)} L ${ii(r.end)}`)}return e.join(" ")}function ni(t,e){if(t.length<2)return{path:"",segments:[],points:[...t]};if(2===t.length||e<=0){const e=t.slice(1).map((e,n)=>({type:"line",start:t[n],end:e}));return{path:ti(e),segments:e,points:[...t]}}const n=[],r=[t[0]];let o=t[0];for(let s=1;s<t.length-1;s+=1){const i=t[s-1],a=t[s],l=t[s+1],c=Math.min(Math.max(0,e),i.dist(a)/2,a.dist(l)/2),d=bt.Nudge(a,i,c),u=bt.Nudge(a,l,c);o.equals(d)||(n.push({type:"line",start:o,end:d}),r.push(d)),n.push({type:"quadratic",start:d,control:a,end:u}),r.push(a,u),o=u}const i=t[t.length-1];return o.equals(i)||(n.push({type:"line",start:o,end:i}),r.push(i)),{path:ti(n),segments:n,points:r}}function ri(t){const e=function(t){const e=[];for(const n of t)e[e.length-1]?.equals(n)||e.push(n);return e}(t);if(e.length<=2)return e;const n=[e[0]];for(let r=1;r<e.length-1;r+=1){const t=n[n.length-1],o=e[r],i=e[r+1];t.x===o.x&&o.x===i.x||t.y===o.y&&o.y===i.y||n.push(o)}return n.push(e[e.length-1]),n}function oi(t){return Math.abs(t.x)>=Math.abs(t.y)?new bt(t.x>=0?1:-1,0):new bt(0,t.y>=0?1:-1)}function ii(t){return`${si(t.x)} ${si(t.y)}`}function si(t){return Number(t.toFixed(3)).toString()}var ai="connector.curve-waypoint",li="connector.curve-insert",ci="connector.orthogonal-segment";function di(t){return`waypoint:${t}`}function ui(t){return`segment:${t}`}function pi(t,e){return`segment:${t}:${e}`}function hi(t,e){const n=new RegExp(`^${e}:(\\d+)$`).exec(t);if(!n)return null;const r=Number(n[1]);return Number.isSafeInteger(r)?r:null}function fi(t){const e=/^segment:(\d+):(horizontal|vertical)$/.exec(t);if(!e)return null;const n=Number(e[1]);return Number.isSafeInteger(n)?{index:n,axis:e[2]}:null}var gi=Dt("plugin.connector.runtime");function mi(t){return t.runtime.require(gi)}function yi(t,e){return{kind:"bound",shapeId:t,attachment:io(e)}}function xi(t,e){if("free"===e.kind)return{draft:e,pagePoint:e.pagePoint.clone(),shape:null,port:null};const n=t.shapes.get(e.shapeId);if(!n||Tr(n)||t.shapes.isHidden(n.id)||null===t.shapes.getClippedPageBounds(n.id)||!t.shapes.getUtil(n).canReceiveTerminalBinding(n,{editor:t}))return null;const r=function(t,e,n){return"port"===n.kind?ae(t,e,n.portId):oo(t,e,{portId:lo(n.normalizedAnchor),normalizedAnchor:n.normalizedAnchor})}(t,n,e.attachment);return r?{draft:e,pagePoint:r.pagePoint.clone(),shape:n,port:r,obstacleBounds:t.shapes.getPageBounds(n.id)??void 0}:null}function wi(t,e,n,r){const o=xi(t,e),i=xi(t,n);if(!o||!i)return"missing_endpoint";if(o.shape&&t.layers.isOrAncestorLocked(o.shape.id))return"locked_source";const s=t.pages.getCurrentId(),a=o.shape?t.layers.getPageId(o.shape.id):s,l=i.shape?t.layers.getPageId(i.shape.id):s;if(!a||a!==l||a!==s)return"cross_page";if(o.shape&&o.port&&i.shape&&i.port){if(Ei(o.shape.id,o.port.id,i.shape.id,i.port.id))return"same_attachment";if(Ai(t,o.shape.id,o.port.id,i.shape.id,i.port.id,r))return"duplicate"}return Bi(t,o,i)?null:"invalid_parent"}function bi(t,e,n="user"){if(wi(t,e.start,e.end))return null;const r=xi(t,e.start),o=xi(t,e.end);if(!r||!o)return null;const i=Bi(t,r,o);if(!i)return null;const s={...t.shapes.getDefaultProps("connector"),...e.props},a=$i({editor:t,parentId:i,start:Ti(r,o,"start"),end:Ti(o,r,"end"),props:s}),l=t.operations.begin({kind:"connector.commit",label:"shape.create",source:n,history:"user"===n?"record":"ignore"});try{const i=t.commands.createShapes([a],{source:n,autoReparent:!1})[0];if(!Tr(i))return l.cancel(),null;if(r.shape&&r.port&&Ci(t,i.id,"start",{shape:r.shape,port:r.port},n),o.shape&&o.port&&Ci(t,i.id,"end",{shape:o.shape,port:o.port},n),"none"!==e.selectionAfter){const r=Array.isArray(e.selectionAfter)?[...e.selectionAfter]:[i.id];t.commands.setSelectedShapeIds(r,{source:n})}const s=t.shapes.get(i.id);return Tr(s)?(l.commit(),s):(l.cancel(),null)}catch(c){throw l.isActive&&l.cancel(),c}}function vi(t,e){return Pi(t,e)}function ki(t,e,n,r){return Pi(t,e,{[n]:r})}function Pi(t,e,n={}){const r=Ar(t,e.id),o=t.shapes.computeLocalToPageTransform(e),i=o.applyToPoint(new bt(e.props.start.x,e.props.start.y)),s=o.applyToPoint(new bt(e.props.end.x,e.props.end.y)),a=Si(t,r.start),l=Si(t,r.end),c=n.start??a?.port.pagePoint??i,d=n.end??l?.port.pagePoint??s,u=!n.start&&a?Ii(t,a):Mi(c,d,"start"),p=!n.end&&l?Ii(t,l):Mi(d,c,"end"),h=a&&l?Li(t,a.shape,l.shape):e.parentId;if(!h||!t.layers.canReceiveChildren(h))return null;const f=$i({editor:t,parentId:h,start:u,end:p,props:e.props,manualPageGeometry:{curveWaypoints:e.props.curveWaypoints.map(t=>o.applyToPoint(new bt(t.x,t.y))),orthogonalBends:e.props.orthogonalBends.map(t=>o.applyToPoint(new bt(t.x,t.y)))}});return{...e,parentId:h,x:f.x,y:f.y,rotation:0,scaleX:1,scaleY:1,props:{...e.props,...f.props}}}function Si(t,e){if(!e)return null;const n=t.shapes.get(e.toId);if(!n)return null;const r=oo(t,n,e.props);return r?{shape:n,port:r}:null}function Ii(t,e){return{point:e.port.pagePoint,outwardNormal:e.port.pageOutwardNormal,obstacleId:e.shape.id,obstacleBounds:t.shapes.getPageBounds(e.shape.id)??void 0}}function Mi(t,e,n){const r=e.sub(t).normalize();return{point:t,outwardNormal:r.len()>0?r:new bt("start"===n?1:-1,0)}}function Ti(t,e,n){return t.shape&&t.port?{point:t.pagePoint,outwardNormal:t.port.pageOutwardNormal,obstacleId:t.shape.id,obstacleBounds:t.obstacleBounds}:Mi(t.pagePoint,e.pagePoint,n)}function Ci(t,e,n,r,o){t.commands.createBinding({type:"connector",fromId:e,toId:r.shape.id,props:so(n,r.port)},{source:o})}function Ai(t,e,n,r,o,i){for(const s of t.state.currentPageShapeIds.get()){if(s===i)continue;const a=t.shapes.get(s);if(!Tr(a))continue;const l=Ar(t,a.id);if(l.start?.toId===e&&l.start.props.portId===n&&l.end?.toId===r&&l.end.props.portId===o)return!0}return!1}function Ei(t,e,n,r){return t===n&&e===r}function Li(t,e,n){const r=t.layers.getPageId(e.id);if(!r||r!==t.layers.getPageId(n.id))return null;const o=new Set(Ni(t,n));for(const i of Ni(t,e))if(o.has(i)&&t.layers.canReceiveChildren(i))return i;return r}function Bi(t,e,n){if(e.shape&&n.shape)return Li(t,e.shape,n.shape);const r=t.pages.getCurrentId(),o=e.shape??n.shape,i=e.shape?n.pagePoint:e.pagePoint;if(o){for(const e of Ni(t,o)){if(!e.startsWith("shape:"))return e;const n=t.shapes.get(e);if(n&&Ri(t,n,[i]))return n.id}return t.layers.getPageId(o.id)??r}let s=null;const a=new Map(t.state.currentPageShapeIds.get().map((t,e)=>[t,e]));for(const l of t.state.currentPageShapeIds.get()){const r=t.shapes.get(l);if(!r||Tr(r)||!Ri(t,r,[e.pagePoint,n.pagePoint]))continue;const o=t.shapes.getPageBounds(r.id);if(!o)continue;const i={shape:r,area:o.w*o.h,order:a.get(r.id)??-1};(!s||i.area<s.area||i.area===s.area&&i.order>s.order)&&(s=i)}return s?.shape.id??r}function Ri(t,e,n){if(t.shapes.isHidden(e.id)||t.layers.isOrAncestorLocked(e.id)||null===t.shapes.getClippedPageBounds(e.id))return!1;const r=t.shapes.getUtil(e);if(!r.canReceiveChildren(e)||!r.canAutomaticallyReceiveChildren(e))return!1;const o=t.shapes.computeLocalToPageTransform(e).tryInvert();if(!o)return!1;const i=r.getChildClipLocalPolygons(e),s=r.getLocalBounds(e);return n.every(n=>{if(!t.shapes.isPagePointInClip(e.id,n))return!1;const r=o.applyToPoint(n);return i?function(t,e){return e.some(e=>Mt(t,e))}(r,i):s.containsPoint(r)})}function $i({editor:t,parentId:e,start:n,end:r,props:o,manualPageGeometry:i}){const s=i?.curveWaypoints??[],a=i?.orthogonalBends??[],l=e.startsWith("shape:")?t.shapes.get(e):null,c=l?t.shapes.computeLocalToPageTransform(l):Ht.Identity(),d=Lo({start:n,end:r,routing:o.routing,cornerRadius:o.cornerRadius,headStart:o.headStart,headEnd:o.headEnd,strokeWidth:o.strokeWidth,terminalOffsetMapper:Mo(c),curveWaypoints:s,orthogonalBends:a}),u=function(t,e,n){const r=e.startsWith("shape:")?t.shapes.get(e):null,o=(r?t.shapes.computeLocalToPageTransform(r):Ht.Identity()).tryInvert();return o?{bounds:vt.FromPoints(n.map(t=>o.applyToPoint(t))),pageToParent:o}:null}(t,e,[n.point,...d.points,r.point]),p=u?.pageToParent??Ht.Identity(),h=u?.bounds??d.pageBounds,f=p.applyToPoint(n.point),g=p.applyToPoint(r.point);return{type:"connector",parentId:e,x:h.x,y:h.y,props:{...o,w:Math.max(1,h.w),h:Math.max(1,h.h),start:{x:f.x-h.x,y:f.y-h.y},end:{x:g.x-h.x,y:g.y-h.y},curveWaypoints:s.map(t=>{const e=p.applyToPoint(t);return{x:e.x-h.x,y:e.y-h.y}}),orthogonalBends:a.map(t=>{const e=p.applyToPoint(t);return{x:e.x-h.x,y:e.y-h.y}})}}}function Ni(t,e){const n=[],r=new Set;let o=e.parentId;for(;o.startsWith("shape:");){const e=o;if(r.has(e))break;r.add(e),n.push(e);const i=t.shapes.get(e);if(!i)break;o=i.parentId}return n.push(o),n}var zi=["rectangle","ellipse","message-circle","summary","summary-left","burst","rhombus","triangle","pentagon","hexagon","star","trapezoid","arrow-left","arrow-right"],Oi=["solid","dashed","dotted","none"];function Wi(t){return yt(t)&&"geo"===t.type}function Hi(t){return"string"==typeof t&&zi.includes(t)}function Di(t){return"string"==typeof t&&Oi.includes(t)}var Fi=Dt("plugin.geo.creation-runtime");function ji(t){return t.runtime.require(Fi)}function Ui(t,e){return new vt(t.x,t.y,e.w,e.h)}var Xi=class extends he{kind;constructor(t,e,n){super(t,e),this.kind=n,this.initial="idle",this.addChild(new Yi(t,this)),this.addChild(new Ki(t,this))}getDefaultProps(){return{...this.editor.shapes.getDefaultProps("geo"),kind:this.kind}}onEnter(){this.editor.shapes.updateDefaultProps("geo",{kind:this.kind})}},Yi=class extends he{tool;constructor(t,e){super(t,"idle",e),this.tool=e}onEnter(){this.editor.interaction.clearSelection()}onExit(){ji(this.editor).clearHover()}onPointerMove(t){const e=ji(this.editor);"touch"!==t.pointerType&&0===t.buttons?e.setHover({pagePoint:t.pagePoint,timestamp:t.timestamp}):e.clearHover()}onPointerDown(t){this.transition("creating",{originPagePoint:t.pagePoint.clone(),originScreenPoint:t.screenPoint.clone(),shapeId:null,props:this.tool.getDefaultProps(),isDragCreating:!1})}},Ki=class extends he{info=null;operation=null;constructor(t,e){super(t,"creating",e)}onEnter(t){if(this.info=t,this.info){this.operation=this.editor.operations.begin({kind:"geo.create",label:"shape.create",source:"user",history:"record"});try{const t=this.createShape(Ui(this.info.originPagePoint,this.info.props),this.info.props);this.info.shapeId=t.id}catch(e){throw this.cancelOperation(),e}}}onPointerMove(t){this.updateShape(t.pagePoint,t.screenPoint,t.shiftKey)}onPointerUp(t){this.info?(this.updateShape(t.pagePoint,t.screenPoint,t.shiftKey),this.info.shapeId&&Yt(this.editor,this.info.shapeId,{source:"user"}),this.commitOperation(),this.editor.state.tool.get().isToolLocked?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.cancelOperation(),this.info=null}commitOperation(){const t=this.operation;this.operation=null,t?.commit()}cancelOperation(){const t=this.operation;this.operation=null,t?.isActive&&t.cancel()}updateShape(t,e,n){if(!this.info)return;const r=this.info.originScreenPoint.dist(e);if(!this.info.isDragCreating){if(r<4)return;this.info.isDragCreating=!0}const o=function(t,e,n){let r=e.x-t.x,o=e.y-t.y;if(n){const t=Math.max(Math.abs(r),Math.abs(o));r=(r<0?-1:1)*t,o=(o<0?-1:1)*t}const i=new bt(t.x+r,t.y+o);return new vt(Math.min(t.x,i.x),Math.min(t.y,i.y),Math.max(Math.abs(i.x-t.x),1),Math.max(Math.abs(i.y-t.y),1))}(this.info.originPagePoint,t,n),i=this.info.shapeId;i&&this.editor.commands.updateShapes([{id:i,x:o.x,y:o.y,props:{w:o.w,h:o.h}}],{source:"user"})}createShape(t,e){const[n]=this.editor.commands.createShapes([{type:"geo",x:t.x,y:t.y,props:{...e,w:t.w,h:t.h}}],{source:"user",autoReparent:!1});if(!n)throw new Error("Failed to create geo shape");return this.editor.commands.setSelectedShapeIds([n.id],{source:"system"}),n}},_i=class extends Xi{constructor(t){super(t,"rectangle","rectangle")}},qi=class extends Xi{constructor(t){super(t,"ellipse","ellipse")}},Vi=class extends Xi{constructor(t){super(t,"message-circle","message-circle")}},Gi=class extends Xi{constructor(t){super(t,"summary","summary")}},Ji=class extends Xi{constructor(t){super(t,"summary-left","summary-left")}},Zi=class extends Xi{constructor(t){super(t,"burst","burst")}},Qi=class extends Xi{constructor(t){super(t,"rhombus","rhombus")}},ts=class extends Xi{constructor(t){super(t,"triangle","triangle")}},es=class extends Xi{constructor(t){super(t,"pentagon","pentagon")}},ns=class extends Xi{constructor(t){super(t,"hexagon","hexagon")}},rs=class extends Xi{constructor(t){super(t,"star","star")}},os=class extends Xi{constructor(t){super(t,"trapezoid","trapezoid")}},is=class extends Xi{constructor(t){super(t,"arrow-left","arrow-left")}},ss=class extends Xi{constructor(t){super(t,"arrow-right","arrow-right")}},as=bn("plugin-geo.api");function ls({editor:t}){return function({editor:t}){return{create:e=>function(t,e){const n=t.shapes.getDefaultProps("geo"),[r]=t.commands.createShapes([{type:"geo",x:e.x,y:e.y,meta:e.meta?{...e.meta}:void 0,props:{...n,kind:e.kind,w:e.w??n.w,h:e.h??n.h,fill:e.fill??n.fill,stroke:e.stroke??n.stroke,strokeStyle:e.strokeStyle??n.strokeStyle,strokeWidth:e.strokeWidth??n.strokeWidth,cornerRadiusPercent:e.cornerRadiusPercent??n.cornerRadiusPercent}}],{source:"user"});return"geo"===r?.type?{id:r.id,type:r.type}:null}(t,e),getSelectionStyle:()=>function(t){const e=t.state.selectedShapes.get().filter(Wi);return 0===e.length?null:{kind:cs(e.map(t=>t.props.kind)),fill:cs(e.map(t=>t.props.fill)),stroke:cs(e.map(t=>t.props.stroke)),strokeStyle:cs(e.map(t=>t.props.strokeStyle)),strokeWidth:cs(e.map(t=>t.props.strokeWidth)),cornerRadiusPercent:cs(e.map(t=>t.props.cornerRadiusPercent))}}(t),setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(Wi).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)},getToolDefaults:()=>t.shapes.getDefaultProps("geo"),setToolDefaults:e=>(t.shapes.updateDefaultProps("geo",{...e}),t.shapes.getDefaultProps("geo"))}}({editor:t})}function cs(t){const[e,...n]=t;return void 0!==e&&n.every(t=>t===e)?e:null}var ds=/[AaCcHhLlMmVvZz]|[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?/g,us=/^[AaCcHhLlMmVvZz]$/,ps=Math.PI/6,hs=1e-8;function fs(t){const e=t.match(ds)??[],n=t.replace(ds,"").replace(/[\s,]/g,"");if(n.length>0)throw new Error(`Unsupported SVG path content: ${n}`);const r=[];let o=null,i=null,s=new bt(0,0),a=0;for(;a<e.length;){const t=e[a];if(t&&us.test(t)&&(i=t,a+=1,"z"===i.toLowerCase())){if(!o)throw new Error("SVG path closes before starting a subpath.");o.closed=!0,s=o.start.clone(),i=null;continue}if(!i)throw new Error("SVG path data is missing a command.");const n=i,l=gs(n),c=ms(e,a,l);a+=l;const d=n===n.toLowerCase();switch(n.toLowerCase()){case"m":s=xs(s,c[0],c[1],d),o={start:s.clone(),segments:[],closed:!1},r.push(o),i=d?"l":"L";break;case"l":{const t=xs(s,c[0],c[1],d);ws(o,{type:"line",start:s,end:t}),s=t;break}case"h":{const t=new bt(d?s.x+c[0]:c[0],s.y);ws(o,{type:"line",start:s,end:t}),s=t;break}case"v":{const t=new bt(s.x,d?s.y+c[0]:c[0]);ws(o,{type:"line",start:s,end:t}),s=t;break}case"c":{const t=xs(s,c[0],c[1],d),e=xs(s,c[2],c[3],d),n=xs(s,c[4],c[5],d);ws(o,{type:"cubic",start:s,control1:t,control2:e,end:n}),s=n;break}case"a":{const t=ys(c[3]),e=ys(c[4]),n=xs(s,c[5],c[6],d);ws(o,{type:"arc",start:s,end:n,radiusX:Math.abs(c[0]),radiusY:Math.abs(c[1]),rotation:c[2],largeArc:t,sweep:e}),s=n;break}}}return r}function gs(t){switch(t.toLowerCase()){case"m":case"l":return 2;case"h":case"v":return 1;case"c":return 6;case"a":return 7;default:throw new Error(`Unsupported SVG path command: ${t}`)}}function ms(t,e,n){const r=[];for(let o=0;o<n;o+=1){const n=t[e+o];if(!n||us.test(n))throw new Error("SVG path command has incomplete numeric values.");const i=Number(n);if(!Number.isFinite(i))throw new Error(`Invalid SVG path number: ${n}`);r.push(i)}return r}function ys(t){if(0!==t&&1!==t)throw new Error(`SVG arc flag must be 0 or 1, received ${t}.`);return 1===t}function xs(t,e,n,r){return r?new bt(t.x+e,t.y+n):new bt(e,n)}function ws(t,e){if(!t)throw new Error("SVG path draws before starting a subpath.");t.segments.push(e)}function bs(t){const e=[t.start.clone()];for(const n of t.segments)switch(n.type){case"line":Es(e,n.end);break;case"cubic":{const t=[...Array.from({length:8},(t,e)=>(e+1)/8),...ks(n)].sort((t,e)=>t-e).filter((t,e,n)=>0===e||Math.abs(t-(n[e-1]??t))>hs);for(const r of t)Es(e,vs(n,r));break}case"arc":for(const t of Ss(n))Es(e,t)}return t.closed&&e.length>1&&Ls(e[0],e[e.length-1])&&e.pop(),e}function vs(t,e){const n=1-e,r=n*n*n,o=3*n*n*e,i=3*n*e*e,s=e*e*e;return new bt(t.start.x*r+t.control1.x*o+t.control2.x*i+t.end.x*s,t.start.y*r+t.control1.y*o+t.control2.y*i+t.end.y*s)}function ks(t){return[...Ps(t.start.x,t.control1.x,t.control2.x,t.end.x),...Ps(t.start.y,t.control1.y,t.control2.y,t.end.y)].filter(t=>t>0&&t<1).sort((t,e)=>t-e).filter((t,e,n)=>0===e||Math.abs(t-(n[e-1]??t))>hs)}function Ps(t,e,n,r){const o=3*e-t-3*n+r,i=2*(t-2*e+n),s=e-t;if(Math.abs(o)<=hs)return Math.abs(i)<=hs?[]:[-s/i];const a=i*i-4*o*s;if(a<-1e-8)return[];const l=Math.sqrt(Math.max(0,a));return[(-i-l)/(2*o),(-i+l)/(2*o)]}function Ss(t){const e=Is(t);if(!e)return[t.end.clone()];const n=Math.max(1,Math.ceil(Math.abs(e.deltaAngle)/ps)),r=[...Array.from({length:n},(t,e)=>(e+1)/n),...Ms(e).map(t=>function(t,e){return Ts(t,e)/Math.abs(t.deltaAngle)}(e,t))].filter(t=>t>0&&t<=1).sort((t,e)=>t-e).filter((t,e,n)=>0===e||Math.abs(t-(n[e-1]??t))>hs),o=[];for(const i of r){const t=e.startAngle+e.deltaAngle*i;o.push(As(e,t))}return o[o.length-1]=t.end.clone(),o}function Is(t){if(0===t.radiusX||0===t.radiusY||Ls(t.start,t.end))return null;const e=t.rotation*Math.PI/180,n=Math.cos(e),r=Math.sin(e),o=(t.start.x-t.end.x)/2,i=(t.start.y-t.end.y)/2,s=n*o+r*i,a=-r*o+n*i;let l=t.radiusX,c=t.radiusY;const d=s*s/(l*l)+a*a/(c*c);if(d>1){const t=Math.sqrt(d);l*=t,c*=t}const u=l*l,p=c*c,h=s*s,f=a*a,g=u*f+p*h,m=Math.max(0,u*p-u*f-p*h),y=t.largeArc===t.sweep?-1:1,x=0===g?0:y*Math.sqrt(m/g),w=x*(l*a/c),b=x*(-c*s/l),v=n*w-r*b+(t.start.x+t.end.x)/2,k=r*w+n*b+(t.start.y+t.end.y)/2,P=(s-w)/l,S=(a-b)/c,I=(-s-w)/l,M=(-a-b)/c,T=Math.atan2(S,P);let C=(A=P,E=S,L=I,B=M,Math.atan2(A*B-E*L,A*L+E*B));var A,E,L,B;return!t.sweep&&C>0?C-=2*Math.PI:t.sweep&&C<0&&(C+=2*Math.PI),{centerX:v,centerY:k,radiusX:l,radiusY:c,cosRotation:n,sinRotation:r,startAngle:T,deltaAngle:C}}function Ms(t){const{radiusX:e,radiusY:n,cosRotation:r,sinRotation:o}=t,i=Math.atan2(-n*o,e*r),s=Math.atan2(n*r,e*o);return[i,i+Math.PI,s,s+Math.PI].filter(e=>function(t,e){return Ts(t,e)<=Math.abs(t.deltaAngle)+hs}(t,e))}function Ts(t,e){return t.deltaAngle>=0?Cs(e-t.startAngle):Cs(t.startAngle-e)}function Cs(t){const e=2*Math.PI;return(t%e+e)%e}function As(t,e){const n=t.radiusX*Math.cos(e),r=t.radiusY*Math.sin(e);return new bt(t.centerX+t.cosRotation*n-t.sinRotation*r,t.centerY+t.sinRotation*n+t.cosRotation*r)}function Es(t,e){const n=t[t.length-1];n&&Ls(n,e)||t.push(e.clone())}function Ls(t,e){return Math.abs(t.x-e.x)<=hs&&Math.abs(t.y-e.y)<=hs}var Bs=24,Rs=3.222,$s=12.443999999999999+Math.max(3.191,3.19)+1,Ns="m19.8415 12.945 1.827 1.428h-2.26a1 1 0 0 0-.972 1.232l.676 2.828-2.462-2.204a1 1 0 0 0-1.66.624l-.386 3.152-1.548-2.838c-.417-.765-1.545-.668-1.825.158l-1.064 3.138-.215-2.358a1 1 0 0 0-1.535-.751l-1.482.95.437-1.803a1 1 0 0 0-1.099-1.228l-2.962.38 1.446-1.17a1 1 0 0 0 .036-1.525L2.1425 10.6l3.088-.791a1 1 0 0 0 .534-1.592l-2-2.513L7.7425 7.879a1 1 0 0 0 1.434-.578l.775-2.464 1.377 2.067a1 1 0 0 0 1.635.042l2.539-3.41-.115 2.574a1 1 0 0 0 1.16 1.031l2.59-.42-.804 1.34a1 1 0 0 0 .67 1.496l2.853.544-1.93 1.207a1 1 0 0 0-.085 1.636Z",zs=function(t){const e=function(t){return fs(t).map(t=>({closed:t.closed,points:bs(t)}))}(t),[n]=e;if(1!==e.length||!n||!n.closed)throw new Error("Geo path must contain exactly one closed subpath.");return n.points}(Ns),Os=function(t){const e=[];for(const n of fs(t)){e.push(n.start.clone());for(const t of n.segments)switch(e.push(t.end.clone()),t.type){case"line":break;case"cubic":for(const n of ks(t))e.push(vs(t,n));break;case"arc":{const n=Is(t);if(!n)break;for(const t of Ms(n))e.push(As(n,t));break}}}if(0===e.length)throw new Error("SVG path does not contain any points.");return vt.FromPoints(e)}(Ns),Ws=[[3.383,17.776],[4.46,19.1],[19.54,19.1],[20.617,17.776],[18.117,5.776],[17.04,4.9],[6.96,4.9],[5.883,5.776]],Hs=[[12.444,3.002],[12.444,7.316],[20.709,7.316],[20.809,7.416],[20.809,15.871],[20.709,15.971],[12.444,15.971],[12.444,20.285],[12.275,20.357],[3.222,11.716],[3.222,11.571],[12.275,2.93]],Ds=[[11.556,3.002],[11.556,7.316],[3.29,7.316],[3.19,7.416],[3.19,15.87],[3.29,15.97],[11.556,15.97],[11.556,20.285],[11.725,20.357],[20.778,11.716],[20.778,11.571],[11.725,2.93]];function Fs(t,e,n={}){switch(e){case"ellipse":return function(t,e=32){const n=[];for(let r=0;r<e;r+=1){const o=r/e*Math.PI*2;n.push(new bt(t.center.x+t.w/2*Math.cos(o),t.center.y+t.h/2*Math.sin(o)))}return n}(t);case"message-circle":return function(t){const e=[aa(t,Ks),aa(t,_s)];let n=_s;for(const r of qs){for(let o=1;o<=Ys;o+=1)e.push(aa(t,sa(n,r.control1,r.control2,r.end,o/Ys)));n=r.end}return e}(t);case"summary":case"summary-left":return ha(t);case"burst":return function(t){return zs.map(e=>da(t,(e.x-Os.minX)/Os.w,(e.y-Os.minY)/Os.h))}(t);case"rhombus":return[new bt(t.center.x,t.minY),new bt(t.maxX,t.center.y),new bt(t.center.x,t.maxY),new bt(t.minX,t.center.y)];case"triangle":return[new bt(t.center.x,t.minY),new bt(t.maxX,t.maxY),new bt(t.minX,t.maxY)];case"pentagon":return function(t,e){const n=[];for(let r=0;r<e;r+=1){const t=-Math.PI/2+r*Math.PI*2/e;n.push(new bt(Math.cos(t),Math.sin(t)))}return ua(n,t)}(t,5);case"hexagon":return[new bt(t.minX+.25*t.w,t.minY),new bt(t.maxX-.25*t.w,t.minY),new bt(t.maxX,t.center.y),new bt(t.maxX-.25*t.w,t.maxY),new bt(t.minX+.25*t.w,t.maxY),new bt(t.minX,t.center.y)];case"star":return function(t){const e=[];for(let n=0;n<10;n+=1){const t=-Math.PI/2+n*Math.PI/5,r=n%2==0?1:.48;e.push(new bt(Math.cos(t)*r,Math.sin(t)*r))}return ua(e,t)}(t);case"trapezoid":return function(t){return Ws.map(([e,n])=>da(t,e/Bs,n/Bs))}(t);case"arrow-left":return ta(t,"left").outline;case"arrow-right":return ta(t,"right").outline;case"rectangle":return function(t,e=Us(t),n=4){const r=Math.min(Math.max(0,e),Math.max(0,t.w)/2,Math.max(0,t.h)/2);if(0===r)return ha(t);const o=[];return pa(o,{centerX:t.maxX-r,centerY:t.minY+r,radius:r,startAngle:-Math.PI/2,endAngle:0,segments:n}),pa(o,{centerX:t.maxX-r,centerY:t.maxY-r,radius:r,startAngle:0,endAngle:Math.PI/2,segments:n}),pa(o,{centerX:t.minX+r,centerY:t.maxY-r,radius:r,startAngle:Math.PI/2,endAngle:Math.PI,segments:n}),pa(o,{centerX:t.minX+r,centerY:t.minY+r,radius:r,startAngle:Math.PI,endAngle:3*Math.PI/2,segments:n}),o}(t,Us({cornerRadiusPercent:n.cornerRadiusPercent,w:t.w,h:t.h}))}return ga(e)}function js(t,e=12){return Math.min(50,Math.max(0,"number"==typeof t&&Number.isFinite(t)?t:e))}function Us({cornerRadiusPercent:t=12,h:e,w:n}){return Math.min(Math.max(0,n),Math.max(0,e))*js(t)/100}var Xs=24,Ys=8,Ks=new bt(3,20),_s=new bt(4.3,16.1),qs=[{control1:new bt(1.976,12.663),control2:new bt(2.874,8.228),end:new bt(6.4,5.726)},{control1:new bt(9.926,3.225),control2:new bt(14.99,3.43),end:new bt(18.245,6.206)},{control1:new bt(21.5,8.983),control2:new bt(21.94,13.472),end:new bt(19.274,16.707)},{control1:new bt(16.608,19.942),control2:new bt(11.659,20.922),end:new bt(7.7,19)}];function Vs(t){const e=aa(t,Ks),n=aa(t,_s),r=[`M${la(e)}`,`L${la(n)}`];for(const o of qs)r.push(`C${la(aa(t,o.control1))} ${la(aa(t,o.control2))} ${la(aa(t,o.end))}`);return r.push(`L${la(e)}`),r.join(" ")}function Gs(t){const e=t.w/Bs,n=t.h/Bs;return`translate(${ca(t.x)} ${ca(t.y)}) scale(${ca(e)} ${ca(n)})`}function Js(t){const e=t.w/Os.w,n=t.h/Os.h,r=t.minX-Os.minX*e,o=t.minY-Os.minY*n;return`translate(${ca(r)} ${ca(o)}) scale(${ca(e)} ${ca(n)})`}function Zs(t,e){const n=Math.min(t.w/Bs,t.h/18),r=t.h/18,o="left"===e?t.minX-3*n:t.maxX-20*n,i=t.minY-3*r;return`translate(${ca(o)} ${ca(i)}) scale(${ca(n)} ${ca(r)})`}function Qs(t,e,n={}){switch(e){case"ellipse":return{tag:"ellipse",cx:t.center.x,cy:t.center.y,rx:t.w/2,ry:t.h/2};case"message-circle":return{tag:"path",d:Vs(t)};case"summary":return{tag:"path",d:"M16 15a3.2 3.2 0 0 0-1.618-2.783L14 12l.382-.217C15.382 11.213 16 10.15 16 9V7a4 4 0 0 1 4-4M16 15v2a4 4 0 0 0 4 4",fill:"none",transform:Zs(t,"right"),vectorEffect:"non-scaling-stroke"};case"summary-left":return{tag:"path",d:"M7 15c0-1.151.618-2.214 1.618-2.783L9 12l-.382-.217A3.2 3.2 0 0 1 7 9V7a4 4 0 0 0-4-4M7 15v2a4 4 0 0 1-4 4",fill:"none",transform:Zs(t,"left"),vectorEffect:"non-scaling-stroke"};case"burst":return{tag:"path",d:Ns,transform:Js(t),vectorEffect:"non-scaling-stroke"};case"trapezoid":return{tag:"path",d:"M3.383 17.776A1.1 1.1 0 0 0 4.46 19.1h15.08a1.1 1.1 0 0 0 1.077-1.324l-2.5-12A1.1 1.1 0 0 0 17.04 4.9H6.96a1.1 1.1 0 0 0-1.077.876z",transform:Gs(t),vectorEffect:"non-scaling-stroke"};case"arrow-left":return{tag:"path",d:ta(t,"left").path};case"arrow-right":return{tag:"path",d:ta(t,"right").path};case"rectangle":{const e=Us({cornerRadiusPercent:n.cornerRadiusPercent,w:t.w,h:t.h});return{tag:"rect",x:t.x,y:t.y,width:t.w,height:t.h,rx:e,ry:e}}case"rhombus":case"triangle":case"pentagon":case"hexagon":case"star":return{tag:"polygon",points:Fs(t,e,n)}}return ga(e)}function ta(t,e){const n=Math.min(t.h/Bs,t.w/$s),r=t.center.y-12*n,o="left"===e?t.minX+Rs*n:t.maxX-Rs*n,i="left"===e?o+9.222*n:o-9.222*n;return{outline:("left"===e?Hs:Ds).map(([o,s])=>function(t,e,n){const{neckX:r,originY:o,scale:i,x:s,y:a}=n;let l;l="left"===e?s<=12.444?r+(s-12.444)*i:s>=20.709?t.maxX-(Bs-s)*i:ra(s,12.444,20.709,r,t.maxX-3.2910000000000004*i):s>=11.556?r+(s-11.556)*i:s<=3.29?t.minX+s*i:ra(s,3.29,11.556,t.minX+3.29*i,r);return new bt(l,o+a*i)}(t,e,{neckX:i,originY:r,scale:n,x:o,y:s})),path:"left"===e?ea(t,{neckX:i,originY:r,scale:n}):na(t,{neckX:i,originY:r,scale:n})}}function ea(t,e){if(ia(t))return"M12.444 6.416v.9h8.265a.1.1 0 0 1 .1.1v8.455a.1.1 0 0 1-.1.1h-8.265v4.314c0 .034-.008.048-.014.056a.1.1 0 0 1-.047.036.1.1 0 0 1-.058.009c-.01-.002-.025-.005-.05-.029l-9.053-8.641a.1.1 0 0 1 0-.145l9.053-8.641c.025-.024.04-.028.05-.03a.1.1 0 0 1 .058.01.1.1 0 0 1 .047.036c.006.008.014.022.014.056z";const{neckX:n,originY:r,scale:o}=e,i=t.maxX-3.2910000000000004*o;return[`M${la(new bt(n,r+6.416*o))}`,`v${ca(.9*o)}`,`H${ca(i)}`,`a${oa(o,[.1,.1,0,0,1,.1,.1])}`,`v${ca(8.455*o)}`,`a${oa(o,[.1,.1,0,0,1,-.1,.1])}`,`H${ca(n)}`,`v${ca(4.314*o)}`,`c${oa(o,[0,.034,-.008,.048,-.014,.056])}`,`a${oa(o,[.1,.1,0,0,1,-.047,.036])}`,`a${oa(o,[.1,.1,0,0,1,-.058,.009])}`,`c${oa(o,[-.01,-.002,-.025,-.005,-.05,-.029])}`,`l${oa(o,[-9.053,-8.641])}`,`a${oa(o,[.1,.1,0,0,1,0,-.145])}`,`l${oa(o,[9.053,-8.641])}`,`c${oa(o,[.025,-.024,.04,-.028,.05,-.03])}`,`a${oa(o,[.1,.1,0,0,1,.058,.01])}`,`a${oa(o,[.1,.1,0,0,1,.047,.036])}`,`c${oa(o,[.006,.008,.014,.022,.014,.056])}`,"z"].join(" ")}function na(t,e){if(ia(t))return"M10.656 7.316h.9V3.002c0-.034.008-.048.014-.056a.1.1 0 0 1 .046-.036.1.1 0 0 1 .059-.01c.01.002.025.006.05.03l9.053 8.641a.1.1 0 0 1 0 .145l-9.053 8.641c-.025.024-.04.027-.05.029a.1.1 0 0 1-.059-.01.1.1 0 0 1-.046-.035c-.006-.008-.014-.022-.014-.056V15.97H3.29a.1.1 0 0 1-.1-.1V7.416a.1.1 0 0 1 .1-.1z";const{neckX:n,originY:r,scale:o}=e,i=t.minX+3.29*o;return[`M${la(new bt(n-.9*o,r+7.316*o))}`,`H${ca(n)}`,`V${ca(r+3.002*o)}`,`c${oa(o,[0,-.034,.008,-.048,.014,-.056])}`,`a${oa(o,[.1,.1,0,0,1,.046,-.036])}`,`a${oa(o,[.1,.1,0,0,1,.059,-.01])}`,`c${oa(o,[.01,.002,.025,.006,.05,.03])}`,`l${oa(o,[9.053,8.641])}`,`a${oa(o,[.1,.1,0,0,1,0,.145])}`,`l${oa(o,[-9.053,8.641])}`,`c${oa(o,[-.025,.024,-.04,.027,-.05,.029])}`,`a${oa(o,[.1,.1,0,0,1,-.059,-.01])}`,`a${oa(o,[.1,.1,0,0,1,-.046,-.035])}`,`c${oa(o,[-.006,-.008,-.014,-.022,-.014,-.056])}`,`V${ca(r+15.97*o)}`,`H${ca(i)}`,`a${oa(o,[.1,.1,0,0,1,-.1,-.1])}`,`V${ca(r+7.416*o)}`,`a${oa(o,[.1,.1,0,0,1,.1,-.1])}`,"z"].join(" ")}function ra(t,e,n,r,o){const i=n-e;return 0===i?r:r+(t-e)/i*(o-r)}function oa(t,e){const n=7===e.length;return e.map((e,r)=>ca(n&&r>=2&&r<=4?e:e*t)).join(" ")}function ia(t){return 0===t.x&&0===t.y&&t.w===Bs&&t.h===Bs}function sa(t,e,n,r,o){const i=1-o,s=i*i*i,a=3*i*i*o,l=3*i*o*o,c=o*o*o;return new bt(t.x*s+e.x*a+n.x*l+r.x*c,t.y*s+e.y*a+n.y*l+r.y*c)}function aa(t,e){return da(t,e.x/Xs,e.y/Xs)}function la(t){return`${ca(t.x)} ${ca(t.y)}`}function ca(t){return Number.isFinite(t)?Number(t.toFixed(4)).toString():"0"}function da(t,e,n){return new bt(t.minX+t.w*e,t.minY+t.h*n)}function ua(t,e){const n=vt.FromPoints([...t]);return 0===n.w||0===n.h?[e.center]:t.map(t=>new bt(e.minX+(t.x-n.minX)/n.w*e.w,e.minY+(t.y-n.minY)/n.h*e.h))}function pa(t,{centerX:e,centerY:n,endAngle:r,radius:o,segments:i,startAngle:s}){const a=Math.max(1,Math.floor(i));for(let l=0;l<=a;l+=1){const i=s+(r-s)*(l/a);t.push(new bt(e+Math.cos(i)*o,n+Math.sin(i)*o))}}function ha(t){return[new bt(t.minX,t.minY),new bt(t.maxX,t.minY),new bt(t.maxX,t.maxY),new bt(t.minX,t.maxY)]}function fa(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist(e);const i=t.sub(e),s=Math.max(0,Math.min(1,(i.x*r.x+i.y*r.y)/o));return t.dist(e.add(r.mul(s)))}function ga(t){throw new Error(`Unsupported geo shape kind: ${String(t)}`)}function ma(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function ya(t,e){return t.x*e.y-t.y*e.x}function xa(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist(e);const i=t.sub(e),s=Math.max(0,Math.min(1,(i.x*r.x+i.y*r.y)/o));return t.dist(e.add(r.mul(s)))}function wa(t,e,n,r){return ba(t,e,n,r)?0:Math.min(xa(t,n,r),xa(e,n,r),xa(n,t,e),xa(r,t,e))}function ba(t,e,n,r){const o=e.sub(t),i=r.sub(n),s=ya(o,i);if(Math.abs(s)<1e-8)return null;const a=n.sub(t),l=ya(a,i)/s,c=ya(a,o)/s;return l<0||l>1||c<0||c>1?null:{point:t.add(o.mul(l)),t:l}}function va(t,e,n){const r=new vt(t.x,t.y,t.props.w,t.props.h);return"ellipse"===t.props.kind?function(t,e,n){const r=t.center,o=t.w/2,i=t.h/2;if(o<=0||i<=0)return null;const s=e.sub(r),a=n.sub(e),l=a.x/o,c=a.y/i,d=s.x/o,u=s.y/i,p=l*l+c*c,h=2*(d*l+u*c),f=h*h-4*p*(d*d+u*u-1);if(0===p||f<0)return null;const g=Math.sqrt(f),m=[(-h-g)/(2*p),(-h+g)/(2*p)].filter(t=>t>1e-6&&t<=1).sort((t,e)=>t-e)[0];return void 0===m?null:e.add(a.mul(m))}(r,e,n):function(t,e,n){let r=null;for(let o=0;o<n.length;o+=1){const i=n[o],s=n[(o+1)%n.length]??n[0];if(!i||!s)continue;const a=ba(t,e,i,s);!a||a.t<=1e-6||(!r||a.t<r.t)&&(r=a)}return r?.point??null}(e,n,Fs(r,t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent}))}function ka(t){return Fs(new vt(0,0,t.props.w,t.props.h),t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent})}var Pa=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"];function Sa(t){const e=new vt(0,0,t.props.w,t.props.h);return[new bt(e.minX,e.minY),new bt(e.center.x,e.minY),new bt(e.maxX,e.minY),new bt(e.minX,e.center.y),e.center,new bt(e.maxX,e.center.y),new bt(e.minX,e.maxY),new bt(e.center.x,e.maxY),new bt(e.maxX,e.maxY)].map((t,e)=>({point:t,kind:Pa[e]??"custom"}))}function Ia(t){return"arrow-left"===t.props.kind||"arrow-right"===t.props.kind}function Ma(t){return vt.FromPoints(Fs(new vt(0,0,t.w,t.h),t.kind,{cornerRadiusPercent:t.cornerRadiusPercent}))}var Ta=class extends pe{type="geo";getDefaultProps(){return{w:160,h:108,kind:"rectangle",fill:Et("fill-slate"),stroke:Et("stroke-slate"),strokeStyle:"solid",strokeWidth:2,cornerRadiusPercent:12}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Math.max(24,ma(e.w,n.w)),h:Math.max(24,ma(e.h,n.h)),kind:Hi(e.kind)?e.kind:n.kind,fill:$t(e.fill,n.fill),stroke:$t(e.stroke,n.stroke),strokeStyle:Di(e.strokeStyle)?e.strokeStyle:n.strokeStyle,strokeWidth:Math.max(1,ma(e.strokeWidth,n.strokeWidth)),cornerRadiusPercent:js(e.cornerRadiusPercent,n.cornerRadiusPercent)}}getLocalBounds(t){return new vt(0,0,t.props.w,t.props.h)}canReceiveTerminalBinding(t){return!0}getPositionedOutlineVertices(t){return Fs(this.getPositionedBounds(t),t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent})}getSelectionResizeLocalBounds(t){return Ia(t)?Ma(t.props):this.getLocalBounds(t)}resizeSelectionBounds(t,e){if(!Ia(t))return super.resizeSelectionBounds(t,e);const n=Ma(t.props).w*Math.abs(e.scaleX),r=Math.max(24,t.props.h*Math.abs(e.scaleY)),o=function({direction:t,height:e,selectionWidth:n}){const r=Rs+("left"===t?3.191:3.19),o=e/Bs,i=n+r*o;return i>=$s*o?i:n/(1-r/$s)}({direction:"arrow-left"===t.props.kind?"left":"right",height:r,selectionWidth:n}),i=this.validateProps({...t.props,w:o,h:r}),s=Ma(i),a=Qt({localWidth:s.w,localHeight:s.h,scaleX:t.scaleX,scaleY:t.scaleY}),l=Jt(ee({requestedBounds:e.selectionLocalBounds,handleId:e.handleId,actualWidth:a.width,actualHeight:a.height,scaleX:e.scaleX,scaleY:e.scaleY,isResizingFromCenter:e.isResizingFromCenter}).center,{rotation:e.selectionRotation,rotationCenter:e.selectionRotationCenter}),c=e.scaleX<0!=e.scaleY<0?2*e.selectionRotation-t.rotation:t.rotation,d=e.scaleX<0?-t.scaleX:t.scaleX,u=e.scaleY<0?-t.scaleY:t.scaleY,p=new vt(0,0,i.w,i.h).center,h=s.center.sub(p),f=new bt(h.x*d,h.y*u).rot(c);return{id:t.id,x:l.x-p.x-f.x,y:l.y-p.y-f.y,rotation:c,scaleX:d,scaleY:u,props:i}}getHandleSnapGeometry(t){return{points:Sa(t),outline:ka(t)}}hitTest(t,e){const n=this.getPositionedBounds(t);if("ellipse"===t.props.kind){const t=n.w/2,r=n.h/2;if(t<=0||r<=0)return!1;const o=e.x-n.center.x,i=e.y-n.center.y;return o*o/(t*t)+i*i/(r*r)<=1}return function(t,e){if(e.length<3)return!1;let n=!1;for(let r=0,o=e.length-1;r<e.length;o=r,r+=1){const i=e[r],s=e[o];if(!i||!s)continue;if(fa(t,i,s)<=1e-6)return!0;if(i.y>t.y==s.y>t.y)continue;const a=(s.x-i.x)*(t.y-i.y)/(s.y-i.y)+i.x;t.x<a&&(n=!n)}return n}(e,Fs(n,t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent}))}hitTestLineSegment(t,e){const n=this.getPositionedBounds(t);if("ellipse"===t.props.kind)return function(t,e,n,r){const o=t.center,i=t.w/2+r,s=t.h/2+r;if(i<=0||s<=0)return!1;const a=n.sub(e),l=e.sub(o),c=a.x/i,d=a.y/s,u=l.x/i,p=l.y/s,h=c*c+d*d,f=2*(u*c+p*d),g=u*u+p*p-1;if(g<=0)return!0;const m=f*f-4*h*g;if(0===h||m<0)return!1;const y=Math.sqrt(m),x=(-f-y)/(2*h),w=(-f+y)/(2*h);return x>=0&&x<=1||w>=0&&w<=1}(n,e.positionedStart,e.positionedEnd,e.positionedMargin);{const r=Fs(n,t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent});return this.hitTest(t,e.positionedStart)||this.hitTest(t,e.positionedEnd)||function(t,e,n,r){if(n.length<3)return!1;for(let o=0;o<n.length;o+=1){const i=n[o],s=n[(o+1)%n.length];if(i&&s&&wa(t,e,i,s)<=r)return!0}return!1}(e.positionedStart,e.positionedEnd,r,e.positionedMargin)}}resolveBindingPoint(t,e){const n=e.editor.shapes.computePositionedToPageTransform(t),r=n.tryInvert();if(!r)return e.rawPagePoint;const o=va(t,r.applyToPoint(e.rawPagePoint),r.applyToPoint(e.oppositePagePoint));return o?n.applyToPoint(o):e.rawPagePoint}};function Ca(t,e){switch(t){case"dashed":return`${4*e} ${2*e}`;case"dotted":return"0 "+2*e;default:return}}var Aa=class{type="geo";toSvg(t,e){const{kind:n,fill:r,stroke:o,strokeStyle:i,strokeWidth:s,w:a,h:l}=t.props,c="none"===i?0:s,d=c/2,u=Math.max(a-c,0),p=Math.max(l-c,0),h={fill:e.resolveColor(r),stroke:"none"===i?"none":e.resolveColor(o),"stroke-width":c,"stroke-dasharray":Ca(i,s),"stroke-linejoin":"round","stroke-linecap":"round"};return function(t,e){switch(t.tag){case"ellipse":return{tag:"ellipse",attrs:{...e,cx:t.cx,cy:t.cy,rx:t.rx,ry:t.ry}};case"path":return{tag:"path",attrs:{...e,fill:t.fill??e.fill,d:t.d,transform:t.transform,"vector-effect":t.vectorEffect}};case"polygon":return{tag:"polygon",attrs:{...e,points:t.points.map(t=>`${La(t.x)},${La(t.y)}`).join(" ")}};case"rect":return{tag:"rect",attrs:{...e,x:t.x,y:t.y,width:t.width,height:t.height,rx:t.rx,ry:t.ry}}}}(Qs(new vt(d,d,u,p),n,{cornerRadiusPercent:t.props.cornerRadiusPercent}),h)}};function Ea(){return{id:"land.geo",shapeUtils:[new Ta],shapeSvgExporters:[new Aa],setup(t){t.runtime.provide(Fi,function(t){const e=t.signals.atom("geo.creation-hover",null,{isEqual:(t,e)=>t===e||null!==t&&null!==e&&t.timestamp===e.timestamp&&t.pagePoint.equals(e.pagePoint)});return{preview:t.signals.computed("geo.creation-preview",()=>{const n=e.get(),r=t.inputs.state.get(),o=t.state.tool.get();if(!n||t.state.readonly.get()||t.inputs.isSpacePressed.get()||r.isPointing||r.currentTimestamp!==n.timestamp||!r.currentPagePoint?.equals(n.pagePoint)||!Hi(o.activeToolId))return null;const i={...t.shapes.getDefaultProps("geo"),kind:o.activeToolId};return{bounds:Ui(n.pagePoint,i),props:i}}),setHover(t){e.set({pagePoint:t.pagePoint.clone(),timestamp:t.timestamp})},clearHover(){null!==e.get()&&e.set(null)}}}(t)),t.tools.register("rectangle",t=>new _i(t)),t.tools.register("ellipse",t=>new qi(t)),t.tools.register("message-circle",t=>new Vi(t)),t.tools.register("summary",t=>new Gi(t)),t.tools.register("summary-left",t=>new Ji(t)),t.tools.register("burst",t=>new Zi(t)),t.tools.register("rhombus",t=>new Qi(t)),t.tools.register("triangle",t=>new ts(t)),t.tools.register("pentagon",t=>new es(t)),t.tools.register("hexagon",t=>new ns(t)),t.tools.register("star",t=>new rs(t)),t.tools.register("trapezoid",t=>new os(t)),t.tools.register("arrow-left",t=>new is(t)),t.tools.register("arrow-right",t=>new ss(t))}}}function La(t){return Number.isFinite(t)?Number(t.toFixed(4)).toString():"0"}function Ba(){return{id:"land.geo.react",canvasOverlays:[{id:"land.geo.creation-preview",component:za,order:10}],shapeRenderers:[{type:"geo",component:Ra,hoverComponent:Oa}]}}function Ra({shape:t}){
5
+ return d(Na,{props:t.props})}function $a({geometry:t,fill:e,stroke:n,strokeWidth:r,strokeDasharray:o,vectorEffect:i}){const s={fill:"path"===t.tag&&"none"===t.fill?"none":e,stroke:n,strokeWidth:r,strokeDasharray:o,strokeLinejoin:"round",strokeLinecap:"round",vectorEffect:"path"===t.tag&&t.vectorEffect?t.vectorEffect:i};switch(t.tag){case"ellipse":return d("ellipse",{...s,cx:t.cx,cy:t.cy,rx:t.rx,ry:t.ry});case"path":return d("path",{...s,d:t.d,transform:t.transform});case"polygon":return d("polygon",{...s,points:t.points.map(t=>`${t.x},${t.y}`).join(" ")});case"rect":return d("rect",{...s,x:t.x,y:t.y,width:t.width,height:t.height,rx:t.rx,ry:t.ry})}}function Na({props:t,fill:e=t.fill,stroke:n=t.stroke,strokeStyle:r=t.strokeStyle,strokeWidth:o=t.strokeWidth,width:i="100%",height:s="100%"}){const a="none"===r?0:o,l=a/2,c=Qs(new vt(l,l,Math.max(t.w-a,0),Math.max(t.h-a,0)),t.kind,{cornerRadiusPercent:t.cornerRadiusPercent});
6
+ return d("svg",{width:i,height:s,viewBox:`0 0 ${t.w} ${t.h}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:d($a,{geometry:c,fill:Nt(e),stroke:"none"===r?"none":Nt(n),strokeWidth:a,strokeDasharray:Ca(r,o)})})}var za=g(function(){const t=r(ji(n()).preview);return t?d("g",{"data-ui":"geo-creation-preview",transform:`translate(${t.bounds.x} ${t.bounds.y})`,opacity:.48,pointerEvents:"none",children:d(Na,{props:t.props,width:t.bounds.w,height:t.bounds.h})}):null});function Oa({shape:t,strokeWidth:e}){const{h:n,w:r}=t.props,i=Qs(new vt(0,0,r,n),t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent});
7
+ return d("svg",{"data-ui":"geo-hover-outline",width:"100%",height:"100%",viewBox:`0 0 ${r} ${n}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:d($a,{geometry:i,fill:"none",stroke:o,strokeWidth:e,strokeDasharray:void 0,vectorEffect:"non-scaling-stroke"})})}var Wa={id:"geo",editor:Ea(),render:Ba(),api:as,setup:({editor:t})=>({api:ls({editor:t})})};function Ha(t,e){return t.pagePoint.add(t.pageOutwardNormal.mul(20/Math.max(e,1e-4)))}function Da(t,e,n){return e.dist(Ha(t,n))}function Fa(t,e,n={}){const r=t.state.cameraZoom.get(),o=12/Math.max(r,1e-4),i=o+("target"===n.mode?0:20/Math.max(r,1e-4)),s=t.shapes.getInBounds(new vt(e.x-i,e.y-i,2*i,2*i),n.pageId?{pageId:n.pageId}:void 0);let a=null,l=null,c=o,d=Number.POSITIVE_INFINITY;for(const u of s){if(n.excludeShapeIds?.has(u.id)||Tr(u)||t.shapes.isHidden(u.id)||null===t.shapes.getClippedPageBounds(u.id))continue;const i=se(t,u);if("target"===n.mode){if(0===i.length)continue;const r=ro(t,u,e,o);if(!r)continue;const{borderDistance:s,port:p}=r,h=u.id===n.allowInteriorShapeId&&t.shapes.hitTestPoint(e,{hitTest:"bindingTarget",pageId:n.pageId??void 0,filter:t=>t.id===u.id}).length>0;if(s>o&&h){l={shape:u,port:p};continue}if(s>c||s>o)continue;const f=p.pagePoint.dist(e),g=`${u.index}:${u.id}:${p.id}`,m=`${a?.shape.index}:${a?.shape.id}:${a?.port.id}`;(s<c||s===c&&f<d||s===c&&f===d&&g<m)&&(a={shape:u,port:p},c=s,d=f);continue}for(const t of i){const n=Da(t,e,r);(n<c||n===c&&`${u.index}:${u.id}:${t.id}`<`${a?.shape.index}:${a?.shape.id}:${a?.port.id}`)&&(a={shape:u,port:t},c=n)}}return a??l}function ja(t,e,n,r){const o=Ua(t,e,n);return!!o&&("connect"===o.kind?!!bi(t,{start:yi(e.shape.id,e.port),end:yi(o.target.shape.id,o.target.port),props:r,selectionAfter:[o.target.shape.id]}):function(t,e,n,r){const o=t.commands.createShapes([n.nodeInput],{source:"user",autoReparent:!1})[0];if(!o)return!1;const i=_a(t,o,e.port);if(!i)return t.commands.deleteShapes([o.id],{source:"user"}),!1;if(!bi(t,{start:yi(e.shape.id,e.port),end:yi(o.id,i),props:r,selectionAfter:[o.id]}))return t.commands.deleteShapes([o.id],{source:"user"}),!1;return!0}(t,e,o,r))}function Ua(t,e,n){const r=Va(t,e),o=new Set(r.map(t=>t.id)),i=Ya(t,e);for(const c of i)if(!o.has(c.shape.id)&&!Ai(t,e.shape.id,e.port.id,c.shape.id,c.port.id))return{kind:"connect",target:c};const s=function(t,e,n,r){const o=e.shape.parentId,i=Qa(t,e.shape),s=o.startsWith("shape:")?t.shapes.get(o):null,a=s?t.shapes.computeLocalToPageTransform(s):Ht.Identity(),l=e.port.pageOutwardNormal.normalize(),c=new bt(i.w/2,i.h/2),d=a.applyToPoint(c),u=a.applyToPoint(c.add(new bt(i.w/2,0))),p=a.applyToPoint(c.add(new bt(0,i.h/2))),h=Math.abs(tl(u.sub(d),l))+Math.abs(tl(p.sub(d),l)),f=e.port.pagePoint.add(l.mul(96+h)),g=n.createNode({editor:t,sourceShape:e.shape,sourcePortId:e.port.id,pageCenter:f,parentId:o});return 0===r.length?g:Ga({branchTargets:r,editor:t,input:g,source:e})}(t,e,n,r),a=Za(t,s),l=_a(t,a,e.port);return l?{kind:"create",nodeInput:s,previewShape:a,targetPort:l}:null}function Xa(t,e,n){const r=Va(t,e);return 0===r.length?n:Ga({branchTargets:r,editor:t,input:n,source:e})}function Ya(t,e){const n=e.port.pageOutwardNormal.normalize(),r=e.port.pagePoint.add(n.mul(320)),o=vt.FromPoints([e.port.pagePoint,r]).expand(160),i=t.layers.getPageId(e.shape.id);if(!i)return[];const s=new Map(t.state.currentPageShapeIds.get().map((t,e)=>[t,e])),a=t.shapes.getInBounds(o,{pageId:i}).filter(n=>n.id!==e.shape.id&&!Tr(n)&&!t.shapes.isHidden(n.id)&&null!==t.shapes.getClippedPageBounds(n.id)&&t.shapes.getUtil(n).canReceiveTerminalBinding(n,{editor:t})).flatMap(r=>{const o=t.shapes.getPageCenter(r.id);if(!o)return[];const i=o.sub(e.port.pagePoint),a=tl(i,n),l=Math.abs((d=n,(c=i).x*d.y-c.y*d.x));var c,d;const u=i.len();if(a<=0||a>320||l>160)return[];const p=Ka(t,r,e.port.pagePoint);return p?[{shape:r,port:p,distance:u,forward:a,cross:l,order:s.get(r.id)??1/0}]:[]});return a.sort((t,e)=>t.distance-e.distance||t.cross-e.cross||t.forward-e.forward||t.order-e.order||t.shape.id.localeCompare(e.shape.id)||t.port.id.localeCompare(e.port.id)),a.map(({shape:t,port:e})=>({shape:t,port:e}))}function Ka(t,e,n){return[...se(t,e)].sort((t,e)=>{const r=n.sub(t.pagePoint).normalize(),o=n.sub(e.pagePoint).normalize(),i=tl(t.pageOutwardNormal,r);return tl(e.pageOutwardNormal,o)-i||t.pagePoint.dist(n)-e.pagePoint.dist(n)||t.id.localeCompare(e.id)})[0]??null}function _a(t,e,n){const r=n.pageOutwardNormal.normalize();return[...se(t,e)].sort((t,e)=>tl(t.pageOutwardNormal.normalize(),r)-tl(e.pageOutwardNormal.normalize(),r)||t.pagePoint.dist(n.pagePoint)-e.pagePoint.dist(n.pagePoint)||t.id.localeCompare(e.id))[0]??null}function qa(){return{createNode({editor:t,sourceShape:e,pageCenter:n,parentId:r}){const o=Qa(t,e),i=r.startsWith("shape:")?t.shapes.get(r):null,s=(i?t.shapes.computeLocalToPageTransform(i):Ht.Identity()).tryInvert()?.applyToPoint(n)??n;return{type:"geo",parentId:r,x:s.x-o.w/2,y:s.y-o.h/2,rotation:0,props:{...o}}}}}function Va(t,e){const n=[],r=new Set;for(const o of t.state.currentPageShapeIds.get()){const i=t.shapes.get(o);if(!Tr(i))continue;const s=Ar(t,i.id),a=s.start?.toId===e.shape.id&&s.start.props.portId===e.port.id?s.end:s.end?.toId===e.shape.id&&s.end.props.portId===e.port.id?s.start:null;if(!a)continue;const l=t.shapes.get(a.toId);!l||r.has(l.id)||Tr(l)||t.shapes.isHidden(l.id)||null===t.shapes.getClippedPageBounds(l.id)||(r.add(l.id),n.push(l))}return n}function Ga({branchTargets:t,editor:e,input:n,source:r}){const o=Za(e,n),i=e.shapes.computePageCenter(o),s=new bt(-r.port.pageOutwardNormal.y,r.port.pageOutwardNormal.x).normalize();if(0===s.len2())return n;const a=tl(r.port.pagePoint,s),l=Ja(e,o,s,a),c=(l.max-l.min)/2,d=function(t,e){const n=t.map(({min:t,max:n})=>({min:t-48-e,max:n+48+e})).sort((t,e)=>t.min-e.min||t.max-e.max),r=[];for(const s of n){const t=r[r.length-1];!t||s.min>t.max+1e-6?r.push({...s}):t.max=Math.max(t.max,s.max)}const o=r.find(({min:t,max:e})=>t<-1e-6&&e>1e-6);if(!o)return 0;const i=t.reduce((t,e)=>t+(e.min+e.max)/2,0);return[o.min,o.max].sort((t,e)=>Math.abs(i+t)-Math.abs(i+e)||Math.abs(t)-Math.abs(e)||e-t)[0]}(t.map(t=>Ja(e,t,s,a)),c)-(tl(i,s)-a);if(Math.abs(d)<=1e-6)return n;const u=n.parentId??r.shape.parentId,p=u.startsWith("shape:")?e.shapes.get(u):null,h=(p?e.shapes.computeLocalToPageTransform(p):Ht.Identity()).tryInvert();if(!h)return n;const f=i.add(s.mul(d)),g=h.applyToPoint(i),m=h.applyToPoint(f).sub(g);return{...n,x:n.x+m.x,y:n.y+m.y}}function Ja(t,e,n,r){const o=t.shapes.computePageCorners(e).map(t=>tl(t,n)-r);return{min:Math.min(...o),max:Math.max(...o)}}function Za(t,e){const n={id:"shape:connector-quick-create-preview",typeName:"shape",scope:"document",type:e.type,parentId:e.parentId??t.pages.getCurrentId(),index:e.index??"preview",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:{...t.shapes.getDefaultProps(e.type),...e.props},meta:e.meta??{}};return{...n,props:t.shapes.getUtil(n).validateProps(n.props)}}function Qa(t,e){return Wi(e)?{w:e.props.w,h:e.props.h,kind:e.props.kind,fill:e.props.fill,stroke:e.props.stroke,strokeStyle:e.props.strokeStyle,strokeWidth:e.props.strokeWidth,cornerRadiusPercent:e.props.cornerRadiusPercent}:t.shapes.getDefaultProps("geo")}function tl(t,e){return t.x*e.x+t.y*e.y}function el(t){const e={visibleShapes:[],sourceShapeIds:new Set,targetShapeId:null,highlightedPortId:null};if(t.state.readonly.get()||t.state.shapeEditingSession.get()||t.inputs.isSpacePressed.get())return e;const n=mi(t).previewSignal.get();if(n){const e=new Map;for(const o of[n.start,n.end]){if(!o.shapeId)continue;const n=t.shapes.get(o.shapeId);n&&rl(t,n,"target")&&e.set(n.id,n)}const r=n[n.movingTerminal];return{visibleShapes:[...e.values()],sourceShapeIds:new Set,targetShapeId:r.shapeId,highlightedPortId:r.portId}}const r=t.state.tool.get().activeToolId;let o=null;if("select"===r){const e=t.state.selectedShapes.get();o=1===e.length?e[0]??null:null}else if("connector"===r){const e=t.render.interaction.hoveredShapeId.get();o=e?t.shapes.get(e)??null:null}return o&&rl(t,o,"source")?{visibleShapes:[o],sourceShapeIds:new Set([o.id]),targetShapeId:null,highlightedPortId:null}:e}function nl(t,e){const n=el(t),r=mi(t),o=Math.max(t.state.cameraZoom.get(),1e-4),i=12/o;let s=null;for(const a of n.visibleShapes)if(n.sourceShapeIds.has(a.id)&&t.shapes.getUtil(a).canUseTerminalBindingPortHandles(a,{editor:t}))for(const n of se(t,a)){if(!r.isPortVisible(n.id))continue;const t=Da(n,e,o);t<=i+1e-6&&(!s||t<s.distance||t===s.distance&&`${a.index}:${a.id}:${n.id}`<`${s.shape.index}:${s.shape.id}:${s.port.id}`)&&(s={shape:a,port:n,distance:t})}return s?{shape:s.shape,port:s.port}:null}function rl(t,e,n){const r=se(t,e);return!Tr(e)&&!t.shapes.isHidden(e.id)&&null!==t.shapes.getClippedPageBounds(e.id)&&("target"===n||!t.layers.isOrAncestorLocked(e.id))&&t.shapes.getUtil(e).canReceiveTerminalBinding(e,{editor:t})&&("target"===n?r.length>0:r.some(e=>mi(t).isPortVisible(e.id)))}function ol(){return{id:"land.connector.react",shapeRenderers:[{type:"connector",component:ll,hoverComponent:cl}],selectionCustomHandleRenderers:[{type:ai,component:il},{type:li,component:sl},{type:ci,component:al}],canvasOverlays:[{id:"land.connector.ports-overlay",order:100,component:ul}]}}function il({handle:t,strokeWidth:e}){
8
+ return d("circle",{"data-selection-custom-handle":t.id,"data-selection-custom-handle-type":t.type,"data-selection-custom-handle-id":t.id,cx:t.point.x,cy:t.point.y,r:Math.max(t.bounds.w,t.bounds.h)/2,fill:"rgba(255,255,255,0.98)",stroke:"var(--land-selection, #2563eb)",strokeWidth:e,style:{cursor:t.cursor??"move",pointerEvents:"auto"}})}function sl({handle:t}){const e=.75*Math.max(t.bounds.w,t.bounds.h),n=.36*Math.max(t.bounds.w,t.bounds.h);
9
+ return u("g",{children:[d("circle",{"data-selection-custom-handle":t.id,"data-selection-custom-handle-type":t.type,"data-selection-custom-handle-id":t.id,cx:t.point.x,cy:t.point.y,r:e,fill:"transparent",style:{cursor:t.cursor??"move",pointerEvents:"all"}}),d("circle",{cx:t.point.x,cy:t.point.y,r:n,fill:"rgba(96, 165, 250, 0.72)",pointerEvents:"none"})]})}function al({handle:t,strokeWidth:e}){const n=fi(t.id);if(!n)return null;const r=Math.max(t.bounds.w,t.bounds.h),o="horizontal"===n.axis,i=1.35*r+2*e,s=.4*r,a=o?i:s,l=o?s:i,c=1.8*r;
10
+ return u("g",{children:[d("rect",{"data-selection-custom-handle":t.id,"data-selection-custom-handle-type":t.type,"data-selection-custom-handle-id":t.id,x:t.point.x-c/2,y:t.point.y-c/2,width:c,height:c,fill:"transparent",style:{cursor:t.cursor??"grab",pointerEvents:"all"}}),d("rect",{x:t.point.x-a/2,y:t.point.y-l/2,width:a,height:l,rx:Math.min(a,l)/2,ry:Math.min(a,l)/2,fill:"rgba(255,255,255,0.98)",stroke:"var(--land-selection, #2563eb)",strokeWidth:e,pointerEvents:"none"})]})}function ll({shape:t,editor:e}){
11
+ return d(dl,{shape:t,editor:e,idPrefix:"connector",stroke:Nt(t.props.stroke),strokeWidth:t.props.strokeWidth})}function cl({shape:t,editor:e,strokeWidth:n}){
12
+ return d(dl,{dataUi:"connector-hover-outline",shape:t,editor:e,idPrefix:"connector-hover",stroke:o,strokeWidth:n,vectorEffect:"non-scaling-stroke"})}function dl({dataUi:t,editor:e,idPrefix:n,shape:o,stroke:i,strokeWidth:s,vectorEffect:a}){const l=`${n}-content-clip-${o.id.replace(/[^a-zA-Z0-9_-]/g,"-")}`,c=Eo(e,o),p=ei(c.markerSegments),h=e.shapes.computeRenderBounds(o),f=r(e.shapes.getContentCutoutLocalPolygonsSignal(o.id)),g=ne({outputBounds:c.pageBounds,cutoutLocalPolygons:f});
13
+ return u("svg",{"data-ui":t,width:"100%",height:"100%",viewBox:`${h.x} ${h.y} ${h.w} ${h.h}`,overflow:"visible",children:[g?d("defs",{children:d("clipPath",{id:l,clipPathUnits:"userSpaceOnUse",children:d("path",{d:g,clipRule:"evenodd",fillRule:"evenodd"})})}):null,u("g",{clipPath:g?`url(#${l})`:void 0,children:[d("path",{"data-connector-path":"body",d:c.path,fill:"none",stroke:i,strokeWidth:s,strokeDasharray:"dashed"===o.props.strokeStyle?"8 6":void 0,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:a}),p?d("path",{"data-connector-path":"markers",d:p,fill:"none",stroke:i,strokeWidth:s,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:a}):null]})]})}var ul=g(function(){const t=n(),e=r(t.state.readonly),s=r(t.state.tool).activeToolId;r(t.state.selectedShapes),r(t.render.interaction.hoveredShapeId);const a=r(t.state.shapeEditingSession),l=r(t.inputs.isSpacePressed),c=r(t.render.interaction.selectionTranslationActive),p=r(t.state.cameraZoom),h=mi(t),f=r(h.previewSignal);if(e||a||l||c)return null;const g=el(t),m=new Map(g.visibleShapes.map(t=>[t.id,t])),y=[...m.values()].filter(e=>t.shapes.getUtil(e).canUseTerminalBindingPortHandles(e,{editor:t})),x=g.targetShapeId?t.shapes.get(g.targetShapeId)??null:null,w=f?x:"connector"===s?g.visibleShapes[0]:null,b=w&&!Tr(w)?w:null;if(0===m.size&&!f)return null;const v=Math.max(p,1e-4),k=g.targetShapeId&&g.highlightedPortId?`${g.targetShapeId}:${g.highlightedPortId}`:null,P=f?{point:f.start.pagePoint,outwardNormal:f.start.pageOutwardNormal,obstacleId:f.start.shapeId??void 0,obstacleBounds:f.start.obstacleBounds}:null,S=f?{point:f.end.pagePoint,outwardNormal:f.end.pageOutwardNormal,obstacleId:f.end.shapeId??void 0,obstacleBounds:f.end.obstacleBounds}:null,I=f?Lo({start:P,end:S,routing:f.geometry.routing,cornerRadius:f.geometry.cornerRadius,headStart:f.geometry.headStart,headEnd:f.geometry.headEnd,strokeWidth:f.geometry.strokeWidth,curveWaypoints:f.geometry.curveWaypoints,orthogonalBends:f.geometry.orthogonalBends,terminalOffsetMapper:Mo(f.geometry.localToPageTransform)}):null,M=f&&I?function(t,e){const n=t.geometry.localToPageTransform,r=n.tryInvert();if(!r)return{info:e,localToPageTransform:Ht.Identity()};const o=Jo(e,r);if("rebind"===t.kind)return{info:o,localToPageTransform:n};const i=vt.FromPoints([o.startPagePoint,...o.points,o.endPagePoint]);return{info:Jo(o,Ht.Translate(-i.x,-i.y)),localToPageTransform:n.compose(Ht.Translate(i.x,i.y))}}(f,I):null,T=f?f.start.pagePoint:null,C=f?f.end.pagePoint:null,A=f?Nt(f.geometry.stroke):"var(--land-selection, #2563eb)",E=f?.geometry.strokeWidth??2,L=f?.geometry.strokeStyle??"solid",B=b?wl(t,b):null,R=f?f[f.movingTerminal]:null;
14
+ return u("g",{"data-ui":"connector-ports-overlay",children:[
15
+ d("style",{children:"\n [data-connector-port-idle],\n [data-connector-port-hover-preview] {\n transition: opacity 100ms ease;\n }\n [data-connector-port-hover-preview] {\n opacity: 0;\n }\n [data-connector-port]:hover [data-connector-port-idle] {\n opacity: 0;\n }\n [data-connector-port]:hover [data-connector-port-hover-preview] {\n opacity: 1;\n }\n "}),B?d("path",{"data-ui":"connector-target-border-highlight",d:B,fill:"none",stroke:o,strokeWidth:i/v,strokeLinecap:"round",strokeLinejoin:"round",pointerEvents:"none"}):null,M?d("g",{"data-ui":"connector-creation-preview",pointerEvents:"none",opacity:.78,children:u("g",{"data-ui":"connector-creation-preview-geometry",transform:M.localToPageTransform.toSvgString(),children:[d("path",{"data-ui":"connector-creation-preview-path",d:M.info.path,fill:"none",stroke:A,strokeWidth:E,strokeDasharray:"dashed"===L?"8 6":void 0,strokeLinecap:"round",strokeLinejoin:"round"}),M.info.markerSegments.length>0?d("path",{"data-ui":"connector-creation-preview-markers",d:M.info.markerSegments.map(t=>`M ${t.start.x} ${t.start.y} L ${t.end.x} ${t.end.y}`).join(" "),fill:"none",stroke:A,strokeWidth:E,strokeLinecap:"round",strokeLinejoin:"round"}):null]})}):null,y.flatMap(e=>se(t,e).map(n=>h.isPortVisible(n.id)?d(gl,{editor:t,shape:e,port:n,zoom:v,highlighted:k===`${e.id}:${n.id}`,targetMode:b?.id===e.id,quickCreateNodeFactory:h.quickCreateNodeFactory},`${e.id}:${n.id}`):null)),R?.shapeId?d(hl,{point:R.pagePoint,zoom:v}):!f&&"connector"===s&&b?d(pl,{shape:b,zoom:v}):null,T&&C?d(fl,{start:T,end:C,zoom:v}):null]})});function pl({shape:t,zoom:e}){const o=n(),i=r(o.inputs.state);if(!i.currentPagePoint||i.accelKey)return null;const s=12/e,a=ro(o,t,i.currentPagePoint,s);return!a||a.borderDistance>s?null:d(hl,{point:a.port.pagePoint,zoom:e})}function hl({point:t,zoom:e}){
16
+ return d("circle",{"data-ui":"connector-border-snap-preview",cx:t.x,cy:t.y,r:5/e,fill:"var(--land-selection, #2563eb)",stroke:"#ffffff",strokeWidth:1.5/e,pointerEvents:"none"})}function fl({start:t,end:e,zoom:n}){const r=4/n,o=1/n;
17
+ return d("g",{"data-ui":"connector-creation-terminal-handles",pointerEvents:"none",children:[{terminal:"start",point:t},{terminal:"end",point:e}].map(({terminal:t,point:e})=>d("circle",{"data-connector-creation-terminal":t,cx:e.x,cy:e.y,r:r,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:o},t))})}function gl({editor:t,shape:e,port:n,zoom:r,highlighted:o,targetMode:i,quickCreateNodeFactory:s}){const[a,l]=k(!1),c=i?n.pagePoint:Ha(n,r),p=4/r,h=12/r,f=15/r,g=12/r,m=180*Math.atan2(n.pageOutwardNormal.y,n.pageOutwardNormal.x)/Math.PI;
18
+ return u("g",{"data-ui":"connector-port","data-connector-port":"true","data-connector-port-shape-id":e.id,"data-connector-port-id":n.id,"data-connector-port-target":i?"true":void 0,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[a&&!i?d(ml,{editor:t,source:{shape:e,port:n},quickCreateNodeFactory:s,zoom:r}):null,
19
+ d("circle",{"data-connector-port-hit-area":"true",cx:c.x,cy:c.y,r:g,fill:"transparent",pointerEvents:"all",cursor:"crosshair"}),
20
+ d("circle",{"data-connector-port-idle":"true",cx:c.x,cy:c.y,r:o?1.2*p:p,fill:o?"var(--land-selection, #2563eb)":"rgba(37, 99, 235, 0.28)",pointerEvents:"none"}),i?null:u("g",{"data-connector-port-hover-preview":"true",pointerEvents:"none",children:[d("circle",{cx:c.x,cy:c.y,r:h,fill:"var(--land-selection, #2563eb)"}),d(or,{"data-connector-port-hover-arrow":"true",x:c.x-f/2,y:c.y-f/2,width:f,height:f,color:"#ffffff",strokeWidth:2.4,transform:`rotate(${m} ${c.x} ${c.y})`})]})]})}function ml({editor:t,source:e,quickCreateNodeFactory:n,zoom:r}){const o=Ua(t,e,n);if(!o)return null;const i=t.shapes.getDefaultProps("connector"),s=function(t){return"connect"===t.kind?t.target:{shape:t.previewShape,port:t.targetPort}}(o),a="create"===o.kind?e.shape.parentId:Li(t,e.shape,s.shape);if(!a)return null;const l=a.startsWith("shape:")?t.shapes.get(a):null,c=l?t.shapes.computeLocalToPageTransform(l):Ht.Identity(),p=Lo({start:{point:e.port.pagePoint,outwardNormal:e.port.pageOutwardNormal,obstacleId:e.shape.id,obstacleBounds:t.shapes.getPageBounds(e.shape.id)??void 0},end:{point:s.port.pagePoint,outwardNormal:s.port.pageOutwardNormal,obstacleId:s.shape.id,obstacleBounds:"create"===o.kind?t.shapes.computePageBounds(s.shape):t.shapes.getPageBounds(s.shape.id)??void 0},routing:i.routing,cornerRadius:i.cornerRadius,headStart:i.headStart,headEnd:i.headEnd,strokeWidth:i.strokeWidth,terminalOffsetMapper:Mo(c),curveWaypoints:[],orthogonalBends:[]}),h=Nt(i.stroke);
21
+ return u("g",{"data-ui":"connector-port-quick-connect-preview","data-connector-port-quick-connect-kind":o.kind,pointerEvents:"none",children:[u("g",{opacity:.58,children:[d("path",{"data-ui":"connector-port-quick-connect-path",d:p.path,fill:"none",stroke:h,strokeWidth:i.strokeWidth,strokeDasharray:"dashed"===i.strokeStyle?"8 6":void 0,strokeLinecap:"round",strokeLinejoin:"round"}),p.markerSegments.length>0?d("path",{"data-ui":"connector-port-quick-connect-markers",d:p.markerSegments.map(t=>`M ${t.start.x} ${t.start.y} L ${t.end.x} ${t.end.y}`).join(" "),fill:"none",stroke:h,strokeWidth:i.strokeWidth,strokeLinecap:"round",strokeLinejoin:"round"}):null]}),"create"===o.kind?d(yl,{editor:t,shape:o.previewShape,zoom:r}):null]})}function yl({editor:t,shape:e,zoom:n}){const r=l().getShapeRenderer(e.type)?.component,o=t.shapes.computeRenderBounds(e),i=t.shapes.computeLocalToPageTransform(e).compose(Ht.Translate(o.x,o.y)),s=wl(t,e);
22
+ return u("g",{"data-ui":"connector-port-quick-create-shape",children:[r?d("foreignObject",{"data-ui":"connector-port-quick-create-shape-content",width:o.w,height:o.h,overflow:"visible",opacity:.52,transform:i.toSvgString(),children:d("div",{style:{height:"100%",overflow:"visible",pointerEvents:"none",width:"100%"},children:d(xl,{Renderer:r,editor:t,shape:e})})}):s?d("path",{"data-ui":"connector-port-quick-create-shape-fallback",d:s,fill:"rgba(37, 99, 235, 0.1)",stroke:"none"}):null,s?d("path",{"data-ui":"connector-port-quick-create-shape-outline",d:s,fill:"none",stroke:"var(--land-selection, #2563eb)",strokeWidth:1.5/n,strokeDasharray:`${5/n} ${4/n}`,strokeLinecap:"round",strokeLinejoin:"round"}):null]})}function xl({Renderer:t,editor:e,shape:n}){
23
+ return d(t,{editor:e,isSelected:!1,shape:n,shapeEditingSession:null})}function wl(t,e){const n=[];for(const r of no(t,e)){const[t,...e]=r.points;if(t){n.push(`M ${t.x} ${t.y}`);for(const t of e)n.push(`L ${t.x} ${t.y}`);r.closed&&r.points.length>2&&n.push("Z")}}return n.length>0?n.join(" "):null}var bl=class extends wt{type="connector";getDefaultProps(){return{terminal:"start",portId:"top"}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=e.normalizedAnchor&&"object"==typeof e.normalizedAnchor?e.normalizedAnchor:null;return{terminal:"end"===e.terminal?"end":"start",portId:"string"==typeof e.portId&&e.portId.length>0?e.portId:"top",...n?{normalizedAnchor:{x:vl(n.x),y:vl(n.y)}}:{}}}canBind(t,e,n){return Tr(n.fromShape)&&!Tr(n.toShape)&&t.layers.getPageId(n.fromShape.id)===t.layers.getPageId(n.toShape.id)&&null!==oo(t,n.toShape,e.props)}getExclusiveBindingKey(t){return`${t.fromId}:${t.props.terminal}`}onBindingCreate(t,e){return this.getSyncEffect(t,e.fromId)}onBindingUpdate(t,e,n){return this.getSyncEffect(t,n.fromId)}onBindingLoad(t,e){return this.getSyncEffect(t,e.fromId)}onAfterShapeChange(t,e,n){if("from"!==n.role||"start"===e.props.terminal)return this.getSyncEffect(t,e.fromId)}onBeforeDeleteShape(t,e,n){return"from"===n.role?{deleteBindingIds:Er(t,e.fromId).map(t=>t.id)}:t.shapes.get(e.fromId)?{deleteShapeIds:[e.fromId]}:{}}onBeforeDeleteBinding(t,e){return this.getDetachEffect(t,e)}getExportShapeIds(t,e){return[e.fromId]}getGeometryDependentShapeIds(t,e,n){return"to"===n.role?[e.fromId]:[]}getSyncEffect(t,e){const n=t.shapes.get(e);if(!Tr(n))return;const r=vi(t,n);var o,i;return r&&(i=r,(o=n).parentId!==i.parentId||o.x!==i.x||o.y!==i.y||o.rotation!==i.rotation||o.scaleX!==i.scaleX||o.scaleY!==i.scaleY||JSON.stringify(o.props)!==JSON.stringify(i.props))?{shapes:[r],suppressBindingIds:Er(t,e).map(t=>t.id)}:void 0}getDetachEffect(t,e){const n=t.shapes.get(e.fromId);if(!Tr(n))return{deleteBindingIds:[e.id]};const r=To(t,n),o="start"===e.props.terminal?r.startPagePoint:r.endPagePoint,i=ki(t,n,e.props.terminal,o);return{shapes:i?[i]:void 0,deleteBindingIds:[e.id],suppressBindingIds:Er(t,e.fromId).map(t=>t.id)}}};function vl(t){return"number"==typeof t&&Number.isFinite(t)?Math.max(0,Math.min(1,t)):.5}var kl="connector.rebind",Pl={propagation:"stop"},Sl={propagation:"stop",clickSequence:"break"},Il=class{editor;origin;quickCreateNodeFactory;onClickWithoutDrag;pointerId;originScreenPoint;preview;initialSelectedShapeIds;props;didClearSelection=!1;operation;constructor(t,e,n,r,o,i){this.editor=t,this.origin=e,this.quickCreateNodeFactory=o,this.onClickWithoutDrag=i,this.pointerId=r,this.originScreenPoint=n.clone(),this.initialSelectedShapeIds=t.selection.getIds(),this.props=t.shapes.getDefaultProps("connector");const s=xi(t,e.start);if(!s)throw new Error("Connector creation requires a resolvable start endpoint");const a=xi(t,{kind:"free",pagePoint:s.pagePoint.clone()});this.preview={kind:"create",origin:e.kind,start:Al(s,a,"start"),end:Al(a,s,"end"),invalidReason:null,isDragging:!1,movingTerminal:"end",geometry:Nl(this.props,Ll(t,s,a))},this.operation=t.operations.begin({kind:"connector.create",label:"shape.create",source:"user",history:"record"}),mi(t).setPreview(this.preview)}update(t,e,n){const r=this.originScreenPoint.dist(t)>10;r&&!this.didClearSelection&&(this.initialSelectedShapeIds.length>0&&this.editor.commands.setSelectedShapeIds([],{source:"user"}),this.didClearSelection=!0);const o=r&&!n?Fa(this.editor,e,{allowInteriorShapeId:"bound"===this.origin.start.kind?this.origin.start.shapeId:void 0,mode:"target",pageId:this.editor.pages.getCurrentId()}):null,i=xi(this.editor,this.origin.start);if(!i)return void this.cancel("command");const s=El(this.editor,i,e,this.props.routing,n),a=o?yi(o.shape.id,o.port):{kind:"free",pagePoint:s},l=xi(this.editor,a);if(!l)return void this.cancel("command");const c=wi(this.editor,this.origin.start,a);Object.assign(this.preview,{start:Al(i,l,"start"),end:Al(l,i,"end"),invalidReason:c,isDragging:r,geometry:{...this.preview.geometry,localToPageTransform:Ll(this.editor,i,l)}}),mi(this.editor).setPreview({...this.preview})}complete(t,e,n){if(this.update(t,e,n),mi(this.editor).pointerSession!==this)return!1;let r=!1;if(this.preview.isDragging)this.preview.invalidReason||(r=!!bi(this.editor,{start:this.preview.start.draft,end:this.preview.end.draft,props:this.props,selectionAfter:"connector"}));else{if(this.onClickWithoutDrag)return this.clear(),this.operation.cancel(),this.onClickWithoutDrag(),!1;if("canvas"===this.origin.kind)return!1;const t=xi(this.editor,this.origin.start);r=!!(t?.shape&&t.port&&ja(this.editor,{shape:t.shape,port:t.port},this.quickCreateNodeFactory,this.props))}return this.clear(),r?(this.operation.commit(),"canvas"!==this.origin.kind||this.editor.state.tool.get().isToolLocked||this.editor.commands.setActiveTool("select",{source:"system"})):(this.operation.cancel(),this.restoreInitialSelection()),r}cancel(t){this.clear(),this.operation.isActive&&this.operation.cancel(),this.restoreInitialSelection()}clear(){const t=mi(this.editor);t.setPreview(null),t.setPointerSession(null),this.editor.interaction.setHoveredShapeId(null)}restoreInitialSelection(){this.didClearSelection&&this.editor.commands.setSelectedShapeIds(this.initialSelectedShapeIds,{source:"system"})}};function Ml(t,e){const n=mi(t);if(t.state.readonly.get()||t.state.shapeEditingSession.get()||t.inputs.isSpacePressed.get()||t.layers.isOrAncestorLocked(e.source.shape.id)||t.shapes.isHidden(e.source.shape.id)||n.pointerSession)return!1;const r=new Il(t,{kind:"port",start:yi(e.source.shape.id,e.source.port)},e.originScreenPoint,e.pointerId,n.quickCreateNodeFactory,e.onClickWithoutDrag);return n.setPointerSession(r),!0}function Tl(t){return{id:"land.connector.interactions",editorEvent:{handleEvent(e,n){const r=mi(e),o=r.pointerSession;if("cancel"===n.type)return o?.cancel(n.reason),e.interaction.setHoveredShapeId(null),o?Pl:void 0;if(e.state.readonly.get())return;if(o){if("tick"===n.type){const t=e.inputs.state.get();if(o.preview.isDragging&&t.pointerId===o.pointerId&&t.currentScreenPoint){const r=ge(t.currentScreenPoint,e.state.viewportScreenSize.get(),n.elapsed);0===r.x&&0===r.y||(e.viewport.pan(r),o.update(t.currentScreenPoint,e.viewport.screenToPage(t.currentScreenPoint),t.accelKey))}return Pl}if("pointer"!==n.type)return Pl;if(n.pointerId!==o.pointerId)return Pl;if("pointer_move"===n.name)o.update(n.screenPoint,n.pagePoint,n.accelKey);else{if("pointer_up"===n.name)return o.complete(n.screenPoint,n.pagePoint,n.accelKey)?Sl:Pl;"pointer_cancel"===n.name&&o.cancel("pointer_cancel")}return Pl}if("pointer"!==n.type)return;if("pointer_move"===n.name&&"connector"===e.state.tool.get().activeToolId)return void e.interaction.setHoveredShapeId(function(t,e){if(t.state.readonly.get())return null;const n=t.shapes.hitTest(e),r=n?t.shapes.getUtil(n).getHoverTargetId(n,{editor:t}):null,o=r?t.shapes.get(r)??null:null;return o&&rl(t,o,"source")&&t.shapes.getUtil(o).canUseTerminalBindingPortHandles(o,{editor:t})?o:null}(e,n.pagePoint)?.id??null);if("pointer_down"!==n.name||0!==n.button||e.inputs.isSpacePressed.get()||e.state.shapeEditingSession.get())return;const i=e.state.tool.get().activeToolId;let s=null;if("select"===i){const t=nl(e,n.pagePoint);t&&(s={kind:"port",start:yi(t.shape.id,t.port)})}else"connector"===i&&(s={kind:"canvas",start:Cl(e,n)});if(!s)return;const a=new Il(e,s,n.screenPoint,n.pointerId,t);return r.setPointerSession(a),Pl}},selectionHandle:{createSession:(t,{handle:e,shape:n})=>t.state.readonly.get()?null:Tr(n)?"binding_terminal"===e.kind?function(t,e,n){if(!Tr(t.shapes.get(e)))return null;const r=n.terminal,o="start"===r?"end":"start";let i=null;return{shapeId:e,operationKind:kl,shouldClearBindingPreviewOnExit:!0,onDragStart(){mi(t).setSelectionHandlesHidden(!0)},update({pagePoint:n,accelKey:s,source:a}){const l=Ar(t,e)[o],c=s?null:Fa(t,n,{allowInteriorShapeId:l?.toId,mode:"target",pageId:l?t.layers.getPageId(l.toId):t.pages.getCurrentId()});if(c&&l&&Ei(c.shape.id,c.port.id,l.toId,l.props.portId))return{status:"continue",finalPagePoint:c?.port.pagePoint};const d=c,u=!!d&&(l&&"start"===r?Ai(t,d.shape.id,d.port.id,l.toId,l.props.portId,e):!!l&&Ai(t,l.toId,l.props.portId,d.shape.id,d.port.id,e));i=d&&!u?d:null;let p=Ar(t,e)[r];!i&&p&&(t.commands.deleteBinding(p.id,{source:a}),p=null);const h=t.shapes.get(e);if(!Tr(h))return{status:"stop"};const f=l?t.shapes.get(l.toId):null,g=f&&l?oo(t,f,l.props):null,m=f&&g?xi(t,yi(f.id,g)):null,y=i?.port.pagePoint??(!c&&m?El(t,m,n,h.props.routing,s):n),x=ki(t,h,r,y);x&&function(t,e,n){const r=new Set(Er(t,e.id).map(t=>t.id));t.commands.updateShapes([{id:e.id,parentId:e.parentId,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,props:e.props}],{source:n,suppressBindingIds:r})}(t,x,a),i&&(p=Ar(t,e)[r],p?p.toId===i.shape.id&&p.props.portId===i.port.id||t.commands.updateBinding({id:p.id,toId:i.shape.id,props:so(r,i.port)},{source:a}):t.commands.createBinding({type:"connector",fromId:e,toId:i.shape.id,props:so(r,i.port)},{source:a}));const w=Ar(t,e)[o],b=w?t.shapes.get(w.toId):null,v=b&&w?oo(t,b,w.props):null;if(b&&v){const n=t.shapes.get(e);Tr(n)&&function(t,e,n,r,o,i,s){const a=t.shapes.get(e.id),l=Tr(a)?a:e,c=t.shapes.computeLocalToPageTransform(l),d=yi(r,o),u=i?yi(i.shape.id,i.port):{kind:"free",pagePoint:s.clone()},p=xi(t,d),h=xi(t,u);if(!p||!h)return void mi(t).setPreview(null);const f="start"===n?h:p,g="end"===n?h:p;mi(t).setPreview({kind:"rebind",start:Al(f,g,"start"),end:Al(g,f,"end"),isDragging:!0,movingTerminal:n,geometry:Nl(l.props,c,{curveWaypoints:l.props.curveWaypoints.map(t=>c.applyToPoint(new bt(t.x,t.y))),orthogonalBends:l.props.orthogonalBends.map(t=>c.applyToPoint(new bt(t.x,t.y)))})})}(t,n,r,b.id,v,i,y)}else mi(t).setPreview(null);return{status:"continue",finalPagePoint:y}},onCancel(){const e=mi(t);e.setPreview(null),e.setSelectionHandlesHidden(!1)},onComplete(){const e=mi(t);e.setPreview(null),e.setSelectionHandlesHidden(!1)}}}(t,n.id,e):"custom"===e.kind?function(t,e,n){const r=To(t,e);if("connector.curve-waypoint"===n.type&&"curved"===e.props.routing){const o=hi(n.id,"waypoint"),i=r.routePoints.slice(1,-1).map(t=>t.clone());return null!==o&&i[o]?Bl(t,e.id,(n,r)=>{const s=i.map(t=>t.clone());s[o]=n.clone(),Rl(t,e.id,"curveWaypoints",s,r)},n=>{Rl(t,e.id,"curveWaypoints",i.filter((t,e)=>e!==o),n)}):null}if("connector.curve-insert"===n.type&&"curved"===e.props.routing){const o=hi(n.id,"segment"),i=r.routePoints.slice(1,-1).map(t=>t.clone());return null===o||o>i.length?null:Bl(t,e.id,(n,r)=>{const s=i.map(t=>t.clone());s.splice(o,0,n.clone()),Rl(t,e.id,"curveWaypoints",s,r)})}if("connector.orthogonal-segment"===n.type&&"orthogonal"===e.props.routing){const o=fi(n.id);if(!o||!r.routePoints[o.index+1])return null;const i=r.routePoints.map(t=>t.clone()),s=t.shapes.computeLocalToPageTransform(e),a=e.props.orthogonalBends.map(t=>s.applyToPoint(new bt(t.x,t.y)));return Bl(t,e.id,(n,r)=>{const s=function(t,e,n,r,o){const i=t[e];if(!i)return r;const s="horizontal"===n?r.y:r.x,a=["horizontal"===n?i.y:i.x],l=t[e-1];e>=2&&l&&a.push("horizontal"===n?l.y:l.x);const c=t[e+2];e<=t.length-4&&c&&a.push("horizontal"===n?c.y:c.x);const d=a.reduce((t,e)=>Math.abs(e-s)<Math.abs(t-s)?e:t);return Math.abs(d-s)>o?r:"horizontal"===n?new bt(r.x,d):new bt(d,r.y)}(i,o.index,o.axis,n,8/Math.max(t.state.cameraZoom.get(),1e-4)),l=i[o.index],c=("horizontal"===o.axis?s.y===l.y:s.x===l.x)?a:ri(function(t,e,n,r){const o=t[e],i=t[e+1];if(!o||!i)return t.map(t=>t.clone());const s="horizontal"===n?o.y:o.x;if(("horizontal"===n?r.y:r.x)===s)return t.map(t=>t.clone());const a=t=>"horizontal"===n?new bt(t.x,r.y):new bt(r.x,t.y),l=t.length-2;if(0===e){const e=$l(o,i);return[o.clone(),e,a(e),a(i),...t.slice(2).map(t=>t.clone())]}if(e===l){const e=$l(i,o);return[...t.slice(0,-2).map(t=>t.clone()),a(o),a(e),e,i.clone()]}const c=t.map(t=>t.clone());return c[e]=a(o),c[e+1]=a(i),c}(i,o.index,o.axis,s)).slice(1,-1);Rl(t,e.id,"orthogonalBends",c,r)})}return null}(t,n,e):null:null}}}function Cl(t,e){if(e.accelKey)return{kind:"free",pagePoint:e.pagePoint.clone()};const n=Fa(t,e.pagePoint,{mode:"target",pageId:t.pages.getCurrentId()})??Fa(t,e.pagePoint,{pageId:t.pages.getCurrentId()});return!n||t.layers.isOrAncestorLocked(n.shape.id)?{kind:"free",pagePoint:e.pagePoint.clone()}:yi(n.shape.id,n.port)}function Al(t,e,n){const r=Ti(t,e,n);return{draft:t.draft,pagePoint:t.pagePoint.clone(),pageOutwardNormal:r.outwardNormal.clone(),shapeId:t.shape?.id??null,portId:t.port?.id??null,obstacleBounds:t.obstacleBounds}}function El(t,e,n,r,o){if("orthogonal"!==r||o||!e.port)return n.clone();const i=e.port.pageOutwardNormal,s=n.sub(e.pagePoint);if(s.x*i.x+s.y*i.y<=0)return n.clone();const a=Math.abs(i.x)>=Math.abs(i.y),l=a?s.y:s.x,c=8/Math.max(t.state.cameraZoom.get(),1e-4);return Math.abs(l)>c?n.clone():a?new bt(n.x,e.pagePoint.y):new bt(e.pagePoint.x,n.y)}function Ll(t,e,n){const r=Bi(t,e,n);if(!r?.startsWith("shape:"))return Ht.Identity();const o=t.shapes.get(r);return o?t.shapes.computeLocalToPageTransform(o):Ht.Identity()}function Bl(t,e,n,r){const o={shapeId:e,operationKind:"connector.adjust",onDragStart(){mi(t).setSelectionHandlesHidden(!0)},update:({pagePoint:t,source:e})=>(n(t,e),{status:"continue",finalPagePoint:t}),onCancel(){mi(t).setSelectionHandlesHidden(!1)},onComplete(){mi(t).setSelectionHandlesHidden(!1)}};return r&&(o.onDoubleClick=({source:t})=>r(t)),o}function Rl(t,e,n,r,o){const i=t.shapes.get(e);if(!Tr(i))return;const s=t.shapes.computeLocalToPageTransform(i).tryInvert();if(!s)return;const a={...i.props,[n]:r.map(t=>{const e=s.applyToPoint(t);return{x:e.x,y:e.y}})},l=vi(t,{...i,props:a});if(!l)return;const c=Ar(t,i.id),d=new Set([c.start?.id,c.end?.id].filter(t=>!!t));t.commands.updateShapes([{id:i.id,parentId:l.parentId,x:l.x,y:l.y,rotation:l.rotation,scaleX:l.scaleX,scaleY:l.scaleY,props:l.props}],{source:o,suppressBindingIds:d})}function $l(t,e){const n=e.sub(t),r=n.len();return 0===r?t.clone():t.add(n.mul(Math.min(24,r/2)/r))}function Nl(t,e,n={curveWaypoints:[],orthogonalBends:[]}){return{routing:t.routing,cornerRadius:t.cornerRadius,headStart:t.headStart,headEnd:t.headEnd,stroke:t.stroke,strokeWidth:t.strokeWidth,strokeStyle:t.strokeStyle,...n,localToPageTransform:e}}var zl=new Set(["straight","orthogonal","curved"]),Ol=new Set(["solid","dashed"]),Wl=new Set(["none","arrow"]);function Hl(t,e,n=-1/0){return"number"==typeof t&&Number.isFinite(t)?Math.max(n,t):e}function Dl(t,e){const n=t&&"object"==typeof t?t:{};return{x:Hl(n.x,e.x),y:Hl(n.y,e.y)}}function Fl(t){return Array.isArray(t)?t.flatMap(t=>{if(!t||"object"!=typeof t)return[];const e=t;return"number"==typeof e.x&&Number.isFinite(e.x)&&"number"==typeof e.y&&Number.isFinite(e.y)?[{x:e.x,y:e.y}]:[]}):[]}function jl(t,e,n){const r=e.sub(t).normalize();return{point:t,outwardNormal:r.len()>0?r:new bt("start"===n?1:-1,0)}}var Ul=class extends pe{type="connector";getDefaultProps(){return{w:1,h:1,start:{x:0,y:.5},end:{x:1,y:.5},routing:"orthogonal",stroke:Et("stroke-slate"),strokeWidth:2,strokeStyle:"solid",headStart:"none",headEnd:"arrow",cornerRadius:8,curveWaypoints:[],orthogonalBends:[]}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Hl(e.w,n.w,1),h:Hl(e.h,n.h,1),start:Dl(e.start,n.start),end:Dl(e.end,n.end),routing:zl.has(e.routing)?e.routing:n.routing,stroke:Bt(e.stroke)?$t(e.stroke,n.stroke):n.stroke,strokeWidth:Hl(e.strokeWidth,n.strokeWidth,.5),strokeStyle:Ol.has(e.strokeStyle)?e.strokeStyle:n.strokeStyle,headStart:Wl.has(e.headStart)?e.headStart:n.headStart,headEnd:Wl.has(e.headEnd)?e.headEnd:n.headEnd,cornerRadius:Hl(e.cornerRadius,n.cornerRadius,0),curveWaypoints:Fl(e.curveWaypoints),orthogonalBends:Fl(e.orthogonalBends)}}getLocalBounds(t){const e="arrow"===t.props.headStart||"arrow"===t.props.headEnd?fo(t.props.strokeWidth)+t.props.strokeWidth/2:t.props.strokeWidth/2;return new vt(0,0,t.props.w,t.props.h).expand(e)}getPointHitTestBounds(t,e){const n=Math.max(8,t.props.strokeWidth+4);if(!e?.editor)return vt.FromPoints([new bt(t.x+t.props.start.x,t.y+t.props.start.y),new bt(t.x+t.props.end.x,t.y+t.props.end.y)]).expand(n);const r=To(e.editor,t),o=[...r.points,...r.markerSegments.flatMap(t=>[t.start,t.end])],i=e.editor.shapes.computePositionedToPageTransform(t).tryInvert();if(!i||0===o.length)return super.getPointHitTestBounds(t,e).expand(n);const s=Xl(e.editor,t)*i.getMaximumLinearScale();return vt.FromPoints(o.map(t=>i.applyToPoint(t))).expand(s)}canSnap(){return!1}canParticipateInSelectionResize(t,e){return!1===e.isOnlyAffectedShape}resizeSelectionBounds(t,e){const n=this.getLocalTransform(t),r=n.applyToPoint(this.getSelectionResizeLocalBounds(t).center),o=Ht.Translate(e.pageCenter.x,e.pageCenter.y).compose(Ht.Rotate(e.selectionRotation)).compose(Ht.Scale(e.scaleX,e.scaleY)).compose(Ht.Rotate(-e.selectionRotation)).compose(Ht.Translate(-r.x,-r.y)).compose(n),i=o.applyToPoint(new bt(t.props.start.x,t.props.start.y)),s=o.applyToPoint(new bt(t.props.end.x,t.props.end.y)),a=t.props.curveWaypoints.map(t=>o.applyToPoint(new bt(t.x,t.y))),l=t.props.orthogonalBends.map(t=>o.applyToPoint(new bt(t.x,t.y))),c=Lo({start:jl(i,s,"start"),end:jl(s,i,"end"),routing:t.props.routing,cornerRadius:t.props.cornerRadius,headStart:t.props.headStart,headEnd:t.props.headEnd,strokeWidth:t.props.strokeWidth,curveWaypoints:a,orthogonalBends:l}),d=vt.FromPoints([i,...c.points,s]),u=t=>({x:t.x-d.x,y:t.y-d.y});return{id:t.id,x:d.x,y:d.y,rotation:0,scaleX:1,scaleY:1,props:{w:Math.max(1,d.w),h:Math.max(1,d.h),start:u(i),end:u(s),curveWaypoints:a.map(u),orthogonalBends:l.map(u)}}}canParticipateInSelectionFlip(){return!0}canParticipateInSelectionRotation(){return!1}canParticipateInSelectionTranslation(){return!1}contributesToSelectionFrame(t,e){return!0}canUseSelectionResizeHandles(t,e){return e.editor.selection.getIds().length>1}canUseSelectionRotateHandle(t,e){return e.editor.selection.getIds().length>1}canStartTranslateFromSelectionBounds(t,e){return e.editor.selection.getIds().length>1}getSelectionHandleAnchors(t,e){if(!e.isOnlySelected)return{terminalHandleAnchors:[],middleHandleAnchors:[]};if(mi(e.editor).selectionHandlesHiddenSignal.get())return{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};const n=To(e.editor,t),r=[];if("curved"===t.props.routing){for(let e=1;e<n.routePoints.length-1;e+=1)r.push({kind:"custom",type:ai,id:di(e-1),point:n.routePoints[e],cursor:"move"});let t=0;n.segments.forEach(e=>{"cubic"===e.type&&(r.push({kind:"custom",type:li,id:ui(t),point:yo(e,.5),cursor:"move"}),t+=1)})}else if("orthogonal"===t.props.routing){const t=Math.max(e.editor.state.cameraZoom.get(),1e-4);for(let e=0;e<n.routePoints.length-1;e+=1){const o=n.routePoints[e],i=n.routePoints[e+1];if(o.dist(i)*t<36)continue;const s=o.y===i.y?"horizontal":"vertical";r.push({kind:"custom",type:ci,id:pi(e,s),point:bt.Med(o,i),cursor:"horizontal"===s?"ns-resize":"ew-resize"})}}return{terminalHandleAnchors:[{kind:"binding_terminal",terminal:"start",point:n.startPagePoint},{kind:"binding_terminal",terminal:"end",point:n.endPagePoint}],middleHandleAnchors:[],customHandleAnchors:r}}getSelectionOverlayInfo(t,e){const n=To(e.editor,t),r=Eo(e.editor,t),o=ei(r.markerSegments),i=e.editor.shapes.computeLocalToPageTransform(t);return{usesSelectionPathOverlay:!0,startPagePoint:n.startPagePoint,endPagePoint:n.endPagePoint,middlePagePoint:null,path:n.path,pathStyle:{localPath:r.path,localDecorationPaths:o?[o]:[],localBounds:r.pageBounds,localToPage:i,strokeWidth:t.props.strokeWidth,strokeDasharray:"dashed"===t.props.strokeStyle?"8 6":void 0},pageClipPath:ne({outputBounds:n.pageBounds,cutoutLocalPolygons:e.editor.shapes.getContentCutoutLocalPolygonsSignal(t.id).get(),localToOutput:i}),bindingSegments:[]}}getLabelPathGeometry(t,e){return xo(To(e.editor,t))}canCopyToClipboard(t,e){const n=Ar(e.editor,t.id);return(!n.start||e.copiedShapeIds.has(n.start.toId))&&(!n.end||e.copiedShapeIds.has(n.end.toId))}isWrappedByBrush(t,e){return To(e.editor,t).points.every(t=>e.brushBounds.containsPoint(t))}hitTest(t,e,n){const r=n?.editor?To(n.editor,t):null,o=r?r.points:[new bt(t.x+t.props.start.x,t.y+t.props.start.y),new bt(t.x+t.props.end.x,t.y+t.props.end.y)],i=n?.pagePoint??e,s=n?.editor?Xl(n.editor,t):Math.max(8,t.props.strokeWidth+4);return Yl(o,i)<=s||(r?.markerSegments.some(t=>Yl([t.start,t.end],i)<=s)??!1)}hitTestLineSegment(t,e){const n=e.editor?To(e.editor,t):null,r=n?n.points:[new bt(t.x+t.props.start.x,t.y+t.props.start.y),new bt(t.x+t.props.end.x,t.y+t.props.end.y)],o=e.editor?e.pageStart:e.positionedStart,i=e.editor?e.pageEnd:e.positionedEnd,s=e.editor?Math.max(Xl(e.editor,t),e.pageMargin):Math.max(t.props.strokeWidth+4,e.positionedMargin);for(let a=1;a<r.length;a+=1)if(_l(r[a-1],r[a],o,i)<=s)return!0;for(const a of n?.markerSegments??[])if(_l(a.start,a.end,o,i)<=s)return!0;return!1}};function Xl(t,e){const n=Math.max(t.state.cameraZoom.get(),1e-4),r=t.shapes.computePositionedToPageTransform(e).getMaximumLinearScale(),o=e.props.strokeWidth*r/2;return Math.max(12/n,o)}function Yl(t,e){let n=1/0;for(let r=1;r<t.length;r+=1)n=Math.min(n,Kl(e,t[r-1],t[r]));return n}function Kl(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist(e);const i=t.sub(e),s=Math.max(0,Math.min(1,(i.x*r.x+i.y*r.y)/o));return t.dist(e.add(r.mul(s)))}function _l(t,e,n,r){return Math.min(Kl(t,n,r),Kl(e,n,r),Kl(n,t,e),Kl(r,t,e))}var ql=class extends he{constructor(t){super(t,"connector")}},Vl=class{type="connector";toSvg(t,e){const n=e.resolveColor(t.props.stroke),r=Eo(e.editor,t),o=ne({outputBounds:r.pageBounds,cutoutLocalPolygons:e.editor.shapes.getContentCutoutLocalPolygonsSignal(t.id).get()}),i=o?e.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"path",attrs:{d:o,"clip-rule":"evenodd","fill-rule":"evenodd"}}]}):void 0,s="arrow"===t.props.headStart&&r.startArrowScale>0?`url(#${e.addDef(Jl("start",n,t.props.strokeWidth,r.startArrowScale))})`:void 0,a="arrow"===t.props.headEnd&&r.endArrowScale>0?`url(#${e.addDef(Jl("end",n,t.props.strokeWidth,r.endArrowScale))})`:void 0;return{tag:"path",attrs:{d:r.path,fill:"none",stroke:n,"stroke-width":t.props.strokeWidth,"stroke-dasharray":"dashed"===t.props.strokeStyle?"8 6":void 0,"stroke-linecap":"round","stroke-linejoin":"round","marker-start":s,"marker-end":a,"clip-path":i?`url(#${i})`:void 0}}}};function Gl(t,e){return{id:"land.connector",shapeUtils:[new Ul],shapeSvgExporters:[new Vl],bindingUtils:[new bl],interactionHandlers:[Tl(t)],setup(n){n.runtime.provide(gi,function(t,e,n){const r=t.signals.atom("connector.preview",null),o=t.signals.atom("connector.selectionHandlesHidden",!1),i=n?new Set(n):null;let s=null;return{previewSignal:r,quickCreateNodeFactory:e,selectionHandlesHiddenSignal:o,get pointerSession(){return s},isPortVisible:t=>i?.has(t)??!0,setPointerSession(t){s=t},setPreview(t){r.set(t)},setSelectionHandlesHidden(t){o.get()!==t&&o.set(t)},dispose(){s?.cancel("dispose"),s=null,r.set(null),o.set(!1)}}}(n,t,e),t=>t.dispose()),n.tools.register("connector",t=>new ql(t))}}}function Jl(t,e,n,r){return{tag:"marker",attrs:{markerWidth:12,markerHeight:12,viewBox:"0 0 24 24",refX:go(t,n,r),refY:12,orient:"auto",markerUnits:"strokeWidth"},children:[{tag:"path",attrs:{d:mo(t,n,r),fill:"none",stroke:e,"stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"}}]}}var Zl=bn("plugin-connector.api");function Ql({editor:t}){return function({editor:t}){return{getSelectionStyle(){const e=t.state.selectedShapes.get().filter(Tr);return 0===e.length?null:{routing:tc(e.map(t=>t.props.routing)),stroke:ec(e.map(t=>t.props.stroke)),strokeWidth:tc(e.map(t=>t.props.strokeWidth)),strokeStyle:tc(e.map(t=>t.props.strokeStyle)),headStart:tc(e.map(t=>t.props.headStart)),headEnd:tc(e.map(t=>t.props.headEnd))}},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(Tr).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)},getToolDefaults:()=>t.shapes.getDefaultProps("connector"),setToolDefaults:e=>(t.shapes.updateDefaultProps("connector",e),t.shapes.getDefaultProps("connector"))}}({editor:t})}function tc(t){const[e,...n]=t;return void 0!==e&&n.every(t=>t===e)?e:null}function ec(t){const[e,...n]=t;return void 0!==e&&n.every(t=>Wt(e,t))?e:null}function nc(t={}){const e=t.quickCreateNodeFactory??qa(),n=t.visiblePortIds?[...t.visiblePortIds]:void 0;return{id:"connector",requires:[Wa],editor:Gl(e,n),render:ol(),api:Zl,setup:({editor:t})=>({api:Ql({editor:t})})}}var rc=nc();function oc(t){return Number.isInteger(t)?`${t}`:`${Number(t.toFixed(2))}`}function ic(t,e,n){return Math.max(e,Math.min(n,t))}function sc(t){return t?640:480}function ac(t,e){return t.x===e.x&&t.y===e.y&&t.pressure===e.pressure&&t.segment===e.segment}function lc(t){return new bt(t.x,t.y)}function cc(t){return{x:t.x,y:t.y,...void 0===t.pressure?null:{pressure:t.pressure},...void 0===t.segment?null:{segment:t.segment}}}function dc(t){const e=[];for(const n of t)e.push(...n.points.map(cc));return e}function uc(t){return[{points:t.map(cc)}]}function pc(t){if(void 0!==t&&Number.isFinite(t))return ic(t,.05,1)}function hc(t,e,n,r,o={}){const i=cc(e),s=t[t.length-1];if(!s)return t.push(i),{anchorPoint:cc(i),hasProvisionalPoint:!1};if(ac(s,i))return o.force&&r.hasProvisionalPoint?{anchorPoint:cc(i),hasProvisionalPoint:!1}:r;if(ac(r.anchorPoint,i))return r.hasProvisionalPoint&&t.pop(),{anchorPoint:cc(r.anchorPoint),hasProvisionalPoint:!1};const a=function(t,e){if(t<=e.softMaxPointCount)return e.minPointDistance;const n=ic((t-e.softMaxPointCount)/Math.max(e.hardMaxPointCount-e.softMaxPointCount,1),0,1);return e.minPointDistance*(1+n*e.maxDistanceMultiplier)}(t.length,n),l=i.x-r.anchorPoint.x,c=i.y-r.anchorPoint.y,d=Math.abs((i.pressure??0)-(r.anchorPoint.pressure??0)),u=!0===o.force||l*l+c*c>=a*a||d>=n.pressureDeltaThreshold;return r.hasProvisionalPoint?t[t.length-1]=i:t.push(i),u?{anchorPoint:cc(i),hasProvisionalPoint:!1}:{anchorPoint:cc(r.anchorPoint),hasProvisionalPoint:!0}}function fc(t,e){const n=Math.max(2,Math.floor(e));if(t.length<=n)return t.map(cc);const r=function(t,e){let n=gc(t,!0);n.length<e&&(n=gc(t,!1));return new Set(n.slice(0,e).map(t=>t.index))}(t,t.length-n);return t.filter((t,e)=>!r.has(e)).map(cc)}function gc(t,e){const n=[];for(let r=1;r<t.length-1;r+=1){if(e&&mc(t,r))continue;const o=t[r],i=t[r-1],s=t[r+1];o&&i&&s&&n.push({index:r,score:yc(o,i,s)})}return n.sort((t,e)=>t.score-e.score||t.index-e.index),n}function mc(t,e){return"straight"===t[e]?.segment||"straight"===t[e+1]?.segment}function yc(t,e,n){const r=function(t,e,n){const r=n.x-e.x,o=n.y-e.y,i=r*r+o*o;if(0===i){const n=t.x-e.x,r=t.y-e.y;return n*n+r*r}const s=ic(((t.x-e.x)*r+(t.y-e.y)*o)/i,0,1),a=e.x+r*s,l=e.y+o*s,c=t.x-a,d=t.y-l;return c*c+d*d}(t,e,n),o=function(t,e,n){if(void 0===t.pressure)return 0;const r=e.pressure??t.pressure,o=n.pressure??t.pressure;return 8*Math.abs(t.pressure-(r+o)/2)}(t,e,n);return r+o*o}function xc(t){if(0===t.length)return null;if(1===t.length){const e=t[0];return`M ${oc(e.x)} ${oc(e.y)}`}if(2===t.length){const e=t[0],n=t[1];return[`M ${oc(e.x)} ${oc(e.y)}`,`L ${oc(n.x)} ${oc(n.y)}`].join(" ")}const e=[],n=t[0];e.push(`M ${oc(n.x)} ${oc(n.y)}`);for(let r=1;r<t.length;r+=1){const n=t[r];if(!n)continue;if("straight"===n.segment){e.push(`L ${oc(n.x)} ${oc(n.y)}`);continue}const o=t[r+1];if(!o||"straight"===o.segment){if(wc(t,r)){const o=t[r-1];e.push(`Q ${oc(o.x)} ${oc(o.y)} ${oc(n.x)} ${oc(n.y)}`)}else e.push(`L ${oc(n.x)} ${oc(n.y)}`);continue}const i=bt.Med(lc(n),lc(o));e.push(`Q ${oc(n.x)} ${oc(n.y)} ${oc(i.x)} ${oc(i.y)}`)}return e.join(" ")}function wc(t,e){return e>=2&&"straight"!==t[e-1]?.segment&&"straight"!==t[e-2]?.segment}function bc(t){if(t.length<3)return function(t){if(0===t.length)return null;const[e,...n]=t;return e?[`M ${oc(e.x)} ${oc(e.y)}`,...n.map(t=>`L ${oc(t.x)} ${oc(t.y)}`),"Z"].join(" "):null}(t);const e=t[0],n=t[t.length-1];if(!e||!n)return null;const r=bt.Med(n,e),o=[`M ${oc(r.x)} ${oc(r.y)}`];for(let i=0;i<t.length;i+=1){const e=t[i],n=t[(i+1)%t.length];if(!e||!n)continue;const r=bt.Med(e,n);o.push(`Q ${oc(e.x)} ${oc(e.y)} ${oc(r.x)} ${oc(r.y)}`)}return o.push("Z"),o.join(" ")}function vc(t){return t.map(cc)}function kc(t){return t.map(Pc)}function Pc(t){return function(t){return{points:t.points.map(cc)}}(t)}function Sc(t,e,n){return t.map(t=>({x:t.x+e,y:t.y+n,...void 0===t.pressure?null:{pressure:t.pressure},...void 0===t.segment?null:{segment:t.segment}}))}function Ic(t,e,n){return t.map(t=>({points:Sc(t.points,e,n)}))}function Mc(t,e){return t.map((t,n)=>({points:t.points.map((t,r)=>{const o=e(lc(t),n,r);return{x:o.x,y:o.y,...void 0===t.pressure?null:{pressure:t.pressure},...void 0===t.segment?null:{segment:t.segment}}})}))}function Tc(t,e,n){const r=0===e.w?1:e.w,o=0===e.h?1:e.h,i=0===n.w?1:n.w,s=0===n.h?1:n.h;return t.map(t=>({x:n.minX+(t.x-e.minX)/r*i,y:n.minY+(t.y-e.minY)/o*s,...void 0===t.pressure?null:{pressure:t.pressure},...void 0===t.segment?null:{segment:t.segment}}))}function Cc(t,e,n){return t.map(t=>({points:Tc(t.points,e,n)}))}function Ac(t){return{rotation:t.selectionRotation,rotationCenter:t.selectionRotationCenter}}function Ec(t,e){const n=Ac(e);return Mc(t,t=>function(t,e){return 0===e.rotation?t.clone():bt.RotWith(t,e.rotationCenter,-e.rotation)}(t,n))}function Lc(t,e){const n=Ac(e);return Mc(t,t=>Jt(t,n))}function Bc(t,e){return Mc(t,t=>Zt({axis:e.axis,bounds:e.selectionMirrorBounds,point:t}))}var Rc=.08;function $c(t,e,n){return Math.max(e,Math.min(n,t))}function Nc(t,e,n){return t+(e-t)*n}function zc(t,e,n){if(t.length<=1)return new bt(1,0);if(n&&t.length>=3){const n=t[e],r=t[(e-1+t.length)%t.length],o=t[(e+1)%t.length],i=n.sub(r).normalize(),s=o.sub(n).normalize(),a=i.add(s);return a.len2()>1e-6?a.normalize():s.len2()>0?s:i.len2()>0?i:new bt(1,0)}const r=t[e],o=t[e-1]??r,i=t[e+1]??r,s=r.sub(o).normalize(),a=i.sub(r).normalize();if(0===e)return a.len2()>0?a:new bt(1,0);if(e===t.length-1)return s.len2()>0?s:new bt(1,0);const l=s.add(a);return l.len2()>1e-6?l.normalize():a.len2()>0?a:s.len2()>0?s:new bt(1,0)}function Oc(t,e){return t.x*e.x+t.y*e.y}function Wc(t,e,n,r,o,i,s,a){if(n.simulatePressure)return function({distanceFromPrevious:t,previousPressure:e,runningLength:n,totalLength:r,strokeWidth:o,isClosed:i}){const s=$c(t/Math.max(1.5*o,1),0,1),a=$c(1-s,Rc,1),l=null===e?Nc(.5,a,.275):Nc(e,a,.275*Math.max(s,.36));if(i)return $c(l,Rc,1);const c=$c(n/Math.max(1.8*o,1),0,1),d=$c((r-n)/Math.max(2.6*o,1),0,1);return $c(l*Nc(.72,1,Math.min(c,d)),Rc,1)}({distanceFromPrevious:o,previousPressure:e,runningLength:i,totalLength:s,strokeWidth:r,isClosed:a});const l="number"==typeof t.pressure&&Number.isFinite(t.pressure)?$c(t.pressure,.05,1):e??.55;return null===e?l:Nc(e,l,.68)}function Hc(t,e,n,r,o={}){if(0===t.length)return[];const i=function(t,e){const n=Math.max(t+1,1.6);return{baseRadius:n,minRadius:Math.max(.6,.32*n),minRadiusScale:e?.5:.48,maxRadiusScale:e?1.22:1.24,startTaper:Math.max(1.8*t,2.5),endTaper:Math.max(2.3*t,3.5),simulatePressure:!e}}(e,n),s=t.map(lc),a=[0];let l=0;for(let u=1;u<s.length;u+=1)l+=s[u].dist(s[u-1]),a.push(l);let c=null;const d=t.map((t,n)=>{const d=a[n]??0,u=0===n?0:s[n].dist(s[n-1]),p=Wc(t,c,i,e,u,d,l,r);c=p;const h=o.taperStart??!0,f=o.taperEnd??!0,g=r||s.length<=1?1:Math.min(h?$c(d/i.startTaper,0,1):1,f?$c((l-d)/i.endTaper,0,1):1),m=Nc(i.minRadiusScale,i.maxRadiusScale,p),y=Math.max(i.minRadius,i.baseRadius*m*Nc(.7,1,g));return{point:s[n],direction:zc(s,n,r),pressure:p,radius:y,runningLength:d}});return l<.5*i.baseRadius?d.map(t=>({...t,radius:Math.max(t.radius,.92*i.baseRadius)})):d}function Dc(t,e){const n=t[t.length-1];n&&n.dist2(e)<.04?t[t.length-1]=e:t.push(e)}function Fc(t,e,n){const r=t.dist(e);if(0===r)return[];const o=bt.Angle(t,e),i=[];for(let s=1;s<n;s+=1){const e=o-Math.PI*(s/n);i.push(new bt(t.x+Math.cos(e)*r,t.y+Math.sin(e)*r))}return i}function jc(t,e,n={}){if(0===t.length)return[];if(1===t.length)return function(t,e,n){const r=[];for(let o=0;o<n;o+=1){const i=2*Math.PI*o/n;r.push(new bt(t.x+Math.cos(i)*e,t.y+Math.sin(i)*e))}return r}(t[0].point,t[0].radius,16);const r=[],o=[];let i=.12;for(const c of t)i=Math.max(i,.38*c.radius);const s=i**2;let a=null;for(let c=0;c<t.length;c+=1){const e=t[c],n=t[c+1]??e,i=e.direction,l=n.direction,d=Oc(i,l);let u=0===c||c===t.length-1?i.per().normalize():bt.Lrp(l,i,d).per().normalize();u.len2()<1e-6&&(u=a??new bt(0,1)),a=u,Uc(r,e.point.add(u.mul(e.radius)),s,{force:c===t.length-1}),Uc(o,e.point.sub(u.mul(e.radius)),s,{force:c===t.length-1})}if(e&&t.length>=3){const t=[];for(const e of r)Dc(t,e);for(let e=o.length-1;e>=0;e-=1){Dc(t,o[e])}return t}const l=[];for(const c of r)Dc(l,c);if(n.capEnd??1){const e=t[t.length-1];for(const t of Fc(e.point,r[r.length-1],8))Dc(l,t)}for(let c=o.length-1;c>=0;c-=1){Dc(l,o[c])}if(n.capStart??1){const e=t[0];for(const t of Fc(e.point,o[0],8))Dc(l,t)}return l}function Uc(t,e,n,r={}){const o=t[t.length-1];(!o||!0===r.force||o.dist2(e)>n)&&Dc(t,e)}var Xc=new WeakMap;function Yc(t){return{...t}}function Kc(t,e,n){return t.map(t=>new bt(t.x+e,t.y+n))}function _c(t,e,n){return t.map(t=>Kc(t,e,n))}function qc({segments:t,outlineVertices:e,outlinePolygons:n,strokeWidth:r,sampling:o,isClosed:i}){const s=dc(t),a=s.map(lc),l=a.length>0?vt.FromPoints(a):new vt(0,0,1,1),c=e.length>0?vt.FromPoints([...e]):l.expand(Math.max(r/2,1)),d=i&&s.length>=3?function(t){if(t.length<3)return null;const e=xc(t);return e?`${e} Z`:null}(s):null,u=void 0!==n?function(t){const e=t.map(t=>bc(t)).filter(t=>null!==t);return e.length>0?e.join(" "):null}(n):bc(e);return{normalizedSegments:kc(t),normalizedPoints:vc(s),pointBounds:l,path:u,selectionPath:d??xc(s),fillPath:d,localBounds:c,renderBounds:c.clone(),outlineVertices:e.map(t=>t.clone()),outlinePolygons:n?n.map(t=>t.map(t=>t.clone())):[e.map(t=>t.clone())],sampling:Yc(o)}}function Vc(t,e,n,r){const o=function({strokeWidth:t,isPen:e}){return[t,e?"pen":"pointer"].join(":")}({strokeWidth:n,isPen:r}),i=Xc.get(t),s=i?.get(o);if(s)return{normalizedSegment:Pc(s.normalizedSegment),sampling:Yc(s.sampling)};const a=function(t,e){if(t.length<=1)return{points:t.map(cc),rawPointCount:t.length,sampledPointCount:t.length,maxPointCount:e.maxPointCount,reduced:!1,capped:!1};const n=[cc(t[0])],r=e.minPointDistance*e.minPointDistance;let o=lc(t[0]),i=pc(t[0].pressure);for(let l=1;l<t.length;l+=1){const s=t[l];if(!s)continue;const a=lc(s),c=pc(s.pressure),d=l===t.length-1,u="straight"===s.segment,p=d||u?a:bt.Lrp(o,a,e.positionBlend),h=u?c:void 0===c?void 0:void 0===i?c:i+(c-i)*e.pressureBlend;o=p,i=h;const f=void 0===h?{x:p.x,y:p.y,...void 0===s.segment?null:{segment:s.segment}}:{x:p.x,y:p.y,pressure:h,...void 0===s.segment?null:{segment:s.segment}},g=n[n.length-1];if(!g){n.push(f);continue}const m=f.x-g.x,y=f.y-g.y,x=Math.abs((f.pressure??0)-(g.pressure??0));if(m*m+y*y<r){if(u){if(ac(g,f))continue;n.push(f);continue}(x>.08||d)&&(n[n.length-1]=f)}else n.push(f)}const s=n.length>e.maxPointCount,a=fc(n,e.maxPointCount);return{points:a,rawPointCount:t.length,sampledPointCount:a.length,maxPointCount:e.maxPointCount,reduced:a.length<t.length,capped:s}}(t.points,e),l={normalizedSegment:{points:vc(a.points)},sampling:{rawPointCount:a.rawPointCount,sampledPointCount:a.sampledPointCount,sampledPointLimit:a.maxPointCount,reduced:a.reduced,capped:a.capped}},c=i??new Map;return c.set(o,{normalizedSegment:Pc(l.normalizedSegment),sampling:Yc(l.sampling)}),i||Xc.set(t,c),l}function Gc(t,e,n=!1,r=!1){const o=function(t,e){return{minPointDistance:e?Math.max(.35,.18*t):Math.max(.55,.28*t),positionBlend:e?.68:.66,pressureBlend:e?.68:.45,maxPointCount:sc(e)}}(e,n),i=[],s=[],a=t.filter(t=>t.points.length>0);for(let p=0;p<a.length;p+=1){const t=Vc(a[p],o,e,n);i.push(Pc(t.normalizedSegment)),s.push(Yc(t.sampling))}const l=jc(Hc(dc(i),e,n,r),r),c=(d=s,u=o.maxPointCount,{rawPointCount:d.reduce((t,e)=>t+e.rawPointCount,0),sampledPointCount:d.reduce((t,e)=>t+e.sampledPointCount,0),sampledPointLimit:u,reduced:d.some(t=>t.reduced),capped:d.some(t=>t.capped)});var d,u;return qc({segments:i,outlineVertices:l,outlinePolygons:l.length>0?[l]:[],strokeWidth:e,sampling:c,isClosed:r})}var Jc=new WeakMap,Zc=new WeakMap;function Qc(t){return t.segments}function td(t,e,n){return function(t,e){const n=Math.max(0,t.w-e.left-e.right),r=Math.max(0,t.h-e.top-e.bottom);return new vt(t.x+e.left,t.y+e.top,n,r)}(n,{left:t.minX-e.minX,right:e.maxX-t.maxX,top:t.minY-e.minY,bottom:e.maxY-t.maxY})}function ed(t){const e=t,n=Jc.get(e);if(n)return n;const r=Gc(Qc(t.props),t.props.strokeWidth,t.props.isPen??!1,t.props.isClosed);return Jc.set(e,r),r}function nd(t,e,n=!1,r=!1){const o=Gc(t,e,n,r),i=o.pointBounds,s=Gc(Mc(o.normalizedSegments,t=>new bt(t.x-i.x,t.y-i.y)),e,n,r);return{x:i.x,y:i.y,segments:s.normalizedSegments,pointBounds:s.pointBounds,localBounds:s.localBounds,renderBounds:s.renderBounds,path:s.path,selectionPath:s.selectionPath,fillPath:s.fillPath,outlineVertices:s.outlineVertices,outlinePolygons:s.outlinePolygons,sampling:s.sampling}}function rd(t,e,n=!1,r=!1){return function(t,e,n=!1,r=!1){return nd(uc(t),e,n,r)}(t,e,n,r)}function od(t,e,n=!1,r=!1){return nd(t,e,n,r)}function id(t){const e=t,n=Zc.get(e);if(n)return n;const r=function(t,e,n,r,o){return qc({segments:Ic(t.normalizedSegments,n,r),outlineVertices:Kc(t.outlineVertices,n,r),outlinePolygons:_c(t.outlinePolygons,n,r),strokeWidth:e,sampling:t.sampling,isClosed:o})}(ed(t),t.props.strokeWidth,t.x,t.y,t.props.isClosed);return Zc.set(e,r),r}function sd(t){return dc(ad(t))}function ad(t){const e=function(t,e){return new bt(t.x+e.localBounds.center.x,t.y+e.localBounds.center.y)}(t,ed(t));return Mc(function(t){return Ic(Qc(t.props),t.x,t.y)}(t),n=>function(t,e,n){if(0===t.rotation&&1===t.scaleX&&1===t.scaleY)return e;const r=e.sub(n),o=new bt(r.x*t.scaleX,r.y*t.scaleY);return n.add(o.rot(t.rotation))}(t,n,e))}function ld(t,e){let n=function({segments:t,strokeWidth:e,isPen:n,isClosed:r,targetSelectionStrokeBounds:o}){let i=kc(t);for(let s=0;s<2;s+=1){const t=Gc(i,e,n,r),s=td(t.pointBounds,t.localBounds,o);i=Cc(i,t.pointBounds,s)}return i}({segments:Ec(ad(t),e),strokeWidth:t.props.strokeWidth,isPen:t.props.isPen??!1,isClosed:t.props.isClosed,targetSelectionStrokeBounds:e.targetSelectionStrokeBounds});return e.scaleX<0&&(n=Bc(n,{axis:"horizontal",selectionMirrorBounds:e.targetSelectionStrokeBounds,selectionRotation:e.selectionRotation,selectionRotationCenter:e.selectionRotationCenter})),e.scaleY<0&&(n=Bc(n,{axis:"vertical",selectionMirrorBounds:e.targetSelectionStrokeBounds,selectionRotation:e.selectionRotation,selectionRotationCenter:e.selectionRotationCenter})),od(Lc(n,e),t.props.strokeWidth,t.props.isPen??!1,t.props.isClosed)}function cd(t,e){return od(Lc(Bc(Ec(ad(t),e),e),e),t.props.strokeWidth,t.props.isPen??!1,t.props.isClosed)}function dd(t){return kc(t)}function ud(t){const e=ed(t);return{...e.sampling,hasPath:null!==e.path,hasSelectionPath:null!==e.selectionPath,outlineVertexCount:e.outlineVertices.length}}var pd=class extends he{constructor(t){super(t,"draw"),this.initial="idle",this.addChild(new hd(t,this)),this.addChild(new fd(t,this))}getDefaultProps(){return this.editor.shapes.getDefaultProps("draw")}},hd=class extends he{constructor(t,e){super(t,"idle",e)}onEnter(){this.editor.interaction.clearSelection()}onPointerDown(t){const e=this.parent.getDefaultProps(),n=function(t,e){const n=t.pages.getCurrentId();let r=null,o=1/0,i=-1;const s=t.state.currentPageShapeIds.get();for(let a=0;a<s.length;a+=1){const n=t.shapes.get(s[a]);if(!n||t.shapes.isHidden(n.id))continue;const l=t.shapes.getUtil(n);if(!l.canAutomaticallyReceiveChildren(n))continue;if(!t.layers.canReceiveChildren(n.id))continue;if(!t.shapes.isPagePointInClip(n.id,e))continue;const c=l.getChildClipLocalBounds(n)??l.getLocalBounds(n),d=t.shapes.computeLocalToPageTransform(n).invert().applyToPoint(e);if(!c.containsPoint(d))continue;const u=t.shapes.computePageBounds(n),p=u.w*u.h;(!r||p<o||p===o&&a>i)&&(r=n,o=p,i=a)}return r?.id??n}(this.editor,t.pagePoint),r=n.startsWith("shape:")?this.editor.shapes.get(n):null,o=r?this.editor.shapes.computeLocalToPageTransform(r).invert():Ht.Identity(),i=o.applyToPoint(t.pagePoint),s=gd(i,i,t.pressure,"pen"===t.pointerType);var a,l;this.transition("drawing",{originPagePoint:t.pagePoint.clone(),originScreenPoint:t.screenPoint.clone(),originParentPoint:i,pageToParent:o,parentId:n,shapeId:null,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,isClosed:e.isClosed,isPen:"pen"===t.pointerType,pointGuard:(a=e.strokeWidth,l="pen"===t.pointerType,l?{minPointDistance:Math.max(.12,.08*a),pressureDeltaThreshold:.035,softMaxPointCount:1600,hardMaxPointCount:3200,maxDistanceMultiplier:2.5}:{minPointDistance:Math.max(.3,.14*a),pressureDeltaThreshold:.08,softMaxPointCount:900,hardMaxPointCount:2200,maxDistanceMultiplier:6}),pointGuardState:{anchorPoint:md(s),hasProvisionalPoint:!1},straightSegmentAnchorPoint:null,preserveStraightEndpointOnNextFreePoint:!1,segments:[{points:[s]}]})}},fd=class extends he{tool;info=null;pendingUpdateFrame=null;operation=null;constructor(t,e){super(t,"drawing",e),this.tool=e}onEnter(t){this.info=t,this.editor.interaction.clearSelection(),this.editor.commands.setSelectedShapeIds([],{source:"system"}),this.operation=this.editor.operations.begin({kind:"draw.create",label:"shape.create",source:"user",history:"record"})}onPointerMove(t){this.appendPoint(t,!1)}onPointerUp(t){this.appendPoint(t,!0),this.flushShapeUpdate();const e=this.info?.shapeId??null;if(!e)return this.cancelOperation(),void this.transition("idle");this.info?.parentId.startsWith("shape:")||Yt(this.editor,e,{source:"user"}),this.commitOperation(),this.transition("idle")}onCancel(){this.cancelScheduledShapeUpdate(),this.cancelOperation(),this.transition("idle")}onExit(){this.cancelScheduledShapeUpdate(),this.cancelOperation(),this.info=null}commitOperation(){const t=this.operation;this.operation=null,t?.commit()}cancelOperation(){const t=this.operation;this.operation=null,t?.isActive&&t.cancel()}appendPoint(t,e){if(!this.info)return;const n=gd(this.info.pageToParent.applyToPoint(t.pagePoint),this.info.originParentPoint,t.pressure,this.info.isPen);if(t.shiftKey?this.appendStraightSegmentPoint(n):(this.exitStraightSegmentMode(),this.info.preserveStraightEndpointOnNextFreePoint?this.appendDistinctCurrentPoint(n)&&(this.info.preserveStraightEndpointOnNextFreePoint=!1):this.appendGuardedCurrentPoint(n,{force:e})),this.splitCurrentSegmentAtLimit(),!this.info.shapeId){const n=this.info.originScreenPoint.dist(t.screenPoint);if(!e&&n<2)return;const r=this.createShape();return void(this.info.shapeId=r.id)}this.scheduleShapeUpdate()}scheduleShapeUpdate(){var t;null===this.pendingUpdateFrame&&(this.pendingUpdateFrame=(t=()=>{this.pendingUpdateFrame=null,this.flushShapeUpdate()},"function"==typeof requestAnimationFrame?{type:"animation",id:requestAnimationFrame(t)}:{type:"timeout",id:setTimeout(t,16)}))}cancelScheduledShapeUpdate(){null!==this.pendingUpdateFrame&&(!function(t){if("animation"===t.type)return void cancelAnimationFrame(t.id);clearTimeout(t.id)}(this.pendingUpdateFrame),this.pendingUpdateFrame=null)}flushShapeUpdate(){this.cancelScheduledShapeUpdate(),this.info?.shapeId&&this.editor.commands.updateShapes([{id:this.info.shapeId,props:wd(this.info.segments)}],{source:"user"})}createShape(){const t=this.tool.getDefaultProps(),e=function(t,e){return e&&t.layers.canReceiveChildren(e)?e:t.pages.getCurrentId()}(this.editor,this.info?.parentId);this.info&&(this.info.parentId=e);const[n]=this.editor.commands.createShapes([{type:"draw",x:this.info?.originParentPoint.x??0,y:this.info?.originParentPoint.y??0,...e.startsWith("shape:")?{parentId:e}:{},props:{...t,stroke:this.info?.stroke??t.stroke,strokeWidth:this.info?.strokeWidth??t.strokeWidth,fill:this.info?.fill??t.fill,isClosed:this.info?.isClosed??t.isClosed,...wd(this.info?.segments??[]),isPen:this.info?.isPen??!1}}],{source:"user"});if(!n||"draw"!==n.type)throw new Error("Failed to create draw shape");return n}appendStraightSegmentPoint(t){if(!this.info)return;this.info.preserveStraightEndpointOnNextFreePoint=!1;const e=yd(this.info),n=e[e.length-1];if(!this.info.straightSegmentAnchorPoint){if(!n)return this.replaceCurrentSegmentPoints([{...t,segment:"straight"}]),void this.resetPointGuard(t);this.info.straightSegmentAnchorPoint=md(n)}const r={...t,segment:"straight"};if("straight"===n?.segment)return this.replaceCurrentSegmentPoints([...e.slice(0,-1),r]),void this.resetPointGuard(r);this.replaceCurrentSegmentPoints([...e,r]),this.resetPointGuard(r)}exitStraightSegmentMode(){this.info?.straightSegmentAnchorPoint&&(this.info.straightSegmentAnchorPoint=null,this.info.preserveStraightEndpointOnNextFreePoint=!0)}appendDistinctCurrentPoint(t){if(!this.info)return!1;const e=yd(this.info),n=e[e.length-1];return(!n||(o=t,(r=n).x!==o.x||r.y!==o.y||r.pressure!==o.pressure||r.segment!==o.segment))&&(this.replaceCurrentSegmentPoints([...e,md(t)]),this.resetPointGuard(t),!0);var r,o}appendGuardedCurrentPoint(t,e={}){if(!this.info)return;const n=yd(this.info).map(md);this.info.pointGuardState=hc(n,t,this.info.pointGuard,this.info.pointGuardState,e),this.replaceCurrentSegmentPoints(n)}resetPointGuard(t){this.info&&(this.info.pointGuardState={anchorPoint:md(t),hasProvisionalPoint:!1})}replaceCurrentSegmentPoints(t){if(!this.info)return;const e=xd(this.info.segments);this.info.segments=[...e.slice(0,-1),{points:t.map(md)}]}splitCurrentSegmentAtLimit(){if(!this.info)return;const t=sc(this.info.isPen);let e=xd(this.info.segments),n=e[e.length-1];for(;n.points.length>t;){const r=n.points.slice(0,t).map(md),o=r[r.length-1],i=n.points.slice(t).map(md);if(!o||0===i.length)break;const s={points:[md(o),...i]};e=[...e.slice(0,-1),{points:r},s],n=s}this.info.segments=e}};function gd(t,e,n,r){return{x:t.x-e.x,y:t.y-e.y,...r&&n>0?{pressure:n}:null}}function md(t){return{x:t.x,y:t.y,...void 0===t.pressure?null:{pressure:t.pressure},...void 0===t.segment?null:{segment:t.segment}}}function yd(t){const e=xd(t.segments),n=e[e.length-1];return n?n.points.map(md):[]}function xd(t){return t.length>0?[...t]:[{points:[]}]}function wd(t){return{segments:dd(xd(t))}}function bd(t){return yt(t)&&"draw"===t.type}var vd=bn("plugin-draw.api");function kd({editor:t}){return function({editor:t}){return{getSelectionStyle(){const e=t.state.selectedShapes.get().filter(bd);return 0===e.length?null:{fill:Pd(e.map(t=>t.props.fill)),stroke:Pd(e.map(t=>t.props.stroke)),strokeWidth:Pd(e.map(t=>t.props.strokeWidth)),isClosed:Pd(e.map(t=>t.props.isClosed))}},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(bd).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)},getToolDefaults:()=>t.shapes.getDefaultProps("draw"),setToolDefaults:e=>(t.shapes.updateDefaultProps("draw",e),t.shapes.getDefaultProps("draw"))}}({editor:t})}function Pd(t){const[e,...n]=t;return void 0!==e&&n.every(t=>t===e)?e:void 0}function Sd(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist(e);const i=Math.max(0,Math.min(1,((t.x-e.x)*r.x+(t.y-e.y)*r.y)/o)),s=new bt(e.x+r.x*i,e.y+r.y*i);return t.dist(s)}function Id(t,e,n,r){return function(t,e,n,r){const o=e.sub(t),i=r.sub(n),s=o.x*i.y-o.y*i.x;if(Math.abs(s)<1e-8)return!1;const a=n.sub(t),l=(a.x*i.y-a.y*i.x)/s,c=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&c>=0&&c<=1}(t,e,n,r)?0:Math.min(Sd(t,n,r),Sd(e,n,r),Sd(n,t,e),Sd(r,t,e))}function Md(t,e){let n=!1;for(let r=0,o=e.length-1;r<e.length;o=r,r+=1){const i=e[r],s=e[o];i&&s&&(i.y>t.y!=s.y>t.y&&t.x<(s.x-i.x)*(t.y-i.y)/(s.y-i.y)+i.x&&(n=!n))}return n}function Td(t,e){if(0===e.length)return Number.POSITIVE_INFINITY;let n=Number.POSITIVE_INFINITY;for(let r=0;r<e.length;r+=1){const o=e[r],i=e[(r+1)%e.length];o&&i&&(n=Math.min(n,Sd(t,o,i)))}return n}function Cd(t,e,n,r){if(0===n.length)return!1;if(Md(t,n)||Md(e,n))return!0;for(let o=0;o<n.length;o+=1){const i=n[o],s=n[(o+1)%n.length];if(i&&s&&Id(t,e,i,s)<=r)return!0}return!1}function Ad(t,e,n,r={}){if(r.isClosed&&void 0!==r.fill&&!Ot(r.fill)&&t.normalizedPoints.length>=3&&Md(n,t.normalizedPoints.map(lc)))return!0;if(r.isClosed&&function(t,e,n){if(0===e.length)return Number.POSITIVE_INFINITY;if(1===e.length)return t.dist(lc(e[0]));let r=Number.POSITIVE_INFINITY;for(let o=1;o<e.length;o+=1){const n=e[o-1],i=e[o];n&&i&&(r=Math.min(r,Sd(t,lc(n),lc(i))))}return n&&e.length>=3&&(r=Math.min(r,Sd(t,lc(e[e.length-1]),lc(e[0])))),r}(n,t.normalizedPoints,!0)<=Math.max(4,.5*e))return!0;if(0===t.outlineVertices.length)return!1;for(const o of t.outlinePolygons){if(Md(n,o))return!0;if(Td(n,o)<=Math.max(4,.5*e))return!0}return!1}function Ed(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function Ld(t){if(!t||"object"!=typeof t)return null;const e=t,n=Ed(e.x,NaN),r=Ed(e.y,NaN);if(!Number.isFinite(n)||!Number.isFinite(r))return null;const o=Ed(e.pressure,NaN);return e.x!==n||e.y!==r||void 0!==e.pressure&&e.pressure!==o||void 0!==e.segment&&"straight"!==e.segment?{x:n,y:r,...Number.isFinite(o)?{pressure:o}:null,..."straight"===e.segment?{segment:"straight"}:null}:t}function Bd(t){if(!t||"object"!=typeof t)return null;const e=t,n=function(t,e){if(!Array.isArray(t))return e;let n=!1;const r=[];for(const o of t){const t=Ld(o);t?(n=n||t!==o,r.push(t)):n=!0}return 0===r.length?e:n?r:t}(e.points,[]);return 0===n.length?null:n===e.points?t:{points:n}}function Rd(t,e){if(!Array.isArray(t))return e;let n=!1;const r=[];for(const o of t){const t=Bd(o);t?(n=n||t!==o,r.push(t)):n=!0}return 0===r.length?e:n?r:t}var $d=class extends pe{type="draw";getDefaultProps(){return{segments:uc([{x:0,y:0},{x:24,y:12}]),stroke:Et("stroke-slate"),strokeWidth:4,fill:Lt("transparent"),isClosed:!1,isPen:!1}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{segments:Rd(e.segments,n.segments),stroke:$t(e.stroke,n.stroke),strokeWidth:Math.max(4,Ed(e.strokeWidth,n.strokeWidth)),fill:$t(e.fill,n.fill),isClosed:"boolean"==typeof e.isClosed?e.isClosed:n.isClosed,isPen:"boolean"==typeof e.isPen?e.isPen:n.isPen}}getPositionedBounds(t){const e=ed(t);return new vt(t.x+e.localBounds.x,t.y+e.localBounds.y,e.localBounds.w,e.localBounds.h)}getLocalBounds(t){return ed(t).localBounds}getRenderBounds(t){return ed(t).renderBounds}getExportBounds(t){return this.getRenderBounds(t)}canReceiveTerminalBinding(t){return!0}getSelectionResizeLocalBounds(t){return this.getLocalBounds(t)}resizeSelectionBounds(t,e){const n=ld(t,{targetSelectionStrokeBounds:e.selectionLocalBounds,scaleX:e.scaleX,scaleY:e.scaleY,selectionRotation:e.selectionRotation,selectionRotationCenter:e.selectionRotationCenter});return{id:t.id,x:n.x,y:n.y,rotation:0,scaleX:1,scaleY:1,props:{segments:dd(n.segments)}}}flipSelectionBounds(t,e){const n=cd(t,{axis:e.axis,selectionMirrorBounds:e.selectionBounds,selectionRotation:e.selectionRotation,selectionRotationCenter:e.selectionRotationCenter});return{id:t.id,x:n.x,y:n.y,rotation:0,scaleX:1,scaleY:1,props:{segments:dd(n.segments)}}}getSelectionOverlayInfo(t){return{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,pathStyle:null}}isWrappedByBrush(t,e){return e.pageOutlineVertices.every(t=>e.brushBounds.containsPoint(t))}canSelectByBrush(t,e){if(this.isWrappedByBrush(t,e))return!0;if(e.isWrapping)return!1;const n=e.pageOutlineVertices;return!!n.some(t=>e.brushBounds.containsPoint(t))||function(t){const e=new bt(t.minX,t.minY),n=new bt(t.maxX,t.minY),r=new bt(t.maxX,t.maxY),o=new bt(t.minX,t.maxY);return[[e,n],[n,r],[r,o],[o,e]]}(e.brushBounds).some(([t,e])=>{for(let r=0;r<n.length;r+=1){const o=n[r],i=n[(r+1)%n.length];if(o&&i&&St(t,e,o,i))return!0}return!1})}getPositionedOutlineVertices(t){return id(t).outlineVertices}hitTest(t,e){return Ad(id(t),t.props.strokeWidth,e,{fill:t.props.fill,isClosed:t.props.isClosed})}hitTestLineSegment(t,e){return function(t,e,n,r,o={}){const i=Math.max(4,.5*e,o.margin??0);return!!(o.isClosed&&void 0!==o.fill&&!Ot(o.fill)&&t.normalizedPoints.length>=3&&Cd(n,r,t.normalizedPoints.map(lc),i))||0!==t.outlineVertices.length&&t.outlinePolygons.some(t=>Cd(n,r,t,i))}(id(t),t.props.strokeWidth,e.positionedStart,e.positionedEnd,{fill:t.props.fill,isClosed:t.props.isClosed,margin:e.positionedMargin})}},Nd=class{type="draw";toSvg(t,e){const n=ed(t);if(!n.path&&!n.selectionPath)return null;const r=[];return n.fillPath&&!Ot(t.props.fill)&&r.push({tag:"path",attrs:{d:n.fillPath,fill:e.resolveColor(t.props.fill),stroke:"none"}}),t.props.isClosed&&n.selectionPath?r.push({tag:"path",attrs:{d:n.selectionPath,fill:"none",stroke:e.resolveColor(t.props.stroke),"stroke-width":t.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round"}}):n.path&&r.push({tag:"path",attrs:{d:n.path,fill:e.resolveColor(t.props.stroke),stroke:"none"}}),{tag:"g",children:r}}};function zd(){return{id:"land.draw",shapeUtils:[new $d],shapeSvgExporters:[new Nd],setup(t){t.tools.register("draw",t=>new pd(t))}}}function Od({shape:t,stroke:e=t.props.stroke,strokeWidth:n=t.props.strokeWidth}){const{fillPath:r,renderBounds:o,path:i,selectionPath:s}=ed({props:{...t.props,strokeWidth:n}});if(!i&&!s)return null;const a=Nt(e);
24
+ return u("svg",{width:"100%",height:"100%",viewBox:`${o.x} ${o.y} ${Math.max(o.w,1)} ${Math.max(o.h,1)}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[r&&!Ot(t.props.fill)?d("path",{d:r,fill:Nt(t.props.fill),stroke:"none"}):null,t.props.isClosed&&s?d("path",{d:s,fill:"none",stroke:a,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}):i?d("path",{d:i,fill:a,stroke:"none"}):null]})}function Wd({shape:t,strokeWidth:e}){const{path:n,renderBounds:r,selectionPath:i}=ed(t),s=i??n;return s?d("svg",{"data-ui":"draw-hover-outline",width:"100%",height:"100%",viewBox:`${r.x} ${r.y} ${Math.max(r.w,1)} ${Math.max(r.h,1)}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:d("path",{d:s,fill:"none",stroke:o,strokeWidth:e,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:"non-scaling-stroke"})}):null}function Hd(){return{id:"land.draw.react",shapeRenderers:[{type:"draw",component:Dd,hoverComponent:Fd}]}}function Dd({shape:t}){
25
+ return d(Od,{shape:t})}function Fd({shape:t,strokeWidth:e}){
26
+ return d(Wd,{shape:t,strokeWidth:e})}var jd={id:"draw",editor:zd(),render:Hd(),api:vd,setup:({editor:t})=>({api:kd({editor:t})})};function Ud(t,e,n){return Math.max(e,Math.min(n,t))}function Xd(t,e,n){return t+(e-t)*n}function Yd(t,e,n){if(void 0!==t||void 0!==e)return Xd(t??e??0,e??t??0,n)}function Kd(t,e,n){const r=Math.max(2,Math.round(e));if(0===t.length)return[];if(1===t.length)return Array.from({length:r},()=>({point:cc(t[0]),segmentWeight:0}));const o=function(t,e){const n=[];for(let r=1;r<t.length;r+=1){const e=t[r-1],o=t[r];e&&o&&n.push({start:e,end:o,length:lc(e).dist(lc(o)),segmentWeight:"straight"===o.segment?1:0})}if(e&&t.length>=3){const e=t[t.length-1],r=t[0];e&&r&&n.push({start:e,end:r,length:lc(e).dist(lc(r)),segmentWeight:1})}return n}(t,n),i=o.reduce((t,e)=>t+e.length,0);return 0===o.length||i<=1e-6?Array.from({length:r},()=>({point:cc(t[0]),segmentWeight:0})):Array.from({length:r},(t,e)=>{let s=n?e/r*i:e/Math.max(r-1,1)*i,a=o[o.length-1];for(const n of o){if(s<=n.length||n===a){a=n;break}s-=n.length}const l=a.length<=1e-6?0:Ud(s/a.length,0,1),c=lc(a.start),d=lc(a.end),u=bt.Lrp(c,d,l),p=Yd(a.start.pressure,a.end.pressure,l);return{point:{x:u.x,y:u.y,...void 0===p?null:{pressure:p}},segmentWeight:a.segmentWeight}})}function _d(t,e,n,r={}){if(t.parentId!==e.parentId)throw new Error("Cannot interpolate draw shapes with different parents");const o=Ud(n,0,1),i=t.props.isClosed&&e.props.isClosed,s=sd(t),a=sd(e),l=(c=s.length,d=a.length,"number"==typeof(u=r.pointCount)&&Number.isFinite(u)?Math.max(2,Math.round(u)):Math.max(2,c,d,12));var c,d,u;const p=Kd(s,l,i),h=Kd(a,l,i),f=p.map((t,e)=>{const n=h[e]??h[h.length-1]??t,r=bt.Lrp(lc(t.point),lc(n.point),o),i=Yd(t.point.pressure,n.point.pressure,o),s=Xd(t.segmentWeight,n.segmentWeight,o);return{x:r.x,y:r.y,...void 0===i?null:{pressure:i},...e>0&&s>=.5?{segment:"straight"}:null}}),g=o<.5?t.props.isClosed:e.props.isClosed,m=o<.5?t.props.isPen??!1:e.props.isPen??!1,y=Math.max(1,Xd(t.props.strokeWidth,e.props.strokeWidth,o)),x=rd(f,y,m,g),w=o<.5?t:e;return{...w,id:t.id,x:x.x,y:x.y,rotation:0,scaleX:1,scaleY:1,opacity:Xd(t.opacity,e.opacity,o),props:{...w.props,segments:kc(x.segments),strokeWidth:y,isClosed:g,isPen:m}}}var qd=Dt("plugin.eraser.runtime");function Vd(t,e){if(t.length!==e.length)return!1;const n=new Set(e);return t.every(t=>n.has(t))}function Gd(t){return t.runtime.require(qd)}function Jd(t){return 4/t.state.camera.get().z}function Zd(t,e,n,r){const o=[new bt(e.minX,e.minY),new bt(e.maxX,e.minY),new bt(e.maxX,e.maxY),new bt(e.minX,e.maxY)].map(t=>n.applyToPoint(t));let i=0,s=Number.POSITIVE_INFINITY;for(let a=0;a<o.length;a+=1){const e=o[a],n=o[(a+1)%o.length].sub(e),r=t.sub(e),l=n.x*r.y-n.y*r.x;if(Math.abs(l)<=1e-8)return!1;const c=Math.sign(l);if(0===i)i=c;else if(c!==i)return!1;const d=n.len2(),u=0===d?0:Math.max(0,Math.min(1,(r.x*n.x+r.y*n.y)/d));s=Math.min(s,t.dist(e.add(n.mul(u))))}return s>r}function Qd(t,e){const n=new Set,r=Jd(t);for(const o of t.shapes.hitTestPoint(e,{hitTest:"bindingTarget"})){const i=t.shapes.getUtil(o);if(!i.canReceiveChildren(o))continue;const s=i.getChildClipLocalBounds(o);s&&(Zd(e,s,t.shapes.computeLocalToPageTransform(o),r)&&n.add(o.id))}return n}function tu(t,e,n){return n.protectedContainerIds.has(e.id)||t.layers.isOrAncestorLocked(e.id)||t.shapes.getUtil(e).canReceiveChildren(e)&&t.layers.hasLockedDescendant(e.id)?null:e.id}function eu(t,e,n,r){const o=r.topMostOnly?n.slice(0,1):n;for(const i of o){const n=tu(t,i,e);n&&e.erasingShapeIds.add(n)}}function nu(t,e,n){eu(t,e,t.shapes.hitTestPoint(n.pagePoint),{topMostOnly:n.accelKey})}function ru(t,e,n){eu(t,e,t.shapes.hitTestLineSegment(e.previousPagePoint,n.pagePoint,{margin:Jd(t)}),{topMostOnly:n.accelKey})}function ou(t,e){const n=t.trail[t.trail.length-1];n&&n.dist2(e)<=1e-6||t.trail.push(e.clone())}function iu(t,e){Gd(t).setPreview(Array.from(e.erasingShapeIds),e.trail)}function su(t){Gd(t).clear()}var au=class extends he{constructor(t){super(t,"eraser"),this.initial="idle",this.addChild(new lu(t,this)),this.addChild(new cu(t,this)),this.addChild(new du(t,this))}onExit(){su(this.editor)}},lu=class extends he{constructor(t,e){super(t,"idle",e)}onEnter(){su(this.editor)}onPointerDown(t){0===t.button&&this.transition("pointing",function(t,e){const n={originScreenPoint:e.screenPoint.clone(),previousPagePoint:e.pagePoint.clone(),protectedContainerIds:Qd(t,e.pagePoint),erasingShapeIds:new Set,trail:[e.pagePoint.clone()]};return nu(t,n,e),iu(t,n),n}(this.editor,t))}},cu=class extends he{info=null;constructor(t,e){super(t,"pointing",e)}onEnter(t){this.info=t}onPointerMove(t){this.info&&function(t,e){return t.dist2(e)>=9}(this.info.originScreenPoint,t.screenPoint)&&(ru(this.editor,this.info,t),ou(this.info,t.pagePoint),this.info.previousPagePoint=t.pagePoint.clone(),iu(this.editor,this.info),this.transition("erasing",this.info))}onPointerUp(t){this.info&&(nu(this.editor,this.info,t),iu(this.editor,this.info),uu(this.editor,this.info)),this.transition("idle")}onCancel(){su(this.editor),this.transition("idle")}onExit(){this.info=null}},du=class extends he{info=null;constructor(t,e){super(t,"erasing",e)}onEnter(t){this.info=t}onPointerMove(t){this.update(t)}onPointerUp(t){this.update(t),this.info&&uu(this.editor,this.info),this.transition("idle")}onCancel(){su(this.editor),this.transition("idle")}onExit(){this.info=null}update(t){this.info&&(ru(this.editor,this.info,t),ou(this.info,t.pagePoint),this.info.previousPagePoint=t.pagePoint.clone(),iu(this.editor,this.info))}};function uu(t,e){const n=Array.from(e.erasingShapeIds);su(t),0!==n.length&&t.commands.deleteShapes(n,{source:"user"})}function pu(){return{id:"land.eraser.react",canvasOverlays:[{id:"land.eraser.trail-overlay",component:hu}],shapeOpacityModifiers:[{id:"land.eraser.preview-opacity",getOpacityValue(t,e){const n=Gd(t).erasingShapeIdSetSignal;return{graph:t.signals,get:()=>t.layers.isOrAncestorInSet(e,n.get())?.32:1}}}]}}var hu=g(function(){return r(Gd(n()).trailActiveSignal)?d(fu,{}):null}),fu=g(function(){const t=n(),e=r(Gd(t).trailSignal),o=r(t.state.cameraZoom),i=Math.max(o,1e-4),s=function(){const[t,e]=k(()=>Tu());return x(()=>{if("undefined"==typeof window)return;let t=0;const n=r=>{e(r),t=window.requestAnimationFrame(n)};return t=window.requestAnimationFrame(n),()=>{window.cancelAnimationFrame(t)}},[]),t}(),a=v({samples:[],sourceLength:0}),l=Math.max(s,Tu());!function(t,e,n,r){Au(t,r),e.length<t.sourceLength&&(t.samples=[],t.sourceLength=0);if(e.length===t.sourceLength)return;const o=t.sourceLength,i=e.length-o,s=t.samples[t.samples.length-1]?.time??r-ku*i;for(let a=o;a<e.length;a++){const l=e[a],c=(a-o+1)/i;Cu(t,{x:l.x,y:l.y},n,Du(s,r,c))}t.sourceLength=e.length,Au(t,r)}(a.current,e,i,l);const c=function(t,e){const n=Eu(t,e);return function(t,e){if(t.length<=1)return[...t];const n=.15+.85*(1-e),r=[t[0]];for(let o=1;o<t.length;o++)r.push(Hu(r[r.length-1],t[o],n));return r}(n.length>mu?n.slice(-48):n,wu)}(a.current.samples,l);if(0===c.length)return null;const u=(h=xu/i,0===(p=c).length||h<=0?null:1===p.length?Uu(Bu(p[0],h/2,vu))??"":Uu(function(t){if(0===t.length)return[];if(1===t.length)return Bu(t[0].point,Math.max(t[0].radius,.01),vu);const e=[],n=[];for(const a of t){const t=Nu(a.direction);ju(e,Ou(a.point,Wu(t,a.radius))),ju(n,zu(a.point,Wu(t,a.radius)))}const r=[];for(const a of e)ju(r,a);const o=t[t.length-1],i=Nu(o.direction),s=function({center:t,direction:e,normal:n,radius:r}){if(r<=0)return[];const o=[];for(let i=1;i<bu;i++){const s=i/bu;o.push(zu(t,zu(Wu(e,Math.sin(Math.PI*s)*r),Wu(n,-Math.cos(Math.PI*s)*r))))}return o}({center:o.point,direction:o.direction,normal:i,radius:o.radius});for(const a of s)ju(r,a);for(let a=n.length-1;a>=0;a--)ju(r,n[a]);return r}(function(t,e){const n=function(t){const e=[0];for(let n=1;n<t.length;n++)e.push(e[n-1]+Ru(t[n-1],t[n]));return e}(t),r=n[n.length-1]??0,o=Math.max(e,r);return t.map((r,i)=>{const s=n[i]??0,a=Fu(s/o,0,1);return{point:r,direction:Lu(t,i),radius:e/2*a,runningLength:s}})}(p,h))));var p,h;return u?d("g",{"data-ui":"eraser-trail-overlay",children:d("path",{"data-ui":"eraser-trail-scribble",d:u,fill:gu})}):null}),gu="rgba(142, 142, 142, 0.16)",mu=48,yu=1,xu=12,wu=.32,bu=8,vu=13,ku=16,Pu=8,Su=180,Iu=180,Mu=680;function Tu(){return"undefined"==typeof performance?Date.now():performance.now()}function Cu(t,e,n,r){const o=t.samples[t.samples.length-1];if(!o)return void t.samples.push({...e,time:r,velocity:0});const i=yu/n,s=Ru(o,e);if(s<i)return void(t.samples[t.samples.length-1]={...o,...e,time:r});const a=s*n/Math.max(Pu,r-o.time);t.samples.push({...e,time:r,velocity:Du(o.velocity,a,.68)})}function Au(t,e){t.samples=Eu(t.samples,e)}function Eu(t,e){const n=t[t.length-1];if(!n)return[];const r=e-Fu(Su+n.velocity*Iu,Su,Mu);if(n.time<r)return[];const o=t.findIndex(t=>t.time>=r);if(-1===o)return[];const i=t.slice(o),s=t[o-1],a=i[0];return s&&a.time>r?[(l=s,c=a,d=Fu((r-s.time)/(a.time-s.time),0,1),{...Hu(l,c,d),time:Du(l.time,c.time,d),velocity:Du(l.velocity,c.velocity,d)}),...i]:i;var l,c,d}function Lu(t,e){if(t.length<=1)return{x:1,y:0};const n=t[e-1]??t[e],r=t[e+1]??t[e];return function(t){const e=Math.sqrt(t.x*t.x+t.y*t.y);return e<=0?{x:1,y:0}:{x:t.x/e,y:t.y/e}}(0===e?Ou(r,t[e]):e===t.length-1?Ou(t[e],n):Ou(r,n))}function Bu(t,e,n){const r=[];for(let o=0;o<n;o++){const i=2*Math.PI*o/n;r.push({x:t.x+Math.cos(i)*e,y:t.y+Math.sin(i)*e})}return r}function Ru(t,e){return Math.sqrt($u(t,e))}function $u(t,e){const n=t.x-e.x,r=t.y-e.y;return n*n+r*r}function Nu(t){return{x:-t.y,y:t.x}}function zu(t,e){return{x:t.x+e.x,y:t.y+e.y}}function Ou(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Wu(t,e){return{x:t.x*e,y:t.y*e}}function Hu(t,e,n){return{x:Du(t.x,e.x,n),y:Du(t.y,e.y,n)}}function Du(t,e,n){return t+(e-t)*n}function Fu(t,e,n){return Math.max(e,Math.min(n,t))}function ju(t,e){const n=t[t.length-1];!n||$u(n,e)>.04?t.push(e):t[t.length-1]=e}function Uu(t){if(t.length<2)return null;if(2===t.length)return`M ${Yu(t[0])} L ${Yu(t[1])} Z`;const e=[`M ${Yu(Xu(t[0],t[1]))}`];for(let n=1;n<t.length;n++){const r=t[n],o=t[(n+1)%t.length];e.push(`Q ${Yu(r)} ${Yu(Xu(r,o))}`)}return e.push("Z"),e.join(" ")}function Xu(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}function Yu(t){return`${Ku(t.x)},${Ku(t.y)}`}function Ku(t){return Number.isInteger(t)?`${t}`:t.toFixed(3)}function _u(){return{id:"land.eraser",setup(t){t.runtime.provide(qd,function(t){const{atom:e,computed:n}=t.signals,r=e("eraser.shapeIds",[],{isEqual:Vd}),o=n("eraser.shapeIdSet",()=>new Set(r.get())),i=e("eraser.trail",[]);return{erasingShapeIdsSignal:r,erasingShapeIdSetSignal:o,trailSignal:i,trailActiveSignal:n("eraser.trailActive",()=>i.get().length>1),setPreview(t,e){r.set(Array.from(new Set(t))),i.set(e.map(t=>t.clone()))},clear(){r.set([]),i.get().length>0&&i.set([])}}}(t)),t.tools.register("eraser",t=>new au(t))}}}var qu={id:"eraser",editor:_u(),render:pu()};function Vu(t){return/^\s*$/.test(t)?"Frame":t}function Gu(t){return new vt(0,-34,t.props.w,t.props.h+34)}function Ju(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function Zu(t){return new vt(t.x,t.y-34,t.props.w,34)}function Qu(t,e,n){const r=n/2;return!!t.expand(r).containsPoint(e)&&(Math.abs(e.x-t.minX)<=r||Math.abs(e.x-t.maxX)<=r||Math.abs(e.y-t.minY)<=r||Math.abs(e.y-t.maxY)<=r)}var tp=class extends pe{type="frame";getDefaultProps(){return{w:640,h:360,name:"",fill:Lt("transparent"),stroke:Et("stroke-muted"),strokeWidth:1}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Math.max(1,Ju(e.w,n.w)),h:Math.max(1,Ju(e.h,n.h)),name:"string"==typeof e.name?e.name:n.name,fill:$t(e.fill,n.fill),stroke:$t(e.stroke,n.stroke),strokeWidth:Math.max(0,Ju(e.strokeWidth,n.strokeWidth))}}getLocalBounds(t){return new vt(0,0,t.props.w,t.props.h)}getRenderBounds(t){return Gu(t)}getPointHitTestBounds(t){const e=this.getPositionedBounds(t).expand(3),n=Zu(t);return vt.FromPoints([new bt(e.minX,e.minY),new bt(e.maxX,e.maxY),new bt(n.minX,n.minY),new bt(n.maxX,n.maxY)])}canEdit(t){return!0}canReceiveChildren(t){return!0}canSnapChildrenToSelf(t){return!0}canReceiveTerminalBinding(t){return!0}getSelectionResizeHandleIds(t,e){return _t}shouldRotateDescendants(t){return!0}getChildClipLocalBounds(t){return this.getLocalBounds(t)}canSelectByBrush(t,e){return super.isWrappedByBrush(t,e)}hitTest(t,e){return Zu(t).containsPoint(e)||Qu(this.getPositionedBounds(t),e,6)}hitTestBindingTarget(t,e){return this.getPositionedBounds(t).containsPoint(e)}hitTestLineSegment(t,e){return function(t,e,n,r){const o=r/2;if(Qu(t,e,r)||Qu(t,n,r))return!0;const i=[new bt(t.minX,t.minY),new bt(t.maxX,t.minY),new bt(t.maxX,t.maxY),new bt(t.minX,t.maxY)];for(let s=0;s<i.length;s+=1){const t=i[s],r=i[(s+1)%i.length];if(t&&r&&It(e,n,t,r)<=o)return!0}return!1}(this.getPositionedBounds(t),e.positionedStart,e.positionedEnd,Math.max(6,e.positionedMargin))}},ep=bn("plugin-frame.api");function np({editor:t}){return function({editor:t}){return{create(e){const n=t.shapes.getDefaultProps("frame"),[r]=t.commands.createShapes([{type:"frame",x:e.x,y:e.y,meta:e.meta?{...e.meta}:void 0,props:{...n,w:e.w??n.w,h:e.h??n.h,name:e.name??n.name,fill:e.fill??n.fill,stroke:e.stroke??n.stroke,strokeWidth:e.strokeWidth??n.strokeWidth}}],{source:"user"});return"frame"===r?.type?{id:r.id,type:r.type}:null},moveShapesToFrame(e,n){const r=t.shapes.get(n);if(!r||"frame"!==r.type)return[];const o=e.filter(e=>{const n=t.shapes.get(e);return!!n&&!n.isLocked});return o.length>0&&t.commands.reparentShapes({ids:[...o],parentId:n},{source:"user"}),o},getSelectionStyle(){const e=t.state.selectedShapes.get().filter(rp);return 0===e.length?null:{name:op(e.map(t=>t.props.name)),fill:ip(e.map(t=>t.props.fill)),stroke:ip(e.map(t=>t.props.stroke)),strokeWidth:op(e.map(t=>t.props.strokeWidth))}},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(rp).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)},getToolDefaults:()=>t.shapes.getDefaultProps("frame"),setToolDefaults:e=>(t.shapes.updateDefaultProps("frame",e),t.shapes.getDefaultProps("frame")),getSelectedChildOrderState(){const e=t.layers.getSelectionSiblingOrderState();if(!e||!e.parentId.startsWith("shape:"))return null;const n=t.shapes.get(e.parentId);return n&&"frame"===n.type?{index:e.index,count:e.count,canMoveBackward:t.layers.canMoveSelectionWithinParent("backward"),canMoveForward:t.layers.canMoveSelectionWithinParent("forward")}:null},moveSelectedChild:e=>t.layers.move(t.selection.getIds(),e,"user")}}({editor:t})}function rp(t){return"frame"===t.type}function op(t){const e=t[0];return void 0!==e&&t.every(t=>t===e)?e:null}function ip(t){const e=t[0];return e&&t.every(t=>Wt(t,e))?e:null}var sp=class extends he{constructor(t){super(t,"frame"),this.initial="idle",this.addChild(new ap(t,this)),this.addChild(new lp(t,this))}getDefaultProps(){return this.editor.shapes.getDefaultProps("frame")}},ap=class extends he{constructor(t,e){super(t,"idle",e)}onEnter(){this.editor.interaction.clearSelection()}onPointerDown(t){this.transition("creating",{originPagePoint:t.pagePoint.clone(),originScreenPoint:t.screenPoint.clone(),currentPagePoint:t.pagePoint.clone(),shapeId:null,shiftKey:t.shiftKey})}},lp=class extends he{tool;info=null;operation=null;constructor(t,e){super(t,"creating",e),this.tool=e}onEnter(t){this.info=t,this.operation=this.editor.operations.begin({kind:"frame.create",label:"shape.create",source:"user",history:"record"})}onPointerMove(t){this.updateShape(t.pagePoint,t.screenPoint,t.shiftKey)}onPointerUp(t){this.info?(this.updateShape(t.pagePoint,t.screenPoint,t.shiftKey,!0),this.commitOperation(),this.editor.state.tool.get().isToolLocked?this.transition("idle"):this.editor.commands.setActiveTool("select",{source:"system"})):this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.cancelOperation(),this.info=null}commitOperation(){const t=this.operation;this.operation=null,t?.commit()}cancelOperation(){const t=this.operation;this.operation=null,t?.isActive&&t.cancel()}updateShape(t,e,n,r=!1){if(!this.info)return;this.info.currentPagePoint=t.clone(),this.info.shiftKey=n;const o=this.info.originScreenPoint.dist(e);if(!this.info.shapeId&&o<4){if(!r)return;const e=function(t,e){return new vt(t.x-e.w/2,t.y-e.h/2,e.w,e.h)}(t,this.tool.getDefaultProps()),n=this.createShape(e);return void(this.info.shapeId=n.id)}const i=function(t,e,n,r){let o=e.x-t.x,i=e.y-t.y;if(n){const t=r.w/r.h,e=Math.abs(o),n=Math.abs(i);0===n||e/Math.max(n,1)>=t?i=e/t*(i<0?-1:1):o=n*t*(o<0?-1:1)}const s=new bt(t.x+o,t.y+i);return new vt(Math.min(t.x,s.x),Math.min(t.y,s.y),Math.max(Math.abs(s.x-t.x),1),Math.max(Math.abs(s.y-t.y),1))}(this.info.originPagePoint,t,n,this.tool.getDefaultProps());if(!this.info.shapeId){const t=this.createShape(i);return void(this.info.shapeId=t.id)}this.editor.commands.updateShapes([{id:this.info.shapeId,x:i.x,y:i.y,props:{w:i.w,h:i.h}}],{source:"user"})}createShape(t){const[e]=this.editor.commands.createShapes([{type:"frame",x:t.x,y:t.y,props:{...this.tool.getDefaultProps(),w:t.w,h:t.h}}],{source:"user",autoReparent:!1});if(!e||"frame"!==e.type)throw new Error("Failed to create frame shape");return this.editor.commands.setSelectedShapeIds([e.id],{source:"system"}),e}};var cp=class{type="frame";toSvg(t,e){const{fill:n,stroke:r,strokeWidth:o,w:i,h:s,name:a}=t.props,l=e.resolveColor(r),c=o/2;return{tag:"g",children:[{tag:"rect",attrs:{x:c,y:c,width:Math.max(i-o,0),height:Math.max(s-o,0),fill:e.resolveColor(n),stroke:l,"stroke-width":o,"stroke-linejoin":"round","stroke-linecap":"round"}},{tag:"text",attrs:{x:0,y:-8,fill:l,"font-family":"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif","font-size":12,"font-weight":400},children:[Vu(a)]}]}}};function dp(){return{id:"land.frame",shapeUtils:[new tp],shapeSvgExporters:[new cp],setup(t){t.tools.register("frame",t=>new sp(t))}}}var up=["Inter","ui-sans-serif","system-ui","-apple-system","BlinkMacSystemFont","'Segoe UI'","sans-serif"].join(", "),pp=a({id:"land.frame.name.dom-events",selector:'[data-ui="frame-canvas-name"]'});function hp(){return{id:"land.frame.react",domEventGuards:[pp],shapeRenderers:[{type:"frame",component:fp,hoverComponent:mp}]}}function fp({editor:t,shape:e,shapeEditingSession:n}){const r=n?.shapeId===e.id;
27
+ return u("div",{style:{height:"100%",overflow:"visible",position:"relative",width:"100%"},children:[d(gp,{shape:e,hideName:!0}),d(yp,{editor:t,shape:e,isEditing:r})]})}function gp({shape:t,hideName:e=!1}){const{fill:n,h:r,name:o,stroke:i,strokeWidth:s,w:a}=t.props,l=s/2,c=Math.max(a-s,0),p=Math.max(r-s,0),h=Vu(o),f=Gu(t);
28
+ return u("svg",{width:"100%",height:"100%",viewBox:`${f.x} ${f.y} ${f.w} ${f.h}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[d("rect",{x:l,y:l,width:c,height:p,fill:Nt(n),stroke:Nt(i),strokeWidth:s,strokeLinejoin:"round",strokeLinecap:"round"}),e?null:d("text",{x:0,y:-8,fill:Nt(i),fontFamily:up,fontSize:12,fontWeight:400,style:{userSelect:"none"},children:h})]})}function mp({shape:t,strokeWidth:e}){const{h:n,w:r}=t.props,i=Gu(t);
29
+ return d("svg",{"data-ui":"frame-hover-outline",width:"100%",height:"100%",viewBox:`${i.x} ${i.y} ${i.w} ${i.h}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:d("rect",{x:0,y:0,width:r,height:n,fill:"none",stroke:o,strokeWidth:e,strokeLinejoin:"round",strokeLinecap:"round",vectorEffect:"non-scaling-stroke"})})}function yp({editor:t,shape:e,isEditing:n}){
30
+ return d(s,{editor:t,shape:e,isEditing:n,value:e.props.name,fallback:Vu(""),bodyWidth:e.props.w,bodyHeight:e.props.h,renderHeight:34,operationKind:"frame.edit",editAriaLabel:"Edit frame name",inputAriaLabel:"Frame name",dataUi:{heading:"frame-canvas-heading",dragHandle:"frame-drag-handle",name:"frame-canvas-name",input:"frame-canvas-name-input"},onValueChange:n=>{t.commands.updateShapes([{id:e.id,props:{name:n}}],{source:"user"})}})}var xp={id:"frame",editor:dp(),render:hp(),api:ep,setup:({editor:t})=>({api:np({editor:t})})},wp=1e-4,bp=1e-4,vp="image.crop",kp=[{label:"1:1",value:"1:1",ratio:1},{label:"4:3",value:"4:3",ratio:4/3},{label:"16:9",value:"16:9",ratio:16/9}],Pp={top_left:"nwse-resize",top:"ns-resize",top_right:"nesw-resize",right:"ew-resize",bottom_right:"nwse-resize",bottom:"ns-resize",bottom_left:"nesw-resize",left:"ew-resize"},Sp=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"];function Ip(t){return Math.min(1,Math.max(0,t))}function Mp(t,e,n){return Math.min(n,Math.max(e,t))}function Tp(t){return!!t&&"object"==typeof t&&"number"==typeof t.x&&Number.isFinite(t.x)&&"number"==typeof t.y&&Number.isFinite(t.y)}function Cp(t,e){const n=Ip(t),r=Ip(e);let o=Math.min(n,r),i=Math.max(n,r);if(i-o<wp){const t=(o+i)/2;o=Math.max(0,Math.min(.9999,t-5e-5)),i=o+wp}return{min:o,max:i}}function Ap(t){if(!t||"object"!=typeof t)return null;const e=t;if(!Tp(e.topLeft)||!Tp(e.bottomRight))return null;const n=Cp(e.topLeft.x,e.bottomRight.x),r=Cp(e.topLeft.y,e.bottomRight.y);return{topLeft:{x:n.min,y:r.min},bottomRight:{x:n.max,y:r.max}}}function Ep(t){const e=Ap(t);if(!e)return null;const n=e.topLeft.x,r=e.topLeft.y,o=e.bottomRight.x,i=e.bottomRight.y;return{left:n,top:r,right:o,bottom:i,width:o-n,height:i-r}}function Lp(t){return Ep(t)??{left:0,top:0,right:1,bottom:1,width:1,height:1}}function Bp(t,e){return Math.abs(t.left-e.left)<=bp&&Math.abs(t.top-e.top)<=bp&&Math.abs(t.right-e.right)<=bp&&Math.abs(t.bottom-e.bottom)<=bp}function Rp(t){return function(t){return Math.abs(t.left)<=bp&&Math.abs(t.top)<=bp&&Math.abs(1-t.right)<=bp&&Math.abs(1-t.bottom)<=bp}(t)?null:Ap({topLeft:{x:t.left,y:t.top},bottomRight:{x:t.right,y:t.bottom}})}function $p({centerX:t,centerY:e,height:n,width:r}){const o=Mp(r,wp,1),i=Mp(n,wp,1),s=Mp(t-o/2,0,1-o),a=Mp(e-i/2,0,1-i);return{left:s,top:a,right:s+o,bottom:a+i,width:o,height:i}}function Np(t){return{x:t.left+t.width/2,y:t.top+t.height/2}}function zp({crop:t,shape:e}){const n=Lp(t);return{w:e.props.w/n.width,h:e.props.h/n.height}}function Op(t){const e=t.props.w/t.props.h;for(const n of kp)if(Math.abs(e-n.ratio)<=.01)return n.value;return null}function Wp(t,e){return e===Hp(t.id)}function Hp(t){return`image.crop:edit:${t}`}function Dp({localToPage:t,shape:e}){const n=e.props.w,r=e.props.h,o=(0+n)/2,i=(0+r)/2,s={top_left:new bt(0,0),top:new bt(o,0),top_right:new bt(n,0),right:new bt(n,i),bottom_right:new bt(n,r),bottom:new bt(o,r),bottom_left:new bt(0,r),left:new bt(0,i)};return Sp.map(e=>{return{kind:"custom",type:vp,id:e,point:t.applyToPoint(s[e]),cursor:(n=e,Pp[n])};var n})}function Fp({change:t,crop:e,shape:n}){const r=zp({crop:e,shape:n}),o=e.bottomRight.x-e.topLeft.x,i=e.bottomRight.y-e.topLeft.y,s=Mp(e.topLeft.x-t.x/r.w,0,1-o),a=Mp(e.topLeft.y-t.y/r.h,0,1-i),l=Ap({topLeft:{x:s,y:a},bottomRight:{x:s+o,y:a+i}});return l?{id:n.id,props:{crop:l}}:null}function jp({preset:t,shape:e}){const n=Np(Lp(e.props.crop)),r=zp({crop:e.props.crop,shape:e}),o=kp.find(e=>e.value===t)?.ratio??null;if(!o)return null;const i=o*(r.h/r.w);let s=1,a=s/i;return a>1&&(a=1,s=a*i),function({nextRect:t,shape:e}){const n=Lp(e.props.crop);if(Bp(n,t))return null;const r=zp({crop:e.props.crop,shape:e}),o=new bt((t.left-n.left)*r.w,(t.top-n.top)*r.h).rot(e.rotation);return{id:e.id,x:e.x+o.x,y:e.y+o.y,props:{w:t.width*r.w,h:t.height*r.h,crop:Rp(t)}}}({nextRect:$p({centerX:n.x,centerY:n.y,width:s,height:a}),shape:e})}function Up(t){return Number.isFinite(t)?Number(t.toFixed(4)).toString():"0"}var Xp=new WeakMap;function Yp(t,e){return Xp.get(t)?.get(e)??null}function Kp(t,e){const n=Xp.get(t);n&&(n.delete(e),0===n.size&&Xp.delete(t))}function _p(t){return xt(t)&&"image"===t.type}function qp(t){return yt(t)&&"image"===t.type}var Vp={propagation:"stop"};function Gp({handleId:t,shapeId:e,startPagePoint:n,startPageToLocal:r,startShape:o,startCrop:i}){return{shapeId:e,operationKind:"image.crop.handle",update({editor:s,pagePoint:a,source:l}){if(!qp(s.shapes.get(e)))return"stop";const c=function({handleId:t,pageToLocal:e,shape:n,startCrop:r,startPagePoint:o,currentPagePoint:i}){const s=Ap(r)??{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},a=zp({crop:s,shape:n});if(a.w<8||a.h<8)return null;const l=e.applyToPoint(o),c=e.applyToPoint(i).sub(l);if(0===c.x&&0===c.y)return null;const d={x:s.topLeft.x*a.w,y:s.topLeft.y*a.h,w:(s.bottomRight.x-s.topLeft.x)*a.w,h:(s.bottomRight.y-s.topLeft.y)*a.h},u=d.x+d.w,p=d.y+d.h;let h=d.x,f=d.y,g=d.w,m=d.h;!function(t){return"top_left"===t||"left"===t||"bottom_left"===t}(t)?function(t){return"top_right"===t||"right"===t||"bottom_right"===t}(t)&&(g=Mp(u+c.x,d.x+8,a.w)-h):(h=Mp(h+c.x,0,u-8),g=u-h),function(t){return"top_left"===t||"top"===t||"top_right"===t}(t)?(f=Mp(f+c.y,0,p-8),m=p-f):function(t){return"bottom_left"===t||"bottom"===t||"bottom_right"===t}(t)&&(m=Mp(p+c.y,d.y+8,a.h)-f);const y=Ap({topLeft:{x:h/a.w,y:f/a.h},bottomRight:{x:(h+g)/a.w,y:(f+m)/a.h}});if(!y)return null;const x=new bt(h-s.topLeft.x*a.w,f-s.topLeft.y*a.h).rot(n.rotation);return{id:n.id,x:n.x+x.x,y:n.y+x.y,props:{w:g,h:m,crop:y}}}({handleId:t,currentPagePoint:a,pageToLocal:r,shape:o,startCrop:i,startPagePoint:n});return c?(s.commands.updateShapes([c],{source:l}),"continue"):"continue"}}}function Jp(){return{createSession(t,{handle:e,shape:n,originPagePoint:r}){return qp(n)&&"custom"===e.kind&&"image.crop"===e.type&&(o=e.id,Sp.some(t=>t===o))?Gp({handleId:e.id,shapeId:n.id,startPagePoint:r,startPageToLocal:t.shapes.computeLocalToPageTransform(n).invert(),startShape:n,startCrop:n.props.crop}):null;var o}}}function Zp(){let t=null;const e=()=>{t?.operation?.isActive&&t.operation.cancel(),t=null};return{id:"land.image.crop.interactions",editorEvent:{handleEvent(n,r){if("cancel"!==r.type){if("keyboard"===r.type)return function(t,e){if("key_down"!==e.name)return;const n=Qp(t);if(!n)return;if("Escape"===e.key&&!e.altKey&&!e.accelKey)return t.editing.cancel("user")&&Kp(t,n.id),Vp;if("Enter"===e.key&&!e.altKey&&!e.accelKey)return t.editing.complete("user")&&Kp(t,n.id),Vp;const r=function(t){if(t.altKey||t.accelKey)return null;const e=t.shiftKey?10:1;switch(t.key){case"ArrowLeft":return new bt(e,0);case"ArrowRight":return new bt(-e,0);case"ArrowUp":return new bt(0,e);case"ArrowDown":return new bt(0,-e);default:return null}}(e);if(r){const e=function({pageDelta:t,shape:e,startCrop:n}){const r=Ap(n);return!r||t.equals(bt.Zero())?null:Fp({change:t.rot(-e.rotation),crop:r,shape:e})}({pageDelta:r,shape:n,startCrop:n.props.crop});return e&&t.commands.updateShapes([e],{source:"user"}),Vp}}(n,r);if("pointer"===r.type)if("pointer_cancel"!==r.name){if("pointer_down"===r.name){if(e(),0!==r.button||"select"!==n.state.tool.get().activeToolId||!n.tools.isInInitialState())return;if(n.selection.hitTestHandle(r.pagePoint))return;const o=Qp(n);if(!o)return;return function(t,e,n){const r=t.shapes.computeLocalToPageTransform(e).invert().applyToPoint(n.pagePoint);return r.x>=0&&r.y>=0&&r.x<=e.props.w&&r.y<=e.props.h}(n,o,r)?(t={pointerId:r.pointerId,shapeId:o.id,startCrop:o.props.crop,startPagePoint:r.pagePoint.clone(),startScreenPoint:r.screenPoint.clone(),startPageToLocal:n.shapes.computeLocalToPageTransform(o).invert(),startShape:o,hasDragged:!1,operation:null},Vp):n.editing.complete("user")?(Kp(n,o.id),n.handleEvent(r),Vp):void 0}if(t&&r.pointerId===t.pointerId)return"pointer_move"===r.name?(th(n,r,t),Vp):"pointer_up"===r.name?(th(n,r,t),t.operation?.isActive&&t.operation.commit(),e(),Vp):void 0}else e()}else e()}},selectionHandle:Jp()}}function Qp(t){const[e]=t.state.selectedShapes.get();if(!qp(e))return null;const n=t.state.shapeEditingSession.get();return n&&n.shapeId===e.id&&Wp(e,n.operationKind)?e:null}function th(t,e,n){if(!n.hasDragged){if(n.startScreenPoint.dist2(e.screenPoint)<9)return;n.operation=t.operations.begin({kind:"image.crop.translate",label:"shape.edit",source:"user",history:"record"}),n.hasDragged=!0}if(!qp(t.shapes.get(n.shapeId)))return;const r=function({currentPagePoint:t,pageToLocal:e,shape:n,startCrop:r,startPagePoint:o,shiftKey:i}){const s=Ap(r);if(!s)return null;const a=e.applyToPoint(o);let l=e.applyToPoint(t).sub(a);return i&&(l=Math.abs(l.x)<Math.abs(l.y)?new bt(0,l.y):new bt(l.x,0)),0===l.x&&0===l.y?null:Fp({change:l,crop:s,shape:n})}({currentPagePoint:e.pagePoint,pageToLocal:n.startPageToLocal,shape:n.startShape,shiftKey:e.shiftKey,startCrop:n.startCrop,startPagePoint:n.startPagePoint});r&&t.commands.updateShapes([r],{source:"user"})}function eh(t,e=0){return Math.max(0,"number"==typeof t&&Number.isFinite(t)?t:e)}function nh({cornerRadius:t,h:e,w:n}){return Math.min(eh(t),Math.max(0,n)/2,Math.max(0,e)/2)}var rh=24,oh="#ffff00",ih=1,sh=128,ah=24,lh=oh,ch=.45,dh=class{editor;confirmHandler=null;deactivateHistoryScope=null;session=null;snapshot=null;subscribers=new Set;constructor(t){this.editor=t,me("image.smudgeSession.lifecycle",t.state.shapeEditingSession,()=>{this.clearIfEditingSessionInvalid()},{fireImmediately:!1})}start(t,e){if(t.isLocked)return!1;const n=fh(t.id),r=this.editor.state.shapeEditingSession.get();if(r&&(r.shapeId!==t.id||r.operationKind!==n))return!1;if(this.session&&r?.shapeId===t.id&&gh(t,r.operationKind))return this.updateSession({...this.session,brush:mh({...this.session.brush,...e})}),!0;this.clear();const o=this.editor.editing.start({shapeId:t.id,operationKind:n,entryMode:"focusEnd"},"user");return!(!o||o.shapeId!==t.id||o.operationKind!==n)&&(this.setSession({shapeId:t.id,brush:mh(e),strokes:[],activeStroke:null,redoStrokes:[],nextStrokeIndex:1}),this.activateHistoryScope(),!0)}cancel(){const t=this.session?.shapeId??null;this.clear();const e=this.editor.state.shapeEditingSession.get();t&&e?.shapeId===t&&e.operationKind===fh(t)&&this.editor.editing.cancel("user")}complete(){const t=this.session?.shapeId??null;this.clear();const e=this.editor.state.shapeEditingSession.get();t&&e?.shapeId===t&&e.operationKind===fh(t)&&this.editor.editing.complete("user")}cancelIfActive(){return!!this.getActiveSession()&&(this.cancel(),!0)}clearForShape(t){this.session?.shapeId===t&&this.clear()}updateBrush(t){if(!this.getActiveSession()||!this.session)return!1;const e=mh({...this.session.brush,...t});return e.size===this.session.brush.size&&e.color===this.session.brush.color&&e.opacity===this.session.brush.opacity||this.updateSession({...this.session,brush:e}),!0}getSnapshot(t){const e=this.getActiveSession();return e&&e.shapeId===t?this.snapshot:null}getActiveSession(){if(!this.session)return null;const t=this.editor.shapes.get(this.session.shapeId),e=this.editor.state.shapeEditingSession.get();return t&&e&&e.shapeId===this.session.shapeId&&e.operationKind===fh(this.session.shapeId)?this.snapshot:(this.clear(),null)}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}beginStroke(t){if(!this.session)return;const e=uh(this.session),n={id:`${e.shapeId}:smudge:${e.nextStrokeIndex}`,points:[Ch(t)],brush:{...e.brush}};this.updateSession({...e,activeStroke:n,nextStrokeIndex:e.nextStrokeIndex+1})}appendPoint(t){if(!this.session?.activeStroke)return;const e=this.session.activeStroke.points[this.session.activeStroke.points.length-1];e&&Math.hypot(e.x-t.x,e.y-t.y)<.5||this.updateSession({...this.session,activeStroke:{...this.session.activeStroke,points:[...this.session.activeStroke.points,Ch(t)]}})}endStroke(){this.session?.activeStroke&&this.updateSession(uh(this.session))}cancelStroke(){this.session?.activeStroke&&this.updateSession({...this.session,activeStroke:null})}undo(){if(!this.getActiveSession()||!this.session)return!1;if(this.session.activeStroke&&this.updateSession(uh(this.session)),!this.session||0===this.session.strokes.length)return!1;const t=this.session.strokes[this.session.strokes.length-1];return!!t&&(this.updateSession({...this.session,strokes:this.session.strokes.slice(0,-1),redoStrokes:[...this.session.redoStrokes,t]}),!0)}redo(){if(!this.getActiveSession()||!this.session)return!1;if(this.session.activeStroke||0===this.session.redoStrokes.length)return!1;const t=this.session.redoStrokes[this.session.redoStrokes.length-1];return!!t&&(this.updateSession({...this.session,strokes:[...this.session.strokes,t],redoStrokes:this.session.redoStrokes.slice(0,-1)}),!0)}registerConfirmHandler(t){return this.confirmHandler=t,()=>{this.confirmHandler===t&&(this.confirmHandler=null)}}requestConfirm(t){return this.confirmHandler?this.confirmHandler(t):Promise.resolve(null)}clear(){this.session&&(this.session=null,this.snapshot=null,this.deactivateHistoryScope?.(),this.deactivateHistoryScope=null,this.notify())}clearIfEditingSessionInvalid(){if(!this.session)return;const t=this.editor.state.shapeEditingSession.get();t?.shapeId===this.session.shapeId&&t.operationKind===fh(this.session.shapeId)||this.clear()}activateHistoryScope(){const t={getState:()=>this.getHistoryScopeState(),subscribe:t=>this.subscribe(t),undo:()=>this.undo(),redo:()=>this.redo()};this.deactivateHistoryScope=this.editor.history.activateScope(t)}getHistoryScopeState(){const t=this.session?.activeStroke?1:0,e=this.session?.activeStroke?0:this.session?.redoStrokes.length??0;return{canUndo:(this.session?.strokes.length??0)+t>0,canRedo:e>0}}setSession(t){this.session=t,this.snapshot=function(t){return{shapeId:t.shapeId,brush:t.brush,strokes:t.activeStroke?[...t.strokes,t.activeStroke]:t.strokes,canUndo:t.strokes.length>0||!!t.activeStroke,canRedo:!t.activeStroke&&t.redoStrokes.length>0}}(t),this.notify()}updateSession(t){this.setSession(t)}notify(){for(const t of this.subscribers)t()}};function uh(t){return t.activeStroke?{...t,strokes:[...t.strokes,t.activeStroke],activeStroke:null,redoStrokes:[]}:t}var ph=new WeakMap;function hh(t){const e=ph.get(t);if(e)return e;const n=new dh(t);return ph.set(t,n),n}function fh(t){return`image.smudge:edit:${t}`}function gh(t,e){return e===fh(t.id)}function mh(t){const e="number"==typeof t?.size&&Number.isFinite(t.size)?t.size:ah,n="number"==typeof t?.opacity&&Number.isFinite(t.opacity)?t.opacity:ch??.45;return{size:Math.min(128,Math.max(1,e)),color:"string"==typeof t?.color&&t.color.trim().length>0?t.color:lh,opacity:Math.min(1,Math.max(0,n))}}function yh({brush:t,editor:e,shape:n}){return hh(e).start(n,t)}function xh(t){hh(t).cancel()}function wh(t){hh(t).complete()}function bh(t){return hh(t).cancelIfActive()}function vh(t,e){return hh(t).updateBrush(e)}function kh(t){return hh(t).getActiveSession()}function Ph(t){return hh(t).undo()}function Sh(t){return hh(t).redo()}function Ih(t,e){return hh(t).registerConfirmHandler(e)}async function Mh(t,e){return hh(t).requestConfirm(e)}function Th(t){return t.map(t=>({id:t.id,brush:{...t.brush},points:t.points.map(Ch)}))}function Ch(t){return{x:t.x,y:t.y,...void 0===t.pressure?{}:{pressure:t.pressure}}}function Ah(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}var Eh=class extends pe{type="image";getDefaultProps(){return{w:240,h:180,assetId:null,crop:null,cornerRadius:0,altText:""}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Math.max(24,Ah(e.w,n.w)),h:Math.max(24,Ah(e.h,n.h)),assetId:(r=e.assetId,"string"==typeof r&&r.startsWith("asset:")?e.assetId:null),crop:Ap(e.crop),cornerRadius:eh(e.cornerRadius,n.cornerRadius),altText:"string"==typeof e.altText?e.altText:n.altText};var r}getLocalBounds(t){return new vt(0,0,t.props.w,t.props.h)}canReceiveTerminalBinding(t){return!0}getAllowedSelectionResizeModes(t,e){return Gt}canEdit(t){return!0}onEditEnd(t,e){var n,r;n=e.editor,r=t.id,hh(n).clearForShape(r)}getSelectionHandleAnchors(t,e){const n={terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};if(!e.isOnlySelected)return n;const r=e.editor.state.shapeEditingSession.get();return r&&r.shapeId===t.id&&Wp(t,r.operationKind)?{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:Dp({crop:t.props.crop,localToPage:e.editor.shapes.computeLocalToPageTransform(t),shape:t})}:n}},Lh=class{type="image";toSvg(t,e){const{assetId:n,altText:r,crop:o,h:i,w:s}=t.props;if(!n)return null;const a=e.resolveAssetUrl(n);if(!a)return null;const l=Ep(o),c=l?{tag:"svg",attrs:{x:0,y:0,width:s,height:i,viewBox:(d=l,[Up(d.left),Up(d.top),Up(d.width),Up(d.height)].join(" ")),preserveAspectRatio:"none",overflow:"hidden"},children:[{tag:"image",attrs:{href:a,x:0,y:0,width:1,height:1,preserveAspectRatio:"none","aria-label":r||void 0}}]}:{tag:"image",attrs:{href:a,width:s,height:i,preserveAspectRatio:"none","aria-label":r||void 0}};var d;const u=nh({cornerRadius:t.props.cornerRadius,h:i,w:s});return u<=0?c:{tag:"g",attrs:{"clip-path":`url(#${e.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"rect",attrs:{x:0,y:0,width:s,height:i,rx:u,ry:u}}]})})`},children:[c]}}},Bh={propagation:"stop"};function Rh(){let t=null;const e=e=>{t=null,function(t){hh(t).endStroke()}(e)},n=e=>{t=null,function(t){hh(t).cancelStroke()}(e)};return{id:"land.image.smudge.interactions",editorEvent:{handleEvent(r,o){if("keyboard"===o.type)return(Nh(o)||$h(o))&&zh(r)&&e(r),function(t,e){if("key_down"!==e.name)return;if(!zh(t))return;if("Escape"===e.key&&!e.altKey&&!e.accelKey)return xh(t),Bh;if($h(e))return Mh(t,{replace:!0}),Bh;if(Nh(e))return e.shiftKey?t.history.redo():t.history.undo(),Bh;return Bh}(r,o);if("cancel"===o.type)return zh(r)?(n(r),"command"!==o.reason&&xh(r),Bh):void 0;if("pointer"!==o.type)return;const i=zh(r);if(i){if("pointer_down"===o.name){if(e(r),0!==o.button)return 1===o.button?void 0:Bh;const n=Wh(r,i,o.pagePoint),s=Hh(n,i);return t={mode:s?"draw":"pan",originCamera:s?null:r.state.camera.get(),originScreenPoint:s?null:o.screenPoint.clone(),pointerId:o.pointerId,acceptsDrawPoints:s},s&&function(t,e){hh(t).beginStroke(e)}(r,{x:n.x,y:n.y,pressure:o.pressure}),Bh}return t&&t.pointerId===o.pointerId?"pointer_move"===o.name?("draw"===t.mode&&1&o.buttons?t.acceptsDrawPoints&&(t.acceptsDrawPoints=Oh(r,i,o)):"pan"===t.mode&&t.originCamera&&t.originScreenPoint&&1&o.buttons?Dh(r,o,t):e(r),Bh):"pointer_up"===o.name?("draw"===t.mode&&t.acceptsDrawPoints?Oh(r,i,o):"pan"===t.mode&&Dh(r,o,t),e(r),Bh):"pointer_cancel"===o.name?(n(r),Bh):Bh:Bh}n(r)}}}}function $h(t){return"key_down"===t.name&&"Enter"===t.key&&!t.altKey&&!t.accelKey}function Nh(t){return"key_down"===t.name&&"z"===t.key.toLowerCase()&&t.accelKey&&!t.altKey}function zh(t){const[e]=t.state.selectedShapes.get();if(!qp(e))return null;const n=t.state.shapeEditingSession.get();return n&&n.shapeId===e.id&&gh(e,n.operationKind)?e:null}function Oh(t,e,n){const r=Wh(t,e,n.pagePoint);return!!Hh(r,e)&&(function(t,e){hh(t).appendPoint(e)}(t,{x:r.x,y:r.y,pressure:n.pressure}),!0)}function Wh(t,e,n){return t.shapes.computeLocalToPageTransform(e).invert().applyToPoint(n)}function Hh(t,e){return t.x>=0&&t.y>=0&&t.x<=e.props.w&&t.y<=e.props.h}function Dh(t,e,n){if(!n.originCamera||!n.originScreenPoint)return;const r=e.screenPoint.sub(n.originScreenPoint),o=n.originCamera.z;t.viewport.setCamera({x:n.originCamera.x-r.x/o,y:n.originCamera.y-r.y/o},{source:"user"})}function Fh(){return{id:"land.image",shapeUtils:[new Eh],shapeSvgExporters:[new Lh],interactionHandlers:[Zp(),Rh()],setup:t=>function(t){let e=null;return me("image.cropSession.lifecycle",t.state.shapeEditingSession,()=>{const n=t.state.shapeEditingSession.get(),r=n?.shapeId,o=r&&n?.operationKind===Hp(r)?r:null;e&&e!==o&&Kp(t,e),e=o})}(t)}}var jh={id:"land.image.crop.dom-events",handle:()=>"continue",getCursor({clientPoint:t,editor:e,element:n,container:r}){const o=function(t){const[e]=t.state.selectedShapes.get();if(!qp(e))return null;const n=t.state.shapeEditingSession.get();return n&&n.shapeId===e.id&&Wp(e,n.operationKind)?e:null}(e);if(!o)return;if(n?.closest('[data-selection-custom-handle-type="image.crop"]'))return;if(!t)return;const i=r.getBoundingClientRect(),s=new bt(t.x-i.left,t.y-i.top);return Zh(e,o,e.viewport.screenToPage(s))?0!==e.inputs.state.get().buttons?"grabbing":"grab":void 0}},Uh={id:"land.image.smudge.dom-events",handle:()=>"continue",getCursor({clientPoint:t,container:e,editor:n}){const r=function(t){const[e]=t.state.selectedShapes.get();if(!qp(e))return null;const n=t.state.shapeEditingSession.get();return n&&n.shapeId===e.id&&gh(e,n.operationKind)?e:null}(n);if(!r||!t)return;const o=e.getBoundingClientRect(),i=new bt(t.x-o.left,t.y-o.top);return Zh(n,r,n.viewport.screenToPage(i))?"crosshair":0!==n.inputs.state.get().buttons?"grabbing":"grab"}};function Xh(){return{id:"land.image.react",domEventGuards:[jh,Uh],selectionCustomHandleRenderers:[{type:vp,component:Vh}],shapeRenderers:[{type:"image",component:Yh,hoverComponent:qh}]}}function Yh({editor:t,shape:e,shapeEditingSession:n}){const{altText:r,assetId:o,crop:i,h:s,w:a}=e.props,l=o?t.assets.resolveUrl(o):null,c=nh({cornerRadius:e.props.cornerRadius,h:s,w:a}),p=function(t,e){return P(e=>function(t,e){return hh(t).subscribe(e)}(t,e),()=>function(t,e){return hh(t).getSnapshot(e)}(t,e),()=>null)}(t,e.id);if(!l)return d("div",{"aria-label":"Empty image","data-ui":"image-shape-missing-asset",role:"img",style:{alignItems:"center",background:"#f8fafc",border:"1px solid #cbd5e1",borderRadius:c,boxSizing:"border-box",color:"#cbd5e1",display:"flex",height:s,justifyContent:"center",overflow:"hidden",width:a},children:u("svg",{"aria-hidden":"true",className:"lucide lucide-sparkles-icon lucide-sparkles",fill:"none",height:"40",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",width:"40",xmlns:"http://www.w3.org/2000/svg",children:[
31
+ d("path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}),
32
+ d("path",{d:"M20 2v4"}),
33
+ d("path",{d:"M22 4h-4"}),
34
+ d("circle",{cx:"4",cy:"20",r:"2"})]})});const h=function({crop:t,shapeHeight:e,shapeWidth:n}){const r=Ep(t);if(!r)return null;const o=n/r.width,i=e/r.height;return{imageX:-r.left*o,imageY:-r.top*i,imageWidth:o,imageHeight:i,rect:r}}({crop:i,shapeHeight:s,shapeWidth:a});if(h){const t=n?.shapeId===e.id&&Wp(e,n.operationKind),o={display:"block",height:h.imageHeight,left:h.imageX,maxWidth:"none",objectFit:"fill",pointerEvents:"none",position:"absolute",top:h.imageY,userSelect:"none",width:h.imageWidth};
35
+ return u("div",{"data-ui":"image-shape",style:{display:"block",height:s,overflow:t?"visible":"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:a},children:[t?d("img",{alt:"","aria-hidden":"true","data-ui":"image-crop-preview",draggable:!1,src:l,style:{...o,opacity:.1}}):null,u("div",{"data-ui":"image-crop-window",style:{height:s,overflow:"hidden",position:"absolute",borderRadius:c,inset:0,width:a},children:[d("img",{alt:r,draggable:!1,src:l,style:o}),d(Kh,{shape:e,session:p})]})]})}
36
+ return u("div",{"data-ui":"image-shape",style:{borderRadius:c,display:"block",height:s,overflow:"hidden",pointerEvents:"none",position:"relative",userSelect:"none",width:a},children:[d("img",{alt:r,draggable:!1,src:l,style:{display:"block",height:s,objectFit:"fill",width:a}}),d(Kh,{shape:e,session:p})]})}function Kh({shape:t,session:e}){return e&&e.shapeId===t.id&&0!==e.strokes.length?d("svg",{"aria-hidden":"true","data-ui":"image-smudge-preview",viewBox:`0 0 ${t.props.w} ${t.props.h}`,style:{display:"block",height:t.props.h,inset:0,overflow:"hidden",pointerEvents:"none",position:"absolute",width:t.props.w},children:e.strokes.map(t=>d(_h,{stroke:t},t.id))}):null}function _h({stroke:t}){const e=t.points[0];if(!e)return null;const n=t.brush.color??"#ffff00",r=t.brush.opacity??.45,o=t.brush.size;if(1===t.points.length)return d("circle",{cx:e.x,cy:e.y,r:o/2,fill:n,opacity:r});const i=function(t){const[e,...n]=t.points;return e?[`M ${Jh(e.x)} ${Jh(e.y)}`,...n.map(t=>`L ${Jh(t.x)} ${Jh(t.y)}`)].join(" "):null}(t);return i?d("path",{d:i,fill:"none",opacity:r,stroke:n,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:o}):null}function qh({shape:t,strokeWidth:e}){
37
+ return d("div",{"data-ui":"image-hover-outline",style:{borderRadius:nh({cornerRadius:t.props.cornerRadius,h:t.props.h,w:t.props.w}),boxShadow:`inset 0 0 0 ${e}px ${o}`,inset:0,position:"absolute"}})}function Vh({handle:t,strokeWidth:e}){const{x:n,y:r,w:o,h:i,center:s}=t.bounds,a=1.35*Math.max(o,i),l=Math.max(2.5*e,2),c=l/2,p={fill:"none",stroke:"rgba(37, 99, 235, 0.96)",strokeLinecap:"butt",strokeLinejoin:"miter",strokeWidth:l,pointerEvents:"none"},h=function({id:t,extension:e,outwardOffset:n,centerX:r,centerY:o}){switch(t){case"top_left":return{kind:"corner",points:[Gh(r-n,o+e),Gh(r-n,o-n),Gh(r+e,o-n)].join(" ")};case"top":return{kind:"edge",x1:r-e,y1:o-n,x2:r+e,y2:o-n};case"top_right":return{kind:"corner",points:[Gh(r-e,o-n),Gh(r+n,o-n),Gh(r+n,o+e)].join(" ")};case"right":return{kind:"edge",x1:r+n,y1:o-e,x2:r+n,y2:o+e};case"bottom_right":return{kind:"corner",points:[Gh(r+n,o-e),Gh(r+n,o+n),Gh(r-e,o+n)].join(" ")};case"bottom":return{kind:"edge",x1:r-e,y1:o+n,x2:r+e,y2:o+n};case"bottom_left":return{kind:"corner",points:[Gh(r+e,o+n),Gh(r-n,o+n),Gh(r-n,o-e)].join(" ")};case"left":return{kind:"edge",x1:r-n,y1:o-e,x2:r-n,y2:o+e};default:return{kind:"edge",x1:r,y1:o,x2:r,y2:o}}}({id:t.id,extension:a,outwardOffset:c,centerX:s.x,centerY:s.y});
38
+ return u("g",{children:[d("rect",{"data-selection-custom-handle":t.id,"data-selection-custom-handle-type":t.type,"data-selection-custom-handle-id":t.id,x:n-.8*o,y:r-.8*i,width:2.6*o,height:2.6*i,fill:"transparent",style:{cursor:t.cursor??"grab",pointerEvents:"auto"}}),"corner"===h.kind?d("polyline",{points:h.points,...p}):d("line",{x1:h.x1,y1:h.y1,x2:h.x2,y2:h.y2,...p})]})}function Gh(t,e){return`${t},${e}`}function Jh(t){return Number.isFinite(t)?Number(t.toFixed(2)).toString():"0"}function Zh(t,e,n){const r=t.shapes.computeLocalToPageTransform(e).invert().applyToPoint(n);return r.x>=0&&r.y>=0&&r.x<=e.props.w&&r.y<=e.props.h}var Qh=bn("plugin-image.api");function tf({editor:t}){return function({editor:t}){return{getSelectionState(){const e=rf(t);if(!e)return null;const n=t.state.shapeEditingSession.get();return{shapeId:e.id,cornerRadius:eh(e.props.cornerRadius),crop:e.props.crop,cropPreset:Op(e),isCropping:n?.shapeId===e.id&&Wp(e,n.operationKind),smudge:kh(t)}},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(qp).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...void 0===e.cornerRadius?{}:{cornerRadius:eh(e.cornerRadius)}}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)},startCrop(e){const n=nf(t,e);return!(!n||n.isLocked)&&(!!t.editing.start({shapeId:n.id,operationKind:Hp(n.id),entryMode:"focusEnd"},"user")&&(function(t,e){const n=Xp.get(t)??new Map;Xp.set(t,n),n.set(e.id,{...e,props:{...e.props,crop:e.props.crop?{topLeft:{...e.props.crop.topLeft},bottomRight:{...e.props.crop.bottomRight}}:null},meta:{...e.meta}})}(t,n),!0))},finishCrop(){const e=rf(t);if(!e||!of(t,e))return!1;const n=t.editing.complete("user");return n&&Kp(t,e.id),n},cancelCrop(){const e=rf(t);if(!e||!of(t,e))return!1;const n=t.editing.cancel("user");return n&&Kp(t,e.id),n},zoomCrop:e=>ef(t,t=>function({direction:t,shape:e}){const n=Lp(e.props.crop),r=Np(n),o=Mp("in"===t?.8:1.25,Math.max(wp/n.width,wp/n.height),Math.min(1/n.width,1/n.height)),i=$p({centerX:r.x,centerY:r.y,width:n.width*o,height:n.height*o});return Bp(n,i)?null:{id:e.id,props:{crop:Rp(i)}}}({direction:e,shape:t})),setCropAspectRatio:e=>ef(t,t=>jp({preset:e,shape:t})),resetCrop:()=>ef(t,e=>function({baselineShape:t,shape:e}){const n=t.x,r=t.y,o=t.props.w,i=t.props.h,s=Ap(t.props.crop);return Math.abs(e.x-n)<=bp&&Math.abs(e.y-r)<=bp&&Math.abs(e.props.w-o)<=bp&&Math.abs(e.props.h-i)<=bp&&(null===e.props.crop&&null===s||null!==e.props.crop&&null!==s&&Math.abs(e.props.crop.topLeft.x-s.topLeft.x)<=bp&&Math.abs(e.props.crop.topLeft.y-s.topLeft.y)<=bp&&Math.abs(e.props.crop.bottomRight.x-s.bottomRight.x)<=bp&&Math.abs(e.props.crop.bottomRight.y-s.bottomRight.y)<=bp)?null:{id:e.id,x:n,y:r,props:{w:o,h:i,crop:s}}}({baselineShape:Yp(t,e.id)??e,shape:e})),smudge:{start(e){const n=nf(t,e?.shapeId);return!!n&&!!n.props.assetId&&!n.isLocked&&yh({brush:e?.brush,editor:t,shape:n})},setBrush:e=>vh(t,e),cancel(){xh(t)},undo:()=>Ph(t),redo:()=>Sh(t),getSnapshot:()=>kh(t)}}}({editor:t})}function ef(t,e){const n=rf(t);if(!n||n.isLocked||!of(t,n))return!1;const r=e(n);return!!r&&(t.commands.updateShapes([r],{source:"user"}),!0)}function nf(t,e){const n=e?t.shapes.get(e):t.state.selectedShapes.get()[0];return qp(n)?n:null}function rf(t){return 1===t.selection.getIds().length?nf(t):null}function of(t,e){const n=t.state.shapeEditingSession.get();return n?.shapeId===e.id&&Wp(e,n.operationKind)}var sf={id:"image",editor:Fh(),render:Xh(),api:Qh,setup:({editor:t})=>({api:tf({editor:t})})},af=bn("image.host-api");async function lf(t){const e=new Uint8Array(await t.arrayBuffer());let n="";for(let r=0;r<e.length;r+=32768)n+=String.fromCharCode(...e.subarray(r,r+32768));return`data:${t.type||"application/octet-stream"};base64,${btoa(n)}`}var cf="blobs",df=null;function uf(){return"undefined"==typeof indexedDB?Promise.resolve(null):(df||(df=new Promise((t,e)=>{const n=indexedDB.open("land.plugin-image",1);n.addEventListener("upgradeneeded",()=>{n.result.objectStoreNames.contains(cf)||n.result.createObjectStore(cf)}),n.addEventListener("success",()=>{const e=n.result;e.addEventListener("versionchange",()=>{e.close(),df=null}),t(e)}),n.addEventListener("error",()=>{df=null,e(n.error)})})),df)}var pf="image-blob:";function hf(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?`${pf}${crypto.randomUUID()}`:`${pf}${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}async function ff(t){const e=hf();if("undefined"==typeof indexedDB)throw new Error("IndexedDB is not available for image storage.");return await async function(t,e){const n=await uf();n&&await new Promise((r,o)=>{const i=n.transaction(cf,"readwrite");i.addEventListener("complete",()=>r()),i.addEventListener("abort",()=>o(i.error)),i.addEventListener("error",()=>o(i.error)),i.objectStore(cf).put(e,t)})}(e,t),{storageKey:e}}async function gf(t){const e=await async function(t){const e=await uf();return e?new Promise((n,r)=>{const o=e.transaction(cf,"readonly").objectStore(cf).get(t);o.addEventListener("success",()=>{n(o.result??null)}),o.addEventListener("error",()=>r(o.error))}):null}(t);return e instanceof Blob?e:null}async function mf(t){const e=await gf(t);return e?lf(e):null}async function yf(t){await async function(t){const e=await uf();e&&await new Promise((n,r)=>{const o=e.transaction(cf,"readwrite");o.addEventListener("complete",()=>n()),o.addEventListener("abort",()=>r(o.error)),o.addEventListener("error",()=>r(o.error)),o.objectStore(cf).delete(t)})}(t)}async function xf(){return(await async function(){const t=await uf();return t?new Promise((e,n)=>{const r=t.transaction(cf,"readonly").objectStore(cf).getAllKeys();r.addEventListener("success",()=>e([...r.result])),r.addEventListener("error",()=>n(r.error))}):null}())?.map(String)??[]}function wf(t,e){const n=t.assets.get(e);if(!_p(n)||"local"!==n.props.source.kind)return null;const{storageKey:r}=n.props.source;return r.length>0?r:null}function bf(t,e){const n=t.assets.get(e);return _p(n)&&"remote"===n.props.source.kind&&n.props.source.url.length>0?n.props.source.url:null}function vf(t){const e=new Set;for(const n of t.assets.getAll())_p(n)&&"local"===n.props.source.kind&&n.props.source.storageKey.length>0&&e.add(n.props.source.storageKey);return e}async function kf({editor:t,objectUrls:e}){const n=vf(t),r=await xf(),o=[];for(const i of r)n.has(i)||(e?.release(i),await yf(i),o.push(i));return o}function Pf(){const t=new Map,e=new Map;let n=0,r=!1;const o=async(o,i={})=>{if(i.signal?.throwIfAborted(),r)return null;const s=t.get(o);if(s)return s;const a=e.get(o);if(a)return a;const l=n,c=gf(o).then(e=>{if(i.signal?.throwIfAborted(),!e||r||l!==n)return null;const s=URL.createObjectURL(e);return t.set(o,s),s}).finally(()=>{e.delete(o)});return e.set(o,c),c};return{async preloadForEditor(t,e={}){e.signal?.throwIfAborted(),await Promise.all(Array.from(vf(t)).map(t=>o(t,e)))},preload:o,resolve:e=>t.get(e)??null,resolveAssetUrl(e,n){const r=bf(e,n);if(r)return r;const o=wf(e,n);return o?t.get(o)??null:null},release(n){const r=t.get(n);r&&(URL.revokeObjectURL(r),t.delete(n)),e.delete(n)},releaseAll(){r=!0,n+=1;for(const e of t.values())URL.revokeObjectURL(e);t.clear(),e.clear()}}}function Sf(){const t=Pf(),e={objectUrls:t,async cleanupAfterRestore(e,{signal:n}){n.throwIfAborted(),await kf({editor:e,objectUrls:t}),n.throwIfAborted()},preloadForEditor:(e,{signal:n})=>t.preloadForEditor(e,{signal:n}),resolveAssetUrl:(e,n)=>t.resolveAssetUrl(e,n)};return{value:e,dispose(){e.objectUrls.releaseAll()}}}function If(t,{signal:e}={}){return e?.throwIfAborted(),new Promise((n,r)=>{const o=new Image,i=()=>{o.removeEventListener("load",s),o.removeEventListener("error",a),e?.removeEventListener("abort",l)},s=()=>{i(),n({width:o.naturalWidth||o.width,height:o.naturalHeight||o.height})},a=()=>{i(),r(new Error("Could not decode image file."))},l=()=>{i(),r(e?.reason)};o.addEventListener("load",s),o.addEventListener("error",a),e?.addEventListener("abort",l,{once:!0}),o.src=t,e?.aborted&&l()})}async function Mf(t,{signal:e}={}){e?.throwIfAborted();const n=Cf(t)?t:t.blob,r=(Cf(t),t.name),o=Cf(t)?t.type:t.mimeType||t.blob.type,i=URL.createObjectURL(n),s=await If(i,{signal:e}).finally(()=>{URL.revokeObjectURL(i)});e?.throwIfAborted();const{storageKey:a}=await ff(n);try{e?.throwIfAborted()}catch(l){try{await yf(a)}catch(c){throw new AggregateError([l,c],"Could not discard an aborted image blob write.")}throw l}return{name:r||"Image",source:{kind:"local",storageKey:a,...!Cf(t)&&t.originalUrl?{originalUrl:t.originalUrl}:{}},mimeType:o||"image/png",fileSize:n.size,width:s.width,height:s.height}}async function Tf({name:t,signal:e,url:n}){const r=await If(n,{signal:e});return{name:t||Af(n)||"Image",source:{kind:"remote",url:n},mimeType:null,width:r.width,height:r.height}}function Cf(t){return"undefined"!=typeof File&&t instanceof File}function Af(t){try{const e=new URL(t).pathname.split("/").filter(Boolean).at(-1);return e?decodeURIComponent(e):null}catch{return null}}function Ef(t){for(const e of t)if(e.type.startsWith("image/"))return e;return null}function Lf({filename:t,url:e}){const n=document.createElement("a");n.href=e,n.download=t,n.click()}async function Bf({blob:t,filename:e}){const n=URL.createObjectURL(t);try{Lf({filename:e,url:n})}finally{window.setTimeout(()=>URL.revokeObjectURL(n),0)}}var Rf=1;function $f(t,e){return t.commands.createAsset({type:"image",props:{w:e.width,h:e.height,name:e.name,source:e.source,mimeType:e.mimeType,fileSize:e.fileSize,isAnimated:"image/gif"===e.mimeType}},{source:"user"})}async function Nf({editor:t,imageObjectUrls:e,pagePoint:n,signal:r,size:o,source:i}){return"file"===i.type?jf(i.file)?zf({editor:t,imageObjectUrls:e,input:await Mf(i.file,{signal:r}),pagePoint:n,size:o,signal:r}):null:"blob"===i.type?jf(i.blob)?zf({editor:t,imageObjectUrls:e,input:await Mf(i,{signal:r}),pagePoint:n,size:o,signal:r}):null:async function({editor:t,imageObjectUrls:e,pagePoint:n,signal:r,size:o,source:i}){return zf({editor:t,imageObjectUrls:e,input:await Tf({...i,signal:r}),pagePoint:n,size:o,signal:r,altText:i.altText})}({editor:t,imageObjectUrls:e,source:i,pagePoint:n,size:o,signal:r})}async function zf({editor:t,imageObjectUrls:e,input:n,pagePoint:r,size:o,signal:i,altText:s}){const a="local"===n.source.kind?n.source.storageKey:null;a&&await e.preload(a,{signal:i}),i.throwIfAborted();let l=null;try{try{const e=$f(t,n);l=e.id;const i=o??function({height:t,width:e}){const n=Math.min(1,360/Math.max(e,t));return{w:Math.max(24,Math.round(e*n)),h:Math.max(24,Math.round(t*n))}}({width:e.props.w,height:e.props.h}),a=t.state.viewportPageBounds.get(),c=r??a?.center??t.viewport.screenToPage(new bt(360,240)),[d]=t.commands.createShapes([{type:"image",x:Math.round(c.x-i.w/2),y:Math.round(c.y-i.h/2),props:{...i,assetId:e.id,crop:null,altText:s??n.name}}],{source:"user"});return d?(t.commands.setSelectedShapeIds([d.id],{source:"user"}),d.id):null}catch(c){throw l&&t.commands.deleteAsset(l,{source:"system"}),c}}catch(c){throw a&&(e.release(a),await yf(a)),c}}async function Of({editor:t,file:e,imageObjectUrls:n,signal:r}){if(!jf(e))return;const[o]=t.state.selectedShapes.get();if(!qp(o)||o.isLocked)return;const i=await Mf(e,{signal:r});await Hf({editor:t,imageObjectUrls:n,input:i,nextProps:{crop:null,altText:i.name},signal:r,shape:o})}async function Wf({editor:t,imageObjectUrls:e,onError:n}){const[r]=t.state.selectedShapes.get();if(!qp(r)||!r.props.assetId)return;const o=t.assets.get(r.props.assetId);if(!_p(o))return;const i="string"==typeof o.props.name&&o.props.name.length>0?o.props.name:"land-image";if("remote"===o.props.source.kind)return void(await async function({filename:t,onError:e,url:n}){try{const e=await fetch(n);if(!e.ok)throw new Error(`Could not download image URL (${e.status}).`);await Bf({blob:await e.blob(),filename:t})}catch(r){e?.(new Error("Could not download remote image; opening URL instead.",{cause:r})),function(t){const e=document.createElement("a");e.href=t,e.rel="noreferrer",e.target="_blank",e.click()}(n)}}({filename:i,onError:n,url:o.props.source.url}));const s=o.props.source.storageKey;if(!s)return;const a=await gf(s);if(a)return void(await Bf({blob:a,filename:i}));const l=e.resolve(s);l&&Lf({filename:i,url:l})}async function Hf({canCommit:t,editor:e,imageObjectUrls:n,input:r,nextProps:o,shape:i,signal:s}){const a=i.props.assetId,l="local"===r.source.kind?r.source.storageKey:null;try{s.throwIfAborted(),l&&await n.preload(l,{signal:s}),s.throwIfAborted()}catch(c){throw await Df({imageObjectUrls:n,storageKey:l}),c}try{const s=e.shapes.get(i.id);if(!qp(s)||s.isLocked||s.props.assetId!==a||t&&!t())return await Df({imageObjectUrls:n,storageKey:l}),null;const d=`image.asset.replace:${i.id}:${Rf++}`,u=e.operations.begin({kind:d,label:"image.asset.replace",source:"user",history:"record"});try{const t=$f(e,r);return e.commands.updateShapes([{id:i.id,props:{assetId:t.id,...o}}],{source:"user"}),a&&!function(t,e){return t.snapshots.getDocument().records.some(t=>"shape"===t.typeName&&t.props.assetId===e)}(e,a)&&e.commands.deleteAsset(a,{source:"user"}),u.commit(),{assetId:t.id,storageKey:l}}catch(c){throw u.isActive&&u.cancel(),c}}catch(c){throw await Df({imageObjectUrls:n,storageKey:l}),c}}async function Df({imageObjectUrls:t,storageKey:e}){e&&(t.release(e),await yf(e))}async function Ff(t){try{const e=await fetch(t);if(!e.ok)return null;const n=await e.blob();return jf(n)?n:null}catch{return null}}function jf(t){return!t.type||t.type.startsWith("image/")}var Uf=new WeakSet;async function Xf({editor:t,imageObjectUrls:e,replace:n=!0,signal:r}){r.throwIfAborted();const o=kh(t);if(!o)return null;const i=Th(o.strokes);if(0===i.length)return wh(t),null;if(Uf.has(o))return null;Uf.add(o);try{return await async function({editor:t,imageObjectUrls:e,replace:n,session:r,signal:o,strokes:i}){o.throwIfAborted();const s=t.shapes.get(r.shapeId);if(!qp(s)||s.isLocked||!s.props.assetId)return null;const a=t.assets.get(s.props.assetId);if(!_p(a))return null;const l=s.props.assetId,c=await async function({asset:t,imageObjectUrls:e}){if("remote"===t.props.source.kind)return Ff(t.props.source.url);const n=t.props.source.storageKey,r=await gf(n);if(r)return r;const o=e.resolve(n);return o?Ff(o):null}({asset:a,imageObjectUrls:e});if(o.throwIfAborted(),!c)return null;if(!Yf(t,r,l,s)||t.assets.get(l)!==a)return null;const{imageBlob:d,maskBlob:u,height:p,width:h}=await async function({crop:t,shape:e,signal:n,sourceBlob:r,strokes:o}){n.throwIfAborted();const i=await async function(t){if("function"==typeof createImageBitmap){const e=await createImageBitmap(t);return{source:e,width:e.width,height:e.height,dispose(){e.close()}}}const e=URL.createObjectURL(t),n=new Image;n.decoding="async",n.src=e,"function"==typeof n.decode?await n.decode():await new Promise((t,e)=>{n.onload=()=>t(),n.onerror=()=>e(new Error("Could not decode image."))});return{source:n,width:n.naturalWidth||n.width,height:n.naturalHeight||n.height,dispose(){URL.revokeObjectURL(e)}}}(r);try{n.throwIfAborted();const r=i.width,s=i.height,a=Kf(r,s);a.context.drawImage(i.source,0,0,r,s),_f({context:a.context,crop:t,imageHeight:s,imageWidth:r,mask:!1,shape:e,strokes:o});const l=Kf(r,s);_f({context:l.context,crop:t,imageHeight:s,imageWidth:r,mask:!0,shape:e,strokes:o});const c=await a.toBlob("image/png");n.throwIfAborted();const d=await l.toBlob("image/png");return n.throwIfAborted(),{imageBlob:c,maskBlob:d,width:r,height:s}}finally{i.dispose()}}({crop:s.props.crop,shape:s,signal:o,sourceBlob:c,strokes:i});if(o.throwIfAborted(),!Yf(t,r,l,s)||t.assets.get(l)!==a)return null;const f={shapeId:s.id,sourceAssetId:l,imageBlob:d,maskBlob:u,width:h,height:p,crop:s.props.crop?{topLeft:{...s.props.crop.topLeft},bottomRight:{...s.props.crop.bottomRight}}:null,strokes:i};if(n){o.throwIfAborted();const n=await async function({blob:t,canCommit:e,editor:n,imageObjectUrls:r,name:o,shape:i,signal:s}){s.throwIfAborted();const a=await Mf({blob:t,name:o},{signal:s});return s.throwIfAborted(),Hf({editor:n,imageObjectUrls:r,input:a,nextProps:{},shape:i,canCommit:e,signal:s})}({blob:d,canCommit:()=>!o.aborted&&Yf(t,r,l,s)&&t.assets.get(l)===a,editor:t,imageObjectUrls:e,name:Gf(a.props.name),shape:s,signal:o});if(o.throwIfAborted(),!n)return null;if(!Yf(t,r,n.assetId,s)){const o=kh(t),i=t.shapes.get(r.shapeId);return o?.shapeId===r.shapeId&&qp(i)&&i.props.assetId===n.assetId&&xh(t),await async function({assetId:t,editor:e,imageObjectUrls:n,storageKey:r}){if(!r||t&&e.assets.get(t))return;n.release(r),await yf(r)}({assetId:n.assetId,editor:t,imageObjectUrls:e,storageKey:n.storageKey}),null}return o.throwIfAborted(),wh(t),f}return o.throwIfAborted(),wh(t),f}({editor:t,imageObjectUrls:e,replace:n,session:o,signal:r,strokes:i})}finally{Uf.delete(o)}}function Yf(t,e,n,r){if(kh(t)!==e)return!1;const o=t.shapes.get(e.shapeId);return qp(o)&&!o.isLocked&&o.props.assetId===n&&function(t,e){if(t.props.w!==e.props.w||t.props.h!==e.props.h)return!1;const n=t.props.crop,r=e.props.crop;return n&&r?n.topLeft.x===r.topLeft.x&&n.topLeft.y===r.topLeft.y&&n.bottomRight.x===r.bottomRight.x&&n.bottomRight.y===r.bottomRight.y:n===r}(o,r)}function Kf(t,e){if("undefined"!=typeof OffscreenCanvas){const n=new OffscreenCanvas(t,e),r=n.getContext("2d");if(!r)throw new Error("Could not create image smudge canvas context.");return{context:r,toBlob:t=>n.convertToBlob({type:t})}}const n=document.createElement("canvas");n.width=t,n.height=e;const r=n.getContext("2d");if(!r)throw new Error("Could not create image smudge canvas context.");return{context:r,toBlob:t=>new Promise((e,r)=>{n.toBlob(t=>{t?e(t):r(new Error("Could not encode image smudge canvas."))},t)})}}function _f({context:t,crop:e,imageHeight:n,imageWidth:r,mask:o,shape:i,strokes:s}){if(0===s.length)return;const a=Lp(e),l={x:a.left*r,y:a.top*n,w:a.width*r,h:a.height*n},c=l.w/i.props.w,d=l.h/i.props.h,u=(Math.abs(c)+Math.abs(d))/2;t.save(),t.beginPath(),t.rect(l.x,l.y,l.w,l.h),t.clip(),t.lineCap="round",t.lineJoin="round";for(const p of s){const e=p.points[0];if(!e)continue;const n=Vf(p.brush.opacity),r=Math.max(1,p.brush.size*u),i=p.brush.color??"#ffff00";t.globalAlpha=n,t.strokeStyle=o?"#ffffff":i,t.fillStyle=o?"#ffffff":i,t.lineWidth=r;const s=qf({cropPixelRect:l,point:e,scaleX:c,scaleY:d});if(1!==p.points.length){t.beginPath(),t.moveTo(s.x,s.y);for(const e of p.points.slice(1)){const n=qf({cropPixelRect:l,point:e,scaleX:c,scaleY:d});t.lineTo(n.x,n.y)}t.stroke()}else t.beginPath(),t.arc(s.x,s.y,r/2,0,2*Math.PI),t.fill()}t.restore()}function qf({cropPixelRect:t,point:e,scaleX:n,scaleY:r}){return{x:t.x+e.x*n,y:t.y+e.y*r}}function Vf(t){return"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):.45}function Gf(t){const e=t.trim();if(!e)return"Image smudged.png";const n=e.lastIndexOf(".");return n<=0?`${e} smudged.png`:`${e.slice(0,n)} smudged.png`}function Jf({editor:t,imageAssetService:e,imageApi:n,onError:r,tasks:o}){let i,s=!1;const a=Zf(t=>i.insert({source:{type:"file",file:t}}),r),l=Zf(t=>i.replaceSelection({file:t}),r),c={start:t=>n.smudge.start(t),setBrush:t=>n.smudge.setBrush(t),cancel(){n.smudge.cancel()},confirm:n=>o.run(async r=>{const o=await Xf({editor:t,imageObjectUrls:e.objectUrls,replace:n?.replace??!0,signal:r});return r.throwIfAborted(),o}),isActive:()=>null!==n.smudge.getSnapshot()};i={openInsertFilePicker(){a.open()},openReplaceFilePicker(){l.open()},insert:({source:n,pagePoint:r,size:i})=>o.run(async o=>{o.throwIfAborted();const s=await Nf({editor:t,imageObjectUrls:e.objectUrls,source:n,pagePoint:r,size:i,signal:o});return o.throwIfAborted(),s}),replaceSelection:({file:n})=>o.run(async r=>{if(!n.type.startsWith("image/"))return!1;const[o]=t.state.selectedShapes.get();return!(!qp(o)||o.isLocked)&&(await Of({editor:t,file:n,imageObjectUrls:e.objectUrls,signal:r}),r.throwIfAborted(),!0)}),downloadSelectionOriginal:()=>o.run(async n=>{await Wf({editor:t,imageObjectUrls:e.objectUrls,onError:r}),n.throwIfAborted()}),smudge:c};const d=Ih(t,t=>c.confirm(t));return{value:i,dispose(){s||(s=!0,a.dispose(),l.dispose(),d())}}}function Zf(t,e){let n=null,r=!1;return{open(){if(!r){if(!globalThis.document)throw new Error("Image file selection requires a browser document.");n??=function(){const n=document.createElement("input");return n.type="file",n.accept="image/*",n.hidden=!0,n.onchange=()=>{const o=n.files?.[0]??null;n.value="",o&&!r&&t(o).catch(t=>{e?.(new Error("Image file selection failed.",{cause:t}))})},n}(),n.click()}},dispose(){r=!0,n&&(n.onchange=null),n=null}}}function Qf(t){return{kind:"svg-inliner",id:"image.svg-inliner",async prepare({editor:e,requestedShapeIds:n}){const r=tg(e,e.layers.getExportTraversalIds(n).flatMap(t=>{const n=e.shapes.get(t);return n?[n]:[]})),o=new Set;for(const i of r.values()){if("local"!==i.props.source.kind)continue;const{storageKey:e}=i.props.source;if(!o.has(e)&&(o.add(e),0===e.length||!(await t.objectUrls.preload(e))))throw new Error(`Could not load image asset "${i.id}".`)}},async inline({editor:e,exportedShapes:n,svg:r}){let o=r;const i=tg(e,n),s=new Set;for(const a of i.values()){const e=ng(a,t);if(!e)throw new Error(`Could not resolve image asset "${a.id}".`);if(s.has(e))continue;const n=await eg(a,e);if(n.href===n.dataUrl){s.add(e);continue}const r=`href="${rg(n.href)}"`;if(!o.includes(r))throw new Error(`Could not find image asset "${a.id}" in the generated SVG.`);o=o.split(r).join(`href="${n.dataUrl}"`),s.add(e)}return o}}}function tg(t,e){const n=new Map;for(const r of e){if(!qp(r)||!r.props.assetId)continue;const e=t.assets.get(r.props.assetId);if(!_p(e))throw new Error(`Image asset "${r.props.assetId}" is unavailable.`);n.set(e.id,e)}return n}async function eg(t,e){const{source:n}=t.props;if("local"===n.kind){const r=await mf(n.storageKey);if(!r)throw new Error(`Could not embed local image asset "${t.id}".`);return{href:e,dataUrl:r}}if(e.startsWith("data:"))return{href:e,dataUrl:e};let r;try{r=await fetch(e)}catch(i){throw new Error(`Could not download image asset "${t.id}".`,{cause:i})}if(!r.ok)throw new Error(`Could not download image asset "${t.id}" (${r.status}).`);const o=await lf(await r.blob());if(!o)throw new Error(`Could not embed remote image asset "${t.id}".`);return{href:e,dataUrl:o}}function ng(t,e){return"local"===t.props.source.kind?e.objectUrls.resolve(t.props.source.storageKey):t.props.source.url}function rg(t){return t.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function og(t={}){return{id:"image.host",requires:[sf],api:af,setup({apis:e,editor:n,tasks:r}){const o=(t.createAssetService??Sf)();let i=null;try{const s=Jf({editor:n,imageApi:e.require(Qh),imageAssetService:o.value,onError:t.onError,tasks:r});return i=s.dispose,{api:s.value,imports:[{id:"image.host-import",order:100,acceptsPreview:t=>t.fileTypes.some(t=>t.startsWith("image/"))||t.dataTypes.some(t=>{const e=t.toLowerCase();return"files"===e||"text/uri-list"===e}),accepts:t=>null!==Ef(t.files)||(t.urls?.some(ig)??!1),async import(t){const e=Ef(t.files),n=t.urls?.find(ig);return(e||n)&&await s.value.insert({source:e?{type:"file",file:e}:{type:"url",url:n},pagePoint:t.pagePoint})?"handled":"ignored"}}],assetResolvers:[{id:"image.host.asset-resolver",resolve:t=>o.value.resolveAssetUrl(n,t),preload:({signal:t})=>o.value.preloadForEditor(n,{signal:t}),cleanupAfterRestore:({signal:t})=>o.value.cleanupAfterRestore(n,{signal:t})}],exports:[Qf(o.value)],dispose(){i?.(),o.dispose()}}}catch(s){throw i?.(),o.dispose(),s}}}}function ig(t){return t.startsWith("data:image/")||/\.(?:avif|bmp|gif|jpe?g|png|svg|webp)(?:[?#].*)?$/i.test(t)}var sg="land:",ag="shape";function lg(t){const e=t.trim();if(!e)return null;const n=function(t){return/^[a-z][a-z0-9+.-]*:/i.test(t)}(e)?e:`https://${e}`;return cg(n)?n:null}function cg(t){return null!==pg(t)||dg(t)}function dg(t){try{const e=new URL(t);return"http:"===e.protocol||"https:"===e.protocol||"mailto:"===e.protocol}catch{return!1}}function ug(t){return`${sg}//${ag}/${encodeURIComponent(t)}`}function pg(t){try{const e=new URL(t);if(e.protocol!==sg||e.hostname!==ag||e.username||e.password||e.port||e.search||e.hash||!e.pathname.startsWith("/"))return null;const n=decodeURIComponent(e.pathname.slice(1));return n.startsWith("shape:")&&n.length>6?n:null}catch{return null}}function hg({href:t,openExternal:e,openInternal:n}){const r=pg(t);r?n?.(r):dg(t)&&e(t)}var fg=/[;{}<>\u0000-\u001f\u007f]/u,gg=/(?:url|expression)\s*\(|!\s*important|@\s*import|javascript\s*:/iu,mg=/^((?:\d+(?:\.\d{1,3})?)|(?:\.\d{1,3}))(px|em|rem|%)?$/iu;function yg(t){return{type:"doc",content:t.split("\n").map(t=>({type:"paragraph",content:t.length>0?[{type:"text",text:t}]:[]}))}}function xg(t){return t.content.map(t=>Sg(t)).join("\n")}function wg(t){if(!t||"object"!=typeof t)return yg("");const e=t,n=Array.isArray(e.content)?e.content.map(t=>Eg(t,0)).filter(t=>null!==t):[];return{type:"doc",attrs:Wg(e.attrs),content:n}}function bg(t){return"text"===t.type&&"string"==typeof t.text}function vg(t){if("paragraph"===t.type)return Og(t.attrs?.textAlign)}function kg(t,e){const n=t?.some(t=>"code"===t.type)?void 0:e;if(!(t&&0!==t.length||n))return;const r=n?{backgroundColor:n}:{},o=new Set;for(const i of t??[])switch(i.type){case"bold":case"strong":r.fontWeight=700;break;case"italic":case"em":r.fontStyle="italic";break;case"strike":case"s":o.add("line-through");break;case"underline":case"u":o.add("underline");break;case"textStyle":{const t=Rg(i.attrs);void 0!==t?.color&&(r.color=t.color),void 0!==t?.backgroundColor&&(r.backgroundColor=t.backgroundColor),void 0!==t?.fontFamily&&(r.fontFamily=t.fontFamily),void 0!==t?.fontSize&&(r.fontSize=t.fontSize),void 0!==t?.lineHeight&&(r.lineHeight=t.lineHeight);break}}return o.size>0&&(r.textDecorationLine=["line-through","underline"].filter(t=>o.has(t)).join(" ")),Object.keys(r).length>0?r:void 0}function Pg(t){if(t&&0!==t.length)for(const e of t){if("link"!==e.type)continue;const t=e.attrs?.href;return"string"==typeof t?t:void 0}}function Sg(t){return bg(t)?t.text:t.content?.map(t=>Sg(t)).join("")??""}function Ig(t){const e=[];return void 0!==t.color&&e.push(`color:${t.color}`),void 0!==t.backgroundColor&&e.push(`background-color:${t.backgroundColor}`),void 0!==t.fontFamily&&e.push(`font-family:${t.fontFamily}`),void 0!==t.fontSize&&e.push(`font-size:${t.fontSize}`),void 0!==t.fontWeight&&e.push(`font-weight:${String(t.fontWeight)}`),void 0!==t.fontStyle&&e.push(`font-style:${t.fontStyle}`),void 0!==t.lineHeight&&e.push(`line-height:${t.lineHeight}`),void 0!==t.textDecorationLine&&e.push(`text-decoration-line:${t.textDecorationLine}`),e.join(";")}function Mg(t){const e=t.content?.map(t=>function(t){if(bg(t)){const e=kg(t.marks),n=Pg(t.marks),r=Tg(t.text),o=e?`<span style="${Cg(Ig(e))}">${r}</span>`:r;return n&&dg(n)?`<a href="${Cg(n)}" target="_blank" rel="noopener noreferrer">${o}</a>`:e?o:r}return"hardBreak"===t.type?"<br>":Mg(t)}(t)).join("")??"";if("bulletList"===t.type)return`<ul style="margin:0;padding-inline-start:1.5em;list-style-type:disc">${e}</ul>`;if("orderedList"===t.type)return`<ol style="margin:0;padding-inline-start:1.5em;list-style-type:decimal">${e}</ol>`;if("listItem"===t.type)return`<li>${e}</li>`;if("blockquote"===t.type)return`<blockquote style="margin:0;padding-inline-start:0.75em;border-inline-start:2px solid currentColor">${e}</blockquote>`;const n=vg(t);return`<p style="${n?`margin:0;text-align:${n}`:"margin:0"}">${e.length>0?e:"<br>"}</p>`}function Tg(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Cg(t){return Tg(t).replaceAll('"',"&quot;")}function Ag(t,e){if(!t||"object"!=typeof t||e>8)return null;const n=t;if("text"===n.type){const t=function(t){return{type:"text",text:"string"==typeof t.text?t.text:"",marks:Array.isArray(t.marks)?t.marks.map(Lg).filter(t=>null!==t):void 0}}(n);return t.text.length>0?t:null}return Eg(n,e)}function Eg(t,e){if(!t||"object"!=typeof t)return null;const n=t,r="string"==typeof n.type?n.type:"paragraph",o=Array.isArray(n.content)?n.content.map(t=>Ag(t,e+1)).filter(t=>null!==t):[];return{type:r,attrs:Bg(r,n.attrs),content:o}}function Lg(t){if(!t||"object"!=typeof t)return null;const e=t;if("string"!=typeof e.type)return null;if("link"===e.type){const t=Wg(e.attrs),n=t?.href;return"string"==typeof n&&cg(n)?{type:"link",attrs:{...t,href:n}}:null}if("textStyle"===e.type){const t=Rg(e.attrs);return t?{type:"textStyle",attrs:t}:null}return{type:e.type,attrs:Wg(e.attrs)}}function Bg(t,e){const n=Wg(e);if("paragraph"!==t)return n;const r={...n};delete r.textAlign;const o=e&&"object"==typeof e&&!Array.isArray(e)?Og(e.textAlign):void 0;return void 0!==o&&(r.textAlign=o),Object.keys(r).length>0?r:void 0}function Rg(t){if(!t||"object"!=typeof t||Array.isArray(t))return;const e=t,n={color:$g(e.color,128),backgroundColor:$g(e.backgroundColor,128),fontFamily:$g(e.fontFamily,256),fontSize:Ng(e.fontSize),lineHeight:zg(e.lineHeight)},r=Object.entries(n).filter(t=>void 0!==t[1]);return r.length>0?Object.fromEntries(r):void 0}function $g(t,e){if("string"!=typeof t)return;const n=t.trim();return 0===n.length||n.length>e||fg.test(n)||gg.test(n)?void 0:n}function Ng(t){const e="string"==typeof t?mg.exec(t.trim()):null;if(!e||"px"!==e[2]?.toLowerCase())return;const n=Number(e[1]);return n>=1&&n<=512?`${String(n)}px`:void 0}function zg(t){const e="string"==typeof t?mg.exec(t.trim()):null;if(!e)return;const n=Number(e[1]),r=e[2]?.toLowerCase()??"";return("px"===r?n>=1&&n<=1024:"%"===r?n>=50&&n<=1e3:n>=.5&&n<=10)?`${String(n)}${r}`:void 0}function Og(t){return"left"===t||"center"===t||"right"===t?t:void 0}function Wg(t){if(!t||"object"!=typeof t)return;const e=Object.entries(t).map(([t,e])=>[t,Hg(e)]).filter(t=>void 0!==t[1]);return e.length>0?Object.fromEntries(e):void 0}function Hg(t,e=0){if(null===t||"string"==typeof t||"number"==typeof t||"boolean"==typeof t)return t;if(!(e>8)){if(Array.isArray(t))return t.map(t=>Hg(t,e+1)).filter(t=>void 0!==t);if(t&&"object"==typeof t){const n=Object.entries(t).map(([t,n])=>[t,Hg(n,e+1)]).filter(t=>void 0!==t[1]);return Object.fromEntries(n)}}}function Dg(t){return yt(t)&&"text"===t.type}function Fg(t){return{richText:t.richText,w:t.w,h:t.h,autoSize:t.autoSize,scale:t.scale,font:t.font,size:t.size,color:t.color,backgroundColor:t.backgroundColor,textAlign:t.textAlign}}function jg(t){return Fg(t.shapes.getDefaultProps("text"))}function Ug(t,e,n="user"){const r={...jg(t),...e.props,richText:e.props?.richText??yg("")},[o]=t.commands.createShapes([{type:"text",x:e.x,y:e.y,parentId:e.parentId,index:e.index,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,meta:e.meta,props:{richText:r.richText,w:r.w,h:r.h,autoSize:r.autoSize,scale:r.scale,font:r.font,size:r.size,color:r.color,backgroundColor:r.backgroundColor,textAlign:r.textAlign}}],{source:n});if(!Dg(o))throw new Error("Failed to create text shape");return o}function Xg(t,e,n,r,o="user"){const i=t.shapes.get(e);Dg(i)&&t.commands.updateShapes([{id:i.id,props:{richText:n,..."number"==typeof r?.w?{w:r.w}:null,..."number"==typeof r?.h?{h:r.h}:null}}],{source:o})}var Yg="path-label",Kg="geo-label",_g={[Yg]:{selectionTarget:"owner",hoverTarget:"owner",hoverDecorationTarget:"owner",translateTarget:"owner",canSnap:!1,canReceiveTerminalBinding:!1,contributesToSelectionFrame:!0,canUseSelectionResizeHandles:!1,canUseSelectionRotateHandle:!1,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!0},[Kg]:{selectionTarget:"owner",hoverTarget:"owner",hoverDecorationTarget:"label",translateTarget:"owner",canSnap:!1,canReceiveTerminalBinding:!1,contributesToSelectionFrame:!1,canUseSelectionResizeHandles:!0,canUseSelectionRotateHandle:!0,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!1}};function qg(t,e){return t?Math.min(t.paddingInline,Math.max(0,(e-1)/2)):0}function Vg(t,e){return Xt(t.shapes.computeLocalToPageTransform(e),t.shapes.computeLocalBounds(e),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY})?.rotation??e.rotation}function Gg(t,e,n,r){const o=t.shapes.getUtil(e),i=Xt(t.shapes.computeLocalToPageTransform(e),t.shapes.computeLocalBounds(e),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY});if(!i)return null;const s={...e,...i,x:r.x,y:r.y,rotation:r.rotation,props:o.validateProps({...e.props,...r.props})},a=n.startsWith("shape:")?t.shapes.get(n):null;if(n.startsWith("shape:")&&!a)return null;const l=(a?t.shapes.computeLocalToPageTransform(a):Ht.Identity()).tryInvert();return l?Xt(l.compose(o.getLocalTransform(s)),o.getLocalBounds(s),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY}):null}function Jg(t,e,n){const r=t.bindings.getToShape(e).find(t=>t.type===n);if(!r)return null;const o=t.shapes.get(r.fromId);return Dg(o)?o:null}function Zg(t,e){const n={...jg(t),...e.layout.props,autoSize:!1,textAlign:"middle"},r=Gg(t,{id:"shape:draft-label",typeName:"shape",scope:"document",type:"text",parentId:e.owner.parentId,index:e.index,x:0,y:0,rotation:0,scaleX:1,scaleY:1,opacity:1,isHidden:!1,isLocked:!1,meta:{},props:n},e.owner.parentId,e.layout);if(!r)return null;const o=t.operations.begin({kind:e.operationKind,label:"shape.create",source:"user",history:"record"});try{const o=Ug(t,{x:r.x,y:r.y,parentId:e.owner.parentId,index:e.index,rotation:r.rotation,scaleX:r.scaleX,scaleY:r.scaleY,props:n},"user");return t.commands.createBinding({type:e.bindingType,fromId:o.id,toId:e.owner.id,props:e.bindingProps},{source:"user"}),o}catch(i){throw o.cancel(),i}}function Qg(t,e){const n=t.shapes.get(e);if(!Dg(n))return null;const r=t.bindings.getFromShape(e).find(t=>t.type in _g);if(!r)return null;const o=r.type;return{label:n,ownerId:r.toId,bindingType:o,behavior:_g[o]}}function tm(t,e,n,r){if("path-label"===r)return{minWidth:24,maxWidth:120,paddingInline:4.25};const o=Math.max(.01,e.props.scale),i=t.shapes.computeLocalBounds(n),s="geo"===n.type?n.props.kind:null,a="summary"===s||"summary-left"===s?.75:1;return{minWidth:16,maxWidth:Math.max(16,i.w*a/o),paddingInline:16,normalizedCenterX:"summary-left"===s?1-a/2:a/2}}function em(t,e){const n=Qg(t,e.id);if(!n)return null;const r=t.shapes.get(n.ownerId);return r?tm(t,e,r,n.bindingType):null}function nm(t,e,n){t.editing.start({shapeId:e.id,entryMode:n.entryMode??"selectAll",operationKind:n.isExisting?n.editOperationKind:n.createOperationKind,reuseActiveOperation:!n.isExisting},"user")}function rm(t,e={}){const n={offset:0};return t.content.map((t,r)=>(r>0&&(n.offset+=1),om(t,`block:${r}`,n,e)))}function om(t,e,n,r){const o="codeBlock"===t.type?void 0:r.defaultBackgroundColor,i=function(t,e,n,r){return t.content?.map((t,o)=>function(t,e,n,r){if(bg(t)){const o=n.offset;n.offset+=t.text.length;const i=function(t,e,n){const r=e+t.length,o=n.searchRanges?.filter(t=>t.from<r&&t.to>e);if(!o||0===o.length)return t;const i=[];let s=0;for(const a of o){const o=Math.max(a.from,e)-e,l=Math.min(a.to,r)-e;o>s&&i.push(t.slice(s,o)),i.push(d("mark",{className:"land-text-search-match","data-active":n.activeSearchRange?.from===a.from&&n.activeSearchRange.to===a.to?"true":void 0,children:t.slice(o,l)},`search:${a.from}:${a.to}:${e}`)),s=l}s<t.length&&i.push(t.slice(s));return i}(t.text,o,r),s=kg(t.marks,r.defaultBackgroundColor),a=Pg(t.marks);return a&&cg(a)?d("span",{"data-rich-text-link":"true","data-rich-text-link-href":a,onPointerEnter:t=>{r.linkHandlers?.onPointerEnter?.({href:a,element:t.currentTarget})},onPointerLeave:()=>{r.linkHandlers?.onPointerLeave?.()},style:{...s,cursor:r.linkHandlers?"pointer":void 0,pointerEvents:r.linkHandlers?"auto":"none",textDecorationLine:im(s?.textDecorationLine)},children:i},e):d("span",{style:s,children:i},e)}return"hardBreak"===t.type?d("br",{},e):om(t,e,n,{...r,defaultBackgroundColor:"codeBlock"===t.type?void 0:r.defaultBackgroundColor})}(t,`${e}:${o}`,n,r))??[]}(t,e,n,{...r,defaultBackgroundColor:o});return"bulletList"===t.type?d("ul",{style:{listStyleType:"disc",margin:0,paddingInlineStart:"1.5em"},children:i},e):"orderedList"===t.type?d("ol",{style:{listStyleType:"decimal",margin:0,paddingInlineStart:"1.5em"},children:i},e):"listItem"===t.type?d("li",{children:i},e):"blockquote"===t.type?d("blockquote",{style:{borderInlineStart:"2px solid currentColor",margin:0,paddingInlineStart:"0.75em"},children:i},e):d("p",{style:{margin:0,textAlign:vg(t)},children:i.length>0?i:d("br",{})},e)}function im(t){const e=new Set(t?.split(/\s+/u)??[]);return e.add("underline"),["line-through","underline"].filter(t=>e.has(t)).join(" ")}var sm="default",am={id:"host-default",label:"Host default",cssFamily:"inherit",source:{kind:"system"}};function lm(){return{defaultFont:am,defaultFontLabel:"Default",fonts:[]}}function cm(){return dm(lm())}function dm(t){const e=new Map;for(const r of t.fonts)um(r.id)&&"default"!==r.id&&e.set(r.id,r);const n={id:sm,label:t.defaultFontLabel,cssFamily:t.defaultFont.cssFamily,source:t.defaultFont.source};return{defaultFont:t.defaultFont,defaultFontLabel:t.defaultFontLabel,fontOptions:[n,...e.values()],fontsById:e}}function um(t){return"string"==typeof t&&t.trim().length>0}function pm(t,e){return"default"===e?t.defaultFont:t.fontsById.get(e)??t.defaultFont}var hm=new WeakMap;function fm(t,e,n){const r=pm(e,t),o=n??("undefined"==typeof document?void 0:document);if(!o||!gm(r.source))return Promise.resolve();const i=function(t){const{source:e}=t;return e&&"system"!==e.kind?"stylesheet"===e.kind?`${t.id}:stylesheet:${e.cssUrl}`:`${t.id}:font-face:${e.family}:${String(e.src)}`:t.id}(r),s=function(t){const e=hm.get(t);if(e)return e;const n=new Map;return hm.set(t,n),n}(o),a=s.get(i);if(a)return a;const l=async function(t,e){const{source:n}=e;if(!gm(n))return;if("stylesheet"===n.kind)return await function(t,e,n){return Array.from(t.querySelectorAll("link[data-land-text-font]")).find(t=>t.dataset.landTextFont===e.id)?Promise.resolve():new Promise(r=>{const o=t.createElement("link");o.rel="stylesheet",o.href=n.cssUrl,o.dataset.landTextFont=e.id;const i=()=>r();o.addEventListener("load",i,{once:!0}),o.addEventListener("error",i,{once:!0}),(t.head??t.documentElement).appendChild(o)})}(t,e,n),void(await mm(t,n));await async function(t,e){const{fonts:n}=t,r=t.defaultView?.FontFace;if(!n||!r)return;if(Array.from(n).filter(t=>t.family===e.family&&"loaded"===t.status).length>0)return;const o=await new r(e.family,e.src,e.descriptors).load();n.add(o)}(t,n),await mm(t,n)}(o,r).catch(()=>{s.delete(i)});return s.set(i,l),l}function gm(t){return!!t&&"system"!==t.kind}async function mm(t,e){const{fonts:n}=t;if(!n)return;const r=function(t){if(t.weights)return t.weights;if("font-face"===t.kind){const e=t.descriptors?.weight;if("string"==typeof e&&/^\d+$/.test(e))return[Number(e)]}return[400]}(e),o=e.sampleText??"Aa";await Promise.all(r.map(t=>n.load(`${t} 16px "${e.family}"`,o)))}var ym=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,xm=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,wm=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,bm=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,vm=T.create({name:"bold",addOptions:()=>({HTMLAttributes:{}}),parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:t=>"normal"!==t.style.fontWeight&&null},{style:"font-weight=400",clearMark:t=>t.type.name===this.name},{style:"font-weight",getAttrs:t=>/^(bold(er)?|[5-9]\d{2,})$/.test(t)&&null}]},renderHTML({HTMLAttributes:t}){
39
+ return et("strong",{...V(this.options.HTMLAttributes,t),children:et("slot",{})})},markdownTokenName:"strong",parseMarkdown:(t,e)=>e.applyMark("bold",e.parseInline(t.tokens||[])),markdownOptions:{htmlReopen:{open:"<strong>",close:"</strong>"}},renderMarkdown:(t,e)=>`**${e.renderChildren(t)}**`,addCommands(){return{setBold:()=>({commands:t})=>t.setMark(this.name),toggleBold:()=>({commands:t})=>t.toggleMark(this.name),unsetBold:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[_({find:ym,type:this.type}),_({find:wm,type:this.type})]},addPasteRules(){return[q({find:xm,type:this.type}),q({find:bm,type:this.type})]}}),km=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,Pm=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Sm=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Im=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,Mm=T.create({name:"italic",addOptions:()=>({HTMLAttributes:{}}),parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:t=>"normal"!==t.style.fontStyle&&null},{style:"font-style=normal",clearMark:t=>t.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:t}){return["em",V(this.options.HTMLAttributes,t),0]},addCommands(){return{setItalic:()=>({commands:t})=>t.setMark(this.name),toggleItalic:()=>({commands:t})=>t.toggleMark(this.name),unsetItalic:()=>({commands:t})=>t.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(t,e)=>e.applyMark("italic",e.parseInline(t.tokens||[])),markdownOptions:{htmlReopen:{open:"<em>",close:"</em>"}},renderMarkdown:(t,e)=>`*${e.renderChildren(t)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[_({find:km,type:this.type}),_({find:Sm,type:this.type})]},addPasteRules(){return[q({find:Pm,type:this.type}),q({find:Im,type:this.type})]}}),Tm="numeric",Cm="ascii",Am="alpha",Em="asciinumeric",Lm="alphanumeric",Bm="domain",Rm="emoji",$m="scheme",Nm="slashscheme",zm="whitespace";function Om(t,e){return t in e||(e[t]=[]),e[t]}function Wm(t,e,n){e[Tm]&&(e[Em]=!0,e[Lm]=!0),e[Cm]&&(e[Em]=!0,e[Am]=!0),e[Em]&&(e[Lm]=!0),e[Am]&&(e[Lm]=!0),e[Lm]&&(e[Bm]=!0),e[Rm]&&(e[Bm]=!0);for(const r in e){const e=Om(r,n);e.indexOf(t)<0&&e.push(t)}}function Hm(t=null){this.j={},this.jr=[],this.jd=null,this.t=t}Hm.groups={},Hm.prototype={accepts(){return!!this.t},go(t){const e=this,n=e.j[t];if(n)return n;for(let r=0;r<e.jr.length;r++){const n=e.jr[r][0],o=e.jr[r][1];if(o&&n.test(t))return o}return e.jd},has(t,e=!1){return e?t in this.j:!!this.go(t)},ta(t,e,n,r){for(let o=0;o<t.length;o++)this.tt(t[o],e,n,r)},tr(t,e,n,r){let o;return r=r||Hm.groups,e&&e.j?o=e:(o=new Hm(e),n&&r&&Wm(e,n,r)),this.jr.push([t,o]),o},ts(t,e,n,r){let o=this;const i=t.length;if(!i)return o;for(let s=0;s<i-1;s++)o=o.tt(t[s]);return o.tt(t[i-1],e,n,r)},tt(t,e,n,r){r=r||Hm.groups;const o=this;if(e&&e.j)return o.j[t]=e,e;const i=e;let s,a=o.go(t);return a?(s=new Hm,Object.assign(s.j,a.j),s.jr.push.apply(s.jr,a.jr),s.jd=a.jd,s.t=a.t):s=new Hm,i&&(r&&(s.t&&"string"==typeof s.t?Wm(i,Object.assign(function(t,e){const n={};for(const r in e)e[r].indexOf(t)>=0&&(n[r]=!0);return n}(s.t,r),n),r):n&&Wm(i,n,r)),s.t=i),o.j[t]=s,s}};var Dm=(t,e,n,r,o)=>t.ta(e,n,r,o),Fm=(t,e,n,r,o)=>t.tr(e,n,r,o),jm=(t,e,n,r,o)=>t.ts(e,n,r,o),Um=(t,e,n,r,o)=>t.tt(e,n,r,o),Xm="WORD",Ym="UWORD",Km="ASCIINUMERICAL",_m="ALPHANUMERICAL",qm="LOCALHOST",Vm="TLD",Gm="UTLD",Jm="SCHEME",Zm="SLASH_SCHEME",Qm="NUM",ty="WS",ey="NL",ny="OPENBRACE",ry="CLOSEBRACE",oy="OPENBRACKET",iy="CLOSEBRACKET",sy="OPENPAREN",ay="CLOSEPAREN",ly="OPENANGLEBRACKET",cy="CLOSEANGLEBRACKET",dy="FULLWIDTHLEFTPAREN",uy="FULLWIDTHRIGHTPAREN",py="LEFTCORNERBRACKET",hy="RIGHTCORNERBRACKET",fy="LEFTWHITECORNERBRACKET",gy="RIGHTWHITECORNERBRACKET",my="FULLWIDTHLESSTHAN",yy="FULLWIDTHGREATERTHAN",xy="AMPERSAND",wy="APOSTROPHE",by="ASTERISK",vy="AT",ky="BACKSLASH",Py="BACKTICK",Sy="CARET",Iy="COLON",My="COMMA",Ty="DOLLAR",Cy="DOT",Ay="EQUALS",Ey="EXCLAMATION",Ly="HYPHEN",By="PERCENT",Ry="PIPE",$y="PLUS",Ny="POUND",zy="QUERY",Oy="QUOTE",Wy="FULLWIDTHMIDDLEDOT",Hy="SEMI",Dy="SLASH",Fy="TILDE",jy="UNDERSCORE",Uy="EMOJI",Xy="SYM",Yy=Object.freeze({__proto__:null,ALPHANUMERICAL:_m,AMPERSAND:xy,APOSTROPHE:wy,ASCIINUMERICAL:Km,ASTERISK:by,AT:vy,BACKSLASH:ky,BACKTICK:Py,CARET:Sy,CLOSEANGLEBRACKET:cy,CLOSEBRACE:ry,CLOSEBRACKET:iy,CLOSEPAREN:ay,COLON:Iy,COMMA:My,DOLLAR:Ty,DOT:Cy,EMOJI:Uy,EQUALS:Ay,EXCLAMATION:Ey,FULLWIDTHGREATERTHAN:yy,FULLWIDTHLEFTPAREN:dy,FULLWIDTHLESSTHAN:my,FULLWIDTHMIDDLEDOT:Wy,FULLWIDTHRIGHTPAREN:uy,HYPHEN:Ly,LEFTCORNERBRACKET:py,LEFTWHITECORNERBRACKET:fy,LOCALHOST:qm,NL:ey,NUM:Qm,OPENANGLEBRACKET:ly,OPENBRACE:ny,OPENBRACKET:oy,OPENPAREN:sy,PERCENT:By,PIPE:Ry,PLUS:$y,POUND:Ny,QUERY:zy,QUOTE:Oy,RIGHTCORNERBRACKET:hy,RIGHTWHITECORNERBRACKET:gy,SCHEME:Jm,SEMI:Hy,SLASH:Dy,SLASH_SCHEME:Zm,SYM:Xy,TILDE:Fy,TLD:Vm,UNDERSCORE:jy,UTLD:Gm,UWORD:Ym,WORD:Xm,WS:ty}),Ky=/[a-z]/,_y=/\p{L}/u,qy=/\p{Emoji}/u,Vy=/\d/,Gy=/\s/,Jy=null,Zy=null;function Qy(t,e){const n=function(t){const e=[],n=t.length;let r=0;for(;r<n;){let o,i=t.charCodeAt(r),s=i<55296||i>56319||r+1===n||(o=t.charCodeAt(r+1))<56320||o>57343?t[r]:t.slice(r,r+2);e.push(s),r+=s.length}return e}(e.replace(/[A-Z]/g,t=>t.toLowerCase())),r=n.length,o=[];let i=0,s=0;for(;s<r;){let a=t,l=null,c=0,d=null,u=-1,p=-1;for(;s<r&&(l=a.go(n[s]));)a=l,a.accepts()?(u=0,p=0,d=a):u>=0&&(u+=n[s].length,p++),c+=n[s].length,i+=n[s].length,s++;i-=u,s-=p,c-=u,o.push({t:d.t,v:e.slice(i-c,i),s:i-c,e:i})}return o}function tx(t,e,n,r,o){let i;const s=e.length;for(let a=0;a<s-1;a++){const n=e[a];t.j[n]?i=t.j[n]:(i=new Hm(r),i.jr=o.slice(),t.j[n]=i),t=i}return i=new Hm(n),i.jr=o.slice(),t.j[e[s-1]]=i,i}function ex(t){const e=[],n=[];let r=0;for(;r<t.length;){let o=0;for(;"0123456789".indexOf(t[r+o])>=0;)o++;if(o>0){e.push(n.join(""));for(let e=parseInt(t.substring(r,r+o),10);e>0;e--)n.pop();r+=o}else n.push(t[r]),r++}return e}var nx={defaultProtocol:"http",events:null,format:ox,formatHref:ox,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function rx(t,e=null){let n=Object.assign({},nx);t&&(n=Object.assign(n,t instanceof rx?t.o:t));const r=n.ignoreTags,o=[];for(let i=0;i<r.length;i++)o.push(r[i].toUpperCase());this.o=n,e&&(this.defaultRender=e),this.ignoreTags=o}function ox(t){return t}function ix(t,e){this.t="token",this.v=t,this.tk=e}function sx(t,e){class n extends ix{constructor(e,n){super(e,n),this.t=t}}for(const r in e)n.prototype[r]=e[r];return n.t=t,n}rx.prototype={o:nx,ignoreTags:[],defaultRender:t=>t,check(t){return this.get("validate",t.toString(),t)},get(t,e,n){const r=null!=e;let o=this.o[t];return o?("object"==typeof o?(o=n.t in o?o[n.t]:nx[t],"function"==typeof o&&r&&(o=o(e,n))):"function"==typeof o&&r&&(o=o(e,n.t,n)),o):o},getObj(t,e,n){let r=this.o[t];return"function"==typeof r&&null!=e&&(r=r(e,n.t,n)),r},render(t){const e=t.render(this);return(this.get("render",null,t)||this.defaultRender)(e,t.t,t)}},ix.prototype={isLink:!1,toString(){return this.v},toHref(t){return this.toString()},toFormattedString(t){const e=this.toString(),n=t.get("truncate",e,this),r=t.get("format",e,this);return n&&r.length>n?r.substring(0,n)+"…":r},toFormattedHref(t){return t.get("formatHref",this.toHref(t.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(t=nx.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(t),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(t){return{type:this.t,value:this.toFormattedString(t),isLink:this.isLink,href:this.toFormattedHref(t),start:this.startIndex(),end:this.endIndex()}},validate(t){return t.get("validate",this.toString(),this)},render(t){const e=this,n=this.toHref(t.get("defaultProtocol")),r=t.get("formatHref",n,this),o=t.get("tagName",n,e),i=this.toFormattedString(t),s={},a=t.get("className",n,e),l=t.get("target",n,e),c=t.get("rel",n,e),d=t.getObj("attributes",n,e),u=t.getObj("events",n,e);return s.href=r,a&&(s.class=a),l&&(s.target=l),c&&(s.rel=c),d&&Object.assign(s,d),{tagName:o,attributes:s,content:i,eventListeners:u}}};var ax=sx("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),lx=sx("text"),cx=sx("nl"),dx=sx("url",{isLink:!0,toHref(t=nx.defaultProtocol){return this.hasProtocol()?this.v:`${t}://${this.v}`},hasProtocol(){const t=this.tk;return t.length>=2&&t[0].t!==qm&&t[1].t===Iy}}),ux=t=>new Hm(t);function px(t,e,n){const r=n[0].s,o=n[n.length-1].e;return new t(e.slice(r,o),n)}var hx="undefined"!=typeof console&&console&&console.warn||(()=>{}),fx={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function gx(t,e=!1){if(fx.initialized&&hx(`linkifyjs: already initialized - will not register custom scheme "${t}" until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(t))throw new Error('linkifyjs: incorrect scheme format.\n1. Must only contain digits, lowercase ASCII letters or "-"\n2. Cannot start or end with "-"\n3. "-" cannot repeat');fx.customSchemes.push([t,e])}function mx(){fx.scanner=function(t=[]){const e={};Hm.groups=e;const n=new Hm;null==Jy&&(Jy=ex("aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2")),null==Zy&&(Zy=ex("ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2")),Um(n,"'",wy),Um(n,"{",ny),Um(n,"}",ry),Um(n,"[",oy),Um(n,"]",iy),Um(n,"(",sy),Um(n,")",ay),Um(n,"<",ly),Um(n,">",cy),Um(n,"(",dy),Um(n,")",uy),Um(n,"「",py),Um(n,"」",hy),Um(n,"『",fy),Um(n,"』",gy),Um(n,"<",my),Um(n,">",yy),Um(n,"&",xy),Um(n,"*",by),Um(n,"@",vy),Um(n,"`",Py),Um(n,"^",Sy),Um(n,":",Iy),Um(n,",",My),Um(n,"$",Ty),Um(n,".",Cy),Um(n,"=",Ay),Um(n,"!",Ey),Um(n,"-",Ly),Um(n,"%",By),Um(n,"|",Ry),Um(n,"+",$y),Um(n,"#",Ny),Um(n,"?",zy),Um(n,'"',Oy),Um(n,"/",Dy),Um(n,";",Hy),Um(n,"~",Fy),Um(n,"_",jy),Um(n,"\\",ky),Um(n,"・",Wy);const r=Fm(n,Vy,Qm,{[Tm]:!0});Fm(r,Vy,r);const o=Fm(r,Ky,Km,{[Em]:!0}),i=Fm(r,_y,_m,{[Lm]:!0}),s=Fm(n,Ky,Xm,{[Cm]:!0});Fm(s,Vy,o),Fm(s,Ky,s),Fm(o,Vy,o),Fm(o,Ky,o);const a=Fm(n,_y,Ym,{[Am]:!0});Fm(a,Ky),Fm(a,Vy,i),Fm(a,_y,a),Fm(i,Vy,i),Fm(i,Ky),Fm(i,_y,i);const l=Um(n,"\n",ey,{[zm]:!0}),c=Um(n,"\r",ty,{[zm]:!0}),d=Fm(n,Gy,ty,{[zm]:!0});Um(n,"",d),Um(c,"\n",l),Um(c,"",d),Fm(c,Gy,d),Um(d,"\r"),Um(d,"\n"),Fm(d,Gy,d),Um(d,"",d);const u=Fm(n,qy,Uy,{[Rm]:!0});Um(u,"#"),Fm(u,qy,u),Um(u,"️",u);const p=Um(u,"‍");Um(p,"#"),Fm(p,qy,u);const h=[[Ky,s],[Vy,o]],f=[[Ky,null],[_y,a],[Vy,i]];for(let g=0;g<Jy.length;g++)tx(n,Jy[g],Vm,Xm,h);for(let g=0;g<Zy.length;g++)tx(n,Zy[g],Gm,Ym,f);Wm(Vm,{tld:!0,ascii:!0},e),Wm(Gm,{utld:!0,alpha:!0},e),tx(n,"file",Jm,Xm,h),tx(n,"mailto",Jm,Xm,h),tx(n,"http",Zm,Xm,h),tx(n,"https",Zm,Xm,h),tx(n,"ftp",Zm,Xm,h),tx(n,"ftps",Zm,Xm,h),Wm(Jm,{scheme:!0,ascii:!0},e),Wm(Zm,{slashscheme:!0,ascii:!0},e),t=t.sort((t,e)=>t[0]>e[0]?1:-1);for(let g=0;g<t.length;g++){const e=t[g][0],r=t[g][1]?{[$m]:!0}:{[Nm]:!0};e.indexOf("-")>=0?r[Bm]=!0:Ky.test(e)?Vy.test(e)?r[Em]=!0:r[Cm]=!0:r[Tm]=!0,jm(n,e,e,r)}return jm(n,"localhost",qm,{ascii:!0}),n.jd=new Hm(Xy),{start:n,tokens:Object.assign({groups:e},Yy)}}(fx.customSchemes);for(let t=0;t<fx.tokenQueue.length;t++)fx.tokenQueue[t][1]({scanner:fx.scanner});fx.parser=function({groups:t}){const e=t.domain.concat([xy,by,vy,ky,Py,Sy,Ty,Ay,Ly,Qm,By,Ry,$y,Ny,Dy,Xy,Fy,jy]),n=[wy,Iy,My,Cy,Ey,By,zy,Oy,Hy,ly,cy,ny,ry,iy,oy,sy,ay,dy,uy,py,hy,fy,gy,my,yy],r=[xy,wy,by,ky,Py,Sy,Ty,Ay,Ly,ny,ry,By,Ry,$y,Ny,zy,Dy,Xy,Fy,jy],o=ux(),i=Um(o,Fy);Dm(i,r,i),Dm(i,t.domain,i);const s=ux(),a=ux(),l=ux();Dm(o,t.domain,s),Dm(o,t.scheme,a),Dm(o,t.slashscheme,l),Dm(s,r,i),Dm(s,t.domain,s);const c=Um(s,vy);Um(i,vy,c),Um(a,vy,c),Um(l,vy,c);const d=Um(i,Cy);Dm(d,r,i),Dm(d,t.domain,i);const u=ux();Dm(c,t.domain,u),Dm(u,t.domain,u);const p=Um(u,Cy);Dm(p,t.domain,u);const h=ux(ax);Dm(p,t.tld,h),Dm(p,t.utld,h),Um(c,qm,h);const f=Um(u,Ly);Um(f,Ly,f),Dm(f,t.domain,u),Dm(h,t.domain,u),Um(h,Cy,p),Um(h,Ly,f);const g=Um(s,Ly),m=Um(s,Cy);Um(g,Ly,g),Dm(g,t.domain,s),Dm(m,r,i),Dm(m,t.domain,s);const y=ux(dx);Dm(m,t.tld,y),Dm(m,t.utld,y),Dm(y,t.domain,s),Dm(y,r,i),Um(y,Cy,m),Um(y,Ly,g),Um(y,vy,c);const x=Um(y,Iy),w=ux(dx);Dm(x,t.numeric,w);const b=ux(dx),v=ux();Dm(b,e,b),Dm(b,n,v),Dm(v,e,b),Dm(v,n,v),Um(y,Dy,b),Um(w,Dy,b);const k=Um(a,Iy),P=Um(Um(Um(l,Iy),Dy),Dy);Dm(a,t.domain,s),Um(a,Cy,m),Um(a,Ly,g),Dm(l,t.domain,s),Um(l,Cy,m),Um(l,Ly,g),Dm(k,t.domain,b),Um(k,Dy,b),Um(k,zy,b),Dm(P,t.domain,b),Dm(P,e,b),Um(P,Dy,b);const S=[[ny,ry],[oy,iy],[sy,ay],[ly,cy],[dy,uy],[py,hy],[fy,gy],[my,yy]];for(let I=0;I<S.length;I++){const[t,r]=S[I],o=Um(b,t);Um(v,t,o);const i=ux(dx);Dm(o,e,i);const s=ux();Dm(o,n,s),Um(o,r,b),Dm(i,e,i),Dm(i,n,s),Dm(s,e,i),Dm(s,n,s),Um(i,r,b),Um(s,r,b)}return Um(o,qm,y),Um(o,ey,cx),{start:o,tokens:Yy}}(fx.scanner.tokens);for(let t=0;t<fx.pluginQueue.length;t++)fx.pluginQueue[t][1]({scanner:fx.scanner,parser:fx.parser});return fx.initialized=!0,fx}function yx(t){return fx.initialized||mx(),function(t,e,n){let r=n.length,o=0,i=[],s=[];for(;o<r;){let a=t,l=null,c=null,d=0,u=null,p=-1;for(;o<r&&!(l=a.go(n[o].t));)s.push(n[o++]);for(;o<r&&(c=l||a.go(n[o].t));)l=null,a=c,a.accepts()?(p=0,u=a):p>=0&&p++,o++,d++;if(p<0)o-=d,o<r&&(s.push(n[o]),o++);else{s.length>0&&(i.push(px(lx,e,s)),s=[]),o-=p,d-=p;const t=u.t,r=n.slice(o-d,o);i.push(px(t,e,r))}}return s.length>0&&i.push(px(lx,e,s)),i}(fx.parser.start,t,Qy(fx.scanner.start,t))}function xx(t,e=null,n=null){if(e&&"object"==typeof e){if(n)throw Error(`linkifyjs: Invalid link type ${e}; must be a string`);n=e,e=null}const r=new rx(n),o=yx(t),i=[];for(let s=0;s<o.length;s++){const t=o[s];!t.isLink||e&&t.t!==e||!r.check(t)||i.push(t.toFormattedObject(r))}return i}yx.scan=Qy;var wx="[\0-   ᠎ -\u2029  ]",bx=new RegExp(wx),vx=new RegExp(`${wx}$`),kx=new RegExp(wx,"g");function Px(t,e){const n=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(t=>{const e="string"==typeof t?t:t.scheme;e&&n.push(e)}),!t||t.replace(kx,"").match(new RegExp(`^(?:(?:${n.map(t=>t.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")).join("|")}):|[^a-z]|[a-z0-9+.\\-]+(?:[^a-z+.\\-:]|$))`,"i"))}var Sx=T.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(t=>{"string"!=typeof t?gx(t.scheme,t.optionalSlashes):gx(t)})},onDestroy(){Hm.groups={},fx.scanner=null,fx.parser=null,fx.tokenQueue=[],fx.pluginQueue=[],fx.customSchemes=[],fx.initialized=!1},inclusive(){return this.options.autolink},addOptions:()=>({openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(t,e)=>!!Px(t,e.protocols),validate:t=>!!t,shouldAutoLink:t=>{const e=/^[a-z][a-z0-9+.-]*:\/\//i.test(t),n=/^[a-z][a-z0-9+.-]*:/i.test(t);if(e||n&&!t.includes("@"))return!0;const r=(t.includes("@")?t.split("@").pop():t).split(/[/?#:]/)[0];return!/^\d{1,3}(\.\d{1,3}){3}$/.test(r)&&!!/\./.test(r)}}),addAttributes(){var t,e,n;return{href:{default:null,parseHTML:t=>t.getAttribute("href")},target:{default:null!=(t=this.options.HTMLAttributes.target)?t:null},rel:{default:null!=(e=this.options.HTMLAttributes.rel)?e:null},class:{default:null!=(n=this.options.HTMLAttributes.class)?n:null},title:{default:null}}},parseHTML(){return[{tag:"a[href]",getAttrs:t=>{const e=t.getAttribute("href");return!(!e||!this.options.isAllowedUri(e,{defaultValidate:t=>!!Px(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol}))&&null}}]},renderHTML({HTMLAttributes:t}){return this.options.isAllowedUri(t.href,{defaultValidate:t=>!!Px(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",V(this.options.HTMLAttributes,t),0]:["a",V(this.options.HTMLAttributes,{...t,href:""}),0]},markdownTokenName:"link",parseMarkdown:(t,e)=>e.applyMark("link",e.parseInline(t.tokens||[]),{href:t.href,title:t.title||null}),renderMarkdown:(t,e)=>{var n,r,o,i;const s=null!=(r=null==(n=t.attrs)?void 0:n.href)?r:"",a=null!=(i=null==(o=t.attrs)?void 0:o.title)?i:"",l=e.renderChildren(t);return a?`[${l}](${s} "${a}")`:`[${l}](${s})`},addCommands(){return{setLink:t=>({chain:e})=>{const{href:n}=t;return!!this.options.isAllowedUri(n,{defaultValidate:t=>!!Px(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})&&e().setMark(this.name,t).setMeta("preventAutolink",!0).run()},toggleLink:t=>({chain:e})=>{const{href:n}=t||{};return!(n&&!this.options.isAllowedUri(n,{defaultValidate:t=>!!Px(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol}))&&e().toggleMark(this.name,t,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()},unsetLink:()=>({chain:t})=>t().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[q({find:t=>{const e=[];if(t){const{protocols:n,defaultProtocol:r}=this.options,o=xx(t).filter(t=>t.isLink&&this.options.isAllowedUri(t.value,{defaultValidate:t=>!!Px(t,n),protocols:n,defaultProtocol:r}));o.length&&o.forEach(t=>{this.options.shouldAutoLink(t.value)&&e.push({text:t.value,data:{href:t.href},index:t.start})})}return e},type:this.type,getAttributes:t=>{var e;return{href:null==(e=t.data)?void 0:e.href}}})]},addProseMirrorPlugins(){const t=[],{protocols:e,defaultProtocol:n}=this.options;var r;return this.options.autolink&&t.push((r={type:this.type,defaultProtocol:this.options.defaultProtocol,validate:t=>this.options.isAllowedUri(t,{defaultValidate:t=>!!Px(t,e),protocols:e,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink},new rt({key:new ot("autolink"),appendTransaction:(t,e,n)=>{const o=t.some(t=>t.docChanged)&&!e.doc.eq(n.doc),i=t.some(t=>t.getMeta("preventAutolink"));if(!o||i)return;const{tr:s}=n;return N(L(e.doc,[...t])).forEach(({newRange:t})=>{const e=R(n.doc,t,t=>t.isTextblock);let o,i;if(e.length>1)o=e[0],i=n.doc.textBetween(o.pos,o.pos+o.node.nodeSize,void 0," ");else if(e.length){const r=n.doc.textBetween(t.from,t.to," "," ");if(!vx.test(r))return;o=e[0],i=n.doc.textBetween(o.pos,t.to,void 0," ")}if(o&&i){const t=i.split(bx).filter(Boolean);if(t.length<=0)return!1;const e=t[t.length-1],l=o.pos+i.lastIndexOf(e);if(!e)return!1;const c=yx(e).map(t=>t.toObject(r.defaultProtocol));if(!(1===(a=c).length?a[0].isLink:3===a.length&&a[1].isLink&&["()","[]"].includes(a[0].value+a[2].value)))return!1;c.filter(t=>t.isLink).map(t=>({...t,from:l+t.start+1,to:l+t.end+1})).filter(t=>!n.schema.marks.code||!n.doc.rangeHasMark(t.from,t.to,n.schema.marks.code)).filter(t=>r.validate(t.value)).filter(t=>r.shouldAutoLink(t.value)).forEach(t=>{O(t.from,t.to,n.doc).some(t=>t.mark.type===r.type)||s.addMark(t.from,t.to,r.type.create({href:t.href}))})}var a}),s.steps.length?s:void 0}}))),t.push(function(t){return new rt({key:new ot("handleClickLink"),props:{handleClick:(e,n,r)=>{var o,i;if(0!==r.button)return!1;if(!e.editable)return!1;let s=null;if(r.target instanceof HTMLAnchorElement)s=r.target;else{const e=r.target;if(!e)return!1;const n=t.editor.view.dom;s=e.closest("a"),s&&!n.contains(s)&&(s=null)}if(!s)return!1;let a=!1;if(t.enableClickSelection&&(a=t.editor.commands.extendMarkRange(t.type.name)),t.openOnClick){const n=$(e.state,t.type.name),r=null!=(o=s.href)?o:n.href,l=null!=(i=s.target)?i:n.target;r&&(window.open(r,l),a=!0)}return a}}})}({type:this.type,editor:this.editor,openOnClick:"whenNotEditable"===this.options.openOnClick||this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&t.push(function(t){return new rt({key:new ot("handlePasteLink"),props:{handlePaste:(e,n,r)=>{const{shouldAutoLink:o}=t,{state:i}=e,{selection:s}=i,{empty:a}=s;if(a)return!1;let l="";r.content.forEach(t=>{l+=t.textContent});const c=xx(l,{defaultProtocol:t.defaultProtocol}).find(t=>t.isLink&&t.value===l);return!(!l||!c||void 0!==o&&!o(c.value))&&t.editor.commands.setMark(t.type,{href:c.href})}}})}({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),t}}),Ix=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Mx=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,Tx=T.create({name:"strike",addOptions:()=>({HTMLAttributes:{}}),parseHTML:()=>[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:t=>!!t.includes("line-through")&&{}}],renderHTML({HTMLAttributes:t}){return["s",V(this.options.HTMLAttributes,t),0]},markdownTokenName:"del",parseMarkdown:(t,e)=>e.applyMark("strike",e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>`~~${e.renderChildren(t)}~~`,addCommands(){return{setStrike:()=>({commands:t})=>t.setMark(this.name),toggleStrike:()=>({commands:t})=>t.toggleMark(this.name),unsetStrike:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[_({find:Ix,type:this.type})]},addPasteRules(){return[q({find:Mx,type:this.type})]}}),Cx=M.create({name:"textAlign",addOptions:()=>({types:[],alignments:["left","center","right","justify"],defaultAlignment:null}),addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:t=>{const e=t.style.textAlign;return this.options.alignments.includes(e)?e:this.options.defaultAlignment},renderHTML:t=>t.textAlign?{style:`text-align: ${t.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:t=>({commands:e})=>!!this.options.alignments.includes(t)&&this.options.types.map(n=>e.updateAttributes(n,{textAlign:t})).some(t=>t),unsetTextAlign:()=>({commands:t})=>this.options.types.map(e=>t.resetAttributes(e,"textAlign")).some(t=>t),toggleTextAlign:t=>({editor:e,commands:n})=>!!this.options.alignments.includes(t)&&(e.isActive({textAlign:t})?n.unsetTextAlign():n.setTextAlign(t))}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign("left"),"Mod-Shift-e":()=>this.editor.commands.setTextAlign("center"),"Mod-Shift-r":()=>this.editor.commands.setTextAlign("right"),"Mod-Shift-j":()=>this.editor.commands.setTextAlign("justify")}}}),Ax=(t,e=0)=>{const n=[];return!t.children.length||e>20||Array.from(t.children).forEach(t=>{"SPAN"===t.tagName?n.push(t):t.children.length&&n.push(...Ax(t,e+1))}),n},Ex=T.create({name:"textStyle",priority:101,addOptions:()=>({HTMLAttributes:{},mergeNestedSpanStyles:!0}),parseHTML(){return[{tag:"span",consuming:!1,getAttrs:t=>!!t.hasAttribute("style")&&(this.options.mergeNestedSpanStyles&&(t=>{if(!t.children.length)return;const e=Ax(t);e&&e.forEach(t=>{var e,n;const r=t.getAttribute("style"),o=null==(n=null==(e=t.parentElement)?void 0:e.closest("span"))?void 0:n.getAttribute("style");t.setAttribute("style",`${o};${r}`)})})(t),{})}]},renderHTML({HTMLAttributes:t}){return["span",V(this.options.HTMLAttributes,t),0]},addCommands(){return{toggleTextStyle:t=>({commands:e})=>e.toggleMark(this.name,t),removeEmptyTextStyle:()=>({tr:t})=>{const{selection:e}=t;return t.doc.nodesBetween(e.from,e.to,(e,n)=>{if(e.isTextblock)return!0;e.marks.filter(t=>t.type===this.type).some(t=>Object.values(t.attrs).some(t=>!!t))||t.removeMark(n,n+e.nodeSize,this.type)}),!0}}}}),Lx=M.create({name:"backgroundColor",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{backgroundColor:{default:null,parseHTML:t=>{var e;const n=null!=(e=F(t,"background-color"))?e:t.style.backgroundColor;return null==n?void 0:n.replace(/['"]+/g,"")},renderHTML:t=>t.backgroundColor?{style:`background-color: ${t.backgroundColor}`}:{}}}}]},addCommands:()=>({setBackgroundColor:t=>({chain:e})=>e().setMark("textStyle",{backgroundColor:t}).run(),unsetBackgroundColor:()=>({chain:t})=>t().setMark("textStyle",{backgroundColor:null}).removeEmptyTextStyle().run()})}),Bx=M.create({name:"color",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{color:{default:null,parseHTML:t=>{var e;const n=null!=(e=F(t,"color"))?e:t.style.color;return null==n?void 0:n.replace(/['"]+/g,"")},renderHTML:t=>t.color?{style:`color: ${t.color}`}:{}}}}]},addCommands:()=>({setColor:t=>({chain:e})=>e().setMark("textStyle",{color:t}).run(),unsetColor:()=>({chain:t})=>t().setMark("textStyle",{color:null}).removeEmptyTextStyle().run()})}),Rx=M.create({name:"fontFamily",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{fontFamily:{default:null,parseHTML:t=>{var e;return null!=(e=F(t,"font-family"))?e:t.style.fontFamily},renderHTML:t=>t.fontFamily?{style:`font-family: ${t.fontFamily}`}:{}}}}]},addCommands:()=>({setFontFamily:t=>({chain:e})=>e().setMark("textStyle",{fontFamily:t}).run(),unsetFontFamily:()=>({chain:t})=>t().setMark("textStyle",{fontFamily:null}).removeEmptyTextStyle().run()})}),$x=M.create({name:"fontSize",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{fontSize:{default:null,parseHTML:t=>{var e;return null!=(e=F(t,"font-size"))?e:t.style.fontSize},renderHTML:t=>t.fontSize?{style:`font-size: ${t.fontSize}`}:{}}}}]},addCommands:()=>({setFontSize:t=>({chain:e})=>e().setMark("textStyle",{fontSize:t}).run(),unsetFontSize:()=>({chain:t})=>t().setMark("textStyle",{fontSize:null}).removeEmptyTextStyle().run()})}),Nx=M.create({name:"lineHeight",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{lineHeight:{default:null,parseHTML:t=>{var e;return null!=(e=F(t,"line-height"))?e:t.style.lineHeight},renderHTML:t=>t.lineHeight?{style:`line-height: ${t.lineHeight}`}:{}}}}]},addCommands:()=>({setLineHeight:t=>({chain:e})=>e().setMark("textStyle",{lineHeight:t}).run(),unsetLineHeight:()=>({chain:t})=>t().setMark("textStyle",{lineHeight:null}).removeEmptyTextStyle().run()})}),zx=(M.create({name:"textStyleKit",addExtensions(){const t=[];return!1!==this.options.backgroundColor&&t.push(Lx.configure(this.options.backgroundColor)),!1!==this.options.color&&t.push(Bx.configure(this.options.color)),!1!==this.options.fontFamily&&t.push(Rx.configure(this.options.fontFamily)),!1!==this.options.fontSize&&t.push($x.configure(this.options.fontSize)),!1!==this.options.lineHeight&&t.push(Nx.configure(this.options.lineHeight)),!1!==this.options.textStyle&&t.push(Ex.configure(this.options.textStyle)),t}}),T.create({name:"underline",addOptions:()=>({HTMLAttributes:{}}),parseHTML:()=>[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:t=>!!t.includes("underline")&&{}}],renderHTML({HTMLAttributes:t}){return["u",V(this.options.HTMLAttributes,t),0]},parseMarkdown(t,e){return e.applyMark(this.name||"underline",e.parseInline(t.tokens||[]))},renderMarkdown:(t,e)=>`++${e.renderChildren(t)}++`,markdownTokenizer:{name:"underline",level:"inline",start:t=>t.indexOf("++"),tokenize(t,e,n){const r=/^(\+\+)([\s\S]+?)(\+\+)/.exec(t);if(!r)return;const o=r[2].trim();return{type:"underline",raw:r[0],text:o,tokens:n.inlineTokens(o)}}},addCommands(){return{setUnderline:()=>({commands:t})=>t.setMark(this.name),toggleUnderline:()=>({commands:t})=>t.toggleMark(this.name),unsetUnderline:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}})),Ox=M.create({name:"selection",addOptions:()=>({className:"selection"}),addProseMirrorPlugins(){const{editor:t,options:e}=this;return t.options.injectCSS&&"undefined"!=typeof document&&B(".ProseMirror:not(.ProseMirror-focused) *::selection {\n background: transparent;\n}\n\n.ProseMirror:not(.ProseMirror-focused) *::-moz-selection {\n background: transparent;\n}",t.options.injectNonce,"selection"),[new rt({key:new ot("selection"),props:{decorations:n=>n.selection.empty||t.isFocused||!t.isEditable||K(n.selection)||t.view.dragging?null:lt.create(n.doc,[at.inline(n.selection.from,n.selection.to,{class:e.className})])}})]}});function Wx(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let o=t.child(r),i=e.child(r);if(o!=i){if(!o.sameMarkup(i))return n;if(o.isText&&o.text!=i.text){let t=o.text,e=i.text,r=0;for(;t[r]==e[r];r++)n++;return r&&r<t.length&&r<e.length&&Fx(t.charCodeAt(r-1))&&Dx(t.charCodeAt(r))&&n--,n}if(o.content.size||i.content.size){let t=Wx(o.content,i.content,n+1);if(null!=t)return t}n+=o.nodeSize}else n+=o.nodeSize}}function Hx(t,e,n,r){for(let o=t.childCount,i=e.childCount;;){if(0==o||0==i)return o==i?null:{a:n,b:r};let s=t.child(--o),a=e.child(--i),l=s.nodeSize;if(s!=a){if(!s.sameMarkup(a))return{a:n,b:r};if(s.isText&&s.text!=a.text){let t=s.text,e=a.text,o=t.length,i=e.length;for(;o>0&&i>0&&t[o-1]==e[i-1];)o--,i--,n--,r--;return o&&i&&o<t.length&&Fx(t.charCodeAt(o-1))&&Dx(t.charCodeAt(o))&&(n++,r++),{a:n,b:r}}if(s.content.size||a.content.size){let t=Hx(s.content,a.content,n-1,r-1);if(t)return t}n-=l,r-=l}else n-=l,r-=l}}function Dx(t){return t>=56320&&t<57344}function Fx(t){return t>=55296&&t<56320}var jx=class t{constructor(t,e){if(this.content=t,this.size=e||0,null==e)for(let n=0;n<t.length;n++)this.size+=t[n].nodeSize}nodesBetween(t,e,n,r=0,o){for(let i=0,s=0;s<e;i++){let a=this.content[i],l=s+a.nodeSize;if(l>t&&!1!==n(a,r+s,o||null,i)&&a.content.size){let o=s+1;a.nodesBetween(Math.max(0,t-o),Math.min(a.content.size,e-o),n,r+o)}s=l}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,e,n,r){let o="",i=!0;return this.nodesBetween(t,e,(s,a)=>{let l=s.isText?s.text.slice(Math.max(t,a)-a,e-a):s.isLeaf?r?"function"==typeof r?r(s):r:s.type.spec.leafText?s.type.spec.leafText(s):"":"";s.isBlock&&(s.isLeaf&&l||s.isTextblock)&&n&&(i?i=!1:o+=n),o+=l},0),o}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,o=this.content.slice(),i=0;for(n.isText&&n.sameMarkup(r)&&(o[o.length-1]=n.withText(n.text+r.text),i=1);i<e.content.length;i++)o.push(e.content[i]);return new t(o,this.size+e.size)}cut(e,n=this.size){if(0==e&&n==this.size)return this;let r=[],o=0;if(n>e)for(let t=0,i=0;i<n;t++){let s=this.content[t],a=i+s.nodeSize;a>e&&((i<e||a>n)&&(s=s.isText?s.cut(Math.max(0,e-i),Math.min(s.text.length,n-i)):s.cut(Math.max(0,e-i-1),Math.min(s.content.size,n-i-1))),r.push(s),o+=s.nodeSize),i=a}return new t(r,o)}cutByIndex(e,n){return e==n?t.empty:0==e&&n==this.content.length?this:new t(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let o=this.content.slice(),i=this.size+n.nodeSize-r.nodeSize;return o[e]=n,new t(o,i)}addToStart(e){return new t([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new t(this.content.concat(e),this.size+e.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let e=0;e<this.content.length;e++)if(!this.content[e].eq(t.content[e]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(t){let e=this.content[t];if(!e)throw new RangeError("Index "+t+" out of range for "+this);return e}maybeChild(t){return this.content[t]||null}forEach(t){for(let e=0,n=0;e<this.content.length;e++){let r=this.content[e];t(r,n,e),n+=r.nodeSize}}findDiffStart(t,e=0){return Wx(this,t,e)}findDiffEnd(t,e=this.size,n=t.size){return Hx(this,t,e,n)}findIndex(t){if(0==t)return Xx(0,t);if(t==this.size)return Xx(this.content.length,t);if(t>this.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let e=0,n=0;;e++){let r=n+this.child(e).nodeSize;if(r>=t)return r==t?Xx(e+1,r):Xx(e,n);n=r}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(t=>t.toJSON()):null}static fromJSON(e,n){if(!n)return t.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return t.fromArray(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return t.empty;let n,r=0;for(let t=0;t<e.length;t++){let o=e[t];r+=o.nodeSize,t&&o.isText&&e[t-1].sameMarkup(o)?(n||(n=e.slice(0,t)),n[n.length-1]=o.withText(n[n.length-1].text+o.text)):n&&n.push(o)}return new t(n||e,r)}static from(e){if(!e)return t.empty;if(e instanceof t)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new t([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}};jx.empty=new jx([],0);var Ux={index:0,offset:0};function Xx(t,e){return Ux.index=t,Ux.offset=e,Ux}function Yx(t,e){if(t===e)return!0;if(!t||"object"!=typeof t||!e||"object"!=typeof e)return!1;let n=Array.isArray(t);if(Array.isArray(e)!=n)return!1;if(n){if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!Yx(t[n],e[n]))return!1}else{for(let n in t)if(!(n in e)||!Yx(t[n],e[n]))return!1;for(let n in e)if(!(n in t))return!1}return!0}var Kx=class t{constructor(t,e){this.type=t,this.attrs=e}addToSet(t){let e,n=!1;for(let r=0;r<t.length;r++){let o=t[r];if(this.eq(o))return t;if(this.type.excludes(o.type))e||(e=t.slice(0,r));else{if(o.type.excludes(this.type))return t;!n&&o.type.rank>this.type.rank&&(e||(e=t.slice(0,r)),e.push(this),n=!0),e&&e.push(o)}}return e||(e=t.slice()),n||e.push(this),e}removeFromSet(t){for(let e=0;e<t.length;e++)if(this.eq(t[e]))return t.slice(0,e).concat(t.slice(e+1));return t}isInSet(t){for(let e=0;e<t.length;e++)if(this.eq(t[e]))return!0;return!1}eq(t){return this==t||this.type==t.type&&Yx(this.attrs,t.attrs)}toJSON(){let t={type:this.type.name};for(let e in this.attrs){t.attrs=this.attrs;break}return t}static fromJSON(t,e){if(!e)throw new RangeError("Invalid input for Mark.fromJSON");let n=t.marks[e.type];if(!n)throw new RangeError(`There is no mark type ${e.type} in this schema`);let r=n.create(e.attrs);return n.checkAttrs(r.attrs),r}static sameSet(t,e){if(t==e)return!0;if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!t[n].eq(e[n]))return!1;return!0}static setFrom(e){if(!e||Array.isArray(e)&&0==e.length)return t.none;if(e instanceof t)return[e];let n=e.slice();return n.sort((t,e)=>t.type.rank-e.type.rank),n}};Kx.none=[];var _x=class extends Error{},qx=class t{constructor(t,e,n){this.content=t,this.openStart=e,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let r=Gx(this.content,e+this.openStart,n,this.openStart+1,this.openEnd+1);return r&&new t(r,this.openStart,this.openEnd)}removeBetween(e,n){return new t(Vx(this.content,e+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(e,n){if(!n)return t.empty;let r=n.openStart||0,o=n.openEnd||0;if("number"!=typeof r||"number"!=typeof o)throw new RangeError("Invalid input for Slice.fromJSON");return new t(jx.fromJSON(e,n.content),r,o)}static maxOpen(e,n=!0){let r=0,o=0;for(let t=e.firstChild;t&&!t.isLeaf&&(n||!t.type.spec.isolating);t=t.firstChild)r++;for(let t=e.lastChild;t&&!t.isLeaf&&(n||!t.type.spec.isolating);t=t.lastChild)o++;return new t(e,r,o)}};function Vx(t,e,n){let{index:r,offset:o}=t.findIndex(e),i=t.maybeChild(r),{index:s,offset:a}=t.findIndex(n);if(o==e||i.isText){if(a!=n&&!t.child(s).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=s)throw new RangeError("Removing non-flat range");return t.replaceChild(r,i.copy(Vx(i.content,e-o-1,n-o-1)))}function Gx(t,e,n,r,o,i){let{index:s,offset:a}=t.findIndex(e),l=t.maybeChild(s);if(a==e||l.isText)return i&&r<=0&&o<=0&&!i.canReplace(s,s,n)?null:t.cut(0,e).append(n).append(t.cut(e));let c=Gx(l.content,e-a-1,n,0==s?r-1:0,s==t.childCount-1?o-1:0,l);return c&&t.replaceChild(s,l.copy(c))}qx.empty=new qx(jx.empty,0,0);var Jx=class t{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new Zx(e,n);if(null==r.next)return t.empty;let o=Qx(r);r.next&&r.err("Unexpected trailing text");let i=function(t){let e=Object.create(null);return n(iw(t,0));function n(r){let o=[];r.forEach(e=>{t[e].forEach(({term:e,to:n})=>{if(!e)return;let r;for(let t=0;t<o.length;t++)o[t][0]==e&&(r=o[t][1]);iw(t,n).forEach(t=>{r||o.push([e,r=[]]),-1==r.indexOf(t)&&r.push(t)})})});let i=e[r.join(",")]=new Jx(r.indexOf(t.length-1)>-1);for(let t=0;t<o.length;t++){let r=o[t][1].sort(ow);i.next.push({type:o[t][0],next:e[r.join(",")]||n(r)})}return i}}(function(t){let e=[[]];return o(i(t,0),n()),e;function n(){return e.push([])-1}function r(t,n,r){let o={term:r,to:n};return e[t].push(o),o}function o(t,e){t.forEach(t=>t.to=e)}function i(t,e){if("choice"==t.type)return t.exprs.reduce((t,n)=>t.concat(i(n,e)),[]);if("seq"!=t.type){if("star"==t.type){let s=n();return r(e,s),o(i(t.expr,s),s),[r(s)]}if("plus"==t.type){let s=n();return o(i(t.expr,e),s),o(i(t.expr,s),s),[r(s)]}if("opt"==t.type)return[r(e)].concat(i(t.expr,e));if("range"==t.type){let s=e;for(let e=0;e<t.min;e++){let e=n();o(i(t.expr,s),e),s=e}if(-1==t.max)o(i(t.expr,s),s);else for(let e=t.min;e<t.max;e++){let e=n();r(s,e),o(i(t.expr,s),e),s=e}return[r(s)]}if("name"==t.type)return[r(e,void 0,t.value)];throw new Error("Unknown expr type")}for(let r=0;;r++){let s=i(t.exprs[r],e);if(r==t.exprs.length-1)return s;o(s,e=n())}}}(o));return function(t,e){for(let n=0,r=[t];n<r.length;n++){let t=r[n],o=!t.validEnd,i=[];for(let e=0;e<t.next.length;e++){let{type:n,next:s}=t.next[e];i.push(n.name),!o||n.isText||n.hasRequiredAttrs()||(o=!1),-1==r.indexOf(s)&&r.push(s)}o&&e.err("Only non-generatable nodes ("+i.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}(i,r),i}matchType(t){for(let e=0;e<this.next.length;e++)if(this.next[e].type==t)return this.next[e].next;return null}matchFragment(t,e=0,n=t.childCount){let r=this;for(let o=e;r&&o<n;o++)r=r.matchType(t.child(o).type);return r}get inlineContent(){return 0!=this.next.length&&this.next[0].type.isInline}get defaultType(){for(let t=0;t<this.next.length;t++){let{type:e}=this.next[t];if(!e.isText&&!e.hasRequiredAttrs())return e}return null}compatible(t){for(let e=0;e<this.next.length;e++)for(let n=0;n<t.next.length;n++)if(this.next[e].type==t.next[n].type)return!0;return!1}fillBefore(t,e=!1,n=0){let r=[this];return function o(i,s){let a=i.matchFragment(t,n);if(a&&(!e||a.validEnd))return jx.from(s.map(t=>t.createAndFill()));for(let t=0;t<i.next.length;t++){let{type:e,next:n}=i.next[t];if(!e.isText&&!e.hasRequiredAttrs()&&-1==r.indexOf(n)){r.push(n);let t=o(n,s.concat(e));if(t)return t}}return null}(this,[])}findWrapping(t){for(let n=0;n<this.wrapCache.length;n+=2)if(this.wrapCache[n]==t)return this.wrapCache[n+1];let e=this.computeWrapping(t);return this.wrapCache.push(t,e),e}computeWrapping(t){let e=Object.create(null),n=[{match:this,type:null,via:null}];for(;n.length;){let r=n.shift(),o=r.match;if(o.matchType(t)){let t=[];for(let e=r;e.type;e=e.via)t.push(e.type);return t.reverse()}for(let t=0;t<o.next.length;t++){let{type:i,next:s}=o.next[t];i.isLeaf||i.hasRequiredAttrs()||i.name in e||r.type&&!s.validEnd||(n.push({match:i.contentMatch,type:i,via:r}),e[i.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(t){if(t>=this.next.length)throw new RangeError(`There's no ${t}th edge in this content match`);return this.next[t]}toString(){let t=[];return function e(n){t.push(n);for(let r=0;r<n.next.length;r++)-1==t.indexOf(n.next[r].next)&&e(n.next[r].next)}(this),t.map((e,n)=>{let r=n+(e.validEnd?"*":" ")+" ";for(let o=0;o<e.next.length;o++)r+=(o?", ":"")+e.next[o].type.name+"->"+t.indexOf(e.next[o].next);return r}).join("\n")}};Jx.empty=new Jx(!0);var Zx=class{constructor(t,e){this.string=t,this.nodeTypes=e,this.inline=null,this.pos=0,this.tokens=t.split(/\s*(?=\b|\W|$)/),""==this.tokens[this.tokens.length-1]&&this.tokens.pop(),""==this.tokens[0]&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(t){return this.next==t&&(this.pos++||!0)}err(t){throw new SyntaxError(t+" (in content expression '"+this.string+"')")}};function Qx(t){let e=[];do{e.push(tw(t))}while(t.eat("|"));return 1==e.length?e[0]:{type:"choice",exprs:e}}function tw(t){let e=[];do{e.push(ew(t))}while(t.next&&")"!=t.next&&"|"!=t.next);return 1==e.length?e[0]:{type:"seq",exprs:e}}function ew(t){let e=function(t){if(t.eat("(")){let e=Qx(t);return t.eat(")")||t.err("Missing closing paren"),e}if(!/\W/.test(t.next)){let e=function(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let o=[];for(let i in n){let t=n[i];t.isInGroup(e)&&o.push(t)}0==o.length&&t.err("No node type or group '"+e+"' found");return o}(t,t.next).map(e=>(null==t.inline?t.inline=e.isInline:t.inline!=e.isInline&&t.err("Mixing inline and block content"),{type:"name",value:e}));return t.pos++,1==e.length?e[0]:{type:"choice",exprs:e}}t.err("Unexpected token '"+t.next+"'")}(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else{if(!t.eat("{"))break;e=rw(t,e)}return e}function nw(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function rw(t,e){let n=nw(t),r=n;return t.eat(",")&&(r="}"!=t.next?nw(t):-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function ow(t,e){return e-t}function iw(t,e){let n=[];return function e(r){let o=t[r];if(1==o.length&&!o[0].term)return e(o[0].to);n.push(r);for(let t=0;t<o.length;t++){let{term:r,to:i}=o[t];r||-1!=n.indexOf(i)||e(i)}}(e),n.sort(ow)}var sw=Math.pow(2,16);function aw(t,e){return t+e*sw}function lw(t){return 65535&t}var cw=class{constructor(t,e,n){this.pos=t,this.delInfo=e,this.recover=n}get deleted(){return(8&this.delInfo)>0}get deletedBefore(){return(5&this.delInfo)>0}get deletedAfter(){return(6&this.delInfo)>0}get deletedAcross(){return(4&this.delInfo)>0}},dw=class t{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&t.empty)return t.empty}recover(t){let e=0,n=lw(t);if(!this.inverted)for(let r=0;r<n;r++)e+=this.ranges[3*r+2]-this.ranges[3*r+1];return this.ranges[3*n]+e+function(t){return(t-(65535&t))/sw}(t)}mapResult(t,e=1){return this._map(t,e,!1)}map(t,e=1){return this._map(t,e,!0)}_map(t,e,n){let r=0,o=this.inverted?2:1,i=this.inverted?1:2;for(let s=0;s<this.ranges.length;s+=3){let a=this.ranges[s]-(this.inverted?r:0);if(a>t)break;let l=this.ranges[s+o],c=this.ranges[s+i],d=a+l;if(t<=d){let o=a+r+((l?t==a?-1:t==d?1:e:e)<0?0:c);if(n)return o;let i=t==(e<0?a:d)?null:aw(s/3,t-a),u=t==a?2:t==d?1:4;return(e<0?t!=a:t!=d)&&(u|=8),new cw(o,u,i)}r+=c-l}return n?t+r:new cw(t+r,0,null)}touches(t,e){let n=0,r=lw(e),o=this.inverted?2:1,i=this.inverted?1:2;for(let s=0;s<this.ranges.length;s+=3){let e=this.ranges[s]-(this.inverted?n:0);if(e>t)break;let a=this.ranges[s+o];if(t<=e+a&&s==3*r)return!0;n+=this.ranges[s+i]-a}return!1}forEach(t){let e=this.inverted?2:1,n=this.inverted?1:2;for(let r=0,o=0;r<this.ranges.length;r+=3){let i=this.ranges[r],s=i-(this.inverted?o:0),a=i+(this.inverted?0:o),l=this.ranges[r+e],c=this.ranges[r+n];t(s,s+l,a,a+c),o+=c-l}}invert(){return new t(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return 0==e?t.empty:new t(e<0?[0,-e,0]:[0,0,e])}};dw.empty=new dw([]);var uw=Object.create(null),pw=class{getMap(){return dw.empty}merge(t){return null}static fromJSON(t,e){if(!e||!e.stepType)throw new RangeError("Invalid input for Step.fromJSON");let n=uw[e.stepType];if(!n)throw new RangeError(`No step type ${e.stepType} defined`);return n.fromJSON(t,e)}static jsonID(t,e){if(t in uw)throw new RangeError("Duplicate use of step JSON ID "+t);return uw[t]=e,e.prototype.jsonID=t,e}},hw=class t{constructor(t,e){this.doc=t,this.failed=e}static ok(e){return new t(e,null)}static fail(e){return new t(null,e)}static fromReplace(e,n,r,o){try{return t.ok(e.replace(n,r,o))}catch(i){if(i instanceof _x)return t.fail(i.message);throw i}}};function fw(t,e,n){let r=[];for(let o=0;o<t.childCount;o++){let i=t.child(o);i.content.size&&(i=i.copy(fw(i.content,e,i))),i.isInline&&(i=e(i,n,o)),r.push(i)}return jx.fromArray(r)}var gw=class t extends pw{constructor(t,e,n){super(),this.from=t,this.to=e,this.mark=n}apply(t){let e=t.slice(this.from,this.to),n=t.resolve(this.from),r=n.node(n.sharedDepth(this.to)),o=new qx(fw(e.content,(t,e)=>t.isAtom&&e.type.allowsMarkType(this.mark.type)?t.mark(this.mark.addToSet(t.marks)):t,r),e.openStart,e.openEnd);return hw.fromReplace(t,this.from,this.to,o)}invert(){return new mw(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new t(n.pos,r.pos,this.mark)}merge(e){return e instanceof t&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new t(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if("number"!=typeof n.from||"number"!=typeof n.to)throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new t(n.from,n.to,e.markFromJSON(n.mark))}};pw.jsonID("addMark",gw);var mw=class t extends pw{constructor(t,e,n){super(),this.from=t,this.to=e,this.mark=n}apply(t){let e=t.slice(this.from,this.to),n=new qx(fw(e.content,t=>t.mark(this.mark.removeFromSet(t.marks)),t),e.openStart,e.openEnd);return hw.fromReplace(t,this.from,this.to,n)}invert(){return new gw(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new t(n.pos,r.pos,this.mark)}merge(e){return e instanceof t&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new t(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if("number"!=typeof n.from||"number"!=typeof n.to)throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new t(n.from,n.to,e.markFromJSON(n.mark))}};pw.jsonID("removeMark",mw);var yw=class t extends pw{constructor(t,e){super(),this.pos=t,this.mark=e}apply(t){let e=t.nodeAt(this.pos);if(!e)return hw.fail("No node at mark step's position");let n=e.type.create(e.attrs,null,this.mark.addToSet(e.marks));return hw.fromReplace(t,this.pos,this.pos+1,new qx(jx.from(n),0,e.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);if(n){let e=this.mark.addToSet(n.marks);if(e.length==n.marks.length){for(let r=0;r<n.marks.length;r++)if(!n.marks[r].isInSet(e))return new t(this.pos,n.marks[r]);return new t(this.pos,this.mark)}}return new xw(this.pos,this.mark)}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new t(n.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,n){if("number"!=typeof n.pos)throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new t(n.pos,e.markFromJSON(n.mark))}};pw.jsonID("addNodeMark",yw);var xw=class t extends pw{constructor(t,e){super(),this.pos=t,this.mark=e}apply(t){let e=t.nodeAt(this.pos);if(!e)return hw.fail("No node at mark step's position");let n=e.type.create(e.attrs,null,this.mark.removeFromSet(e.marks));return hw.fromReplace(t,this.pos,this.pos+1,new qx(jx.from(n),0,e.isLeaf?0:1))}invert(t){let e=t.nodeAt(this.pos);return e&&this.mark.isInSet(e.marks)?new yw(this.pos,this.mark):this}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new t(n.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,n){if("number"!=typeof n.pos)throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new t(n.pos,e.markFromJSON(n.mark))}};pw.jsonID("removeNodeMark",xw);var ww=class t extends pw{constructor(t,e,n,r=!1){super(),this.from=t,this.to=e,this.slice=n,this.structure=r}apply(t){return this.structure&&vw(t,this.from,this.to)?hw.fail("Structure replace would overwrite content"):hw.fromReplace(t,this.from,this.to,this.slice)}getMap(){return new dw([this.from,this.to-this.from,this.slice.size])}invert(e){return new t(this.from,this.from+this.slice.size,e.slice(this.from,this.to))}map(e){let n=e.mapResult(this.to,-1),r=this.from==this.to&&t.MAP_BIAS<0?n:e.mapResult(this.from,1);return r.deletedAcross&&n.deletedAcross?null:new t(r.pos,Math.max(r.pos,n.pos),this.slice,this.structure)}merge(e){if(!(e instanceof t)||e.structure||this.structure)return null;if(this.from+this.slice.size!=e.from||this.slice.openEnd||e.slice.openStart){if(e.to!=this.from||this.slice.openStart||e.slice.openEnd)return null;{let n=this.slice.size+e.slice.size==0?qx.empty:new qx(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new t(e.from,this.to,n,this.structure)}}{let n=this.slice.size+e.slice.size==0?qx.empty:new qx(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new t(this.from,this.to+(e.to-e.from),n,this.structure)}}toJSON(){let t={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(e,n){if("number"!=typeof n.from||"number"!=typeof n.to)throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new t(n.from,n.to,qx.fromJSON(e,n.slice),!!n.structure)}};ww.MAP_BIAS=1,pw.jsonID("replace",ww);var bw=class t extends pw{constructor(t,e,n,r,o,i,s=!1){super(),this.from=t,this.to=e,this.gapFrom=n,this.gapTo=r,this.slice=o,this.insert=i,this.structure=s}apply(t){if(this.structure&&(vw(t,this.from,this.gapFrom)||vw(t,this.gapTo,this.to)))return hw.fail("Structure gap-replace would overwrite content");let e=t.slice(this.gapFrom,this.gapTo);if(e.openStart||e.openEnd)return hw.fail("Gap is not a flat range");let n=this.slice.insertAt(this.insert,e.content);return n?hw.fromReplace(t,this.from,this.to,n):hw.fail("Content does not fit in gap")}getMap(){return new dw([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(e){let n=this.gapTo-this.gapFrom;return new t(this.from,this.from+this.slice.size+n,this.from+this.insert,this.from+this.insert+n,e.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1),o=this.from==this.gapFrom?n.pos:e.map(this.gapFrom,-1),i=this.to==this.gapTo?r.pos:e.map(this.gapTo,1);return n.deletedAcross&&r.deletedAcross||o<n.pos||i>r.pos?null:new t(n.pos,r.pos,o,i,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(e,n){if("number"!=typeof n.from||"number"!=typeof n.to||"number"!=typeof n.gapFrom||"number"!=typeof n.gapTo||"number"!=typeof n.insert)throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new t(n.from,n.to,n.gapFrom,n.gapTo,qx.fromJSON(e,n.slice),n.insert,!!n.structure)}};function vw(t,e,n){let r=t.resolve(e),o=n-e,i=r.depth;for(;o>0&&i>0&&r.indexAfter(i)==r.node(i).childCount;)i--,o--;if(o>0){let t=r.node(i).maybeChild(r.indexAfter(i));for(;o>0;){if(!t||t.isLeaf)return!0;t=t.firstChild,o--}}return!1}pw.jsonID("replaceAround",bw);pw.jsonID("attr",class t extends pw{constructor(t,e,n){super(),this.pos=t,this.attr=e,this.value=n}apply(t){let e=t.nodeAt(this.pos);if(!e)return hw.fail("No node at attribute step's position");let n=Object.create(null);for(let o in e.attrs)n[o]=e.attrs[o];n[this.attr]=this.value;let r=e.type.create(n,null,e.marks);return hw.fromReplace(t,this.pos,this.pos+1,new qx(jx.from(r),0,e.isLeaf?0:1))}getMap(){return dw.empty}invert(e){return new t(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new t(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,n){if("number"!=typeof n.pos||"string"!=typeof n.attr)throw new RangeError("Invalid input for AttrStep.fromJSON");return new t(n.pos,n.attr,n.value)}});pw.jsonID("docAttr",class t extends pw{constructor(t,e){super(),this.attr=t,this.value=e}apply(t){let e=Object.create(null);for(let r in t.attrs)e[r]=t.attrs[r];e[this.attr]=this.value;let n=t.type.create(e,t.content,t.marks);return hw.ok(n)}getMap(){return dw.empty}invert(e){return new t(this.attr,e.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,n){if("string"!=typeof n.attr)throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new t(n.attr,n.value)}});var kw=Error;((kw=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n}).prototype=Object.create(Error.prototype)).constructor=kw,kw.prototype.name="TransformError";var Pw=Object.create(null),Sw=class{constructor(t,e,n){this.$anchor=t,this.$head=e,this.ranges=n||[new Iw(t.min(e),t.max(e))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let t=this.ranges;for(let e=0;e<t.length;e++)if(t[e].$from.pos!=t[e].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(t,e=qx.empty){let n=e.content.lastChild,r=null;for(let s=0;s<e.openEnd;s++)r=n,n=n.lastChild;let o=t.steps.length,i=this.ranges;for(let s=0;s<i.length;s++){let{$from:a,$to:l}=i[s],c=t.mapping.slice(o);t.replaceRange(c.map(a.pos),c.map(l.pos),s?qx.empty:e),0==s&&Nw(t,o,(n?n.isInline:r&&r.isTextblock)?-1:1)}}replaceWith(t,e){let n=t.steps.length,r=this.ranges;for(let o=0;o<r.length;o++){let{$from:i,$to:s}=r[o],a=t.mapping.slice(n),l=a.map(i.pos),c=a.map(s.pos);o?t.deleteRange(l,c):(t.replaceRangeWith(l,c,e),Nw(t,n,e.isInline?-1:1))}}static findFrom(t,e,n=!1){let r=t.parent.inlineContent?new Cw(t):$w(t.node(0),t.parent,t.pos,t.index(),e,n);if(r)return r;for(let o=t.depth-1;o>=0;o--){let r=e<0?$w(t.node(0),t.node(o),t.before(o+1),t.index(o),e,n):$w(t.node(0),t.node(o),t.after(o+1),t.index(o)+1,e,n);if(r)return r}return null}static near(t,e=1){return this.findFrom(t,e)||this.findFrom(t,-e)||new Bw(t.node(0))}static atStart(t){return $w(t,t,0,0,1)||new Bw(t)}static atEnd(t){return $w(t,t,t.content.size,t.childCount,-1)||new Bw(t)}static fromJSON(t,e){if(!e||!e.type)throw new RangeError("Invalid input for Selection.fromJSON");let n=Pw[e.type];if(!n)throw new RangeError(`No selection type ${e.type} defined`);return n.fromJSON(t,e)}static jsonID(t,e){if(t in Pw)throw new RangeError("Duplicate use of selection JSON ID "+t);return Pw[t]=e,e.prototype.jsonID=t,e}getBookmark(){return Cw.between(this.$anchor,this.$head).getBookmark()}};Sw.prototype.visible=!0;var Iw=class{constructor(t,e){this.$from=t,this.$to=e}},Mw=!1;function Tw(t){Mw||t.parent.inlineContent||(Mw=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}var Cw=class t extends Sw{constructor(t,e=t){Tw(t),Tw(e),super(t,e)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,n){let r=e.resolve(n.map(this.head));if(!r.parent.inlineContent)return Sw.near(r);let o=e.resolve(n.map(this.anchor));return new t(o.parent.inlineContent?o:r,r)}replace(t,e=qx.empty){if(super.replace(t,e),e==qx.empty){let e=this.$from.marksAcross(this.$to);e&&t.ensureMarks(e)}}eq(e){return e instanceof t&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Aw(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,n){if("number"!=typeof n.anchor||"number"!=typeof n.head)throw new RangeError("Invalid input for TextSelection.fromJSON");return new t(e.resolve(n.anchor),e.resolve(n.head))}static create(t,e,n=e){let r=t.resolve(e);return new this(r,n==e?r:t.resolve(n))}static between(e,n,r){let o=e.pos-n.pos;if(r&&!o||(r=o>=0?1:-1),!n.parent.inlineContent){let t=Sw.findFrom(n,r,!0)||Sw.findFrom(n,-r,!0);if(!t)return Sw.near(n,r);n=t.$head}return e.parent.inlineContent||(0==o||(e=(Sw.findFrom(e,-r,!0)||Sw.findFrom(e,r,!0)).$anchor).pos<n.pos!=o<0)&&(e=n),new t(e,n)}};Sw.jsonID("text",Cw);var Aw=class t{constructor(t,e){this.anchor=t,this.head=e}map(e){return new t(e.map(this.anchor),e.map(this.head))}resolve(t){return Cw.between(t.resolve(this.anchor),t.resolve(this.head))}},Ew=class t extends Sw{constructor(t){let e=t.nodeAfter,n=t.node(0).resolve(t.pos+e.nodeSize);super(t,n),this.node=e}map(e,n){let{deleted:r,pos:o}=n.mapResult(this.anchor),i=e.resolve(o);return r?Sw.near(i):new t(i)}content(){return new qx(jx.from(this.node),0,0)}eq(e){return e instanceof t&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new Lw(this.anchor)}static fromJSON(e,n){if("number"!=typeof n.anchor)throw new RangeError("Invalid input for NodeSelection.fromJSON");return new t(e.resolve(n.anchor))}static create(e,n){return new t(e.resolve(n))}static isSelectable(t){return!t.isText&&!1!==t.type.spec.selectable}};Ew.prototype.visible=!1,Sw.jsonID("node",Ew);var Lw=class t{constructor(t){this.anchor=t}map(e){let{deleted:n,pos:r}=e.mapResult(this.anchor);return n?new Aw(r,r):new t(r)}resolve(t){let e=t.resolve(this.anchor),n=e.nodeAfter;return n&&Ew.isSelectable(n)?new Ew(e):Sw.near(e)}},Bw=class t extends Sw{constructor(t){super(t.resolve(0),t.resolve(t.content.size))}replace(t,e=qx.empty){if(e==qx.empty){t.delete(0,t.doc.content.size);let e=Sw.atStart(t.doc);e.eq(t.selection)||t.setSelection(e)}else super.replace(t,e)}toJSON(){return{type:"all"}}static fromJSON(e){return new t(e)}map(e){return new t(e)}eq(e){return e instanceof t}getBookmark(){return Rw}};Sw.jsonID("all",Bw);var Rw={map(){return this},resolve:t=>new Bw(t)};function $w(t,e,n,r,o,i=!1){if(e.inlineContent)return Cw.create(t,n);for(let s=r-(o>0?0:1);o>0?s<e.childCount:s>=0;s+=o){let r=e.child(s);if(r.isAtom){if(!i&&Ew.isSelectable(r))return Ew.create(t,n-(o<0?r.nodeSize:0))}else{let e=$w(t,r,n+o,o<0?r.childCount:0,o,i);if(e)return e}n+=r.nodeSize*o}return null}function Nw(t,e,n){let r=t.steps.length-1;if(r<e)return;let o,i=t.steps[r];(i instanceof ww||i instanceof bw)&&(t.mapping.maps[r].forEach((t,e,n,r)=>{null==o&&(o=r)}),t.setSelection(Sw.near(t.doc.resolve(o),n)))}function zw(t,e){return e&&t?t.bind(e):t}var Ow=class{constructor(t,e,n){this.name=t,this.init=zw(e.init,n),this.apply=zw(e.apply,n)}};new Ow("doc",{init:t=>t.doc||t.schema.topNodeType.createAndFill(),apply:t=>t.doc}),new Ow("selection",{init:(t,e)=>t.selection||Sw.atStart(e.doc),apply:t=>t.selection}),new Ow("storedMarks",{init:t=>t.storedMarks||null,apply:(t,e,n,r)=>r.selection.$cursor?t.storedMarks:null}),new Ow("scrollToSelection",{init:()=>0,apply:(t,e)=>t.scrolledIntoView?e+1:e});var Ww=/^\s*>\s$/,Hw=C.create({name:"blockquote",addOptions:()=>({HTMLAttributes:{}}),content:"block+",group:"block",defining:!0,parseHTML:()=>[{tag:"blockquote"}],renderHTML({HTMLAttributes:t}){
40
+ return et("blockquote",{...V(this.options.HTMLAttributes,t),children:et("slot",{})})},parseMarkdown:(t,e)=>{var n;const r=null!=(n=e.parseBlockChildren)?n:e.parseChildren;return e.createNode("blockquote",void 0,r(t.tokens||[]))},renderMarkdown:(t,e)=>{if(!t.content)return"";const n=[];return t.content.forEach((t,r)=>{var o,i;const s=(null!=(i=null==(o=e.renderChild)?void 0:o.call(e,t,r))?i:e.renderChildren([t])).split("\n").map(t=>""===t.trim()?">":`> ${t}`);n.push(s.join("\n"))}),n.join("\n>\n")},addCommands(){return{setBlockquote:()=>({commands:t})=>t.wrapIn(this.name),toggleBlockquote:()=>({commands:t})=>t.toggleWrap(this.name),unsetBlockquote:()=>({commands:t})=>t.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote(),Backspace:()=>((t,e)=>{var n;const{state:r,view:o}=t,{selection:i}=r;if(!i.empty)return!1;const{$from:s}=i;if(0!==s.parentOffset)return!1;const a=s.depth-1,l=s.node(a),c=s.index(a);if(0===c)return!1;if(l.type===e)return t.commands.lift(e.name);const d=l.child(c-1);if(d.type!==e||!(null==(n=d.lastChild)?void 0:n.isTextblock))return!1;const u=s.before(),p=u-1-1,{tr:h}=r;return h.delete(u,s.after()).insert(p,s.parent.content),h.setSelection(Cw.create(h.doc,p)),o.dispatch(h.scrollIntoView()),!0})(this.editor,this.type)}},addInputRules(){return[tt({find:Ww,type:this.type})]}}),Dw=t=>{const e=/`([^`]+)`(?!`)$/.exec(t);return e?e.index>0&&"`"===t[e.index-1]?null:{index:e.index,text:e[0],replaceWith:e[1]}:null},Fw=t=>{const e=/`([^`]+)`(?!`)/g,n=[];let r;for(;null!==(r=e.exec(t));)r.index>0&&"`"===t[r.index-1]||n.push({index:r.index,text:r[0],replaceWith:r[1]});return n},jw=T.create({name:"code",addOptions:()=>({HTMLAttributes:{}}),excludes:"_",code:!0,exitable:!0,parseHTML:()=>[{tag:"code"}],renderHTML({HTMLAttributes:t}){return["code",V(this.options.HTMLAttributes,t),0]},markdownTokenName:"codespan",parseMarkdown:(t,e)=>e.applyMark("code",[{type:"text",text:t.text||""}]),renderMarkdown:(t,e)=>t.content?`\`${e.renderChildren(t.content)}\``:"",addCommands(){return{setCode:()=>({commands:t})=>t.setMark(this.name),toggleCode:()=>({commands:t})=>t.toggleMark(this.name),unsetCode:()=>({commands:t})=>t.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[_({find:Dw,type:this.type})]},addPasteRules(){return[q({find:Fw,type:this.type})]}}),Uw=/^```([a-z]+)?[\s\n]$/,Xw=/^~~~([a-z]+)?[\s\n]$/,Yw=C.create({name:"codeBlock",addOptions:()=>({languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:4,HTMLAttributes:{}}),content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:t=>{var e;const{languageClassPrefix:n}=this.options;if(!n)return null;const r=[...(null==(e=t.firstElementChild)?void 0:e.classList)||[]].filter(t=>t.startsWith(n)).map(t=>t.replace(n,""))[0];return r||null},rendered:!1}}},parseHTML:()=>[{tag:"pre",preserveWhitespace:"full"}],renderHTML({node:t,HTMLAttributes:e}){return["pre",V(this.options.HTMLAttributes,e),["code",{class:t.attrs.language?this.options.languageClassPrefix+t.attrs.language:null},0]]},markdownTokenName:"code",parseMarkdown:(t,e)=>{var n,r;return!1===(null==(n=t.raw)?void 0:n.startsWith("```"))&&!1===(null==(r=t.raw)?void 0:r.startsWith("~~~"))&&"indented"!==t.codeBlockStyle?[]:e.createNode("codeBlock",{language:t.lang||null},t.text?[e.createTextNode(t.text)]:[])},renderMarkdown:(t,e)=>{var n;let r="";const o=(null==(n=t.attrs)?void 0:n.language)||"";return r=t.content?[`\`\`\`${o}`,e.renderChildren(t.content),"```"].join("\n"):`\`\`\`${o}\n\n\`\`\``,r},addCommands(){return{setCodeBlock:t=>({commands:e})=>e.setNode(this.name,t),toggleCodeBlock:t=>({commands:e})=>e.toggleNode(this.name,"paragraph",t)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:t,$anchor:e}=this.editor.state.selection,n=1===e.pos;return!(!t||e.parent.type.name!==this.name)&&(!(!n&&e.parent.textContent.length)&&this.editor.commands.clearNodes())},Tab:({editor:t})=>{var e;if(!this.options.enableTabIndentation)return!1;const n=null!=(e=this.options.tabSize)?e:4,{state:r}=t,{selection:o}=r,{$from:i,empty:s}=o;if(i.parent.type!==this.type)return!1;const a=" ".repeat(n);return s?t.commands.insertContent(a):t.commands.command(({tr:t})=>{const{from:e,to:n}=o,i=r.doc.textBetween(e,n,"\n","\n").split("\n").map(t=>a+t).join("\n");return t.replaceWith(e,n,r.schema.text(i)),!0})},"Shift-Tab":({editor:t})=>{var e;if(!this.options.enableTabIndentation)return!1;const n=null!=(e=this.options.tabSize)?e:4,{state:r}=t,{selection:o}=r,{$from:i,empty:s}=o;return i.parent.type===this.type&&(s?t.commands.command(({tr:t})=>{var e;const{pos:o}=i,s=i.start(),a=i.end(),l=r.doc.textBetween(s,a,"\n","\n").split("\n");let c=0,d=0;const u=o-s;for(let n=0;n<l.length;n+=1){if(d+l[n].length>=u){c=n;break}d+=l[n].length+1}const p=(null==(e=l[c].match(/^ */))?void 0:e[0])||"",h=Math.min(p.length,n);if(0===h)return!0;let f=s;for(let n=0;n<c;n+=1)f+=l[n].length+1;return t.delete(f,f+h),o-f<=h&&t.setSelection(st.create(t.doc,f)),!0}):t.commands.command(({tr:t})=>{const{from:e,to:i}=o,s=r.doc.textBetween(e,i,"\n","\n").split("\n").map(t=>{var e;const r=(null==(e=t.match(/^ */))?void 0:e[0])||"",o=Math.min(r.length,n);return t.slice(o)}).join("\n");return t.replaceWith(e,i,r.schema.text(s)),!0}))},Enter:({editor:t})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:e}=t,{selection:n}=e,{$from:r,empty:o}=n;if(!o||r.parent.type!==this.type)return!1;const i=r.parentOffset===r.parent.nodeSize-2,s=r.parent.textContent.endsWith("\n\n");return!(!i||!s)&&t.chain().command(({tr:t})=>(t.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowDown:({editor:t})=>{if(!this.options.exitOnArrowDown)return!1;const{state:e}=t,{selection:n,doc:r}=e,{$from:o,empty:i}=n;if(!i||o.parent.type!==this.type)return!1;if(o.parentOffset!==o.parent.nodeSize-2)return!1;const s=o.after();return void 0!==s&&(r.nodeAt(s)?t.commands.command(({tr:t})=>(t.setSelection(it.near(r.resolve(s))),!0)):t.commands.exitCode())}}},addInputRules(){return[Q({find:Uw,type:this.type,getAttributes:t=>({language:t[1]})}),Q({find:Xw,type:this.type,getAttributes:t=>({language:t[1]})})]},addProseMirrorPlugins(){return[new rt({key:new ot("codeBlockVSCodeHandler"),props:{handlePaste:(t,e)=>{if(!e.clipboardData)return!1;if(this.editor.isActive(this.type.name))return!1;const n=e.clipboardData.getData("text/plain"),r=e.clipboardData.getData("vscode-editor-data"),o=r?JSON.parse(r):void 0,i=null==o?void 0:o.mode;if(!n||!i)return!1;const{tr:s,schema:a}=t.state,l=a.text(n.replace(/\r\n?/g,"\n"));return s.replaceSelectionWith(this.type.create({language:i},l)),s.selection.$from.parent.type!==this.type&&s.setSelection(st.near(s.doc.resolve(Math.max(0,s.selection.from-2)))),s.setMeta("paste",!0),t.dispatch(s),!0}}})]}}),Kw=C.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,"\n\n"):""}),_w=C.create({name:"hardBreak",markdownTokenName:"br",addOptions:()=>({keepMarks:!0,HTMLAttributes:{}}),inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML:()=>[{tag:"br"}],renderHTML({HTMLAttributes:t}){return["br",V(this.options.HTMLAttributes,t)]},renderText:()=>"\n",renderMarkdown:()=>" \n",parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:t,chain:e,state:n,editor:r})=>t.first([()=>t.exitCode(),()=>t.command(()=>{const{selection:t,storedMarks:o}=n;if(t.$from.parent.type.spec.isolating)return!1;const{keepMarks:i}=this.options,{splittableMarks:s}=r.extensionManager,a=o||t.$to.parentOffset&&t.$from.marks();return e().insertContent({type:this.name}).command(({tr:t,dispatch:e})=>{if(e&&a&&i){const e=a.filter(t=>s.includes(t.type.name));t.ensureMarks(e)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),qw=C.create({name:"heading",addOptions:()=>({levels:[1,2,3,4,5,6],HTMLAttributes:{}}),content:"inline*",group:"block",defining:!0,addAttributes:()=>({level:{default:1,rendered:!1}}),parseHTML(){return this.options.levels.map(t=>({tag:`h${t}`,attrs:{level:t}}))},renderHTML({node:t,HTMLAttributes:e}){return[`h${this.options.levels.includes(t.attrs.level)?t.attrs.level:this.options.levels[0]}`,V(this.options.HTMLAttributes,e),0]},parseMarkdown:(t,e)=>e.createNode("heading",{level:t.depth||1},e.parseInline(t.tokens||[])),renderMarkdown:(t,e)=>{var n;const r=(null==(n=t.attrs)?void 0:n.level)?parseInt(t.attrs.level,10):1,o="#".repeat(r);return t.content?`${o} ${e.renderChildren(t.content)}`:""},addCommands(){return{setHeading:t=>({commands:e})=>!!this.options.levels.includes(t.level)&&e.setNode(this.name,t),toggleHeading:t=>({commands:e})=>!!this.options.levels.includes(t.level)&&e.toggleNode(this.name,"paragraph",t)}},addKeyboardShortcuts(){return this.options.levels.reduce((t,e)=>({...t,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(t=>Q({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${t}})\\s$`),type:this.type,getAttributes:{level:t}}))}}),Vw=C.create({name:"horizontalRule",addOptions:()=>({HTMLAttributes:{},nextNodeType:"paragraph"}),group:"block",parseHTML:()=>[{tag:"hr"}],renderHTML({HTMLAttributes:t}){return["hr",V(this.options.HTMLAttributes,t)]},markdownTokenName:"hr",parseMarkdown:(t,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:t,state:e})=>{if(!E(e,e.schema.nodes[this.name]))return!1;const{selection:n}=e,{$to:r}=n,o=t();return K(n)?o.insertContentAt(r.pos,{type:this.name}):o.insertContent({type:this.name}),o.command(({state:t,tr:e,dispatch:n})=>{if(n){const{$to:n}=e.selection,r=n.end();if(n.nodeAfter)n.nodeAfter.isTextblock?e.setSelection(st.create(e.doc,n.pos+1)):n.nodeAfter.isBlock?e.setSelection(nt.create(e.doc,n.pos)):e.setSelection(st.create(e.doc,n.pos));else{const o=t.schema.nodes[this.options.nextNodeType]||n.parent.type.contentMatch.defaultType,i=null==o?void 0:o.create();i&&(e.insert(r,i),e.setSelection(st.create(e.doc,r+1)))}e.scrollIntoView()}return!0}).run()}}},addInputRules(){return[G({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),Gw=Object.defineProperty,Jw="textStyle",Zw=/^\s*([-+*])\s$/,Qw=C.create({name:"bulletList",addOptions:()=>({itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}),group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML:()=>[{tag:"ul"}],renderHTML({HTMLAttributes:t}){return["ul",V(this.options.HTMLAttributes,t),0]},markdownTokenName:"list",parseMarkdown:(t,e)=>"list"!==t.type||t.ordered?[]:{type:"bulletList",content:t.items?e.parseChildren(t.items):[]},renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,"\n"):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes("listItem",this.editor.getAttributes(Jw)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let t=tt({find:Zw,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(t=tt({find:Zw,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(Jw),editor:this.editor})),[t]}}),tb=(t,e,n)=>((t,e,n,r)=>{const o=((t,e,n)=>{const{selection:r}=t;if(!r.empty)return null;const{$from:o}=r;if(!o.parent.isTextblock)return null;if(o.parentOffset!==o.parent.content.size)return null;let i=-1;for(let h=o.depth;h>0;h-=1)if(o.node(h).type.name===e){i=h;break}if(i<0)return null;const s=o.node(i),a=o.index(i);if(a+1>=s.childCount)return null;const l=s.child(a+1);if(!n.includes(l.type.name))return null;const c=t.schema.nodes[e];let d=!1;if(l.forEach(t=>{t.type===c&&t.childCount>1&&(d=!0)}),!d)return null;const u=t.doc.resolve(o.after()).nodeAfter;if(!u||!n.includes(u.type.name))return null;const p=[];return u.forEach(t=>{p.push(t)}),0===p.length?null:{listItemDepth:i,nestedList:u,nestedListPos:o.after(),insertPos:o.after(i),items:p}})(t,n,r);if(!o)return!1;const{selection:i}=t,{nestedList:s,nestedListPos:a,insertPos:l,items:c}=o,d=t.tr;d.delete(a,a+s.nodeSize);const u=d.mapping.map(l);return d.insert(u,ct.from(c)),d.setSelection(i.map(d.doc,d.mapping)),e&&e(d),!0})(t.state,t.view.dispatch,e,n),eb=(t,e)=>M.create({name:`${t}BranchingDeleteKeymap`,priority:101,addKeyboardShortcuts(){const n=()=>tb(this.editor,t,e);return{Delete:n,"Mod-Delete":n}}}),nb=[[1e3,"m"],[900,"cm"],[500,"d"],[400,"cd"],[100,"c"],[90,"xc"],[50,"l"],[40,"xl"],[10,"x"],[9,"ix"],[5,"v"],[4,"iv"],[1,"i"]],rb="abcdefghijklmnopqrstuvwxyz",ob=String.raw`\d+|[ivxlcdmIVXLCDM]+|${"[a-zA-Z]{1,2}"}`;function ib(t){let e=t,n="";for(const[r,o]of nb)for(;e>=r;)n+=o,e-=r;return n}function sb(t){return ib(t).toUpperCase()}function ab(t){const e=t.toLowerCase();let n=0,r=0;for(;n<e.length;){let t=!1;for(const[o,i]of nb)if(e.startsWith(i,n)){r+=o,n+=i.length,t=!0;break}if(!t)return 0}return r}function lb(t){if(t<=26)return rb[t-1];const e=Math.floor((t-1)/26)-1,n=(t-1)%26;return e<0?rb[n]:rb[e]+rb[n]}function cb(t){if(t&&!/^\d+$/.test(t))return function(t){if(!/^[ivxlcdmIVXLCDM]+$/.test(t))return!1;const e=ab(t);return!(e<=0)&&(t===t.toLowerCase()?ib(e):sb(e))===t}(t)?t===t.toLowerCase()?"i":"I":/^[a-z]{1,2}$/.test(t)?"a":/^[A-Z]{1,2}$/.test(t)?"A":void 0}function db(t){if(/^\d+$/.test(t))return parseInt(t,10);const e=cb(t);if("i"===e||"I"===e)return ab(t);if("a"===e||"A"===e){const e=function(t){const e=t.toLowerCase();if(1===e.length)return e.charCodeAt(0)-"a".charCodeAt(0)+1;if(2===e.length)return 26*(e.charCodeAt(0)-"a".charCodeAt(0)+1)+(e.charCodeAt(1)-"a".charCodeAt(0))+1;return 0}(t);return e>0?e:1}const n=parseInt(t,10);return Number.isNaN(n)?1:n}function ub(t,e){if("numeric"===t)return String(e);switch(t){case"a":return lb(e);case"A":return lb(e).toUpperCase();case"i":return ib(e);case"I":return sb(e);default:return String(e)}}function pb(t){const{type:e,start:n}=function(t){return{type:cb(t),start:db(t)}}(t),r={};return e&&(r.type=e),1!==n&&(r.start=n),r}function hb(t,e){return e.tokenizeInline?e.parseInline(e.tokenizeInline(t)):e.parseInline([{type:"text",raw:t,text:t}])}var fb=C.create({name:"listItem",addOptions:()=>({HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}),content:"paragraph block*",defining:!0,parseHTML:()=>[{tag:"li"}],renderHTML({HTMLAttributes:t}){return["li",V(this.options.HTMLAttributes,t),0]},markdownTokenName:"list_item",parseMarkdown:(t,e)=>{var n;if("list_item"!==t.type)return[];const r=null!=(n=e.parseBlockChildren)?n:e.parseChildren;let o=[];if(t.tokens&&t.tokens.length>0){if(function(t){var e,n;const r=null==(e=t.tokens)?void 0:e[0];return Boolean(t.text&&1===(null==(n=t.tokens)?void 0:n.length)&&"list"===(null==r?void 0:r.type)&&r.ordered&&r.raw===t.text)}(t))return{type:"listItem",content:[{type:"paragraph",content:hb(t.text||"",e)}]};if(t.tokens.some(t=>"paragraph"===t.type))o=r(t.tokens);else{const n=t.tokens[0];if(n&&"text"===n.type&&n.tokens&&n.tokens.length>0){if(o=[{type:"paragraph",content:e.parseInline(n.tokens)}],t.tokens.length>1){const e=r(t.tokens.slice(1));o.push(...e)}}else o=r(t.tokens)}}return 0===o.length&&(o=[{type:"paragraph",content:[]}]),{type:"listItem",content:o}},renderMarkdown:(t,e,n)=>Z(t,e,t=>{var e,n,r,o;if("bulletList"===t.parentType)return"- ";if("orderedList"===t.parentType){const i=(null==(n=null==(e=t.meta)?void 0:e.parentAttrs)?void 0:n.start)||1;return function(t,e,n=". "){const r=e+1;if(!t||"1"===t)return`${r}${n}`;switch(t){case"a":return`${lb(r)}${n}`;case"A":return`${lb(r).toUpperCase()}${n}`;case"i":return`${ib(r)}${n}`;case"I":return`${sb(r)}${n}`;default:return`${r}${n}`}}(null==(o=null==(r=t.meta)?void 0:r.parentAttrs)?void 0:o.type,i-1+(t.index||0),". ")}return"- "},n),addExtensions(){return[eb(this.name,[this.options.bulletListTypeName,this.options.orderedListTypeName])]},addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}});((t,e)=>{for(var n in e)Gw(t,n,{get:e[n],enumerable:!0})})({},{findListItemPos:()=>gb,getNextListDepth:()=>mb,handleBackspace:()=>xb,handleDelete:()=>vb,hasListBefore:()=>yb,hasListItemAfter:()=>kb,hasListItemBefore:()=>Pb,listItemHasSubList:()=>Sb,nextListIsDeeper:()=>wb,nextListIsHigher:()=>bb});var gb=(t,e)=>{const{$from:n}=e.selection,r=H(t,e.schema);let o=null,i=n.depth,s=n.pos,a=null;for(;i>0&&null===a;)o=n.node(i),o.type===r?a=i:(i-=1,s-=1);return null===a?null:{$pos:e.doc.resolve(s),depth:a}},mb=(t,e)=>{const n=gb(t,e);if(!n)return!1;const[,r]=W(e,t,n.$pos.pos+4);return r},yb=(t,e,n)=>{const{$anchor:r}=t.selection,o=Math.max(0,r.pos-2),i=t.doc.resolve(o).node();return!(!i||!n.includes(i.type.name))},xb=(t,e,n)=>{if(t.commands.undoInputRule())return!0;if(t.state.selection.from!==t.state.selection.to)return!1;if(!X(t.state,e)&&yb(t.state,e,n)){const{$anchor:n}=t.state.selection,r=t.state.doc.resolve(n.before()-1),o=[];r.node().descendants((t,n)=>{t.type.name===e&&o.push({node:t,pos:n})});const i=o.at(-1);if(!i)return!1;const s=t.state.doc.resolve(r.start()+i.pos+1);return t.chain().cut({from:n.start()-1,to:n.end()+1},s.end()).joinForward().run()}return!!X(t.state,e)&&(!!U(t.state)&&t.chain().liftListItem(e).run())},wb=(t,e)=>{const n=mb(t,e),r=gb(t,e);return!(!r||!n)&&n>r.depth},bb=(t,e)=>{const n=mb(t,e),r=gb(t,e);return!(!r||!n)&&n<r.depth},vb=(t,e)=>{if(!X(t.state,e))return!1;if(!j(t.state,e))return!1;const{selection:n}=t.state,{$from:r,$to:o}=n;return!(!n.empty&&r.sameParent(o))&&(wb(e,t.state)?t.chain().focus(t.state.selection.from+4).lift(e).joinBackward().run():bb(e,t.state)?t.chain().joinForward().joinBackward().run():t.commands.joinItemForward())},kb=(t,e)=>{var n;const{$anchor:r}=e.selection,o=e.doc.resolve(r.pos-r.parentOffset-2);return o.index()!==o.parent.childCount-1&&(null==(n=o.nodeAfter)?void 0:n.type.name)===t},Pb=(t,e)=>{var n;const{$anchor:r}=e.selection,o=e.doc.resolve(r.pos-2);return 0!==o.index()&&(null==(n=o.nodeBefore)?void 0:n.type.name)===t},Sb=(t,e,n)=>{if(!n)return!1;const r=H(t,e.schema);let o=!1;return n.descendants(t=>{t.type===r&&(o=!0)}),o},Ib=M.create({name:"listKeymap",addOptions:()=>({listTypes:[{itemName:"listItem",wrapperNames:["bulletList","orderedList"]},{itemName:"taskItem",wrapperNames:["taskList"]}]}),addKeyboardShortcuts(){return{Delete:({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n})=>{void 0!==t.state.schema.nodes[n]&&vb(t,n)&&(e=!0)}),e},"Mod-Delete":({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n})=>{void 0!==t.state.schema.nodes[n]&&vb(t,n)&&(e=!0)}),e},Backspace:({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:r})=>{void 0!==t.state.schema.nodes[n]&&xb(t,n,r)&&(e=!0)}),e},"Mod-Backspace":({editor:t})=>{let e=!1;return this.options.listTypes.forEach(({itemName:n,wrapperNames:r})=>{void 0!==t.state.schema.nodes[n]&&xb(t,n,r)&&(e=!0)}),e}}}}),Mb=new RegExp(`^(\\s*)(${ob})([.)])\\s+(.*)$`),Tb=new RegExp(`^(\\s*)(${ob})([.)])\\s+`),Cb=/^\s/,Ab={heading:/^#{1,6}(?:\s|$)/,bulletItem:/^[-+*]\s+/,codeFence:/^(?:```|~~~)/,thematicBreak:/^(?:(?:-[ \t]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})$/};function Eb(t){const e=t.trimStart();return Ab.bulletItem.test(e)||function(t){return Mb.test(t.trimStart())}(e)||Ab.heading.test(e)||Ab.thematicBreak.test(e)&&!e.startsWith("-")||/^>\s?/.test(e)||Ab.codeFence.test(e)}function Lb(t){return Object.values(Ab).some(e=>e.test(t))}function Bb(t){const e=[],n=[];let r=!1;return t.forEach(t=>{if(!r)return""===t.trim()||e.length>0&&Eb(t)?(r=!0,void n.push(t)):void e.push(t);n.push(t)}),{paragraphLines:e,blockLines:n}}var Rb=new RegExp(`^(${ob})([.)])\\s+(.+)$`);function $b(t){const e=t.split("\n").filter(t=>t.trim().length>0);if(0===e.length)return null;const n=[];for(const r of e){const t=r.trim().match(Rb);if(!t)return null;n.push({marker:t[1],content:t[3]})}return function(t){var e;if(0===t.length)return!1;const n=null!=(e=cb(t[0]))?e:"numeric",r=db(t[0]);if(r<1)return!1;for(let o=0;o<t.length;o++){const e=ub(n,r+o);if(t[o]!==e)return!1}return!0}(n.map(t=>t.marker))?{type:"orderedList",attrs:pb(n[0].marker),content:n.map(t=>({type:"listItem",content:[{type:"paragraph",content:[{type:"text",text:t.content}]}]}))}:null}function Nb(t,e,n){const r=[];let o=0;for(;o<t.length;){const i=t[o];if(i.indent===e){const{paragraphLines:s,blockLines:a}=Bb(i.contentLines),l=s.join("\n").trim(),c=[];l&&c.push({type:"paragraph",raw:l,tokens:n.inlineTokens(l)});const d=a.join("\n").trim();if(d){const t=n.blockTokens(d);c.push(...t)}let u=o+1;const p=[];for(;u<t.length&&t[u].indent>e;)p.push(t[u]),u+=1;if(p.length>0){const t=Nb(p,Math.min(...p.map(t=>t.indent)),n);c.push({type:"list",ordered:!0,start:p[0].number,typeMarker:p[0].type,items:t,raw:p.map(t=>t.raw).join("\n")})}r.push({type:"list_item",raw:i.raw,tokens:c}),o=u}else o+=1}return r}var zb="textStyle",Ob=/^(\d+)\.\s$/;function Wb(t){const e=t.match(/list-style-type\s*:\s*([^;]+)/i);if(!e)return null;switch(e[1].trim().toLowerCase()){case"upper-roman":return"I";case"lower-roman":return"i";case"upper-alpha":case"upper-latin":return"A";case"lower-alpha":case"lower-latin":return"a";default:return null}}var Hb=C.create({name:"orderedList",addOptions:()=>({itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}),group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes:()=>({start:{default:1,parseHTML:t=>t.hasAttribute("start")?parseInt(t.getAttribute("start")||"",10):1},type:{default:null,parseHTML:t=>{const e=t.getAttribute("type");if(e)return e;const n=t.getAttribute("style");if(n){const t=Wb(n);if(t)return t}const r=t.querySelector("li");if(r){const t=r.getAttribute("style");if(t){const e=Wb(t);if(e)return e}}return null}}}),parseHTML:()=>[{tag:"ol"}],renderHTML({HTMLAttributes:t}){const{start:e,type:n,...r}=t,o=V(this.options.HTMLAttributes,r);return 1!==e&&(o.start=e),n&&"1"!==n&&(o.type=n),["ol",o,0]},markdownTokenName:"list",parseMarkdown:(t,e)=>{if("list"!==t.type||!t.ordered)return[];const n=t.start||1,r=t.typeMarker,o=t.items?function(t,e){return t.map(t=>{if("list_item"!==t.type)return e.parseChildren([t])[0];const n=[];return t.tokens&&t.tokens.length>0&&t.tokens.forEach(t=>{if("paragraph"===t.type||"list"===t.type||"blockquote"===t.type||"code"===t.type)n.push(...e.parseChildren([t]));else if("text"===t.type&&t.tokens){const r=e.parseChildren([t]);n.push({type:"paragraph",content:r})}else{const r=e.parseChildren([t]);r.length>0&&n.push(...r)}}),{type:"listItem",content:n}})}(t.items,e):[],i={};return 1!==n&&(i.start=n),r&&(i.type=r),Object.keys(i).length>0?{type:"orderedList",attrs:i,content:o}:{type:"orderedList",content:o}},renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,"\n"):"",markdownTokenizer:{name:"orderedList",level:"block",start:t=>{const e=t.match(Tb),n=null==e?void 0:e.index;return void 0!==n?n:-1},tokenize:(t,e,n)=>{var r,o;const i=t.split("\n"),[s,a]=function(t){const e=[];let n=0,r=0;for(;n<t.length;){const o=t[n],i=o.match(Mb);if(!i)break;const[,s,a,l,c]=i,d=s.length,u=parseInt(a,10),p=isNaN(u)?cb(a):void 0,h=isNaN(u)?db(a):u,f=[c];let g=n+1;const m=[o];let y=!1;for(;g<t.length;){const e=t[g];if(e.match(Mb))break;if(""===e.trim())m.push(e),f.push(""),y=!0,g+=1;else if(e.match(Cb)){const t=e.length-e.trimStart().length,n=d+a.length+1;m.push(e),f.push(e.slice(Math.min(t,n))),g+=1}else{if(y||Lb(e))break;m.push(e),f.push(e),g+=1}}e.push({indent:d,number:h,type:p,content:f.join("\n").trim(),contentLines:f,raw:m.join("\n")}),r=g,n=g}return[e,r]}(i);if(0===s.length)return;const l=Nb(s,s[0].indent,n);return 0!==l.length?{type:"list",ordered:!0,start:(null==(r=s[0])?void 0:r.number)||1,typeMarker:null==(o=s[0])?void 0:o.type,items:l,raw:i.slice(0,a).join("\n")}:void 0}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:t,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes("listItem",this.editor.getAttributes(zb)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addProseMirrorPlugins:()=>[new rt({props:{handlePaste:(t,e)=>{var n,r;const o=null==(n=e.clipboardData)?void 0:n.getData("text/html");if(null==o?void 0:o.trim())return!1;const i=null==(r=e.clipboardData)?void 0:r.getData("text/plain");if(!i)return!1;const s=$b(i);if(!s)return!1;try{const e=t.state.schema.nodeFromJSON(s),n=t.state.tr.replaceSelectionWith(e);return t.dispatch(n),!0}catch{return!1}}}})],addInputRules(){const t=(t,e)=>(!e.attrs.type||"1"===e.attrs.type)&&e.childCount+e.attrs.start===+t[1];let e=tt({find:Ob,type:this.type,getAttributes:t=>({start:+t[1]}),joinPredicate:t});return(this.options.keepMarks||this.options.keepAttributes)&&(e=tt({find:Ob,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(zb)}),joinPredicate:t,editor:this.editor})),[e]}}),Db=/^\s*(\[([( |x])?\])\s$/,Fb=C.create({name:"taskItem",addOptions:()=>({nested:!1,HTMLAttributes:{},taskListTypeName:"taskList",a11y:void 0}),content(){return this.options.nested?"paragraph block*":"paragraph+"},defining:!0,addAttributes:()=>({checked:{default:!1,keepOnSplit:!1,parseHTML:t=>{const e=t.getAttribute("data-checked");return""===e||"true"===e},renderHTML:t=>({"data-checked":t.checked})}}),parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51}]},renderHTML({node:t,HTMLAttributes:e}){return["li",V(this.options.HTMLAttributes,e,{"data-type":this.name}),["label",["input",{type:"checkbox",checked:t.attrs.checked?"checked":null}],["span"]],["div",0]]},parseMarkdown:(t,e)=>{const n=[];if(t.tokens&&t.tokens.length>0?n.push(e.createNode("paragraph",{},e.parseInline(t.tokens))):t.text?n.push(e.createNode("paragraph",{},[e.createNode("text",{text:t.text})])):n.push(e.createNode("paragraph",{},[])),t.nestedTokens&&t.nestedTokens.length>0){const r=e.parseChildren(t.nestedTokens);n.push(...r)}return e.createNode("taskItem",{checked:t.checked||!1},n)},renderMarkdown:(t,e)=>{var n;return Z(t,e,`- [${(null==(n=t.attrs)?void 0:n.checked)?"x":" "}] `)},addExtensions(){return this.options.nested?[eb(this.name,[this.options.taskListTypeName])]:[]},addKeyboardShortcuts(){const t={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...t,Tab:()=>this.editor.commands.sinkListItem(this.name)}:t},addNodeView(){return({node:t,HTMLAttributes:e,getPos:n,editor:r})=>{const o=document.createElement("li"),i=document.createElement("label"),s=document.createElement("span"),a=document.createElement("input"),l=document.createElement("div"),c=t=>{var e,n;a.ariaLabel=(null==(n=null==(e=this.options.a11y)?void 0:e.checkboxLabel)?void 0:n.call(e,t,a.checked))||`Task item checkbox for ${t.textContent||"empty task item"}`};c(t),i.contentEditable="false",a.type="checkbox",a.addEventListener("mousedown",t=>t.preventDefault()),a.addEventListener("change",e=>{if(!r.isEditable&&!this.options.onReadOnlyChecked)return void(a.checked=!a.checked);const{checked:o}=e.target;r.isEditable&&"function"==typeof n&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:t})=>{const e=n();if("number"!=typeof e)return!1;const r=t.doc.nodeAt(e);return t.setNodeMarkup(e,void 0,{...null==r?void 0:r.attrs,checked:o}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(t,o)||(a.checked=!a.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([t,e])=>{o.setAttribute(t,e)}),o.dataset.checked=t.attrs.checked,a.checked=t.attrs.checked,i.append(a,s),o.append(i,l),Object.entries(e).forEach(([t,e])=>{o.setAttribute(t,e)});let d=new Set(Object.keys(e));return{dom:o,contentDOM:l,update:t=>{if(t.type!==this.type)return!1;o.dataset.checked=t.attrs.checked,a.checked=t.attrs.checked,c(t);const e=r.extensionManager.attributes,n=D(t,e),i=new Set(Object.keys(n)),s=this.options.HTMLAttributes;return d.forEach(t=>{i.has(t)||(t in s?o.setAttribute(t,s[t]):o.removeAttribute(t))}),Object.entries(n).forEach(([t,e])=>{null==e?t in s?o.setAttribute(t,s[t]):o.removeAttribute(t):o.setAttribute(t,e)}),d=i,!0}}}},addInputRules(){return[tt({find:Db,type:this.type,getAttributes:t=>({checked:"x"===t[t.length-1]})})]}}),jb=C.create({name:"taskList",addOptions:()=>({itemTypeName:"taskItem",HTMLAttributes:{}}),group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`ul[data-type="${this.name}"]`,priority:51}]},renderHTML({HTMLAttributes:t}){return["ul",V(this.options.HTMLAttributes,t,{"data-type":this.name}),0]},parseMarkdown:(t,e)=>e.createNode("taskList",{},e.parseChildren(t.items||[])),renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,"\n"):"",markdownTokenizer:{name:"taskList",level:"block",start(t){var e;const n=null==(e=t.match(/^\s*[-+*]\s+\[([ xX])\]\s+/))?void 0:e.index;return void 0!==n?n:-1},tokenize(t,e,n){const r=t=>{const e=J(t,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:t=>({indentLevel:t[1].length,mainContent:t[4],checked:"x"===t[3].toLowerCase()}),createToken:(t,e)=>({type:"taskItem",raw:"",mainContent:t.mainContent,indentLevel:t.indentLevel,checked:t.checked,text:t.mainContent,tokens:n.inlineTokens(t.mainContent),nestedTokens:e}),customNestedParser:r},n);return e?[{type:"taskList",raw:e.raw,items:e.items}]:n.blockTokens(t)},o=J(t,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:t=>({indentLevel:t[1].length,mainContent:t[4],checked:"x"===t[3].toLowerCase()}),createToken:(t,e)=>({type:"taskItem",raw:"",mainContent:t.mainContent,indentLevel:t.indentLevel,checked:t.checked,text:t.mainContent,tokens:n.inlineTokens(t.mainContent),nestedTokens:e}),customNestedParser:r},n);if(o)return{type:"taskList",raw:o.raw,items:o.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:t})=>t.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}}),Ub=(M.create({name:"listKit",addExtensions(){const t=[];return!1!==this.options.bulletList&&t.push(Qw.configure(this.options.bulletList)),!1!==this.options.listItem&&t.push(fb.configure(this.options.listItem)),!1!==this.options.listKeymap&&t.push(Ib.configure(this.options.listKeymap)),!1!==this.options.orderedList&&t.push(Hb.configure(this.options.orderedList)),!1!==this.options.taskItem&&t.push(Fb.configure(this.options.taskItem)),!1!==this.options.taskList&&t.push(jb.configure(this.options.taskList)),t}}),"&nbsp;"),Xb=C.create({name:"paragraph",priority:1e3,addOptions:()=>({HTMLAttributes:{}}),group:"block",content:"inline*",parseHTML:()=>[{tag:"p"}],renderHTML({HTMLAttributes:t}){return["p",V(this.options.HTMLAttributes,t),0]},parseMarkdown:(t,e)=>{const n=t.tokens||[];if(1===n.length&&"image"===n[0].type)return e.parseChildren([n[0]]);const r=e.parseInline(n);return 1!==n.length||"text"!==n[0].type||n[0].raw!==Ub&&n[0].text!==Ub&&" "!==n[0].raw&&" "!==n[0].text||1!==r.length||"text"!==r[0].type||r[0].text!==Ub&&" "!==r[0].text?e.createNode("paragraph",void 0,r):e.createNode("paragraph",void 0,[])},renderMarkdown:(t,e,n)=>{var r,o;if(!t)return"";const i=Array.isArray(t.content)?t.content:[];if(0===i.length){const t=Array.isArray(null==(r=null==n?void 0:n.previousNode)?void 0:r.content)?n.previousNode.content:[];return"paragraph"===(null==(o=null==n?void 0:n.previousNode)?void 0:o.type)&&0===t.length?Ub:""}return e.renderChildren(i)},addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),Yb=C.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""}),Kb=(M.create({name:"characterCount",addOptions:()=>({limit:null,autoTrim:!0,mode:"textSize",textCounter:t=>t.length,wordCounter:t=>t.split(" ").filter(t=>""!==t).length}),addStorage:()=>({characters:()=>0,words:()=>0}),onBeforeCreate(){this.storage.characters=t=>{const e=(null==t?void 0:t.node)||this.editor.state.doc;if("textSize"===((null==t?void 0:t.mode)||this.options.mode)){const t=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(t)}return e.nodeSize},this.storage.words=t=>{const e=(null==t?void 0:t.node)||this.editor.state.doc,n=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(n)}},addProseMirrorPlugins(){let t=!1;return[new rt({key:new ot("characterCount"),appendTransaction:(e,n,r)=>{if(t)return;const o=this.options.limit,i=this.options.autoTrim;if(null==o||0===o||!1===i)return void(t=!0);const s=this.storage.characters({node:r.doc});if(s>o){const e=0,n=s-o;console.warn(`[CharacterCount] Initial content exceeded limit of ${o} characters. Content was automatically trimmed.`);const i=r.tr.deleteRange(e,n);return t=!0,i}t=!0},filterTransaction:(t,e)=>{const n=this.options.limit;if(!t.docChanged||0===n||null==n)return!0;const r=this.storage.characters({node:e.doc}),o=this.storage.characters({node:t.doc});if(o<=n)return!0;if(r>n&&o>n&&o<=r)return!0;if(r>n&&o>n&&o>r)return!1;if(!t.getMeta("paste"))return!1;const i=t.selection.$head.pos,s=i-(o-n),a=i;return t.deleteRange(s,a),!(this.storage.characters({node:t.doc})>n)}})]}}),M.create({name:"dropCursor",addOptions:()=>({color:"currentColor",width:1,class:void 0}),addProseMirrorPlugins(){return[dt(this.options)]}})),_b=(M.create({name:"focus",addOptions:()=>({className:"has-focus",mode:"all"}),addProseMirrorPlugins(){return[new rt({key:new ot("focus"),props:{decorations:({doc:t,selection:e})=>{const{isEditable:n,isFocused:r}=this.editor,{anchor:o}=e,i=[];if(!n||!r)return lt.create(t,[]);let s=0;"deepest"===this.options.mode&&t.descendants((t,e)=>{if(!t.isText)return o>=e&&o<=e+t.nodeSize-1&&void(s+=1)});let a=0;return t.descendants((t,e)=>!t.isText&&(o>=e&&o<=e+t.nodeSize-1&&(a+=1,"deepest"===this.options.mode&&s-a>0||"shallowest"===this.options.mode&&a>1?"deepest"===this.options.mode:void i.push(at.node(e,e+t.nodeSize,{class:this.options.className}))))),lt.create(t,i)}}})]}}),M.create({name:"gapCursor",addProseMirrorPlugins:()=>[ut()],extendNodeSchema(t){var e;return{allowGapCursor:null!=(e=A(z(t,"allowGapCursor",{name:t.name,options:t.options,storage:t.storage})))?e:null}}})),qb="placeholder",Vb=new ot("tiptap__placeholder");function Gb(t){const{editor:e,placeholder:n,dataAttribute:r,pos:o,node:i,isEmptyDoc:s,hasAnchor:a,classes:{emptyNode:l,emptyEditor:c}}=t,d=[l];return s&&d.push(c),at.node(o,o+i.nodeSize,{class:d.join(" "),[r]:"function"==typeof n?n({editor:e,node:i,pos:o,hasAnchor:a}):n})}function Jb(t,e){return"function"==typeof t?t(e):t}function Zb({editor:t,options:e,dataAttribute:n,doc:r,selection:o,from:i,to:s}){const{anchor:a}=o,l=[],c=t.isEmpty;return r.nodesBetween(i,s,(r,o)=>{const i=a>=o&&a<=o+r.nodeSize,s=!r.isLeaf&&Y(r);return r.type.isTextblock?(!i&&e.showOnlyCurrent||!s||l.push(Gb({editor:t,isEmptyDoc:c,dataAttribute:n,hasAnchor:i,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:Jb(e.emptyNodeClass,{editor:t,node:r,pos:o,hasAnchor:i})},node:r,pos:o})),e.includeChildren):e.includeChildren}),l}function Qb({editor:t,options:e,dataAttribute:n,doc:r,selection:o}){if(!t.isEditable&&e.showOnlyWhenEditable)return null;const{anchor:i}=o,s=[],a=t.isEmpty;if(e.showOnlyCurrent&&!e.includeChildren){const o=r.resolve(i),l=o.depth>0?o.node(1):o.nodeAfter,c=o.depth>0?o.before(1):i;if(l&&l.type.isTextblock&&Y(l)){const r=i>=c&&i<=c+l.nodeSize;s.push(Gb({editor:t,isEmptyDoc:a,dataAttribute:n,hasAnchor:r,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:Jb(e.emptyNodeClass,{editor:t,node:l,pos:c,hasAnchor:r})},node:l,pos:c}))}}else s.push(...Zb({editor:t,options:e,dataAttribute:n,doc:r,selection:o,from:0,to:r.content.size}));return lt.create(r,s)}function tv(t,e){var n;const r=t.resolve(e);if(0===r.depth){const t=null!=(n=r.nodeAfter)?n:r.nodeBefore;if(!t)return{from:e,to:e};const o=r.nodeAfter?e:e-t.nodeSize;return{from:o,to:o+t.nodeSize}}const o=r.before(1);return{from:o,to:o+r.node(1).nodeSize}}function ev(t,e){return{from:Math.max(0,e.from-1),to:Math.min(t.content.size,e.to-1)}}function nv(t,e){const n=function(t,e,n){const r=[];return t.forEach((t,o)=>{const i=o,s=i+t.nodeSize;i+1<n&&s+1>e&&r.push({from:i,to:s})}),r}(t,e.from,e.to);return n.push(ev(t,tv(t,e.from))),e.to>e.from?n.push(ev(t,tv(t,Math.min(e.to,t.content.size+1)-1))):e.from<t.content.size+1&&n.push(ev(t,tv(t,Math.min(e.from+1,t.content.size)))),n}function rv(t,e,n){const r=[];if(t.docChanged){const e=N(t);for(const t of e)r.push(...nv(n.doc,t.newRange))}return t.selectionSet&&(r.push(ev(n.doc,tv(n.doc,t.mapping.map(e.selection.anchor)))),r.push(ev(n.doc,tv(n.doc,n.selection.anchor)))),function(t){if(0===t.length)return[];const e=[...t].sort((t,e)=>t.from-e.from),n=[{...e[0]}];for(let r=1;r<e.length;r+=1){const t=n[n.length-1],o=e[r];o.from<=t.to?t.to=Math.max(t.to,o.to):n.push({...o})}return n}(r)}function ov(t,e,n){const r=Math.max(0,Math.min(t,n.content.size));return{from:r,to:Math.max(r,Math.min(e,n.content.size))}}function iv({editor:t,options:e,dataAttribute:n}){return{init(r,o){const i=Qb({editor:t,options:e,dataAttribute:n,doc:o.doc,selection:o.selection});return null!=i?i:lt.empty},apply:(r,o,i,s)=>r.docChanged||r.selectionSet?function({decorations:t,ranges:e,editor:n,options:r,dataAttribute:o,doc:i,selection:s}){let a=t;for(const l of e){const{from:t,to:e}=ov(l.from,l.to,i),c=a.find(t,e).filter(n=>n.from>=t&&n.to<=e);c.length&&(a=a.remove(c));const d=Zb({editor:n,options:r,dataAttribute:o,doc:i,selection:s,from:t,to:e});d.length&&(a=a.add(i,d))}return a}({decorations:o.map(r.mapping,r.doc),ranges:rv(r,i,s),editor:t,options:e,dataAttribute:n,doc:s.doc,selection:s.selection}):o}}function sv({editor:t,options:e}){const n=e.dataAttribute?`data-${r=e.dataAttribute,r.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}`:`data-${qb}`;var r;const o=e.showOnlyCurrent&&!e.includeChildren;return new rt({key:Vb,...o?{}:{state:iv({editor:t,options:e,dataAttribute:n})},props:{decorations:o?({doc:r,selection:o})=>Qb({editor:t,options:e,dataAttribute:n,doc:r,selection:o}):n=>{var r;return e.showOnlyWhenEditable&&!t.isEditable?lt.empty:null!=(r=Vb.getState(n))?r:lt.empty}}})}M.create({name:"placeholder",addOptions:()=>({emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:qb,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}),addProseMirrorPlugins(){return[sv({editor:this.editor,options:this.options})]}}),M.create({name:"selection",addOptions:()=>({className:"selection"}),addProseMirrorPlugins(){const{editor:t,options:e}=this;return t.options.injectCSS&&"undefined"!=typeof document&&B(".ProseMirror:not(.ProseMirror-focused) *::selection {\n background: transparent;\n}\n\n.ProseMirror:not(.ProseMirror-focused) *::-moz-selection {\n background: transparent;\n}",t.options.injectNonce,"selection"),[new rt({key:new ot("selection"),props:{decorations:n=>n.selection.empty||t.isFocused||!t.isEditable||K(n.selection)||t.view.dragging?null:lt.create(n.doc,[at.inline(n.selection.from,n.selection.to,{class:e.className})])}})]}});function av({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||(null==e?void 0:e.type)===t}var lv=M.create({name:"trailingNode",addOptions:()=>({node:void 0,notAfter:[]}),addProseMirrorPlugins(){var t;const e=new ot(this.name),n=this.options.node||(null==(t=this.editor.schema.topNodeType.contentMatch.defaultType)?void 0:t.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,t])=>t).filter(t=>(this.options.notAfter||[]).concat(n).includes(t.name));return[new rt({key:e,appendTransaction:(t,r,o)=>{const{doc:i,tr:s,schema:a}=o,l=e.getState(o),c=i.content.size,d=a.nodes[n];if(!t.some(t=>t.getMeta("skipTrailingNode"))&&l)return s.insert(c,d.create())},state:{init:(t,e)=>!av({node:e.tr.doc.lastChild,types:r}),apply:(t,e)=>{if(!t.docChanged)return e;if(t.getMeta("__uniqueIDTransaction"))return e;return!av({node:t.doc.lastChild,types:r})}}})]}}),cv=M.create({name:"undoRedo",addOptions:()=>({depth:100,newGroupDelay:500}),addCommands:()=>({undo:()=>({state:t,dispatch:e})=>ft(t,e),redo:()=>({state:t,dispatch:e})=>ht(t,e)}),addProseMirrorPlugins(){return[pt(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-я":()=>this.editor.commands.undo(),"Shift-Mod-я":()=>this.editor.commands.redo()}}}),dv=M.create({name:"starterKit",addExtensions(){var t,e,n,r;const o=[];return!1!==this.options.bold&&o.push(vm.configure(this.options.bold)),!1!==this.options.blockquote&&o.push(Hw.configure(this.options.blockquote)),!1!==this.options.bulletList&&o.push(Qw.configure(this.options.bulletList)),!1!==this.options.code&&o.push(jw.configure(this.options.code)),!1!==this.options.codeBlock&&o.push(Yw.configure(this.options.codeBlock)),!1!==this.options.document&&o.push(Kw.configure(this.options.document)),!1!==this.options.dropcursor&&o.push(Kb.configure(this.options.dropcursor)),!1!==this.options.gapcursor&&o.push(_b.configure(this.options.gapcursor)),!1!==this.options.hardBreak&&o.push(_w.configure(this.options.hardBreak)),!1!==this.options.heading&&o.push(qw.configure(this.options.heading)),!1!==this.options.undoRedo&&o.push(cv.configure(this.options.undoRedo)),!1!==this.options.horizontalRule&&o.push(Vw.configure(this.options.horizontalRule)),!1!==this.options.italic&&o.push(Mm.configure(this.options.italic)),!1!==this.options.listItem&&o.push(fb.configure(this.options.listItem)),!1!==this.options.listKeymap&&o.push(Ib.configure(null==(t=this.options)?void 0:t.listKeymap)),!1!==this.options.link&&o.push(Sx.configure(null==(e=this.options)?void 0:e.link)),!1!==this.options.orderedList&&o.push(Hb.configure(this.options.orderedList)),!1!==this.options.paragraph&&o.push(Xb.configure(this.options.paragraph)),!1!==this.options.strike&&o.push(Tx.configure(this.options.strike)),!1!==this.options.text&&o.push(Yb.configure(this.options.text)),!1!==this.options.underline&&o.push(zx.configure(null==(n=this.options)?void 0:n.underline)),!1!==this.options.trailingNode&&o.push(lv.configure(null==(r=this.options)?void 0:r.trailingNode)),o}}),uv=new WeakMap;function pv(t,e){const n=function(t){const e=uv.get(t);if(e)return e;const n={api:null,disposeApiSubscription:null,listeners:new Set};return uv.set(t,n),n}(t);return n.disposeApiSubscription?.(),n.api=e,n.disposeApiSubscription=e.subscribe(()=>{fv(n)}),fv(n),()=>{n.api===e&&(n.disposeApiSubscription?.(),n.disposeApiSubscription=null,n.api=null,fv(n))}}function hv(t){return uv.get(t)?.api??null}function fv(t){for(const e of t.listeners)e()}function gv(t){const e=t.content.map(t=>"orderedList"===t.type||"bulletList"===t.type?{blockType:t.type,isEmptyTrailingParagraph:!1}:"blockquote"===t.type?{blockType:"blockquote",isEmptyTrailingParagraph:!1}:"paragraph"===t.type?{blockType:"paragraph",isEmptyTrailingParagraph:0===(t.content?.length??0)}:null).filter(t=>null!==t);if(0===e.length)return"paragraph";const n=e.some(({blockType:t})=>"paragraph"!==t)?e.filter(({isEmptyTrailingParagraph:t})=>!t):e,r=n[0]?.blockType??"paragraph";return n.every(({blockType:t})=>t===r)?r:"mixed"}function mv(t,e){if(gv(t)===e)return t;const n=function(t){const e=[],n=t=>{if("paragraph"!==t.type)if("codeBlock"!==t.type)for(const e of t.content??[])n(e);else e.push({type:"paragraph",content:t.content??[]});else e.push(t)},r=t.at(-1),o=t.length>1&&"paragraph"===r?.type&&0===(r.content?.length??0)&&t.slice(0,-1).some(t=>"orderedList"===t.type||"bulletList"===t.type||"blockquote"===t.type)?t.slice(0,-1):t;for(const i of o)n(i);return e.length>0?e:[{type:"paragraph"}]}(t.content),r="paragraph"===e?n:"blockquote"===e?[{type:"blockquote",content:n}]:[{type:e,content:n.map(t=>({type:"listItem",content:[t]}))}];return wg({...t,content:r})}var yv={bold:["bold","strong"],italic:["italic","em"],strike:["strike","s"],underline:["underline","u"]};function xv(t,e){const n=yv[e];let r=!1,o=!1;return kv(t.content,(t,e)=>{"text"!==t.type||!t.text||e.insideCodeBlock||t.marks?.some(t=>"code"===t.type)||(t.marks?.some(t=>n.includes(t.type))?r=!0:o=!0)}),r&&o?"mixed":r}function wv(t,e,n){const r=yv[e],o=Pv(t.content,(t,o)=>{if("text"!==t.type||!t.text)return t;const i=t.marks??[],s=i.filter(t=>r.includes(t.type));if(n&&(o.insideCodeBlock||i.some(t=>"code"===t.type)))return t;if(n&&1===s.length&&s[0]?.type===e)return t;const a=i.filter(t=>!r.includes(t.type)),l=n?[...a,{type:e}]:a;return i.length===l.length&&i.every((t,e)=>t===l[e])?t:{...t,marks:l.length>0?l:void 0}});return o.changed?wg({...t,content:o.nodes}):t}function bv(t,e){const n=Pv(t.content,(t,n)=>{if("text"!==t.type||!t.text)return t;const r=t.marks??[],o=r.filter(t=>"link"===t.type);if(null===e){if(0===o.length)return t;const e=r.filter(t=>"link"!==t.type);return{...t,marks:e.length>0?e:void 0}}if(n.insideCodeBlock||r.some(t=>"code"===t.type))return t;if(1===o.length&&o[0]?.attrs?.href===e)return t;const i=o[0];return{...t,marks:[...r.filter(t=>"link"!==t.type),{type:"link",attrs:{...i?.attrs,href:e}}]}});return n.changed?wg({...t,content:n.nodes}):t}function vv(t){const e=Pv(t.content,t=>"text"===t.type&&t.marks&&t.marks.length>0?{...t,marks:void 0}:function(t){if("paragraph"!==t.type||void 0===t.attrs?.textAlign)return t;const e={...t.attrs};return delete e.textAlign,{...t,attrs:Object.keys(e).length>0?e:void 0}}(t));return e.changed?wg({...t,content:e.nodes}):t}function kv(t,e,n=!1){for(const r of t)e(r,{insideCodeBlock:n}),r.content&&kv(r.content,e,n||"codeBlock"===r.type)}function Pv(t,e,n=!1){let r=!1;return{nodes:t.map(t=>{const o=e(t,{insideCodeBlock:n}),i=o.content;if(!i)return o!==t&&(r=!0),o;const s=Pv(i,e,n||"codeBlock"===o.type);return s.changed?(r=!0,{...o,content:s.nodes}):(o!==t&&(r=!0),o)}),changed:r}}function Sv(t){try{return t.view.dom.isConnected}catch{return!1}}function Iv(t){!t.isDestroyed&&Sv(t)&&(t.view.dom.focus(),t.view.focus())}function Mv(t){if(!Sv(t))return{type:null,text:null};const e=function(t){if(!t)return{type:null,text:null};const e=window.getSelection();if(!e||0===e.rangeCount)return{type:e?.type??null,text:null};const n=e.anchorNode,r=e.focusNode,o=t instanceof HTMLElement?t:t.parentElement,i=!!n&&!!r&&null!==o&&o.contains(n)&&o.contains(r);return{type:i?e.type:null,text:i?e.toString():null}}(t.view.dom);if(null!==e.type)return e;const n=t.state.selection;return{type:n.empty?"Caret":"Range",text:n.empty?"":t.state.doc.textBetween(n.from,n.to,"\n")}}var Tv={s:14,m:16,l:20,xl:28},Cv=Tv.m,Av={[Tv.s]:20,[Tv.m]:24,[Tv.l]:28,[Tv.xl]:36};function Ev(t,e=Cv){return"number"==typeof t&&Number.isFinite(t)?Math.max(1,t):e}function Lv(t,e){return pm(e,t).cssFamily}function Bv(t){return Ev(t)}function Rv(t){const e=Ev(t);return Av[e]??Math.ceil(1.4*e)}function $v(t,e=1){return Math.max(1,Math.ceil(Rv(t)*e))}function Nv(t){switch(t){case"middle":return"center";case"end":return"right";default:return"left"}}function zv(t,e,n,r){if(0===t.getText().trim().length)return Wv(e,r);const o=function(t,e){const n=t.ownerDocument.defaultView?.getComputedStyle(t);return Uv(t.ownerDocument).measureElement(t,e,n)}(t.view.dom,{shape:e,fontCatalog:n,...Dv(e,r)});return!r&&t.view.dom.scrollHeight>e.props.h+1&&(o.h=Math.max(o.h,t.view.dom.scrollHeight)),Hv(e,o,r)}function Ov(t,e,n,r){return 0===xg(t).trim().length?Wv(e,r):Hv(e,(o=function(t){return t.content.map(t=>Mg(t)).join("")}(t),i={...Dv(e,r),shape:e,fontCatalog:n},Uv(document).measureHtml(o,i)),r);var o,i}function Wv(t,e){const n=e?e.minWidth:t.props.autoSize?16:t.props.w,r=$v(t.props.size);if(t.props.w!==n||t.props.h!==r)return{w:n,h:r}}function Hv(t,e,n){const r=n?Math.min(n.maxWidth,Math.max(n.minWidth,Math.ceil(e.w+2*n.paddingInline))):t.props.autoSize?Math.max(16,Math.ceil(e.w)):t.props.w,o=Math.max($v(t.props.size),Math.ceil(e.h));if(r!==t.props.w||o!==t.props.h)return{w:r,h:o}}function Dv(t,e){if(e){const t=qg(e,e.maxWidth);return{maxWidth:Math.max(1,e.maxWidth-2*t)}}return t.props.autoSize?{}:{width:t.props.w}}var Fv=class{ownerDocument;element;constructor(t){this.ownerDocument=t,this.element=t.createElement("div"),this.element.setAttribute("aria-hidden","true"),this.element.style.position="absolute",this.element.style.left="-10000px",this.element.style.top="0",this.element.style.visibility="hidden",this.element.style.pointerEvents="none",t.body.appendChild(this.element)}measureHtml(t,e){const n=this.prepareElement(e);return n.innerHTML=t,this.measurePreparedElement(n)}measureElement(t,e,n){const r=this.prepareElement(e);return r.replaceChildren(...Array.from(t.childNodes).map(t=>t.cloneNode(!0))),Xv(r,"whiteSpace",n?.whiteSpace),Xv(r,"overflowWrap",n?.overflowWrap),Xv(r,"lineHeight",n?.lineHeight),Xv(r,"letterSpacing",n?.letterSpacing),Xv(r,"textAlign",n?.textAlign),this.measurePreparedElement(r)}prepareElement(t){const e=this.element;return e.removeAttribute("contenteditable"),e.className="",e.textContent="",t?.shape&&t.fontCatalog&&function(t,e,n){t.className="land-text-editor__content",t.dir="auto",t.style.color=Nt(e.props.color),t.style.fontFamily=Lv(e.props.font,n),t.style.fontSize=`${Bv(e.props.size)}px`,t.style.lineHeight=`${Rv(e.props.size)}px`,t.style.textAlign=Nv(e.props.textAlign)}(e,t.shape,t.fontCatalog),e.style.position="absolute",e.style.left="-10000px",e.style.top="0",e.style.visibility="hidden",e.style.pointerEvents="none",e.style.width="number"==typeof t?.width?`${t.width}px`:"max-content",e.style.minWidth="0",e.style.height="auto",e.style.minHeight="0",e.style.maxHeight="none",e.style.maxWidth="number"==typeof t?.width?`${t.width}px`:"number"==typeof t?.maxWidth?`${t.maxWidth}px`:"none",e}measurePreparedElement(t){return t.querySelectorAll("p").forEach(t=>{t instanceof HTMLElement&&(t.style.margin="0")}),[t,...Array.from(t.querySelectorAll("*")).filter(t=>t instanceof HTMLElement)].reduce((t,e)=>{const n=e.getBoundingClientRect();return{w:Math.max(t.w,n.width,e.scrollWidth,e.offsetWidth),h:Math.max(t.h,n.height,e.scrollHeight,e.offsetHeight)}},{w:0,h:0})}},jv=new WeakMap;function Uv(t){const e=jv.get(t);if(e)return e;const n=new Fv(t);return jv.set(t,n),n}function Xv(t,e,n){n&&"normal"!==n&&"auto"!==n&&(t.style[e]=n)}function Yv(t,e,n){if(e.isDestroyed()||!e.isConnected())return;const r=e.measure(n);r&&_v(t,n,r,"user")}function Kv(t,e,n,r="system"){const o=Ov(e.props.richText,e,n,em(t,e));o&&_v(t,e,o,r)}function _v(t,e,n,r){const o=t.shapes.get(e.id);Dg(o)&&o.props.w===n.w&&o.props.h===n.h||t.commands.updateShapes([{id:e.id,props:n}],{source:r})}var qv=/[;{}<>\u0000-\u001f\u007f]/u,Vv=/(?:url|expression)\s*\(|!\s*important|@\s*import|javascript\s*:/iu;function Gv({editor:t,fontCatalog:e,landEditor:n,shapeId:r}){const o=()=>{const t=n.shapes.get(r);return Dg(t)?t:null},i={shapeId:r,getSnapshot(){if(t.isDestroyed)return null;const n=o();return n?function({editor:t,fontCatalog:e,shape:n}){const r=t.state.selection,o=function(t){const{selection:e,doc:n}=t.state;return e.empty?{from:0,to:n.content.size}:{from:e.from,to:e.to}}(t),i=r.empty?"shape":"selection",s=zt(n.props.color),a=Ot(n.props.backgroundColor)?null:zt(n.props.backgroundColor),l=n.props.textAlign;return{shapeId:n.id,target:i,bold:nk(t,o,"bold"),italic:nk(t,o,"italic"),strike:nk(t,o,"strike"),underline:nk(t,o,"underline"),blockType:rk(t,o),color:ok(t,o,"color",s),backgroundColor:ok(t,o,"backgroundColor",0===t.state.doc.textContent.length?a:null),font:lk(ok(t,o,"fontFamily",n.props.font),t=>function(t,e){return e.fontOptions.find(e=>e.cssFamily===t)?.id??t}(t,e)),size:lk(ok(t,o,"fontSize",n.props.size),t=>function(t,e){if("number"==typeof t)return t;const n=Number.parseFloat(t);return Number.isFinite(n)&&n>0?n:e}(t,n.props.size)),textAlign:ik(t,o,l),linkHref:sk(t,o),canSetLink:!r.empty||t.state.doc.textContent.length>0}}({editor:t,fontCatalog:e,shape:n}):null},subscribe(e){if(t.isDestroyed)return()=>{};const o=()=>e();t.on("transaction",o),t.on("focus",o),t.on("blur",o);const i=me(`TextFormattingApi(${r})`,n.shapes.getSignal(r),o,{fireImmediately:!1});return()=>{i(),t.off("transaction",o),t.off("focus",o),t.off("blur",o)}},focus(){t.isDestroyed||t.commands.focus()},toggle:e=>function(t,e,n){if(t.isDestroyed||void 0===t.schema.marks[e])return!1;const r=t.state.selection;if(!r.empty)return t.chain().focus().toggleMark(e).run();const o=!0!==n?.[e];if(0===t.state.doc.textContent.length){const n=t.chain().focus();return(o?n.setMark(e):n.unsetMark(e)).run()}let i=t.chain().focus().selectAll();return i=o?i.setMark(e):i.unsetMark(e),i=i.setTextSelection(ek(r)),i=o?i.setMark(e):i.unsetMark(e),i.run()}(t,e,i.getSnapshot()),setBlockType:e=>function(t,e){if(t.isDestroyed)return!1;const n=t.state.selection;if(n.empty&&t.state.doc.textContent.length>0){const r=t.getJSON(),o=mv(r,e);if(o===r)return!1;const i=function(t,e,n){const r=t.schema.nodeFromJSON(e);let o=Math.max(0,n),i=1,s=!1;return r.descendants((t,e)=>!s&&t.isText&&t.text?o<=t.text.length?(i=e+o,s=!0,!1):(o-=t.text.length,i=e+t.text.length,!1):!s),i}(t,o,function(t,e){let n=0,r=!1;return t.state.doc.descendants((t,o)=>!r&&t.isText&&t.text?e<=o+t.text.length?(n+=Math.max(0,e-o),r=!0,!1):(n+=t.text.length,!1):!r),n}(t,n.from));return t.chain().focus().setContent(o).setTextSelection(i).run()}let r=t.chain().focus();r=r.clearNodes(),r="orderedList"===e?r.toggleOrderedList():"bulletList"===e?r.toggleBulletList():"blockquote"===e?r.toggleBlockquote():r.setParagraph();return r.run()}(t,e),setColor(e){if(null!==e&&!ck(e))return!1;const r=o();return!!r&&function({editor:t,landEditor:e,shape:n,color:r}){if(t.isDestroyed||void 0===t.schema.marks.textStyle)return!1;if(!t.state.selection.empty)return null===r?t.chain().focus().unsetColor().run():t.chain().focus().setColor(r).run();const o=Zv(t,"color");null!==r&&tk(e,n,{color:Lt(r)});return o||null!==r}({editor:t,landEditor:n,shape:r,color:e})},setBackgroundColor(e){if(null!==e&&!ck(e))return!1;const r=o();return!!r&&function({editor:t,landEditor:e,shape:n,color:r}){if(t.isDestroyed||void 0===t.schema.marks.textStyle)return!1;const o=t.state.selection,i=t=>null===r?t.unsetBackgroundColor():t.setBackgroundColor(r);if(!o.empty)return tk(e,n,{backgroundColor:Lt("transparent")}),i(t.chain().focus()).run();const s=i(i(t.chain().focus().selectAll()).setTextSelection(ek(o))).run();return tk(e,n,{backgroundColor:Lt(r??"transparent")}),s}({editor:t,landEditor:n,shape:r,color:e})},setFont(r){const i=o();if(!i)return!1;if(null===r)return Jv({editor:t,font:null,fontFamily:null,landEditor:n,shape:i});const s=e.fontOptions.find(t=>t.id===r);return!!s&&(fm(r,e).then(()=>{if(t.isDestroyed)return;const r=o();r&&Kv(n,r,e,"system")}),Jv({editor:t,fontFamily:s.cssFamily,font:r,landEditor:n,shape:i}))},setSize(e){const r=null===e?null:Math.round(1e3*e)/1e3;if(null!==e&&(!Number.isFinite(e)||e<1||e>512||null===r||Math.abs(e-r)>Number.EPSILON*Math.max(1,Math.abs(e))))return!1;const i=o();return!!i&&function({editor:t,landEditor:e,shape:n,size:r}){if(t.isDestroyed||void 0===t.schema.marks.textStyle)return!1;const o=t.state.selection,i=null===r?null:`${r}px`,s=null===r?null:`${Rv(r)}px`,a=t=>null===i||null===s?t.unsetFontSize().unsetLineHeight():t.setFontSize(i).setLineHeight(s);if(!o.empty)return a(t.chain().focus()).run();const l=function(t){const e=t.state.selection;let n=t.chain().focus();t.state.doc.textContent.length>0&&(n=n.selectAll());return Qv(n.unsetFontSize().unsetLineHeight().setTextSelection(ek(e)).unsetFontSize().unsetLineHeight()).run()}(t);null!==r&&tk(e,n,{size:r});return l||null!==r}({editor:t,landEditor:n,shape:i,size:r})},setTextAlign(e){const r=o();return!!r&&function({editor:t,landEditor:e,shape:n,align:r}){if(t.isDestroyed)return!1;const o=function(t){switch(t){case"middle":return"center";case"end":return"right";default:return"left"}}(r),i=t.state.selection;if(!i.empty)return t.chain().focus().setTextAlign(o).run();const s=t.chain().focus().selectAll().unsetTextAlign().setTextSelection(ek(i)).run();return tk(e,n,{textAlign:r}),s||n.props.textAlign!==r}({editor:t,landEditor:n,shape:r,align:e})},setLink(e){if(t.isDestroyed||void 0===t.schema.marks.link)return!1;const n=null===e?null:lg(e);if(null!==e&&null===n)return!1;const r=t.state.selection;if(!r.empty)return null===n?!!t.isActive("link")&&t.chain().focus().unsetLink().run():t.chain().focus().setLink({href:n}).run();if(0===t.state.doc.textContent.length)return!1;const o=t.chain().focus().selectAll();return(null===n?o.unsetLink():o.setLink({href:n})).setTextSelection(ek(r)).run()},clearFormatting(){if(t.isDestroyed)return!1;const e=o();e&&tk(n,e,{backgroundColor:Lt("transparent")});const r=t.state.selection;return r.empty?t.chain().focus().selectAll().unsetAllMarks().unsetTextAlign().setTextSelection(ek(r)).command(({tr:t})=>(t.setStoredMarks([]),!0)).run():t.chain().focus().unsetAllMarks().unsetTextAlign().run()},getUnsafeTiptapEditor:()=>t.isDestroyed?null:t};return i}function Jv({editor:t,font:e,fontFamily:n,landEditor:r,shape:o}){if(t.isDestroyed||void 0===t.schema.marks.textStyle)return!1;if(!t.state.selection.empty)return null===n?t.chain().focus().unsetFontFamily().run():t.chain().focus().setFontFamily(n).run();const i=Zv(t,"fontFamily");return null!==e&&r&&o&&tk(r,o,{font:e}),i||null!==e}function Zv(t,e){const n=t.state.selection;let r=t.chain().focus();return t.state.doc.textContent.length>0&&(r=r.selectAll()),r="color"===e?r.unsetColor():r.unsetFontFamily(),r=r.setTextSelection(ek(n)),r="color"===e?r.unsetColor():r.unsetFontFamily(),Qv(r).run()}function Qv(t){return t.command(({state:t,tr:e})=>{const n=t.schema.marks.textStyle;if(!n)return!0;const r=(e.storedMarks??t.storedMarks)?.find(t=>t.type===n);return r&&Object.values(r.attrs).every(t=>null==t||""===t)&&e.removeStoredMark(n),!0})}function tk(t,e,n){t.commands.updateShapes([{id:e.id,props:n}],{source:"user"})}function ek(t){return t.from===t.to?t.from:{from:t.from,to:t.to}}function nk(t,e,n){if(!t.schema.marks[n])return!1;const r=[];return t.state.doc.nodesBetween(e.from,e.to,(t,e,o)=>{const i=o?.type.schema.marks[n];t.isText&&i&&o?.type.allowsMarkType(i)&&!t.marks.some(t=>"code"===t.type.name)&&r.push(t.marks.some(t=>t.type.name===n))}),0===r.length?(t.state.storedMarks??t.state.selection.$from.marks()).some(t=>t.type.name===n):ak(r)??!1}function rk(t,e){const n=[];return t.state.doc.nodesBetween(e.from,e.to,(e,r)=>{if(!e.isTextblock)return;const o=t.state.doc.resolve(Math.min(r+1,t.state.doc.content.size));let i="paragraph";for(let t=o.depth;t>=0;t-=1){const e=o.node(t).type.name;if("orderedList"===e||"bulletList"===e){i=e;break}if("blockquote"===e){i="blockquote";break}}n.push({blockType:i,isEmptyTrailingParagraph:"paragraph"===i&&0===e.content.size})}),ak((n.some(({blockType:t})=>"paragraph"!==t)?n.filter(({isEmptyTrailingParagraph:t})=>!t):n).map(({blockType:t})=>t))??"paragraph"}function ok(t,e,n,r){const o=[];if(t.state.doc.nodesBetween(e.from,e.to,(t,e,i)=>{if(!t.isText)return;if("backgroundColor"===n&&(t.marks.some(t=>"code"===t.type.name)||"codeBlock"===i?.type.name))return;const s=t.marks.find(t=>"textStyle"===t.type.name)?.attrs[n];o.push("string"==typeof s&&s.length>0?s:r)}),0===o.length){const e=(t.state.storedMarks??t.state.selection.$from.marks()).find(t=>"textStyle"===t.type.name)?.attrs[n];return"string"==typeof e&&e.length>0?e:r}return ak(o)}function ik(t,e,n){const r=[];return t.state.doc.nodesBetween(e.from,e.to,t=>{t.isTextblock&&r.push(function(t,e){switch(t){case"center":return"middle";case"right":return"end";case"left":return"start";default:return e}}(t.attrs.textAlign,n))}),ak(r)??n}function sk(t,e){const n=[];if(t.state.doc.nodesBetween(e.from,e.to,(t,e,r)=>{if(!t.isText||"codeBlock"===r?.type.name||t.marks.some(t=>"code"===t.type.name))return;const o=t.marks.find(t=>"link"===t.type.name)?.attrs.href;n.push("string"==typeof o&&o.length>0?o:null)}),0===n.length)return null;const r=n[0]??null;return n.every(t=>t===r)?r:"mixed"}function ak(t){if(0===t.length)return null;const e=t[0];return t.every(t=>Object.is(t,e))?e:"mixed"}function lk(t,e){return null===t?null:"mixed"===t?"mixed":e(t)}function ck(t){const e=t.trim();return e.length>0&&e.length<=128&&!qv.test(e)&&!Vv.test(e)}function dk({shapeId:t,editor:e,fontCatalog:n,landEditor:r}){return{shapeId:t,formatting:Gv({editor:e,fontCatalog:n,landEditor:r,shapeId:t}),isDestroyed:()=>e.isDestroyed,isConnected:()=>!e.isDestroyed&&Sv(e),isFocused:()=>!e.isDestroyed&&Sv(e)&&e.view.dom.contains(document.activeElement),getValue:()=>wg(e.getJSON()),setValue(t){e.commands.setContent(t)},focus(){Iv(e)},focusEnd(){!e.isDestroyed&&Sv(e)&&e.commands.focus("end")},focusSelectAll(){!e.isDestroyed&&Sv(e)&&(Iv(e),e.chain().focus().selectAll().run())},focusAtPagePoint(t,n){!function(t,e,n){Iv(e);const r=t.viewport.pageToScreen(new bt(n.x,n.y)),o=e.view.posAtCoords({left:r.x,top:r.y})?.pos;if(o)return void e.chain().focus().setTextSelection(o).run();e.chain().focus().selectAll().run()}(t,e,n)},getSelectionSnapshot:()=>e.isDestroyed||!Sv(e)?{type:null,text:null}:Mv(e),collapseSelectionAtClientPoint(t,n){!e.isDestroyed&&Sv(e)&&("Range"===Mv(e).type&&function(t,e,n){if(t.isDestroyed||!Sv(t))return;const r=t.view.posAtCoords({left:e,top:n})?.pos;"number"!=typeof r?t.commands.focus("end"):t.chain().focus().setTextSelection(r).run()}(e,t,n))},measure(t){if(!e.isDestroyed&&Sv(e))return zv(e,t,n,em(r,t))},onCompositionStateChange(t){if(e.isDestroyed)return()=>{};const n=e.view.dom,r=()=>t(!0),o=()=>t(!1);return n.addEventListener("compositionstart",r),n.addEventListener("compositionend",o),()=>{n.removeEventListener("compositionstart",r),n.removeEventListener("compositionend",o),t(!1)}}}}var uk=Sx.extend({inclusive:!1,renderHTML({HTMLAttributes:t}){const{href:e,target:n,rel:r,...o}=t;return["span",V(o,{"data-rich-text-link-href":e,style:"text-decoration-line: underline;"}),0]}}),pk=[dv.configure({bold:!1,italic:!1,link:!1,strike:!1,underline:!1}),vm.extend({keepOnSplit:!0}),Mm.extend({keepOnSplit:!0}),Tx.extend({keepOnSplit:!0}),zx.extend({keepOnSplit:!0}),Ex,Bx,Lx,Rx,$x,Nx,Cx.configure({types:["paragraph"],alignments:["left","center","right"]}),Ox.configure({className:"land-rich-text-selection"}),uk.configure({autolink:!0,defaultProtocol:"https",openOnClick:!1,protocols:["mailto","land"],HTMLAttributes:{target:"_blank",rel:"noopener noreferrer",class:"land-rich-text-link"}})];function hk({landEditor:t,shape:e,fontCatalog:n,initialRichText:r,className:o,editorStyle:i,formattingToolbar:s,onTiptapEditorChange:a,onReady:l,onDispose:c,onRichTextChange:u}){const p=v(null),h=Ot(e.props.backgroundColor)?null:zt(e.props.backgroundColor),f=h&&r.content.length>0?function(t,e){const n=Pv(t.content,(t,n)=>{if("text"!==t.type||!t.text||n.insideCodeBlock||t.marks?.some(t=>"code"===t.type))return t;const r=t.marks??[],o=r.findIndex(t=>"textStyle"===t.type);if(o<0)return{...t,marks:[...r,{type:"textStyle",attrs:{backgroundColor:e}}]};const i=r[o]?.attrs?.backgroundColor;return"string"==typeof i&&i.length>0?t:{...t,marks:r.map((t,n)=>n===o?{...t,attrs:{...t.attrs,backgroundColor:e}}:t)}});return n.changed?wg({...t,content:n.nodes}):t}(r,h):r,g=m(r=>{const o=p.current;if(o?.editor===r)return o.controller;const i=dk({shapeId:e.id,editor:r,fontCatalog:n,landEditor:t});return p.current={editor:r,controller:i},i},[n,t,e.id]),y=I({extensions:pk,content:f,autofocus:!1,editable:!0,immediatelyRender:!0,shouldRerenderOnTransaction:!1,editorProps:{attributes:{"data-ui":"rich-text-editor",class:"land-text-editor__content",dir:"auto"},handleKeyDown:(e,n)=>(n.stopPropagation(),!n.isComposing&&("Escape"===n.key?(n.preventDefault(),t.editing.cancel("user"),!0):!("Enter"!==n.key||!n.metaKey&&!n.ctrlKey)&&(n.preventDefault(),t.editing.complete("user"),!0)))},onUpdate:({editor:t})=>{const e=g(t);u({editor:t,controller:e,richText:e.getValue()})}},[e.id]);return x(()=>{if(!y||y.isDestroyed)return;const n=g(y),r={shapeId:e.id,editor:y,controller:n,formatting:n.formatting},o={shapeId:e.id,formatting:n.formatting},i=!1===s?()=>{}:pv(t,n.formatting);return l(r),a?.(o),()=>{i(),p.current?.editor===y&&(p.current=null),c(r),a?.(null)}},[g,s,t,c,l,a,e.id,y]),d(S,{editor:y,className:o,style:i})}function fk({editor:t,controller:e,shapeId:n,request:r,onApplied:o,attempt:i=0}){if(!e.isDestroyed())if(e.isConnected())!function({editor:t,controller:e,shapeId:n,request:r,onApplied:o}){if(e.isDestroyed())return;if(e.focus(),!r||r.shapeId!==n)return e.focusEnd(),void o?.(r);if("selectAll"===r.entryMode)return window.requestAnimationFrame(()=>{!e.isDestroyed()&&e.isConnected()&&e.focusSelectAll()}),t.editing.consumeEntryRequest(r.id),void o?.(r);if("placeCaret"===r.entryMode&&r.caretPagePoint)return e.focusAtPagePoint(t,r.caretPagePoint),t.editing.consumeEntryRequest(r.id),void o?.(r);e.focusEnd(),t.editing.consumeEntryRequest(r.id),o?.(r)}({editor:t,controller:e,shapeId:n,request:r,onApplied:o});else{if(i>=4)return;window.requestAnimationFrame(()=>{fk({editor:t,controller:e,shapeId:n,request:r,onApplied:o,attempt:i+1})})}}function gk({editor:t,shape:e,tiptapEditor:n,richTextController:r,latestShapeRef:o,fontCatalog:i}){const s=v(e.props.richText),a=v(!1),l=v(null),c=m(({controller:n,richText:r})=>{if(a.current||!n.isConnected())return;const c=wg(r);s.current=c,Xg(t,e.id,c,n.measure(o.current)??Ov(c,o.current,i,em(t,o.current)),"user"),function(t,e,n,r){null!==r.current&&window.clearTimeout(r.current),r.current=window.setTimeout(()=>{r.current=null,Yv(t,e,n.current)},0)}(t,n,o,l)},[t,i,o,e.id]);return x(()=>()=>{null!==l.current&&(window.clearTimeout(l.current),l.current=null)},[]),w(()=>{n&&r&&!n.isDestroyed&&r.isConnected()&&Yv(t,r,e)},[t,r,e,n]),x(()=>{if(!n||!r||!r.isConnected())return;const t=e.props.richText;t!==s.current&&(JSON.stringify(s.current)!==JSON.stringify(t)?(a.current=!0,r.setValue(t),s.current=t,a.current=!1):s.current=t)},[r,e.props.richText,n]),x(()=>{if(r)return r.onCompositionStateChange(e=>{t.editing.setComposition(e,"system")})},[t,r]),x(()=>{if(!r||!r.isConnected())return;let n=!1;return fm(e.props.font,i).then(()=>{!n&&r.isConnected()&&Yv(t,r,o.current)}),()=>{n=!0}},[t,i,o,r,e.props.font]),c}function mk({editor:t,href:e,openExternal:n}){hg({href:e,openExternal:n,openInternal(e){t.viewport.centerOnShape(e,{source:"user",animation:{durationMs:240}})&&t.commands.setSelectedShapeIds([e],{source:"user"})}})}function yk({shapeId:t,operationKind:e,fontCatalog:o,formattingToolbar:i,openLink:s=()=>{},onTiptapEditorChange:a}){const l=n(),c=r(l.shapes.getSignal(t)),u=r(l.state.shapeEditing).session;return Dg(c)&&u?.shapeId===c.id?d(xk,{shape:c,session:u,fontCatalog:o,formattingToolbar:i,openLink:s,onTiptapEditorChange:a},`${c.id}:${e}`):null}function xk({shape:t,session:e,fontCatalog:o,formattingToolbar:i,openLink:s,onTiptapEditorChange:a}){const l=n(),c=v(t.props.richText),u=function(t){const e=v(t);return x(()=>{e.current=t},[t]),e}(t),p=r(l.state.shapeEditingEntryRequest),h=v(null),[f,g]=k(null),[y,w]=k(null),P=m(({editor:t,controller:e})=>{g(t.isDestroyed?null:t),w(e)},[]),S=m(({editor:t,controller:e})=>{g(e=>e===t?null:e),w(t=>t===e?null:t)},[]),I=gk({editor:l,shape:t,tiptapEditor:f,richTextController:y,latestShapeRef:u,fontCatalog:o}),M=m(()=>{f&&function(t,e){!(!e||t.isDestroyed||t.state.doc.textContent.length>0||t.getAttributes("textStyle").backgroundColor===e)&&t.commands.setBackgroundColor(e)}(f,Ot(t.props.backgroundColor)?null:zt(t.props.backgroundColor))},[t.props.backgroundColor,f]);!function({editor:t,shapeId:e,session:n,tiptapEditor:r,richTextController:o,entryRequest:i,consumedEntryRequestIdRef:s,onEntryFocusApplied:a}){const l=v(null),c=v(null);x(()=>{if(!o||o.isDestroyed()||!o.isConnected())return;let t=!1,e=null,n=0;const r=()=>{t||o.isDestroyed()||null===s.current&&(o.isFocused()||(o.focus(),n+=1,o.isFocused()||n>=4||(e=window.setTimeout(r,16))))},i=window.requestAnimationFrame(()=>{r()});return()=>{t=!0,window.cancelAnimationFrame(i),null!==e&&window.clearTimeout(e)}},[s,o,e]),x(()=>{r&&!r.isDestroyed&&o&&null===s.current&&c.current!==n.operationKind&&(c.current=n.operationKind,window.setTimeout(()=>{fk({editor:t,controller:o,shapeId:e,request:{id:-1,shapeId:n.shapeId,entryMode:n.entryMode,caretPagePoint:n.caretPagePoint},onApplied:a})},0))},[s,t,o,n.caretPagePoint,n.entryMode,n.operationKind,n.shapeId,e,r,a]),x(()=>{r&&!r.isDestroyed&&o&&i&&i.shapeId===e&&s.current!==i.id&&fk({editor:t,controller:o,shapeId:e,request:i,onApplied(t){t&&(s.current=t.id),a?.()}})},[s,t,i,o,e,r,a]),x(()=>{if(!r||!o||r.isDestroyed||!o.isConnected())return;const e=o;"selectAll"===n.entryMode&&window.requestAnimationFrame(()=>{"Range"!==e.getSelectionSnapshot().type&&e.focusSelectAll()});const i=l.current,s=n.caretPagePoint;if("placeCaret"===n.entryMode&&s&&(i?.operationKind!==n.operationKind||i.entryMode!==n.entryMode)){l.current={operationKind:n.operationKind,entryMode:n.entryMode};const r={x:s.x,y:s.y};window.requestAnimationFrame(()=>{fk({editor:t,controller:e,shapeId:n.shapeId,request:{id:-1,shapeId:n.shapeId,entryMode:"placeCaret",caretPagePoint:r},onApplied:a})})}},[t,n.caretPagePoint,n.entryMode,n.operationKind,n.shapeId,o,r,a])}({editor:l,shapeId:t.id,session:e,tiptapEditor:f,richTextController:y,entryRequest:p,consumedEntryRequestIdRef:h,onEntryFocusApplied:M});const T=function({editor:t,shapeId:e,richTextController:n}){const r=v(null);return{onPointerDownCapture:m(o=>{if(0!==o.button||1!==o.detail||!n||n.isDestroyed())return void(r.current=null);const i=t.state.shapeEditingSession.get();i&&i.shapeId===e&&!i.isComposing&&"Range"===n.getSelectionSnapshot().type?r.current={pointerId:o.pointerId,clientX:o.clientX,clientY:o.clientY,moved:!1}:r.current=null},[t,n,e]),onPointerMoveCapture:m(t=>{const e=r.current;if(!e||e.pointerId!==t.pointerId)return;const n=t.clientX-e.clientX,o=t.clientY-e.clientY;n*n+o*o>=16&&(e.moved=!0)},[]),onPointerUpCapture:m(o=>{const i=r.current;if(r.current=null,!i||i.pointerId!==o.pointerId||i.moved||!n||n.isDestroyed())return;const s=t.state.shapeEditingSession.get();if(!s||s.shapeId!==e||s.isComposing)return;const a=o.clientX,l=o.clientY;window.setTimeout(()=>{n.isDestroyed()||"Range"!==n.getSelectionSnapshot().type||n.collapseSelectionAtClientPoint(a,l)},0)},[t,n,e]),onPointerCancel:m(()=>{r.current=null},[])}}({editor:l,shapeId:t.id,richTextController:y}),C=function(t,e,n=0){return b(()=>({color:Nt(t.props.color),fontFamily:Lv(t.props.font,e),fontSize:Bv(t.props.size),lineHeight:`${Rv(t.props.size)}px`,textAlign:Nv(t.props.textAlign),pointerEvents:"auto",userSelect:"text",cursor:"text",boxSizing:"border-box",position:"absolute",inset:0,width:"100%",height:"100%",paddingInline:n}),[t.props.color,t.props.font,t.props.size,t.props.textAlign,e,n])}(t,o,qg(em(l,t),t.props.w)),A=m(t=>{if(!t.ctrlKey&&!t.metaKey)return;const e=function(t){const e=t.target;return e instanceof Element?e.closest("[data-rich-text-link-href]")?.getAttribute("data-rich-text-link-href")??null:null}(t.nativeEvent);e&&f&&!f.isDestroyed&&(t.preventDefault(),t.stopPropagation(),mk({editor:l,href:e,openExternal:s}))},[l,s,f]);
41
+ return d("div",{"data-ui":"text-editing-box","data-shape-id":t.id,"data-mount-target-kind":"shape",onPointerDown:t=>{t.stopPropagation()},onClickCapture:A,onPointerDownCapture:T.onPointerDownCapture,onPointerMoveCapture:T.onPointerMoveCapture,onPointerUpCapture:T.onPointerUpCapture,onPointerCancel:T.onPointerCancel,onContextMenu:t=>{t.stopPropagation()},onDragStart:t=>{t.preventDefault()},style:C,children:d(hk,{landEditor:l,shape:t,fontCatalog:o,initialRichText:c.current,className:"land-text-editor__content",formattingToolbar:i,editorStyle:{height:"100%",minHeight:"100%"},onReady:P,onDispose:S,onTiptapEditorChange:a,onRichTextChange:I})})}function wk(t,e,n,o,i,s){const a=r(t.state.shapeEditing).session,l=a?.shapeId===e.id,c=a&&l?d(yk,{shapeId:a.shapeId,operationKind:a.operationKind,fontCatalog:n,formattingToolbar:o,openLink:i,onTiptapEditorChange:s},a.shapeId+":"+a.operationKind):null;return function({editor:t,shape:e,isEditingThisShape:n,fontCatalog:r}){w(()=>{if(n)return;Kv(t,e,r);let o=!1;return fm(e.props.font,r).then(()=>{if(o)return;const n=t.shapes.get(e.id);Dg(n)&&n.props.font===e.props.font&&Kv(t,n,r)}),()=>{o=!0}},[t,r,n,e,e.props.autoSize,e.props.font,e.props.richText,e.props.scale,e.props.size,e.props.textAlign,e.props.w])}({editor:t,shape:e,isEditingThisShape:l,fontCatalog:n}),{hasEditingSession:null!==a,isEditingThisShape:l,editingHost:c}}var bk=p(null);function vk({children:t,presenter:e}){
42
+ return d(bk.Provider,{value:e,children:t})}var kk=p({query:"",activeMatch:null});function Pk({activeMatch:t,children:e,query:n}){const r=b(()=>({activeMatch:t,query:n}),[t,n]);
43
+ return d(kk.Provider,{value:r,children:e})}function Sk(t,e){if(0===e.length)return[];const n=[],r=xg(t),o=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),"giu");for(const i of r.matchAll(o)){const t=i.index,e=i[0];void 0!==t&&0!==e.length&&n.push({from:t,to:t+e.length})}return n}var Ik=new Set(["key_down","key_up","pointer_cancel","pointer_down","pointer_move","pointer_up"]),Mk={id:"land.text.dom-events",handle({event:t,name:e}){if(!Ik.has(e))return"continue";const n=t.target;return n instanceof HTMLElement&&n.closest('[data-ui="text-editing-box"]')?"handled":"continue"},getCursor:({element:t})=>t?.closest('[data-ui="text-editing-box"]')?"text":void 0};function Tk({fontCatalog:t=cm(),formattingToolbar:e,openLink:n=()=>{},onTiptapEditorChange:r}={}){return{id:"land.text.react",domEventGuards:[Mk],canvasComponents:[{id:"land.text.styles",component:Ck},{id:"land.text.default-font-preload",component:function(){
44
+ return d(Ak,{fontCatalog:t})}}],shapeRenderers:[{type:"text",hoverComponent:Lk,component:function(o){
45
+ return d(Ek,{...o,fontCatalog:t,formattingToolbar:e,openLink:n,onTiptapEditorChange:r})}}]}}function Ck(){
46
+ return d("style",{"data-land-plugin":"text",children:'\n.land-text-editor__content {\n width: 100%;\n height: 100%;\n min-height: 100%;\n outline: none;\n white-space: pre-wrap;\n overflow-wrap: break-word;\n}\n\n.land-text-editor__content p {\n margin: 0;\n}\n\n.land-text-editor__content ul,\n.land-text-editor__content ol {\n margin: 0;\n padding-inline-start: 1.5em;\n}\n\n.land-text-editor__content ul {\n list-style: disc;\n}\n\n.land-text-editor__content ol {\n list-style: decimal;\n}\n\n.land-text-editor__content blockquote {\n margin: 0;\n padding-inline-start: 0.75em;\n border-inline-start: 2px solid currentColor;\n}\n\n.land-text-editor__content .land-rich-text-selection {\n background: color-mix(\n in srgb,\n var(--land-selection, #2563eb) 24%,\n transparent\n );\n}\n\n.land-text-search-match {\n border-radius: 2px;\n background: var(--land-text-search-match, #fde68a);\n color: inherit;\n padding: 0;\n}\n\n.land-text-search-match[data-active="true"] {\n background: var(--land-text-search-match-active, #f59e0b);\n}\n'})}function Ak({fontCatalog:t}){return x(()=>{fm(sm,t)},[t]),null}function Ek({shape:t,editor:e,fontCatalog:n,formattingToolbar:o,openLink:i,onTiptapEditorChange:s}){const[a,l]=k(null),c=v(null),p=r(e.state.selectedShapeIds),h=y(kk),f=b(()=>Sk(t.props.richText,h.query),[t.props.richText,h.query]),g=h.activeMatch?.shapeId===t.id?h.activeMatch:null,w=y(bk),{hasEditingSession:P,isEditingThisShape:S,editingHost:I}=wk(e,t,n,o,i,s),M=qg(em(e,t),t.props.w),T=null!==w&&function({isEditing:t,isOnlySelected:e}){return!t&&!e}({isEditing:P,isOnlySelected:1===p.length&&p[0]===t.id}),C=a?pg(a.href):null,A=null!==C&&void 0===e.shapes.get(C),E=m(()=>{null!==c.current&&(window.clearTimeout(c.current),c.current=null)},[]),L=m(()=>{E(),c.current=window.setTimeout(()=>{l(null),c.current=null},160)},[E]);return x(()=>()=>{E()},[E]),x(()=>{T||(E(),l(null))},[T,E]),u("div",{"data-editing-hidden":S?"true":void 0,style:{position:"relative",boxSizing:"border-box",width:t.props.w,minHeight:t.props.h,transform:`scale(${t.props.scale})`,transformOrigin:"top left",color:Nt(t.props.color),fontFamily:Lv(t.props.font,n),fontSize:Bv(t.props.size),lineHeight:`${Rv(t.props.size)}px`,textAlign:Nv(t.props.textAlign),whiteSpace:"pre-wrap",overflowWrap:"break-word",userSelect:"none",pointerEvents:"none"},children:[
47
+ d("div",{style:{boxSizing:"border-box",opacity:S?0:void 0,paddingInline:M,width:"100%"},children:rm(t.props.richText,{linkHandlers:T?{onPointerEnter({href:t,element:e}){E(),l({anchorElement:e,href:t})},onPointerLeave(){L()}}:void 0,defaultBackgroundColor:Ot(t.props.backgroundColor)?void 0:Nt(t.props.backgroundColor),searchRanges:f,activeSearchRange:g})}),T&&a&&w?d(w,{anchorElement:a.anchorElement,href:a.href,kind:C?"internal":"external",unavailable:A,onOpen:()=>{mk({editor:e,href:a.href,openExternal:i})},onPopoverPointerEnter:E,onPopoverPointerLeave:L}):null,
48
+ d("div",{"data-ui":"text-editor-host-slot","data-shape-id":t.id,"data-active":S?"true":"false","aria-hidden":"true",style:{position:"absolute",inset:0,pointerEvents:"none"},children:I})]})}function Lk({strokeWidth:t}){
49
+ return d("div",{"data-ui":"text-hover-outline",style:{boxShadow:`inset 0 0 0 ${t}px ${o}`,inset:0,position:"absolute"}})}var Bk="text.create",Rk=class extends he{constructor(t){super(t,"text"),this.initial="idle",this.addChild(new $k(t,this)),this.addChild(new Nk(t,this))}},$k=class extends he{constructor(t,e){super(t,"idle",e)}onEnter(){this.editor.interaction.clearSelection()}onPointerDown(t){this.transition("pointing",{originPagePoint:t.pagePoint.clone(),originScreenPoint:t.screenPoint.clone(),shapeId:null})}},Nk=class extends he{info=null;operation=null;isHandingOffOperation=!1;constructor(t,e){super(t,"pointing",e)}onEnter(t){this.info=t,this.operation=this.editor.operations.begin({kind:Bk,label:"shape.create",source:"user",history:"record"})}onPointerMove(t){this.updateFixedWidthShape(t.pagePoint,t.screenPoint)}onPointerUp(t){if(!this.info)return void this.transition("idle");const e=null!==this.info.shapeId?this.editor.shapes.get(this.info.shapeId):this.createTextShape(t.pagePoint);if(!Dg(e))return this.cancelOperation(),void this.transition("idle");let n;Yt(this.editor,e.id,{source:"user"}),this.editor.state.tool.get().isToolLocked||(this.isHandingOffOperation=!0,this.transition("idle"),this.editor.commands.setActiveTool("select",{source:"system"}));try{n=this.editor.editing.start({shapeId:e.id,entryMode:"focusEnd",operationKind:Bk,reuseActiveOperation:!0,preserveInteraction:!0},"user")}catch(r){throw this.cancelOperation(),r}finally{this.isHandingOffOperation=!1}n?this.operation=null:this.cancelOperation(),this.editor.state.tool.get().isToolLocked&&this.transition("idle")}onCancel(){this.cancelOperation(),this.transition("idle")}onExit(){this.isHandingOffOperation||this.cancelOperation(),this.info=null}cancelOperation(){const t=this.operation;this.operation=null,t?.isActive&&t.cancel()}updateFixedWidthShape(t,e){if(!this.info)return;const n=function(t,e,n,r,o){const i=Math.abs(r.x-n.x);return n.dist(r)<4||i<8?null:{x:Math.min(t.x,e.x),y:t.y-o.h/2,props:{...zk(o),w:Math.max(16,Math.abs(e.x-t.x)),autoSize:!1}}}(this.info.originPagePoint,t,this.info.originScreenPoint,e,this.getDefaultTextProps());if(n){if(!this.info.shapeId){const t=this.createTextShapeAt(n);return void(this.info.shapeId=t.id)}this.editor.commands.updateShapes([{id:this.info.shapeId,x:n.x,y:n.y,props:{w:n.props.w,h:n.props.h,autoSize:!1}}],{source:"user"})}}createTextShape(t){return this.createTextShapeAt(function(t,e){return{x:t.x,y:t.y-e.h/2,props:zk(e)}}(t,this.getDefaultTextProps()))}createTextShapeAt({x:t,y:e,props:n}){const r=Ug(this.editor,{x:t,y:e,props:n},"user");return this.editor.commands.setSelectedShapeIds([r.id],{source:"system"}),r}getDefaultTextProps(){return jg(this.editor)}};function zk(t){return Fg(t)}var Ok=["start","middle","end"];function Wk(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function Hk(t){return Math.max(.01,t.props.scale)}function Dk(t){return t.props.w*Hk(t)}function Fk(t){return t.props.h*Hk(t)}function jk(t){return new vt(0,0,Dk(t),Fk(t))}function Uk(t){return"left"===t||"right"===t}function Xk(t,e){const n=function(t){return Qt({localWidth:Dk(t),localHeight:Fk(t),scaleX:t.scaleX,scaleY:t.scaleY})}(t),r=e.selectionLocalBounds.w/Math.max(1,n.width),o=e.selectionLocalBounds.h/Math.max(1,n.height);switch(e.handleId){case"left":case"right":return r;case"top":case"bottom":return o;default:return Math.max(r,o)}}var Yk=class extends pe{type="text";getDefaultProps(){return{richText:yg(""),w:16,h:$v(Cv),autoSize:!0,scale:1,font:sm,size:Cv,color:Et("text-slate"),backgroundColor:Lt("transparent"),textAlign:"start"}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{richText:wg(e.richText),w:Math.max(1,Wk(e.w,n.w)),h:Math.max(1,Wk(e.h,n.h)),autoSize:"boolean"==typeof e.autoSize?e.autoSize:n.autoSize,scale:Math.max(.01,Wk(e.scale,n.scale)),font:um(e.font)?e.font:n.font,size:Ev(e.size,n.size),color:$t(e.color,n.color),backgroundColor:$t(e.backgroundColor,n.backgroundColor),textAlign:(r=e.textAlign,"string"==typeof r&&Ok.includes(r)?e.textAlign:n.textAlign)};var r}getPositionedBounds(t){return function(t){return new vt(t.x,t.y,Dk(t),Fk(t))}(t)}getLocalBounds(t){return jk(t)}getRenderBounds(t){return jk(t)}getExportBounds(t){return jk(t)}canSnap(t,e){return!e||(n=e.editor,r=t.id,Qg(n,r)?.behavior.canSnap??null??!0);var n,r}canReceiveTerminalBinding(t,e){return!e||(n=e.editor,r=t.id,Qg(n,r)?.behavior.canReceiveTerminalBinding??null??!0);var n,r}canEdit(t){return!0}contributesToSelectionFrame(t,e){return n=e.editor,r=t.id,Qg(n,r)?.behavior.contributesToSelectionFrame??null??!0;var n,r}canUseSelectionResizeHandles(t,e){return e.editor.state.shapeEditingSession.get()?.shapeId!==t.id&&(n=e.editor,r=t.id,Qg(n,r)?.behavior.canUseSelectionResizeHandles??null??!0);var n,r}canUseSelectionRotateHandle(t,e){return e.editor.state.shapeEditingSession.get()?.shapeId!==t.id&&(n=e.editor,r=t.id,Qg(n,r)?.behavior.canUseSelectionRotateHandle??null??!0);var n,r}getSelectionTargetId(t,e){return function(t,e){const n=Qg(t,e);return n?"owner"===n.behavior.selectionTarget?n.ownerId:e:null}(e.editor,t.id)??t.id}getHoverTargetId(t,e){return function(t,e){const n=Qg(t,e);return n?"owner"===n.behavior.hoverTarget?n.ownerId:e:null}(e.editor,t.id)??t.id}getHoverDecorationTargetId(t,e){return function(t,e){const n=Qg(t,e);return n?"owner"===n.behavior.hoverDecorationTarget?n.ownerId:e:null}(e.editor,t.id)??t.id}getTranslateTargetId(t,e){return function(t,e){const n=Qg(t,e);return n?"owner"===n.behavior.translateTarget?n.ownerId:e:null}(e.editor,t.id)??t.id}resizeSelectionBounds(t,e){const n={};if(e.isOnlyResizeTarget&&Uk(e.handleId)){const r=te({width:e.selectionLocalBounds.w,height:e.selectionLocalBounds.h,scaleX:t.scaleX,scaleY:t.scaleY});n.w=Math.max(16,r.width/Hk(t)),n.autoSize=!1}else n.scale=Math.max(.01,t.props.scale*Xk(t,e));const r=n.scale??Hk(t),o=(n.w??t.props.w)*r,i=t.props.h*r,s=Qt({localWidth:o,localHeight:i,scaleX:t.scaleX,scaleY:t.scaleY}),a=function(t,e){return 0===e.selectionRotation?t.clone():bt.RotWith(t,e.selectionRotationCenter,e.selectionRotation)}(ee({handleId:e.handleId,requestedBounds:e.selectionLocalBounds,actualWidth:s.width,actualHeight:s.height,scaleX:e.scaleX,scaleY:e.scaleY,isResizingFromCenter:e.isResizingFromCenter}).center,e),l=e.scaleX<0!=e.scaleY<0;return{id:t.id,x:a.x-o/2,y:a.y-i/2,rotation:l?2*e.selectionRotation-t.rotation:t.rotation,scaleX:e.scaleX<0?-t.scaleX:t.scaleX,scaleY:e.scaleY<0?-t.scaleY:t.scaleY,props:n}}getAllowedSelectionResizeModes(t,e){return e.isOnlyResizeTarget&&Uk(e.handleId)?Vt:Gt}onEditEnd(t){if(!(xg(t.props.richText).trim().length>0))return{deleteShapeIds:[t.id]}}},Kk=class{fontCatalog;type="text";constructor(t){this.fontCatalog=t}toSvg(t,e){if(0===xg(t.props.richText).trim().length)return null;const n=qg(em(e.editor,t),t.props.w);return{tag:"foreignObject",attrs:{x:0,y:0,width:t.props.w*t.props.scale,height:t.props.h*t.props.scale},children:[{tag:"div",attrs:{xmlns:"http://www.w3.org/1999/xhtml",dir:"auto",style:qk(t,e,this.fontCatalog,n)},children:(r=t.props.richText,o=Ot(t.props.backgroundColor)?void 0:e.resolveColor(t.props.backgroundColor),r.content.map(t=>_k(t,o)))}]};var r,o}};function _k(t,e){const n="codeBlock"===t.type?void 0:e,r=t.content?.map(t=>function(t,e){if(bg(t)){const n=function(t,e){const n=kg(t.marks,e);return n?Ig(n):void 0}(t,e);return n?{tag:"span",attrs:{style:n},children:[t.text]}:t.text}return"hardBreak"===t.type?{tag:"br"}:_k(t,e)}(t,n))??[];if("bulletList"===t.type||"orderedList"===t.type)return{tag:"bulletList"===t.type?"ul":"ol",attrs:{style:"bulletList"===t.type?"margin:0;padding-inline-start:1.5em;list-style-type:disc":"margin:0;padding-inline-start:1.5em;list-style-type:decimal"},children:r};if("listItem"===t.type)return{tag:"li",children:r};if("blockquote"===t.type)return{tag:"blockquote",attrs:{style:"margin:0;padding-inline-start:0.75em;border-inline-start:2px solid currentColor"},children:r};const o=vg(t);return{tag:"p",attrs:{style:o?`margin:0;text-align:${o}`:"margin:0"},children:r.length>0?r:[{tag:"br"}]}}function qk(t,e,n,r){return[`color:${e.resolveColor(t.props.color)}`,`font-family:${Lv(t.props.font,n)}`,`font-size:${Bv(t.props.size)}px`,`line-height:${Rv(t.props.size)}px`,`text-align:${Nv(t.props.textAlign)}`,"white-space:pre-wrap","overflow-wrap:break-word","box-sizing:border-box",`padding-inline:${r}px`,`width:${t.props.w}px`,`height:${t.props.h}px`,`transform:scale(${t.props.scale})`,"transform-origin:top left"].join(";")}var Vk=".label";function Gk(t){return"binding"===t?.typeName&&"path-label"===t.type}function Jk(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):e}var Zk=class extends wt{type=Yg;getDefaultProps(){return{labelPosition:.5}}validateProps(t){const e=this.getDefaultProps();return{labelPosition:Jk((t&&"object"==typeof t?t:{}).labelPosition,e.labelPosition)}}canBind(t,e,n){return this.canUseShapeCompanion(e,n,t)}canUseShapeCompanion(t,e,n){return Dg(e.fromShape)&&(!n||null!==tP(n,e.toShape))}getExclusiveBindingKey(t){return t.toId}onBindingCreate(t,e){return this.syncLabelPosition(t,e)}onBindingUpdate(t,e,n){return this.syncLabelPosition(t,n)}onBindingLoad(t,e){return this.syncLabelPosition(t,e)}getGeometryDependentShapeIds(t,e,n){return"to"===n.role?[e.fromId]:[]}getTargetShapeContentCutoutLocalPolygons(t,e,n){if(!Dg(n.fromShape)||!tP(t,n.toShape))return[];const r=t.shapes.computeLocalToPageTransform(n.toShape).tryInvert();if(!r)return[];const o=t.shapes.computeLocalBounds(n.fromShape),i=r.compose(t.shapes.computeLocalToPageTransform(n.fromShape));return[[new bt(o.minX,o.minY),new bt(o.maxX,o.minY),new bt(o.maxX,o.maxY),new bt(o.minX,o.maxY)].map(t=>i.applyToPoint(t))]}onAfterShapeChange(t,e,n){return this.syncLabelPosition(t,e)}onBeforeDeleteShape(t,e,n){return"from"===n.role?{deleteBindingIds:[e.id]}:{deleteShapeIds:[e.fromId],deleteBindingIds:[e.id]}}onBeforeDeleteBinding(t,e){return{deleteBindingIds:[e.id]}}getExportShapeIds(t,e){return[e.fromId]}getShapeCompanionRootId(t,e){return e===t.fromId?t.toId:null}getSelectionCompanionFrameGeometries(t,e,n){if(e.toId!==n.selectedShape.id)return[];if(!0!==function(t,e){return Qg(t,e)?.behavior.showsCompanionFrameWhenOwnerSelected??null}(t,e.fromId))return[];const r=t.shapes.get(e.fromId),o=t.shapes.get(e.toId);if(!Dg(r)||!o||!tP(t,o))return[];const i=t.shapes.computeGeometry(r),s=t.shapes.computeLocalToPageTransform(r),a=Math.atan2(s.b,s.a);return[{bounds:vt.FromPoints(i.outlineVertices.map(t=>bt.RotWith(t,i.center,-a))),rotation:a,rotationCenter:i.center}]}syncLabelPosition(t,e){if(!Gk(e))return;const n=t.shapes.get(e.fromId),r=t.shapes.get(e.toId);if(!Dg(n)||!r||!tP(t,r))return{deleteBindingIds:[e.id]};const o=function(t,e,n,r){const o=Qk(t,e,n,r),i=n.parentId,s=`${n.index}${Vk}`,a=!1,l=Gg(t,e,i,o);return l?e.x===l.x&&e.y===l.y&&e.rotation===l.rotation&&e.scaleX===l.scaleX&&e.scaleY===l.scaleY&&e.parentId===i&&e.index===s&&e.props.w===o.props.w&&e.props.autoSize===a?null:{id:e.id,...l,parentId:i,index:s,props:{w:o.props.w,autoSize:a}}:null}(t,n,r,e.props.labelPosition);return o?{shapes:[{...n,...o,props:{...n.props,...o.props}}]}:void 0}};function Qk(t,e,n,r=.5){const o=tP(t,n),i=o?eP(t,e,o):{start:0,end:1},s=Math.min(i.end,Math.max(i.start,r)),a=o?.getPointAt(s)??t.shapes.computePageCenter(n),l=tm(t,e,n,Yg),c=Math.min(l.maxWidth,Math.max(l.minWidth,e.props.w));return{x:a.x-c*e.props.scale/2,y:a.y-e.props.h*e.props.scale/2,rotation:Vg(t,n),props:{w:c}}}function tP(t,e){return t.shapes.getUtil(e).getLabelPathGeometry(e,{editor:t})}function eP(t,e,n){if(n.length<=1e-6)return{start:.5,end:.5};const r=t.shapes.getPageBounds(e.id);if(!r)return{start:0,end:1};const o=Math.hypot(r.w,r.h)/2,i=Math.min(.5,(o+8)/n.length);return{start:i,end:1-i}}var nP=".label";function rP(t){return"shape"===t?.typeName&&"geo"===t.type}function oP(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):e}var iP=class extends wt{type=Kg;getDefaultProps(){return{normalizedAnchor:{x:.5,y:.5},ownerBaseHeight:0}}validateProps(t){const e=this.getDefaultProps(),n=t&&"object"==typeof t?t:{},r=n.normalizedAnchor&&"object"==typeof n.normalizedAnchor?n.normalizedAnchor:e.normalizedAnchor;return{normalizedAnchor:{x:oP(r.x,e.normalizedAnchor.x),y:oP(r.y,e.normalizedAnchor.y)},ownerBaseHeight:sP(n.ownerBaseHeight,e.ownerBaseHeight)}}canBind(t,e,n){return this.canUseShapeCompanion(e,n)}canUseShapeCompanion(t,e){return Dg(e.fromShape)&&rP(e.toShape)}getExclusiveBindingKey(t){return t.toId}onBindingCreate(t,e){return this.syncLabelPosition(t,e)}onBindingUpdate(t,e,n){return this.syncLabelPosition(t,n,e.toId===n.toId?void 0:{role:"to"})}onBindingLoad(t,e){return this.syncLabelPosition(t,e)}getGeometryDependentShapeIds(t,e,n){return"from"===n.role?[e.toId]:[e.fromId]}onAfterShapeChange(t,e,n){return this.syncLabelPosition(t,e,n)}onBeforeDeleteShape(t,e,n){if("from"===n.role){const n=t.shapes.get(e.toId),r=n?lP(n,e):null;return{shapes:r?[r]:void 0,deleteBindingIds:[e.id]}}return{deleteShapeIds:[e.fromId],deleteBindingIds:[e.id]}}onBeforeDeleteBinding(t,e){const n=t.shapes.get(e.toId),r=n?lP(n,e):null;return{shapes:r?[r]:void 0,deleteBindingIds:[e.id]}}getExportShapeIds(t,e){return[e.fromId]}getShapeCompanionRootId(t,e){return e===t.fromId?t.toId:null}syncLabelPosition(t,e,n){if(r=e,"binding"!==r?.typeName||"geo-label"!==r.type)return;var r;const o=t.shapes.get(e.fromId),i=t.shapes.get(e.toId);if(!Dg(o)||!rP(i))return{deleteBindingIds:[e.id]};const s=function(t,e,n){const r=aP(e,"h")??1;return"to"===n?.role?r:t.props.ownerBaseHeight>0?t.props.ownerBaseHeight:r}(e,i,n),a=e.props.ownerBaseHeight===s?null:{...e,props:{...e.props,ownerBaseHeight:s}},l=function(t,e,n){const r=aP(t,"h");if(!r)return null;const o=Math.max(n,function(t){return Math.max(1,t.props.h*t.props.scale+32)}(e));return r===o?null:{...t,props:{...t.props,h:o}}}(i,o,s),c=function(t,e,n){const r=cP(t,e,n),o=n.parentId,i=`${n.index}${nP}`,s=!1,a=Gg(t,e,o,r);return a?e.x===a.x&&e.y===a.y&&e.rotation===a.rotation&&e.scaleX===a.scaleX&&e.scaleY===a.scaleY&&e.parentId===o&&e.index===i&&e.props.w===r.props.w&&e.props.autoSize===s?null:{id:e.id,...a,parentId:o,index:i,props:{w:r.props.w,autoSize:s}}:null}(t,o,l??i),d=[];return l&&d.push(l),c&&d.push({...o,...c,props:{...o.props,...c.props}}),d.length>0||a?{shapes:d.length>0?d:void 0,bindings:a?[a]:void 0}:void 0}};function sP(t,e){return"number"==typeof t&&Number.isFinite(t)&&t>0?t:e}function aP(t,e){const n=t.props[e];return"number"==typeof n&&Number.isFinite(n)?n:null}function lP(t,e){const n=aP(t,"h");return!n||e.props.ownerBaseHeight<=0||n===e.props.ownerBaseHeight?null:{...t,props:{...t.props,h:e.props.ownerBaseHeight}}}function cP(t,e,n){const r=t.shapes.computePageCenter(n),o=tm(t,e,n,Kg),i=Math.min(o.maxWidth,Math.max(o.minWidth,e.props.w)),s=t.shapes.computeLocalBounds(n),a=void 0===o.normalizedCenterX||.5===o.normalizedCenterX?r:t.shapes.computeLocalToPageTransform(n).applyToPoint(new bt(s.minX+s.w*o.normalizedCenterX,s.center.y));return{x:a.x-i*e.props.scale/2,y:a.y-e.props.h*e.props.scale/2,rotation:Vg(t,n),props:{w:i}}}var dP="text.edit",uP="path-label.create",pP="path-label.drag",hP="geo-label.edit",fP="geo-label.create",gP={propagation:"stop"};function mP(){let t=null,e=null;const n=()=>{t=null,e=null};return{id:"land.text.interactions",editorEvent:{handleEvent(r,o,i){if("cancel"!==o.type){if("select"===r.state.tool.get().activeToolId)if("pointer"!==o.type||"pointer_move"!==o.name||"dragging"!==r.inputs.state.get().dragPhase){if("pointer"===o.type&&"pointer_up"===o.name){const n=i.pointer?.clickCount??1;return function(t,e,n,r,o){if(!r||r.pointerId!==e.pointerId)return void o();if(o(),n>=2)return;const i=e.screenPoint.x-r.originScreenPoint.x,s=e.screenPoint.y-r.originScreenPoint.y;if(i*i+s*s>9)return;const a=t.shapes.get(r.shapeId);if(!a||!Dg(a)||!t.editing.canEditShape(a))return;t.editing.start({shapeId:a.id,entryMode:"placeCaret",caretPagePoint:e.pagePoint,operationKind:dP,preserveInteraction:!0},"user")}(r,o,n,t,()=>{t=null}),void function(t,e,n,r,o){if(!r||r.pointerId!==e.pointerId)return void o();if(o(),n>=2)return;const i=e.screenPoint.x-r.originScreenPoint.x,s=e.screenPoint.y-r.originScreenPoint.y;if(i*i+s*s>9)return;const a=t.shapes.get(r.shapeId),l=t.selection.getIds();if(!a||!wP(a)||a.isLocked||t.state.shapeEditingSession.get()||1!==l.length||l[0]!==a.id||Jg(t,a.id,"geo-label"))return;const c=vP(t,a);c&&nm(t,c,{editOperationKind:hP,createOperationKind:fP,isExisting:!1,entryMode:"focusEnd"})}(r,o,n,e,()=>{e=null})}if("pointer"!==o.type||"pointer_cancel"!==o.name){if(r.tools.isInInitialState()){if("keyboard"===o.type&&"key_down"===o.name){if(r.state.shapeEditingSession.get())return;if("Enter"!==o.key||o.altKey||o.accelKey)return;const t=r.selection.getIds(),[e]=r.state.selectedShapes.get();if(1!==t.length||!e||!Dg(e)||!r.editing.canEditShape(e))return;return r.editing.start({shapeId:e.id,entryMode:"selectAll",operationKind:dP},"user"),gP}if("double_click"===o.type)return n(),function(t,e){const n=t.shapes.hitTest(e.pagePoint);if(!n)return!1;if(Dg(n))return!!t.editing.canEditShape(n)&&(t.editing.start({shapeId:n.id,entryMode:"selectAll",operationKind:dP},"user"),!0);return wP(n)?function(t,e){return!e.isLocked&&(xP(t,e.id),!0)}(t,n):!!tP(t,n)&&function(t,e,n){return!e.isLocked&&(yP(t,e.id,n),!0)}(t,n,e.pagePoint)}(r,o)?gP:void 0;if("pointer"===o.type&&"pointer_down"===o.name){n();const s=function(t,e,n,r){const o=t.shapes.hitTest(e.pagePoint);if(!o||!Dg(o)||!t.editing.canEditShape(o))return;const i=t.state.shapeEditingSession.get();if(i&&i.shapeId!==o.id)return t.editing.complete("user")?(t.editing.start({shapeId:o.id,entryMode:"placeCaret",caretPagePoint:e.pagePoint,operationKind:dP,preserveInteraction:!0},"user"),gP):gP;!i&&n<2&&function(t,e){const n=t.selection.getIds();if(1!==n.length)return!1;if(n[0]===e)return!0;const r=Qg(t,e);return!!r&&r.behavior.canPlaceCaretWhenOwnerSelected&&n[0]===r.ownerId}(t,o.id)&&r({pointerId:e.pointerId,shapeId:o.id,originScreenPoint:{x:e.screenPoint.x,y:e.screenPoint.y}})}(r,o,i.pointer?.clickCount??1,e=>{t=e});return"stop"===s?.propagation||t?s:void function(t,e,n,r){const o=t.shapes.hitTest(e.pagePoint),i=t.selection.getIds();if(!o||!wP(o)||o.isLocked||t.state.shapeEditingSession.get()||e.shiftKey||e.altKey||e.accelKey||n>=2||1!==i.length||i[0]!==o.id||Jg(t,o.id,"geo-label"))return;r({pointerId:e.pointerId,shapeId:o.id,originScreenPoint:{x:e.screenPoint.x,y:e.screenPoint.y}})}(r,o,i.pointer?.clickCount??1,t=>{e=t})}}}else n()}else n()}else n()}},shapePointer:{createSession:(t,e)=>function(t,e){if(e.event.shiftKey||e.event.accelKey||t.state.shapeEditingSession.get()||!Dg(e.shape))return null;const n=t.bindings.getFromShape(e.shape.id).find(Gk);if(!n||n.toId!==e.selectionTargetId)return null;const r=t.shapes.get(n.toId),o=t.shapes.getPageBounds(e.shape.id);if(!r||!o||t.layers.isOrAncestorLocked(r.id)||!tP(t,r))return null;const i=o.center.sub(e.originPagePoint);return{shapeId:r.id,operationKind:pP,onDragStart({editor:t}){t.commands.setSelectedShapeIds([r.id],{source:"system"})},update({editor:t,pagePoint:e,source:r}){const o=t.bindings.get(n.id),s=t.shapes.get(n.fromId),a=t.shapes.get(n.toId);if(!Gk(o)||!Dg(s)||!a)return"stop";const l=tP(t,a);if(!l)return"stop";const c=bP({editor:t,label:s,pathGeometry:l,pagePoint:e.add(i),hintPosition:o.props.labelPosition,snapToDefault:!0});return Math.abs(c-o.props.labelPosition)>1e-6&&t.commands.updateBinding({id:o.id,props:{labelPosition:c}},{source:r}),{status:"continue",finalPagePoint:l.getPointAt(c)}}}}(t,e)}}}function yP(t,e,n){const r=t.shapes.get(e);if(!r||r.isLocked)return!1;const o=tP(t,r);if(!o)return!1;const i=Jg(t,r.id,Yg),s=i??function(t,e,n){const r=tP(t,e);if(!r)return null;const o=kP(e,{...jg(t),autoSize:!1,textAlign:"middle"}),i=r.getNearestPosition(n,{hintPosition:r.defaultPosition}),s=Qk(t,o,e,i),a=Zg(t,{bindingType:Yg,owner:e,operationKind:uP,index:`${e.index}${Vk}`,layout:s,bindingProps:{labelPosition:i}});if(!a)return null;const l=t.shapes.get(a.id),c=t.bindings.getFromShape(a.id).find(Gk);if(!Dg(l)||!c)return a;const d=bP({editor:t,label:l,pathGeometry:r,pagePoint:n,hintPosition:i,snapToDefault:!1});Math.abs(d-i)>1e-6&&t.commands.updateBinding({id:c.id,props:{labelPosition:d}},{source:"user"});return a}(t,r,n??o.getPointAt(o.defaultPosition));return!!s&&(nm(t,s,{editOperationKind:"path-label.edit",createOperationKind:uP,isExisting:!!i}),!0)}function xP(t,e){const n=t.shapes.get(e);if(!n||!wP(n)||n.isLocked)return!1;const r=Jg(t,n.id,Kg),o=r??vP(t,n);return!!o&&(nm(t,o,{editOperationKind:hP,createOperationKind:fP,isExisting:!!r,entryMode:r?"selectAll":"focusEnd"}),!0)}function wP(t){return"geo"===t.type}function bP({editor:t,label:e,pathGeometry:n,pagePoint:r,hintPosition:o,snapToDefault:i}){let s=n.getNearestPosition(r,{hintPosition:o});if(i){const e=n.defaultPosition,r=n.getPointAt(e),o=n.getPointAt(s),i=Math.max(t.state.cameraZoom.get(),1e-4);o.dist(r)*i<=10&&(s=e)}const a=eP(t,e,n);return Math.min(a.end,Math.max(a.start,s))}function vP(t,e){const n=cP(t,kP(e,{...jg(t),autoSize:!1,textAlign:"middle"}),e);return Zg(t,{bindingType:Kg,owner:e,operationKind:fP,index:`${e.index}${nP}`,layout:n,bindingProps:{normalizedAnchor:{x:.5,y:.5}}})}function kP(t,e){return{id:"shape:draft",typeName:"shape",scope:"document",type:"text",parentId:t.parentId,index:`${t.index}.label`,x:0,y:0,rotation:0,scaleX:1,scaleY:1,opacity:1,isHidden:!1,isLocked:!1,meta:{},props:e}}function PP({fontCatalog:t=cm()}={}){return{id:"land.text",shapeUtils:[new Yk],shapeSvgExporters:[new Kk(t)],bindingUtils:[new iP,new Zk],interactionHandlers:[mP()],setup(t){t.tools.register("text",t=>new Rk(t))}}}var SP=bn("plugin-text.api");function IP({editor:t}){return function({editor:t}){return{create(e){const n=t.shapes.getDefaultProps("text"),[r]=t.commands.createShapes([{type:"text",x:e.x,y:e.y,meta:e.meta?{...e.meta}:void 0,props:{...n,w:e.w??n.w,h:e.h??n.h,font:e.font??n.font,color:e.color??n.color,size:e.size??n.size,textAlign:e.textAlign??n.textAlign,richText:yg(e.text)}}],{source:"user"});return"text"===r?.type?{id:r.id,type:r.type}:null},startEditing(e){const n=e??t.selection.getIds()[0],r=n?t.shapes.get(n):null;return!(!r||"text"!==r.type||r.isLocked)&&(t.editing.start({shapeId:r.id,entryMode:"focusEnd"},"user"),!0)},startEditingGeoLabel(e){const n=t.selection.getIds(),r=e??(1===n.length?n[0]:void 0);return!!r&&xP(t,r)},startEditingPathLabel(e){const n=t.selection.getIds(),r=e??(1===n.length?n[0]:void 0);return!!r&&yP(t,r)},getBoundTextLabel(e){const n=Jg(t,e,"geo-label")??Jg(t,e,"path-label");return n&&xg(n.props.richText).trim().length>0?{id:n.id,type:n.type}:null},getFormattingSnapshot:()=>function(t){return hv(t)?.getSnapshot()??null}(t),setSelectionStyle(e,n){const r=n?null:hv(t);if(r)return void 0!==e.color&&r.setColor(TP(e.color)),void 0!==e.backgroundColor&&r.setBackgroundColor(TP(e.backgroundColor)),void 0!==e.font&&r.setFont(e.font),void 0!==e.size&&r.setSize(e.size),void 0!==e.textAlign&&r.setTextAlign(e.textAlign),[r.shapeId];const o=MP(t,n).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...e}}));return o.length>0&&t.commands.updateShapes(o.map(({id:t,props:e})=>({id:t,props:{...e}})),{source:"user"}),o.map(({id:t})=>t)},getInlineFormatState(e,n){const r=n?null:hv(t);if(r)return r.getSnapshot()?.[e]??!1;const o=MP(t,n).map(t=>xv(t.props.richText,e));if(0===o.length)return!1;const i=o[0]??!1;return o.every(t=>t===i)?i:"mixed"},toggleInlineFormat(e,n){const r=n?null:hv(t);if(r)return r.toggle(e);const o=MP(t,n).filter(t=>!t.isLocked),i=!o.every(t=>!0===xv(t.props.richText,e)),s=o.map(t=>({shape:t,richText:wv(t.props.richText,e,i)})).filter(({shape:t,richText:e})=>e!==t.props.richText);return 0!==s.length&&(t.commands.updateShapes(s.map(({shape:t,richText:e})=>({id:t.id,props:{richText:e}})),{source:"user"}),!0)},getBlockType(e){const n=e?null:hv(t);if(n)return n.getSnapshot()?.blockType??null;const r=MP(t,e).map(t=>gv(t.props.richText));if(0===r.length)return null;const o=r[0]??null;return r.every(t=>t===o)?o:"mixed"},setBlockType(e,n){const r=n?null:hv(t);if(r)return r.setBlockType(e);const o=MP(t,n).filter(t=>!t.isLocked).map(t=>({shape:t,richText:mv(t.props.richText,e)})).filter(({shape:t,richText:e})=>e!==t.props.richText);return 0!==o.length&&(t.commands.updateShapes(o.map(({shape:t,richText:e})=>({id:t.id,props:{richText:e}})),{source:"user"}),!0)},clearFormatting(){const e=hv(t);if(e)return e.clearFormatting();const n=t.state.selectedShapes.get().filter(Dg).filter(t=>!t.isLocked).map(t=>({shape:t,richText:vv(t.props.richText)})).filter(({shape:t,richText:e})=>e!==t.props.richText||!Ot(t.props.backgroundColor));return 0!==n.length&&(t.commands.updateShapes(n.map(({shape:t,richText:e})=>({id:t.id,props:{richText:e,backgroundColor:Lt("transparent")}})),{source:"user"}),!0)},getLinkHref(){const e=hv(t);if(e)return e.getSnapshot()?.linkHref??null;const n=t.state.selectedShapes.get().filter(Dg).map(t=>function(t){const e=[];if(kv(t.content,(t,n)=>{if("text"!==t.type||!t.text||n.insideCodeBlock||t.marks?.some(t=>"code"===t.type))return;const r=t.marks?.find(t=>"link"===t.type)?.attrs?.href;e.push("string"==typeof r&&r.length>0?r:null)}),0===e.length)return null;const n=e[0]??null;return e.every(t=>t===n)?n:"mixed"}(t.props.richText));if(0===n.length)return null;const r=n[0]??null;return n.every(t=>t===r)?r:"mixed"},setLink(e){const n=hv(t);if(n)return n.setLink(e);const r=null===e?null:lg(e);if(null!==e&&null===r)return!1;const o=t.state.selectedShapes.get().filter(Dg).filter(t=>!t.isLocked).map(t=>({shape:t,richText:bv(t.props.richText,r)})).filter(({shape:t,richText:e})=>e!==t.props.richText);return 0!==o.length&&(t.commands.updateShapes(o.map(({shape:t,richText:e})=>({id:t.id,props:{richText:e}})),{source:"user"}),!0)},getToolDefaults:()=>t.shapes.getDefaultProps("text"),setToolDefaults:e=>(t.shapes.updateDefaultProps("text",e),t.shapes.getDefaultProps("text"))}}({editor:t})}function MP(t,e){if(e){const n=t.shapes.get(e);return Dg(n)?[n]:[]}return t.state.selectedShapes.get().filter(Dg)}function TP(t){const e=zt(t);return"transparent"===e?null:e}function CP(t={}){const{fontCatalog:e,openLink:n,...r}=t,o={...lm(),...r},i=e??dm(o);return{id:"text",editor:PP({fontCatalog:i}),render:Tk({fontCatalog:i,formattingToolbar:o.formattingToolbar,openLink:n,onTiptapEditorChange:o.onTiptapEditorChange}),api:SP,setup:({editor:t})=>({api:IP({editor:t})})}}var AP=CP();function EP(t){return{kind:"svg-inliner",id:"text.svg-inliner",async inline({exportedShapes:e,svg:n}){const r=e.filter(Dg),o=r.map(t=>xg(t.props.richText)).join(""),i=new Set(r.map(t=>t.props.font)),s=[t.defaultFont,...t.fontsById.values()].filter(e=>function({definition:t,isDefault:e,svg:n,usedFontIds:r}){return!!t.source&&"system"!==t.source.kind&&(e&&r.has("default")||r.has(t.id)||n.includes(`font-family:${o=t.cssFamily,o.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}`));var o}({definition:e,isDefault:e===t.defaultFont,svg:n,usedFontIds:i})),a=(await Promise.all(s.map(t=>async function(t,e){const{source:n}=t;if(!n||"system"===n.kind)return"";if("stylesheet"===n.kind){const r=function(t,e){const n=zP(t);if(e.length>0&&"fonts.googleapis.com"===n.hostname&&!n.searchParams.has("text")){const t=Array.from(new Set(e)).join("");encodeURIComponent(t).length<=1500&&n.searchParams.set("text",t)}return n.href}(n.cssUrl,e),o=await $P(r,t.id);return RP(BP(await LP(await o.text(),o.url||r,t.id)),t.id)}return async function(t,e){const n="string"==typeof t.src?RP(BP(await LP(t.src,void 0,e)),e):`url("${await NP(new Blob([t.src],{type:"application/octet-stream"}),e)}")`,r=function(t){return t?[["ascent-override",t.ascentOverride],["descent-override",t.descentOverride],["font-display",t.display],["font-feature-settings",t.featureSettings],["line-gap-override",t.lineGapOverride],["font-stretch",t.stretch],["font-style",t.style],["unicode-range",t.unicodeRange],["font-weight",t.weight]].flatMap(([t,e])=>e?[`;${t}:${e}`]:[]).join(""):""}(t.descriptors);return`@font-face{font-family:${o=t.family,`"${o.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`};src:${n}${r}}`;var o}(n,t.id)}(t,o)))).filter(t=>t.length>0);return a.length>0?function(t,e){const n=t.match(/^<svg\b[^>]*>/u);if(!n)throw new Error("Could not embed font resources in the generated SVG.");const r=`<style type="text/css">${o=e,o.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}</style>`;var o;return`${n[0]}${r}${t.slice(n[0].length)}`}(n,a.join("\n")):n}}}async function LP(t,e,n){const r=Array.from(t.matchAll(/\burl\(\s*(["']?)(.*?)\1\s*\)/giu),t=>t[2]?.trim()).filter(t=>!!t),o=new Map;for(const i of new Set(r)){if(i.startsWith("data:")||i.startsWith("#"))continue;const t=zP(i,e).href,r=await NP(await(await $P(t,n)).blob(),n);o.set(i,r)}return t.replace(/\burl\(\s*(["']?)(.*?)\1\s*\)/giu,(t,e,n)=>{const r=o.get(n.trim());return r?`url(${e}${r}${e})`:t})}function BP(t){const e=String.raw`\blocal\(\s*(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|[^)]*)\s*\)`;return t.replace(new RegExp(`${e}\\s*,\\s*`,"giu"),"").replace(new RegExp(`\\s*,\\s*${e}`,"giu"),"").replace(new RegExp(e,"giu"),"")}function RP(t,e){if(!/\burl\(\s*["']?data:/iu.test(t))throw new Error(`Font resource "${e}" has no embeddable source.`);return t}async function $P(t,e){let n;try{n=await fetch(t)}catch(r){throw new Error(`Could not download font resource "${e}".`,{cause:r})}if(!n.ok)throw new Error(`Could not download font resource "${e}" (${n.status}).`);return n}async function NP(t,e){const n=await async function(t){const e=new Uint8Array(await t.arrayBuffer());let n="";for(let r=0;r<e.length;r+=32768)n+=String.fromCharCode(...e.subarray(r,r+32768));return`data:${t.type||"application/octet-stream"};base64,${btoa(n)}`}(t);if(!n)throw new Error(`Could not embed font resource "${e}".`);return n}function zP(t,e){try{return e?new URL(t,e):new URL(t,globalThis.location?.href)}catch(n){throw new Error(`Could not resolve font resource URL "${t}".`,{cause:n})}}function OP({fontCatalog:t}){return{id:"text.svg-export",requires:[AP],setup:()=>({exports:[EP(t)]})}}function WP(t){dg(t)&&window.open(t,"_blank","noopener,noreferrer")}function HP(t){return"text"===t?"文字生成":"图片生成"}function DP(t,e){if("text"===e){const n=t.shapes.getDefaultProps("text"),r=160,o=n.h;return{w:r,h:o,title:HP(e),contentProps:{...n,w:r,h:o,autoSize:!1,richText:yg(""),textAlign:"middle"}}}const n=t.shapes.getDefaultProps("image");return{w:n.w,h:n.h,title:HP(e),contentProps:{...n,altText:""}}}function FP(t,e){if(t.state.readonly.get())return null;const n=t.shapes.get(e),r=XP(n);if(!n||!r||t.layers.isOrAncestorLocked(n.id)||t.shapes.isHidden(n.id)||Math.abs(Math.abs(n.scaleX)-1)>1e-8||Math.abs(Math.abs(n.scaleY)-1)>1e-8)return null;const o=t.shapes.computeLocalBounds(n);if(Math.abs(o.x)>1e-8||Math.abs(o.y)>1e-8)return null;const i=t.bindings.getToShape(n.id).filter(Cr).map(({id:t})=>t),s=t.operations.begin({kind:"flow.wrap-shape",label:"shape.wrap-flow-node",source:"user",history:"record"});try{const e=t.commands.createShapes([{type:"flow-node",parentId:n.parentId,index:n.index,x:n.x,y:n.y,rotation:n.rotation,scaleX:n.scaleX,scaleY:n.scaleY,opacity:n.opacity,props:{w:o.w,h:o.h,title:HP(r),kind:r}}],{source:"user",autoReparent:!1})[0];if(!UP(e))return s.cancel(),null;if(!t.commands.reparentShapes({ids:[n.id],parentId:e.id},{source:"user"}))return s.cancel(),null;t.commands.updateShapes([{id:n.id,opacity:1}],{source:"user"});for(const n of i)t.commands.updateBinding({id:n,toId:e.id},{source:"user"});return t.commands.setSelectedShapeIds([e.id],{source:"system"}),s.commit(),{nodeId:e.id,contentId:n.id}}catch(a){throw s.isActive&&s.cancel(),a}}function jP(t,e){if(t.state.readonly.get())return null;const n=t.shapes.get(e);if(!UP(n)||t.layers.isOrAncestorLocked(n.id)||t.layers.hasLockedDescendant(n.id)||t.shapes.isHidden(n.id))return null;const r=t.layers.getChildren(n.id);if(1!==r.length||!XP(r[0]))return null;const o=r[0],i=t.bindings.getToShape(n.id).filter(Cr).map(({id:t})=>t),s=t.operations.begin({kind:"flow.unwrap-node",label:"shape.unwrap-flow-node",source:"user",history:"record"});try{if(!t.commands.reparentShapes({ids:[o.id],parentId:n.parentId},{source:"user"}))return s.cancel(),null;t.commands.updateShapes([{id:o.id,index:n.index,opacity:o.opacity*n.opacity}],{source:"user"});for(const e of i)t.commands.updateBinding({id:e,toId:o.id},{source:"user"});return t.commands.deleteShapes([n.id],{source:"user"}),t.commands.setSelectedShapeIds([o.id],{source:"system"}),s.commit(),t.shapes.get(o.id)??null}catch(a){throw s.isActive&&s.cancel(),a}}function UP(t){return"flow-node"===t?.type}function XP(t){return"text"===t?.type||"image"===t?.type?t.type:null}var YP=bn("plugin-flow.api");function KP({editor:t}){return{wrapShape(e){const n=FP(t,e);return n?{id:n.nodeId,type:"flow-node",contentId:n.contentId}:null},unwrapNode(e){const n=jP(t,e);return n?{id:n.id,type:n.type}:null}}}var _P=96;function qP(t,e,n){if(t.state.readonly.get())return null;const r=t.shapes.get(e.shape.id);if(!r||t.layers.isOrAncestorLocked(r.id)||t.shapes.isHidden(r.id))return null;const o=ae(t,r,e.port.id);if(!o)return null;const i=Xa(t,{shape:r,port:o},function(t,e,n,r){const o=DP(t,r),i=e.parentId,s=i.startsWith("shape:")?t.shapes.get(i):null,a=s?t.shapes.computeLocalToPageTransform(s):Ht.Identity(),l=a.tryInvert(),c=n.pageOutwardNormal.normalize(),d=new bt(o.w/2,o.h/2),u=a.applyToPoint(d),p=a.applyToPoint(d.add(new bt(o.w/2,0))),h=a.applyToPoint(d.add(new bt(0,o.h/2))),f=Math.abs(VP(p.sub(u),c))+Math.abs(VP(h.sub(u),c)),g=n.pagePoint.add(c.mul(96+f)),m=l?.applyToPoint(g)??g;return{type:"flow-node",parentId:i,x:m.x-o.w/2,y:m.y-o.h/2,rotation:0,props:{w:o.w,h:o.h,title:o.title,kind:r}}}(t,r,o,n)),s=t.operations.begin({kind:`flow.create-${n}-node`,label:"shape.create",source:"user",history:"record"});try{const e=function(t,e,n){const r=DP(t,n),o=t.commands.createShapes([{...e,type:"flow-node",props:{w:r.w,h:r.h,title:r.title,kind:n,...e.props}}],{source:"user",autoReparent:!1})[0];if(!UP(o))return null;const i=t.commands.createShapes([{type:n,parentId:o.id,x:0,y:0,props:r.contentProps}],{source:"user",autoReparent:!1})[0];return i&&i.type===n?{nodeId:o.id,contentId:i.id}:null}(t,i,n);if(!e)return s.cancel(),null;const a=t.shapes.get(e.nodeId);if(!a||"flow-node"!==a.type)return s.cancel(),null;const l=_a(t,a,o);if(!l)return s.cancel(),null;const c=bi(t,{start:yi(r.id,o),end:yi(a.id,l),props:{routing:"curved"},selectionAfter:[a.id]});return c?(s.commit(),{contentId:e.contentId,connectorId:c.id,nodeId:a.id}):(s.cancel(),null)}catch(a){throw s.isActive&&s.cancel(),a}}function VP(t,e){return t.x*e.x+t.y*e.y}var GP=34,JP=["text","image"];function ZP(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.max(1,t):e}function QP(t,e){return JP.includes(t)?t:e}function tS(t){return/^\s*$/.test(t.props.title)?"text"===t.props.kind?"文字生成":"图片生成":t.props.title}function eS(t){return new vt(0,-34,t.props.w,t.props.h+34)}var nS=class extends pe{type="flow-node";getDefaultProps(){return{w:240,h:180,title:"",kind:"image"}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:ZP(e.w,n.w),h:ZP(e.h,n.h),title:"string"==typeof e.title?e.title:n.title,kind:QP(e.kind,n.kind)}}getLocalBounds(t){return new vt(0,0,t.props.w,t.props.h)}getRenderBounds(t){return eS(t)}getPointHitTestBounds(t){const e=eS(t);return new vt(e.x+t.x,e.y+t.y,e.w,e.h)}hitTest(t,e){return this.getPositionedBounds(t).containsPoint(e)||function(t){return new vt(t.x,t.y-34,t.props.w,34)}(t).containsPoint(e)}hitTestBindingTarget(t,e){return this.getPositionedBounds(t).containsPoint(e)}canEdit(t){return!1}canReceiveTerminalBinding(t){return!0}canUseTerminalBindingPortHandles(t){return!1}canReceiveChildren(t){return!0}canReceiveChild(t,e){return"text"===e.type||"image"===e.type}canAutomaticallyReceiveChildren(t){return!1}getChildClipLocalBounds(t){return this.getLocalBounds(t)}isSelectionTransformContainer(t){return!0}shouldResizeDescendants(t){return!0}getResizeToFitDescendantsProps(t,e){return this.validateProps({...t.props,w:e.w,h:e.h})}},rS=184,oS=["left","right"],iS={id:"land.flow.dom-events",handle:({event:t,name:e})=>"pointer_down"===e&&t.target instanceof Element&&t.target.closest("[data-flow-port-button]")?"continue":mS(t.target)?"handled":"continue",getCursor:({element:t})=>t?.closest("[data-flow-connector-port]")?"pointer":void 0};function sS(t={}){const e=new Set(t.visiblePortIds??oS);return{id:"land.flow.react",shapeRenderers:[{type:"flow-node",component:aS,foregroundComponent:lS}],canvasOverlays:[{id:"land.flow.connector-ports",order:110,component:()=>d(cS,{visiblePortIds:e})}],domEventGuards:[iS]}}function aS(t){return null}function lS({editor:t,shape:e}){const n="text"===e.props.kind?lr:ir;
50
+ return d("div",{style:{height:"100%",overflow:"visible",pointerEvents:"none",position:"relative",width:"100%"},children:d(s,{editor:t,shape:e,isEditing:!1,value:e.props.title,fallback:tS(e),bodyWidth:e.props.w,bodyHeight:e.props.h,renderHeight:34,operationKind:"flow-node.edit",editAriaLabel:"Flow node title",inputAriaLabel:"Flow node title",dataUi:{heading:"flow-node-canvas-heading",dragHandle:"flow-node-drag-handle",name:"flow-node-canvas-name",input:"flow-node-canvas-name-input"},onValueChange:n=>{t.commands.updateShapes([{id:e.id,props:{title:n}}],{source:"user"})},leading:d(n,{"data-ui":"flow-node-title-icon","data-flow-node-kind":e.props.kind,size:14,stroke:1.7}),color:"var(--land-text-muted, #64748b)",offsetX:0,editable:!1,showBackground:!1,showDragHandle:!1})})}var cS=g(function({visiblePortIds:t}){const e=n(),o=r(e.state.readonly),i=r(e.state.tool).activeToolId;r(e.state.selectedShapes);const s=r(e.state.shapeEditingSession),a=r(e.inputs.isSpacePressed),l=r(e.render.interaction.selectionTranslationActive),c=r(e.state.cameraZoom),[p,h]=k(null),f=Math.max(c,1e-4),g=el(e),y="select"===i?g.visibleShapes.filter(t=>g.sourceShapeIds.has(t.id)&&function(t){return"flow-node"===t.type||"text"===t.type||"image"===t.type}(t)):[],w=p?function(t,e,n,r){const o=e.find(t=>t.id===n.shapeId);if(!o)return null;const i=ae(t,o,n.portId);return i&&hS(o,i,r)?{shape:o,port:i}:null}(e,y,p,t):null,b=null!==w,v=null!==p&&null===w;x(()=>{v&&h(null)},[v]),x(()=>{if(!b)return;const t=t=>{mS(t.target)||h(null)},e=t=>{"Escape"===t.key&&h(null)};return document.addEventListener("pointerdown",t),document.addEventListener("keydown",e),()=>{document.removeEventListener("pointerdown",t),document.removeEventListener("keydown",e)}},[b]);const P=m(t=>{h(e=>e?.shapeId===t.shapeId&&e.portId===t.portId?null:t)},[]),S=m(t=>{w&&(qP(e,w,t),h(null))},[e,w]);return o||s||a||l||0===y.length?null:u("g",{"data-ui":"flow-connector-ports-overlay",children:[
51
+ d("style",{children:yS}),y.flatMap(n=>se(e,n).map(r=>{if(!hS(n,r,t))return null;const o={shapeId:n.id,portId:r.id};
52
+ return d(dS,{editor:e,isOpen:p?.shapeId===n.id&&p.portId===r.id,onToggle:()=>P(o),port:r,shape:n,zoom:f},`${n.id}:${r.id}`)})),w?d(uS,{onCreate:S,port:w.port,zoom:f}):null]})});function dS({editor:n,isOpen:r,onToggle:o,port:i,shape:s,zoom:a}){const l=Ha(i,a),c=24;
53
+ return d("foreignObject",{"data-flow-connector-port":"true","data-flow-connector-port-id":i.id,"data-flow-connector-port-shape-id":s.id,height:c/a,overflow:"visible",pointerEvents:"all",width:c/a,x:l.x-12/a,y:l.y-12/a,children:d("div",{style:{height:c,transform:`scale(${1/a})`,transformOrigin:"top left",width:c},children:d("button",{"aria-expanded":r,"aria-haspopup":"menu","aria-label":"新增节点","data-flow-port-button":"true","data-flow-ui":"true",onClick:t=>{0===t.detail&&o()},onPointerDown:r=>{0===r.button&&Ml(n,{source:{shape:s,port:i},originScreenPoint:e(r,t(r.currentTarget)),pointerId:r.pointerId,onClickWithoutDrag:o})},style:xS,type:"button",children:d("span",{"data-flow-port-visual":"true",style:wS,children:d(ar,{"aria-hidden":"true","data-flow-port-plus-icon":"true",size:14,strokeWidth:2.5})})})})})}function uS({onCreate:t,port:e,zoom:o}){const i=n(),s=r(i.state.viewportScreenSize),a=function(t,e,n,r){const o=t.viewport.pageToScreen(new bt(e.x,e.y)),i=rS,s=120,a=16,l=8,c=n.pageOutwardNormal;let d,u;if(Math.abs(c.x)>=Math.abs(c.y)){const t=c.x>=0?o.x+a:o.x-a-i,e=c.x>=0?o.x-a-i:o.x+a;d=fS(t,i,r.w,l)?t:e,u=o.y-s/2}else{const t=c.y>=0?o.y+a:o.y-a-s,e=c.y>=0?o.y-a-s:o.y+a;d=o.x-i/2,u=fS(t,s,r.h,l)?t:e}const p=t.viewport.screenToPage(new bt(gS(d,i,r.w,l),gS(u,s,r.h,l)));return{x:p.x,y:p.y}}(i,Ha(e,o),e,s);
54
+ return d("foreignObject",{"data-flow-node-menu":"true",height:120/o,overflow:"visible",pointerEvents:"all",width:rS/o,x:a.x,y:a.y,children:u("div",{"aria-label":"新增节点","data-flow-ui":"true",onPointerDown:t=>{t.stopPropagation()},role:"menu",style:{...bS,transform:`scale(${1/o})`},children:[
55
+ d("div",{"data-flow-menu-title":"true",style:vS,children:"新增节点"}),
56
+ d(pS,{icon:cr,label:"文字生成",onSelect:()=>t("text")}),
57
+ d(pS,{icon:sr,label:"图片生成",onSelect:()=>t("image")})]})})}function pS({icon:t,label:e,onSelect:n}){
58
+ return u("button",{"data-flow-menu-item":e,onClick:n,role:"menuitem",style:kS,type:"button",children:[d(t,{"aria-hidden":"true",size:16,strokeWidth:2}),d("span",{children:e})]})}function hS(t,e,n){return n.has(e.id)&&("flow-node"===t.type||"right"===e.id)}function fS(t,e,n,r){return t>=r&&t+e<=n-r}function gS(t,e,n,r){return Math.min(Math.max(t,r),Math.max(r,n-e-r))}function mS(t){return t instanceof Element&&!!t.closest("[data-flow-ui]")}var yS='\n [data-flow-port-visual] {\n transition: transform 120ms ease, box-shadow 120ms ease;\n }\n [data-flow-port-button]:hover [data-flow-port-visual],\n [data-flow-port-button][aria-expanded="true"] [data-flow-port-visual],\n [data-flow-port-button]:focus-visible [data-flow-port-visual] {\n transform: scale(1.2);\n }\n [data-flow-port-button]:focus-visible [data-flow-port-visual] {\n box-shadow: 0 0 0 2px var(--popover, #ffffff), 0 0 0 4px var(--land-selection, #2563eb);\n }\n [data-flow-menu-item]:hover,\n [data-flow-menu-item]:focus-visible {\n background: rgba(37, 99, 235, 0.1) !important;\n }\n @media (prefers-reduced-motion: reduce) {\n [data-flow-port-visual] {\n transition: none;\n }\n }\n',xS={alignItems:"center",background:"transparent",border:0,cursor:"pointer",display:"flex",height:"100%",justifyContent:"center",outline:"none",padding:0,width:"100%"},wS={alignItems:"center",background:"var(--land-selection, #2563eb)",borderRadius:"999px",boxShadow:"0 1px 3px rgba(15, 23, 42, 0.24)",color:"#ffffff",display:"flex",height:20,justifyContent:"center",transformOrigin:"center",width:20},bS={background:"var(--popover, #ffffff)",border:"1px solid var(--border, #e2e8f0)",borderRadius:10,boxShadow:"0 12px 30px rgba(15, 23, 42, 0.16)",boxSizing:"border-box",color:"var(--popover-foreground, #0f172a)",display:"flex",flexDirection:"column",fontFamily:"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",gap:2,padding:6,transformOrigin:"top left",width:rS},vS={color:"var(--muted-foreground, #64748b)",fontSize:12,fontWeight:600,lineHeight:"18px",padding:"2px 8px 4px"},kS={alignItems:"center",background:"transparent",border:0,borderRadius:7,color:"inherit",cursor:"pointer",display:"flex",flexShrink:0,font:"inherit",fontSize:13,fontWeight:500,gap:9,height:34,outline:"none",padding:"0 8px",textAlign:"left",width:"100%"},PS=class{type="flow-node";toSvg(t,e){return{tag:"rect",attrs:{x:0,y:0,width:t.props.w,height:t.props.h,rx:8,ry:8,fill:"#ffffff"}}}toSvgForeground(t,e){return{tag:"g",children:[{tag:"rect",attrs:{x:.5,y:.5,width:Math.max(t.props.w-1,0),height:Math.max(t.props.h-1,0),rx:8,ry:8,fill:"none",stroke:"#94a3b8","stroke-width":1}},{tag:"text",attrs:{x:0,y:-8,fill:"#0f172a","font-family":"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif","font-size":12,"font-weight":400},children:[tS(t)]}]}}};function SS(){return{id:"land.flow",shapeUtils:[new nS],shapeSvgExporters:[new PS]}}function IS(t={}){const e=t.visiblePortIds?[...t.visiblePortIds]:void 0;return{id:"flow",requires:[rc,sf,AP],editor:SS(),render:sS({visiblePortIds:e}),api:YP,setup:({editor:t})=>({api:KP({editor:t})})}}var MS=IS();function TS(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.max(1,t):e}var CS=class extends pe{type="group";getGroupingShapeCreateInput({parentId:t,parentLocalBounds:e}){return{type:this.type,x:e.x,y:e.y,parentId:t,props:{w:e.w,h:e.h}}}getDefaultProps(){return{w:1,h:1}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:TS(e.w,n.w),h:TS(e.h,n.h)}}getLocalBounds(t){return new vt(0,0,t.props.w,t.props.h)}hitTest(t,e){return!1}hitTestLineSegment(t,e){return!1}isSelectionTransformContainer(t){return!0}canUngroupChildren(t){return!0}shouldResizeDescendants(t){return!0}getResizeToFitDescendantsProps(t,e){return this.validateProps({...t.props,w:e.w,h:e.h})}getMinimumChildCount(t){return 2}contributesToExportBounds(t){return!1}canReceiveChildren(t){return!0}canAutomaticallyReceiveChildren(t){return!1}canBeDirectlyBrushSelected(t){return!1}},AS=class{type="group";toSvg(t){return{tag:"g"}}};function ES(){return{id:"land.group",shapeUtils:[new CS],shapeSvgExporters:[new AS]}}function LS(){return{id:"land.group.react",shapeRenderers:[{type:"group",component:BS,hoverComponent:$S}]}}function BS({editor:t,shape:e,isSelected:n}){const o=r(t.state.selectedShapeIds),i=t.layers.getDescendantIds(e.id),s=o.some(t=>i.includes(t));
59
+ return d(RS,{shape:e,showSelectionBoundary:n||s})}function RS({shape:t,showSelectionBoundary:e=!1}){const{h:n,w:r}=t.props,o=Nt(Lt("#64748b"));
60
+ return d("svg",{width:"100%",height:"100%",viewBox:`0 0 ${r} ${n}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:e?d("rect",{"data-ui":"group-selection-boundary",x:.5,y:.5,width:Math.max(r-1,0),height:Math.max(n-1,0),fill:"none",stroke:o,strokeDasharray:"4 4",strokeWidth:1,vectorEffect:"non-scaling-stroke"}):null})}function $S({shape:t,strokeWidth:e}){const{h:n,w:r}=t.props;
61
+ return d("svg",{"data-ui":"group-hover-outline",width:"100%",height:"100%",viewBox:`0 0 ${r} ${n}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:d("rect",{x:0,y:0,width:r,height:n,fill:"none",stroke:o,strokeWidth:e,vectorEffect:"non-scaling-stroke"})})}var NS={id:"group",editor:ES(),render:LS()};function zS(t){return yt(t)&&"html"===t.type}var OS="html.interact",WS={propagation:"stop"};function HS(t,e){const n=t.shapes.get(e);return!(!zS(n)||!t.editing.canEditShape(n))&&!!t.editing.start({shapeId:e,entryMode:"focusEnd",operationKind:OS},"user")}function DS(){return{id:"land.html.interactions",editorEvent:{handleEvent(t,e){if("select"===t.state.tool.get().activeToolId){if("keyboard"===e.type&&"key_down"===e.name&&"Enter"===e.key&&!e.altKey&&!e.accelKey&&!t.state.shapeEditingSession.get()){const e=t.selection.getIds();return 1===e.length&&HS(t,e[0])?WS:void 0}if("double_click"===e.type){const n=t.shapes.hitTest(e.pagePoint);if(n&&HS(t,n.id))return WS}}}}}}var FS=bn("plugin-html.api");function jS({editor:t}){return{create(e){const n=t.shapes.getDefaultProps("html"),[r]=t.commands.createShapes([{type:"html",x:e.x,y:e.y,meta:e.meta?{...e.meta}:void 0,props:{...n,w:e.w??n.w,h:e.h??n.h,html:e.html,title:e.title??n.title}}],{source:"user"});return"html"===r?.type?{id:r.id,type:r.type}:null},update(e,n){const r=t.shapes.get(e);return!(!zS(r)||r.isLocked)&&(t.commands.updateShapes([{id:e,props:{...n}}],{source:"user"}),!0)},startInteracting:e=>HS(t,e)}}function US(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.max(32,t):e}var XS=class extends pe{type="html";getDefaultProps(){return{w:480,h:320,html:"",title:""}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:US(e.w,n.w),h:US(e.h,n.h),html:"string"==typeof e.html?e.html:n.html,title:"string"==typeof e.title?e.title:n.title}}getLocalBounds(t){return new vt(0,0,t.props.w,t.props.h)}canEdit(t){return!0}canReceiveTerminalBinding(t){return!0}};function YS(t){return t.trim()||"Embedded HTML"}function KS(){return{id:"land.html",shapeUtils:[new XS],interactionHandlers:[DS()]}}var _S="allow-forms allow-pointer-lock allow-presentation allow-scripts";function qS(t={}){return{id:"land.html.react",shapeRenderers:[{type:"html",component:(e=t.sandbox??"allow-forms allow-pointer-lock allow-presentation allow-scripts",function({editor:t,shape:n,shapeEditingSession:o}){const i=v(null),s=r(t.state.readonly),a=s||o?.shapeId===n.id;return x(()=>{a&&!s&&i.current?.focus()},[a,s]),d("iframe",{ref:i,"data-ui":"html-shape-frame",loading:"lazy",referrerPolicy:"no-referrer",sandbox:e,srcDoc:n.props.html,tabIndex:a?0:-1,title:YS(n.props.title),style:{background:"#fff",border:0,display:"block",height:n.props.h,pointerEvents:a?"auto":"none",width:n.props.w}})}),hoverComponent:VS}]};var e}function VS({shape:t,strokeWidth:e}){
62
+ return d("svg",{"aria-hidden":"true","data-ui":"html-hover-outline",width:"100%",height:"100%",viewBox:`0 0 ${t.props.w} ${t.props.h}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},children:d("rect",{x:0,y:0,width:t.props.w,height:t.props.h,fill:"none",stroke:o,strokeWidth:e,vectorEffect:"non-scaling-stroke"})})}function GS(t={}){return{id:"html",editor:KS(),render:qS(t),api:FS,setup:({editor:t})=>({api:jS({editor:t})})}}var JS=GS(),ZS=Dt("plugin.laser.runtime");function QS(t){return t.runtime.require(ZS)}function tI(t,e){const n=t.trail[t.trail.length-1];n&&n.dist2(e)<=1e-6||t.trail.push(e.clone())}function eI(t,e){QS(t).set(e.sessionId,e.trail)}var nI=class extends he{constructor(t){super(t,"laser"),this.initial="idle",this.addChild(new rI(t,this)),this.addChild(new oI(t,this)),this.addChild(new iI(t,this))}},rI=class extends he{constructor(t,e){super(t,"idle",e)}onPointerDown(t){0===t.button&&this.transition("pointing",function(t,e){const n={sessionId:QS(t).start(),originScreenPoint:e.screenPoint.clone(),trail:[e.pagePoint.clone()]};return eI(t,n),n}(this.editor,t))}},oI=class extends he{info=null;constructor(t,e){super(t,"pointing",e)}onEnter(t){this.info=t}onPointerMove(t){this.info&&function(t,e){return t.dist2(e)>=9}(this.info.originScreenPoint,t.screenPoint)&&(tI(this.info,t.pagePoint),eI(this.editor,this.info),this.transition("drawing",this.info))}onPointerUp(){this.info&&QS(this.editor).finish(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&QS(this.editor).finish(this.info.sessionId),this.transition("idle")}onExit(){this.info&&QS(this.editor).finish(this.info.sessionId),this.info=null}},iI=class extends he{info=null;constructor(t,e){super(t,"drawing",e)}onEnter(t){this.info=t}onPointerMove(t){this.info&&(tI(this.info,t.pagePoint),eI(this.editor,this.info))}onPointerUp(){this.info&&QS(this.editor).finish(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&QS(this.editor).finish(this.info.sessionId),this.transition("idle")}onExit(){this.info&&QS(this.editor).finish(this.info.sessionId),this.info=null}};function sI(){return{id:"land.laser.react",canvasOverlays:[{id:"land.laser.trail-overlay",component:aI}]}}var aI=g(function(){return r(QS(n()).activeSignal)?d(lI,{}):null}),lI=g(function(){const t=n(),e=QS(t),o=r(e.trailSignal),i=r(t.state.cameraZoom),s=Math.max(i,1e-4),a=function(){const[t,e]=k(()=>SI());return x(()=>{if("undefined"==typeof window)return;let t=0;const n=r=>{e(r),t=window.requestAnimationFrame(n)};return t=window.requestAnimationFrame(n),()=>{window.cancelAnimationFrame(t)}},[]),t}(),l=v({sessionId:0,samples:[],sourceLength:0}),c=Math.max(a,SI());let p,h=[];o&&(!function(t,e,n,r){e.sessionId!==t.sessionId&&(t.sessionId=e.sessionId,t.samples=[],t.sourceLength=0);const o=e.points;MI(t,r),o.length<t.sourceLength&&(t.samples=[],t.sourceLength=0);if(o.length===t.sourceLength)return;const i=t.sourceLength,s=o.length-i,a=t.samples[t.samples.length-1]?.time??r-xI*s;for(let l=i;l<o.length;l++){const e=o[l],c=(l-i+1)/s;II(t,{x:e.x,y:e.y},n,OI(a,r,c))}t.sourceLength=o.length,MI(t,r)}(l.current,o,s,c),h=function(t,e){const n=TI(t,e);return function(t,e){if(t.length<=1)return[...t];const n=.15+.85*(1-e),r=[t[0]];for(let o=1;o<t.length;o++)r.push(zI(r[r.length-1],t[o],n));return r}(n.length>pI?n.slice(-64):n,gI)}(l.current.samples,c),p=l.current.samples[l.current.samples.length-1]?.time);const f="ending"===o?.phase,g=0===h.length,m=f&&g?o.sessionId:null;if(x(()=>{null!==m&&e.clear(m)},[m,e]),!o||g)return null;const y=f&&void 0!==p?WI(1-(c-p)/PI,0,1):1,w=(P=fI/s,0===(b=h).length||P<=0?null:1===b.length?DI(AI(b[0],P/2,yI))??"":DI(function(t){if(0===t.length)return[];if(1===t.length)return AI(t[0].point,Math.max(t[0].radius,.01),yI);const e=[],n=[];for(const a of t){const t=BI(a.direction);HI(e,$I(a.point,NI(t,a.radius))),HI(n,RI(a.point,NI(t,a.radius)))}const r=[];for(const a of e)HI(r,a);const o=t[t.length-1],i=BI(o.direction),s=function({center:t,direction:e,normal:n,radius:r}){if(r<=0)return[];const o=[];for(let i=1;i<mI;i++){const s=i/mI;o.push(RI(t,RI(NI(e,Math.sin(Math.PI*s)*r),NI(n,-Math.cos(Math.PI*s)*r))))}return o}({center:o.point,direction:o.direction,normal:i,radius:o.radius});for(const a of s)HI(r,a);for(let a=n.length-1;a>=0;a--)HI(r,n[a]);return r}(function(t,e){const n=function(t){const e=[0];for(let n=1;n<t.length;n++)e.push(e[n-1]+EI(t[n-1],t[n]));return e}(t),r=n[n.length-1]??0,o=Math.max(e,r);return t.map((r,i)=>{const s=n[i]??0,a=WI(s/o,0,1);return{point:r,direction:CI(t,i),radius:e/2*a,runningLength:s}})}(b,P))));var b,P;return w?u("g",{"data-ui":"laser-trail-overlay",style:{opacity:y},children:[d("path",{"data-ui":"laser-trail-glow",d:w,fill:dI,style:{filter:`blur(${uI/s}px)`}}),d("path",{"data-ui":"laser-trail-beam",d:w,fill:cI})]}):null}),cI="rgb(255, 38, 38)",dI="rgba(255, 48, 48, 0.55)",uI=4,pI=64,hI=1,fI=12,gI=.32,mI=8,yI=13,xI=16,wI=8,bI=600,vI=300,kI=1400,PI=400;function SI(){return"undefined"==typeof performance?Date.now():performance.now()}function II(t,e,n,r){const o=t.samples[t.samples.length-1];if(!o)return void t.samples.push({...e,time:r,velocity:0});const i=hI/n,s=EI(o,e);if(s<i)return void(t.samples[t.samples.length-1]={...o,...e,time:r});const a=s*n/Math.max(wI,r-o.time);t.samples.push({...e,time:r,velocity:OI(o.velocity,a,.68)})}function MI(t,e){t.samples=TI(t.samples,e)}function TI(t,e){const n=t[t.length-1];if(!n)return[];const r=e-WI(bI+n.velocity*vI,bI,kI);if(n.time<r)return[];const o=t.findIndex(t=>t.time>=r);if(-1===o)return[];const i=t.slice(o),s=t[o-1],a=i[0];return s&&a.time>r?[(l=s,c=a,d=WI((r-s.time)/(a.time-s.time),0,1),{...zI(l,c,d),time:OI(l.time,c.time,d),velocity:OI(l.velocity,c.velocity,d)}),...i]:i;var l,c,d}function CI(t,e){if(t.length<=1)return{x:1,y:0};const n=t[e-1]??t[e],r=t[e+1]??t[e];return function(t){const e=Math.sqrt(t.x*t.x+t.y*t.y);return e<=0?{x:1,y:0}:{x:t.x/e,y:t.y/e}}(0===e?$I(r,t[e]):e===t.length-1?$I(t[e],n):$I(r,n))}function AI(t,e,n){const r=[];for(let o=0;o<n;o++){const i=2*Math.PI*o/n;r.push({x:t.x+Math.cos(i)*e,y:t.y+Math.sin(i)*e})}return r}function EI(t,e){return Math.sqrt(LI(t,e))}function LI(t,e){const n=t.x-e.x,r=t.y-e.y;return n*n+r*r}function BI(t){return{x:-t.y,y:t.x}}function RI(t,e){return{x:t.x+e.x,y:t.y+e.y}}function $I(t,e){return{x:t.x-e.x,y:t.y-e.y}}function NI(t,e){return{x:t.x*e,y:t.y*e}}function zI(t,e,n){return{x:OI(t.x,e.x,n),y:OI(t.y,e.y,n)}}function OI(t,e,n){return t+(e-t)*n}function WI(t,e,n){return Math.max(e,Math.min(n,t))}function HI(t,e){const n=t[t.length-1];!n||LI(n,e)>.04?t.push(e):t[t.length-1]=e}function DI(t){if(t.length<2)return null;if(2===t.length)return`M ${jI(t[0])} L ${jI(t[1])} Z`;const e=[`M ${jI(FI(t[0],t[1]))}`];for(let n=1;n<t.length;n++){const r=t[n],o=t[(n+1)%t.length];e.push(`Q ${jI(r)} ${jI(FI(r,o))}`)}return e.push("Z"),e.join(" ")}function FI(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}function jI(t){return`${UI(t.x)},${UI(t.y)}`}function UI(t){return Number.isInteger(t)?`${t}`:t.toFixed(3)}function XI(){return{id:"land.laser",setup(t){t.runtime.provide(ZS,function(t){const{atom:e,computed:n}=t.signals,r=e("laser.trail",null);let o=1;return{trailSignal:r,activeSignal:n("laser.active",()=>null!==r.get()),start(){const t=o++;return r.set({sessionId:t,phase:"active",points:[]}),t},set(t,e){const n=r.get();n&&n.sessionId===t&&r.set({sessionId:t,phase:"active",points:e.map(t=>t.clone())})},finish(t){const e=r.get();e&&e.sessionId===t&&r.set({...e,phase:"ending"})},clear(t){r.get()?.sessionId===t&&r.set(null)}}}(t)),t.tools.register("laser",t=>new nI(t))}}}var YI={id:"laser",editor:XI(),render:sI()},KI="path.node",_I="path.control";function qI(t,e){return["node",t,e].map(encodeURIComponent).join("|")}function VI(t,e,n){return["control",n,t,e].map(encodeURIComponent).join("|")}function GI(t,e){const n=e.split("|").map(t=>{try{return decodeURIComponent(t)}catch{return""}});return"path.node"===t&&3===n.length&&"node"===n[0]?{type:KI,subpathId:n[1],nodeId:n[2]}:"path.control"!==t||4!==n.length||"control"!==n[0]||"in"!==n[1]&&"out"!==n[1]?null:{type:_I,handle:n[1],subpathId:n[2],nodeId:n[3]}}var JI=new WeakMap;function ZI(t,e){e?JI.set(t,QI(e)):JI.delete(t)}function QI(t){return{...t,pagePoint:t.pagePoint.clone()}}var tM=["nonzero","evenodd"],eM=["corner","smooth","symmetric"];function nM(t){return yt(t)&&"path"===t.type}function rM(t){return"string"==typeof t&&tM.includes(t)}function oM(t){return"string"==typeof t&&eM.includes(t)}function iM(){const t=n(),e=r(t.state.tool),o=r(t.state.shapeEditingSession),i=r(t.state.selectedShapes),s=r(t.state.camera);if(r(t.inputs.state),"select"!==e.activeToolId||!o)return null;const a=1===i.length?i[0]:null;if(!nM(a)||a.id!==o.shapeId)return null;const l=function(t){const e=JI.get(t);return e?QI(e):null}(t);if(!l||l.shapeId!==a.id)return null;const c=8/s.z,u=c/2,p=1.5/s.z;
63
+ return d("g",{"data-ui":"path-edit-insert-preview",pointerEvents:"none",children:d("rect",{"data-ui":"path-edit-insert-preview-control-point",x:l.pagePoint.x-u,y:l.pagePoint.y-u,width:c,height:c,rx:2,ry:2,fill:"rgba(219, 234, 254, 0.72)",stroke:"var(--land-selection, #2563eb)",strokeDasharray:`${3/s.z} ${2/s.z}`,strokeWidth:p})})}function sM(t){return Number.isInteger(t)?`${t}`:`${Number(t.toFixed(2))}`}function aM(t){return new bt(t.x,t.y)}function lM(t,e){const n=aM(e);if(!function(t,e){return!!t.out||!!e.in}(t,e))return`L ${sM(n.x)} ${sM(n.y)}`;const r=function(t){const e=aM(t);return t.out?e.add(new bt(t.out.dx,t.out.dy)):e}(t),o=function(t){const e=aM(t);return t.in?e.add(new bt(t.in.dx,t.in.dy)):e}(e);return["C",sM(r.x),sM(r.y),sM(o.x),sM(o.y),sM(n.x),sM(n.y)].join(" ")}function cM(t){const e=t.nodes[0];if(!e)return null;const n=[`M ${sM(e.x)} ${sM(e.y)}`];for(let r=1;r<t.nodes.length;r+=1){const e=t.nodes[r-1],o=t.nodes[r];e&&o&&n.push(lM(e,o))}if(t.closed&&t.nodes.length>1){const r=t.nodes[t.nodes.length-1];r&&n.push(lM(r,e)),n.push("Z")}return n.join(" ")}function dM(t){const e=t.map(cM).filter(t=>null!==t);return e.length>0?e.join(" "):null}var uM=1e-6,pM=1/3,hM=Math.PI/8,fM=new WeakMap;function gM(t){return Number.isFinite(t)}function mM(t){return{dx:t.dx,dy:t.dy}}function yM(t){return{id:t.id,x:t.x,y:t.y,kind:t.kind,...t.in?{in:mM(t.in)}:null,...t.out?{out:mM(t.out)}:null}}function xM(t){return{id:t.id,closed:t.closed,nodes:t.nodes.map(yM)}}function wM(t){return t.map(xM)}function bM(t){return new bt(t.x,t.y)}function vM(t){const e=bM(t);return t.in?e.add(new bt(t.in.dx,t.in.dy)):e}function kM(t){const e=bM(t);return t.out?e.add(new bt(t.out.dx,t.out.dy)):e}function PM(t,e,n,r,o){const i=1-o,s=i*i*i,a=3*i*i*o,l=3*i*o*o,c=o*o*o;return new bt(t.x*s+e.x*a+n.x*l+r.x*c,t.y*s+e.y*a+n.y*l+r.y*c)}function SM(t,e,n){return new bt(t.x+(e.x-t.x)*n,t.y+(e.y-t.y)*n)}function IM(t,e){return[bM(t),kM(t),vM(e),bM(e)]}function MM(t,e){return!!t.out||!!e.in}function TM(t,e,n){return MM(t,e)?PM(...IM(t,e),n):SM(bM(t),bM(e),n)}function CM(t,e,n){const r=bM(e),o=kM(e),i=vM(n),s=bM(n);if(e.out||n.in)for(let a=1;a<=18;a+=1)t.push(PM(r,o,i,s,a/18));else t.push(s)}function AM(t){const e=t.nodes[0];if(!e)return{id:t.id,closed:t.closed,points:[]};const n=[bM(e)];for(let r=1;r<t.nodes.length;r+=1){const e=t.nodes[r-1],o=t.nodes[r];e&&o&&CM(n,e,o)}if(t.closed&&t.nodes.length>1){const r=t.nodes[t.nodes.length-1];r&&CM(n,r,e)}return{id:t.id,closed:t.closed,points:n}}function EM(t){const e=t.props,n=fM.get(e);if(n)return n;const r=LM(t.props);return fM.set(e,r),r}function LM(t){const e=t.subpaths.map(AM),n=e.flatMap(t=>t.points),r=t.subpaths.flatMap(t=>t.nodes.flatMap(t=>[bM(t),...t.in?[vM(t)]:[],...t.out?[kM(t)]:[]])),o=r.length>0?vt.FromPoints(r):new vt(0,0,1,1),i=Math.max(t.strokeWidth/2,1),s=n.length>0?vt.FromPoints(n).expand(i):o.expand(i),a=new vt(s.x,s.y,Math.max(s.w,1),Math.max(s.h,1));return{path:dM(t.subpaths),pointBounds:o,localBounds:s,renderBounds:a,outlineVertices:n.map(t=>t.clone()),flattenedSubpaths:e}}function BM(t,e){return t.map(t=>({...t,nodes:t.nodes.map(t=>function(t,e){const n=e(bM(t)),r=t.in?e(vM(t)):null,o=t.out?e(kM(t)):null;return{...t,x:n.x,y:n.y,...r?{in:{dx:r.x-n.x,dy:r.y-n.y}}:{in:null},...o?{out:{dx:o.x-n.x,dy:o.y-n.y}}:{out:null}}}(t,e))}))}function RM(t,e){const n=LM({...e,subpaths:wM(t)}).pointBounds,r=Number.isFinite(n.x)?n.x:0,o=Number.isFinite(n.y)?n.y:0,i=function(t,e,n){return BM(t,t=>new bt(t.x+e,t.y+n))}(t,-r,-o);return{x:r,y:o,subpaths:i,geometry:LM({...e,subpaths:i})}}function $M(t,e){return BM(t.props.subpaths,t=>e.applyToPoint(t))}function NM(t,e){return dM($M(t,e))}function zM(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return{distanceSquared:t.dist2(e),t:0};const i=t.sub(e),s=Math.max(0,Math.min(1,(i.x*r.x+i.y*r.y)/o)),a=e.add(r.mul(s));return{distanceSquared:t.dist2(a),t:s}}function OM(t,e,n){return zM(t,e,n).distanceSquared}function WM(t,e,n){const r=n*n;let o=null;for(const i of t){if(i.nodes.length<2)continue;const t=i.closed?i.nodes.length:i.nodes.length-1;for(let n=0;n<t;n+=1){const t=i.nodes[n],s=i.nodes[(n+1)%i.nodes.length];if(!t||!s)continue;const a=MM(t,s)?32:1;let l=bM(t);for(let n=1;n<=a;n+=1){const c=TM(t,s,n/a),d=zM(e,l,c),u=(n-1+d.t)/a;u>.02&&u<.98&&d.distanceSquared<=r&&(!o||d.distanceSquared<o.distanceSquared)&&(o={subpathId:i.id,startNodeId:t.id,endNodeId:s.id,t:u,point:TM(t,s,u),distanceSquared:d.distanceSquared}),l=c}}}return o?{subpathId:o.subpathId,startNodeId:o.startNodeId,endNodeId:o.endNodeId,t:o.t,point:o.point.clone(),distance:Math.sqrt(o.distanceSquared)}:null}function HM(t,e){return t.find(t=>t.id===e)??null}function DM(t,e,n){return HM(t,e)?.nodes.find(t=>t.id===n)??null}function FM(t,e,n,r){return t.map(t=>t.id!==e?xM(t):{...t,nodes:t.nodes.map(t=>t.id===n?r(yM(t)):yM(t))})}function jM(t,e,n){const r=_M(e);return 0===r.size?wM(t):t.map(t=>{const e=r.get(t.id);return e?{...t,nodes:t.nodes.map(t=>e.has(t.id)?n(yM(t)):yM(t))}:xM(t)})}function UM(t,e,n){return t.map(t=>{if(t.id!==e)return xM(t);const r=t.nodes.findIndex(t=>t.id===n),o=t.nodes[r];if(!o)return xM(t);const i=r>0?t.nodes[r-1]:t.closed?t.nodes[t.nodes.length-1]:null,s=r<t.nodes.length-1?t.nodes[r+1]:t.closed?t.nodes[0]:null,a=bM(o),l=function(t,e,n){const r=e?bM(e):null,o=n?bM(n):null;if(r&&o){const e=o.sub(r);if(e.len()<=uM)return null;const n=e.normalize();return function(t,e){const n=Math.abs(t.x*e.y-t.y*e.x),r=t.len()*e.len();return r<=uM||n/r<=.001}(r.sub(t),o.sub(t))?n.rot(hM):n}const i=o?o.sub(t):r?t.sub(r):null;return!i||i.len()<=uM?null:i.normalize().rot(hM)}(a,i,s),c=t.nodes.map(yM);return c[r]={...yM(o),kind:"smooth",in:i&&l?iT(l.mul(-a.dist(bM(i))*pM)):null,out:s&&l?iT(l.mul(a.dist(bM(s))*pM)):null},{...t,nodes:c}})}function XM(t,e,n){return FM(t,e,n,t=>({...t,kind:"corner",in:null,out:null}))}function YM(t,e,n){return null!==KM(t,e,n)}function KM(t,e,n,r=e.at(-1)??null){if(!function(t){const e=new Set;for(const n of t){if(!n.id||e.has(n.id))return!1;e.add(n.id);const t=new Set;for(const e of n.nodes){if(!e.id||t.has(e.id))return!1;t.add(e.id)}}return!0}(t))return null;const o=function(t){const e=new Set,n=[];for(const r of t){const t=JSON.stringify([r.subpathId,r.nodeId]);e.has(t)||(e.add(t),n.push({subpathId:r.subpathId,nodeId:r.nodeId}))}return n}(e);if(o.length<2)return null;let i;switch(n){case"merge":i=function(t,e){const n=qM(e);if(null!==n)return function(t,e,n){const r=t.findIndex(t=>t.id===e),o=t[r];if(!o)return null;const i=function(t,e){const n=e.map(e=>t.nodes.findIndex(t=>t.id===e.nodeId));if(n.some(t=>t<0))return null;const r=Array.from(new Set(n)).sort((t,e)=>t-e);if(r.length!==e.length)return null;if(!t.closed)return r.every((t,e)=>0===e||t===r[e-1]+1)?r:null;if(r.length===t.nodes.length)return r;const o=r.flatMap((e,n)=>{const o=r[(n+1)%r.length];return(e+1)%t.nodes.length===o?[]:[n]});if(1!==o.length)return null;const i=(o[0]+1)%r.length;return[...r.slice(i),...r.slice(0,i)]}(o,n);if(!i||i.length<2)return null;const s=new Set(i),a=i.map(t=>o.nodes[t]),l=i[0],c=a[0],d=a[a.length-1],u=a.reduce((t,e)=>t.add(bM(e)),bt.Zero()).div(a.length),p={...yM(c),x:u.x,y:u.y,kind:"corner",in:eT(c.in,bM(c),u),out:eT(d.out,bM(d),u)},h=o.nodes.flatMap((t,e)=>s.has(e)?e===l?[p]:[]:[yM(t)]),f=o.closed&&h.length>=3;o.closed&&!f&&tT(h);return{subpaths:rT(t,r,[{...o,closed:f,nodes:h}]),selectedNodes:[{subpathId:e,nodeId:p.id}]}}(t,n,e);const r=VM(t,e);return r?function(t,e){const[n,r]=e,o=JM(n),i=ZM(r),s=o[o.length-1],a=i[0],l=bM(s).add(bM(a)).div(2),c={...yM(s),x:l.x,y:l.y,kind:"corner",in:eT(s.in,bM(s),l),out:eT(a.out,bM(a),l)},{nodes:d}=nT(i.slice(1),new Set([...o.slice(0,-1).map(t=>t.id),c.id]),"merged"),u={...n.subpath,closed:!1,nodes:[...o.slice(0,-1),c,...d]};return{subpaths:oT(t,e,u),selectedNodes:[{subpathId:u.id,nodeId:c.id}]}}(t,r):null}(t,o);break;case"join":i=function(t,e){if(2!==e.length)return null;const n=qM(e);if(null!==n)return function(t,e,n){const r=t.findIndex(t=>t.id===e),o=t[r];if(!o||o.closed||o.nodes.length<3)return null;const i=new Set([o.nodes[0].id,o.nodes[o.nodes.length-1].id]);if(2!==n.length||n.some(t=>!i.has(t.nodeId)))return null;const s=o.nodes.map(yM);return s[0]={...s[0],kind:"corner",in:null},s[s.length-1]={...s[s.length-1],kind:"corner",out:null},{subpaths:rT(t,r,[{...o,closed:!0,nodes:s}]),selectedNodes:n.map(t=>({...t}))}}(t,n,e);const r=VM(t,e);return r?function(t,e){const[n,r]=e,o=JM(n),{nodes:i,nodeIdMap:s}=nT(ZM(r),new Set(o.map(t=>t.id)),"joined"),a=o[o.length-1],l=i[0];o[o.length-1]={...a,kind:"corner",out:null},i[0]={...l,kind:"corner",in:null};const c={...n.subpath,closed:!1,nodes:[...o,...i]};return{subpaths:oT(t,e,c),selectedNodes:[{subpathId:c.id,nodeId:n.node.id},{subpathId:c.id,nodeId:s.get(r.node.id)??r.node.id}]}}(t,r):null}(t,o);break;case"separate":i=function(t,e){if(2!==e.length)return null;const n=qM(e);if(null===n)return null;const r=t.findIndex(t=>t.id===n),o=t[r];if(!o||o.nodes.length<2)return null;const i=function(t,e){const[n,r]=e.map(e=>t.nodes.findIndex(t=>t.id===e.nodeId));return void 0===n||void 0===r||n<0||r<0?-1:r===n+1?n:n===r+1?r:t.closed?n===t.nodes.length-1&&0===r?n:r===t.nodes.length-1&&0===n?r:-1:-1}(o,e);if(i<0)return null;if(o.closed){const n=[...o.nodes.slice(i+1).map(yM),...o.nodes.slice(0,i+1).map(yM)];return tT(n),{subpaths:rT(t,r,[{...o,closed:!1,nodes:n}]),selectedNodes:e.map(t=>({...t}))}}const s=o.nodes.slice(0,i+1).map(yM),a=o.nodes.slice(i+1).map(yM);tT(s),tT(a);const l=s.length>=2?{...o,closed:!1,nodes:s}:null,c=function(t,e){const n=new Set(t.map(t=>t.id));if(!n.has(e))return e;let r=2;for(;n.has(`${e}:${r}`);)r+=1;return`${e}:${r}`}(t,`${o.id}:split`),d=a.length>=2?{...o,id:c,closed:!1,nodes:a}:null,u=[l,d].filter(t=>null!==t),p=new Set(s.map(t=>t.id)),h=new Set(a.map(t=>t.id)),f=e.flatMap(t=>l&&p.has(t.nodeId)?[{subpathId:l.id,nodeId:t.nodeId}]:d&&h.has(t.nodeId)?[{subpathId:d.id,nodeId:t.nodeId}]:[]);return{subpaths:rT(t,r,u),selectedNodes:f}}(t,o)}if(!i)return null;const s=r?o.findIndex(t=>{return n=r,(e=t).subpathId===n.subpathId&&e.nodeId===n.nodeId;var e,n}):-1;return{...i,primaryNode:i.selectedNodes[s]??i.selectedNodes.at(-1)??null}}function _M(t){const e=new Map;for(const n of t){const t=e.get(n.subpathId)??new Set;t.add(n.nodeId),e.set(n.subpathId,t)}return e}function qM(t){const e=t[0];return e&&t.every(t=>t.subpathId===e.subpathId)?e.subpathId:null}function VM(t,e){if(2!==e.length)return null;const n=GM(t,e[0]),r=GM(t,e[1]);return n&&r&&n.subpathIndex!==r.subpathIndex?[n,r]:null}function GM(t,e){const n=t.findIndex(t=>t.id===e.subpathId),r=t[n];if(!r||r.closed)return null;const o=r.nodes.findIndex(t=>t.id===e.nodeId),i=r.nodes[o];return!i||0!==o&&o!==r.nodes.length-1?null:{subpath:r,subpathIndex:n,endpoint:0===o?"start":"end",node:i}}function JM(t){return"end"===t.endpoint?t.subpath.nodes.map(yM):QM(t.subpath.nodes)}function ZM(t){return"start"===t.endpoint?t.subpath.nodes.map(yM):QM(t.subpath.nodes)}function QM(t){return[...t].reverse().map(t=>({...yM(t),in:t.out?mM(t.out):null,out:t.in?mM(t.in):null}))}function tT(t){0!==t.length&&(t[0]={...t[0],kind:"corner",in:null},t[t.length-1]={...t[t.length-1],kind:"corner",out:null})}function eT(t,e,n){return t?iT(e.add(new bt(t.dx,t.dy)).sub(n)):null}function nT(t,e,n){const r=new Map;return{nodes:t.map(t=>{let o=t.id;if(e.has(o)){let r=1,i=`${o}:${n}`;for(;e.has(i);)r+=1,i=`${t.id}:${n}:${r}`;o=i}return e.add(o),r.set(t.id,o),{...yM(t),id:o}}),nodeIdMap:r}}function rT(t,e,n){return t.flatMap((t,r)=>r===e?n.map(xM):[xM(t)])}function oT(t,e,n){const r=Math.min(e[0].subpathIndex,e[1].subpathIndex),o=new Set([e[0].subpathIndex,e[1].subpathIndex]);return t.flatMap((t,e)=>e===r?[n]:o.has(e)?[]:[xM(t)])}function iT(t){return t.len2()<=1e-12?null:{dx:t.x,dy:t.y}}function sT(t,e,n){return t.map(t=>{if(t.id!==e.subpathId)return xM(t);const r=t.nodes.findIndex(t=>t.id===e.startNodeId);if(r<0)return xM(t);const o=(r+1)%t.nodes.length,i=t.nodes[r],s=t.nodes[o];if(!i||!s||s.id!==e.endNodeId)return xM(t);const a=function(t,e,n,r){if(!MM(t,e)){const o=SM(bM(t),bM(e),n);return{start:yM(t),node:{id:r,x:o.x,y:o.y,kind:"corner"},end:yM(e)}}const[o,i,s,a]=IM(t,e),l=SM(o,i,n),c=SM(i,s,n),d=SM(s,a,n),u=SM(l,c,n),p=SM(c,d,n),h=SM(u,p,n);return{start:{...yM(t),out:iT(l.sub(o))},node:{id:r,x:h.x,y:h.y,kind:"smooth",in:iT(u.sub(h)),out:iT(p.sub(h))},end:{...yM(e),in:iT(d.sub(a))}}}(i,s,e.t,n),l=t.nodes.map(yM);return l[r]=a.start,l[o]=a.end,l.splice(r+1,0,a.node),{...t,nodes:l}})}var aT=new WeakMap;function lT(t){const e=aT.get(t);return e?function(t){return{shapeId:t.shapeId,nodes:t.nodes.map(t=>({...t})),primary:{...t.primary}}}(e):null}function cT(t){const e=aT.get(t);if(!e)return null;if(t.state.shapeEditingSession.get()?.shapeId!==e.shapeId)return null;const n=t.shapes.get(e.shapeId);if(!nM(n))return null;const r=e.nodes.flatMap(t=>{const e=HM(n.props.subpaths,t.subpathId)?.nodes.find(e=>e.id===t.nodeId);return e?[{ref:{...t},node:e}]:[]});if(0===r.length)return null;const o=r.some(({ref:t})=>mT(t,e.primary))?e.primary:r[r.length-1].ref;return{selection:{shapeId:n.id,nodes:r.map(({ref:t})=>({...t})),primary:{...o}},shape:n,entries:r}}function dT(t){const e=aT.get(t);aT.delete(t),t.state.shapeEditingSession.get()?.shapeId===e?.shapeId&&gT(t,null)}function uT(t,e,n,r){const o={subpathId:n,nodeId:r};pT(t,e,[o],o)}function pT(t,e,n,r=n.at(-1)??null){const o=function(t,e,n){const r=function(t){const e=new Set,n=[];for(const r of t){const t=JSON.stringify([r.subpathId,r.nodeId]);e.has(t)||(e.add(t),n.push({...r}))}return n}(e).filter(e=>null!==fT(t,e));if(0===r.length)return null;const o=(n&&r.find(t=>mT(t,n)))??r[r.length-1];return{shapeId:t.id,nodes:r,primary:{...o}}}(e,n,r);if(!o)return void dT(t);aT.set(t,o);const i=fT(e,o.primary);gT(t,i?t.shapes.computeLocalToPageTransform(e).applyToPoint(bM(i)):null)}function hT(t,e,n){return t.nodes.some(t=>t.subpathId===e&&t.nodeId===n)}function fT(t,e){return HM(t.props.subpaths,e.subpathId)?.nodes.find(t=>t.id===e.nodeId)??null}function gT(t,e){const n=t.state.shapeEditingSession.get();n&&t.session.update({shapeEditingSession:{...n,caretPagePoint:e?{x:e.x,y:e.y}:void 0}},"system")}function mT(t,e){return t.subpathId===e.subpathId&&t.nodeId===e.nodeId}var yT="land.path.draftSubpathId",xT="land.path.previewNodeId";function wT(t){const e=t.meta[yT],n=t.meta[xT];return{subpathId:"string"==typeof e?e:null,previewNodeId:"string"==typeof n?n:null}}function bT(t,e){const n=vT(t);return e.subpathId&&(n[yT]=e.subpathId),e.previewNodeId&&(n[xT]=e.previewNodeId),n}function vT(t){const e={...t};return delete e[yT],delete e[xT],e}var kT="var(--land-selection, #2563eb)",PT="rgba(255, 255, 255, 0.98)";function ST(){const t=n(),e=r(t.state.tool),o=r(t.inputs.state),i=r(t.state.selectedShapes),s=r(t.state.camera);if("path"!==e.activeToolId)return null;const a=1===i.length?i[0]:null,l=nM(a)?a:null,c=8/s.z,p=1.5/s.z,h=6/s.z,f=1/s.z,g=o.currentPagePoint;if(!l)return g?d(TT,{point:g,size:c,strokeWidth:p,variant:"candidate"}):null;const m=function(t,e){const n=wT(e);if(!n.subpathId)return null;const r=HM($M(e,t.shapes.computeLocalToPageTransform(e)),n.subpathId);if(!r)return null;const o=n.previewNodeId?r.nodes.findIndex(t=>t.id===n.previewNodeId):-1,i=o>=0?r.nodes[o]??null:null,s=o>0?r.nodes[o-1]??null:null,a=s&&i?cM({id:`${r.id}:preview`,closed:!1,nodes:[s,i]}):null;return{closed:r.closed,committedNodes:r.nodes.filter(t=>t.id!==n.previewNodeId),previewNode:i,previewPath:a}}(t,l);if(!m)return g?d(TT,{point:g,size:c,strokeWidth:p,variant:"candidate"}):null;const y=m.previewNode?bM(m.previewNode):o.isPointing?null:g,x=y&&!m.committedNodes.some(t=>bM(t).dist2(y)<=.25/(s.z*s.z));
64
+ return u("g",{"data-ui":"path-draft-overlay",pointerEvents:"none",children:[m.previewPath?d("path",{"data-ui":"path-draft-preview-segment",d:m.previewPath,fill:"none",stroke:kT,strokeWidth:Math.max(p,1/s.z),strokeDasharray:`${6/s.z} ${4/s.z}`,strokeLinecap:"round",strokeLinejoin:"round"}):null,x?d(TT,{point:y,size:c,strokeWidth:p,variant:"candidate"}):null,m.committedNodes.map((t,e)=>d(IT,{node:t,showIn:m.closed||e>0,size:h,strokeWidth:f},t.id)),m.committedNodes.map(t=>d(TT,{point:bM(t),size:c,strokeWidth:p,variant:"committed"},t.id))]})}function IT({node:t,showIn:e,size:n,strokeWidth:r}){const o=bM(t);
65
+ return u(c,{children:[e&&t.in?d(MT,{anchor:o,point:vM(t),size:n,strokeWidth:r,variant:"in"}):null,t.out?d(MT,{anchor:o,point:kM(t),size:n,strokeWidth:r,variant:"out"}):null]})}function MT({anchor:t,point:e,size:n,strokeWidth:r,variant:o}){const i=n/2;
66
+ return u("g",{"data-ui":"path-draft-curve-handle","data-path-draft-curve-handle":o,children:[d("line",{"data-ui":"path-draft-control-line",x1:t.x,y1:t.y,x2:e.x,y2:e.y,stroke:"rgba(37, 99, 235, 0.44)",strokeWidth:r}),d("rect",{"data-ui":"path-draft-control-handle",x:e.x-i,y:e.y-i,width:n,height:n,fill:PT,stroke:kT,strokeWidth:r})]})}function TT({point:t,size:e,strokeWidth:n,variant:r}){const o=e/2;
67
+ return d("rect",{"data-ui":"path-draft-control-point","data-path-draft-control-point":r,x:t.x-o,y:t.y-o,width:e,height:e,rx:2,ry:2,fill:"candidate"===r?"rgba(219, 234, 254, 0.98)":PT,stroke:kT,strokeWidth:n})}function CT({shape:t,shapeEditingSession:e=null,fill:n=t.props.fill,stroke:r=t.props.stroke,strokeWidth:o=t.props.strokeWidth}){const{renderBounds:i}=EM({props:{...t.props,strokeWidth:o}}),s=ET(t);if(!s)return null;const a=e?.shapeId===t.id;
68
+ return u("svg",{width:"100%",height:"100%",viewBox:`${i.x} ${i.y} ${Math.max(i.w,1)} ${Math.max(i.h,1)}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[Ot(n)?null:d("path",{d:s,fill:Nt(n),fillRule:t.props.fillRule,clipRule:t.props.fillRule,stroke:"none"}),
69
+ d("path",{d:s,fill:"none",stroke:Nt(r),strokeWidth:o,strokeLinecap:"round",strokeLinejoin:"round"}),a?d(LT,{shape:t}):null]})}function AT({shape:t,strokeWidth:e}){const{renderBounds:n}=EM(t),r=ET(t);return r?d("svg",{"data-ui":"path-hover-outline",width:"100%",height:"100%",viewBox:`${n.x} ${n.y} ${Math.max(n.w,1)} ${Math.max(n.h,1)}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:d("path",{d:r,fill:"none",stroke:o,strokeWidth:e,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:"non-scaling-stroke"})}):null}function ET(t){const e=function(t){return wT(t).previewNodeId}(t);return dM(function(t,e){return e?t.map(t=>({...t,nodes:t.nodes.filter(t=>t.id!==e).map(t=>({...t}))})).filter(t=>t.nodes.length>0):t.map(t=>({...t,nodes:t.nodes.map(t=>({...t}))}))}(t.props.subpaths,e))}function LT({shape:t}){
70
+ return d(c,{children:t.props.subpaths.flatMap(t=>t.nodes.flatMap(e=>{const n=bM(e),r=[];if(e.in){const o=vM(e);r.push(d("line",{x1:n.x,y1:n.y,x2:o.x,y2:o.y,stroke:"rgba(37, 99, 235, 0.44)",strokeWidth:1,strokeDasharray:"4 3",vectorEffect:"non-scaling-stroke"},`${t.id}:${e.id}:in`))}if(e.out){const o=kM(e);r.push(d("line",{x1:n.x,y1:n.y,x2:o.x,y2:o.y,stroke:"rgba(37, 99, 235, 0.44)",strokeWidth:1,strokeDasharray:"4 3",vectorEffect:"non-scaling-stroke"},`${t.id}:${e.id}:out`))}return r}))})}function BT(){return{id:"land.path.react",canvasOverlays:[{id:"land.path.draft-overlay",component:ST,order:20},{id:"land.path.edit-insert-preview-overlay",component:iM,order:21}],shapeRenderers:[{type:"path",component:RT,hoverComponent:$T}],selectionCustomHandleRenderers:[{type:KI,component:NT},{type:_I,component:zT}]}}function RT({shape:t,shapeEditingSession:e}){
71
+ return d(CT,{shape:t,shapeEditingSession:e})}function $T({shape:t,strokeWidth:e}){
72
+ return d(AT,{shape:t,strokeWidth:e})}function NT({handle:t,strokeWidth:e}){const n=OT(t.type,t.id);
73
+ return d("rect",{"data-selection-custom-handle":t.id,"data-selection-custom-handle-type":t.type,"data-selection-custom-handle-id":t.id,x:t.bounds.x,y:t.bounds.y,width:t.bounds.w,height:t.bounds.h,rx:2,ry:2,fill:n?"rgba(219, 234, 254, 0.98)":"rgba(255,255,255,0.98)",stroke:n?"rgba(29, 78, 216, 1)":"rgba(37, 99, 235, 0.94)",strokeWidth:n?1.5*e:e,style:{cursor:t.cursor??"grab",pointerEvents:"auto"}})}function zT({handle:t,strokeWidth:e}){const n=OT(t.type,t.id);
74
+ return d("circle",{"data-selection-custom-handle":t.id,"data-selection-custom-handle-type":t.type,"data-selection-custom-handle-id":t.id,cx:t.point.x,cy:t.point.y,r:Math.max(t.bounds.w,t.bounds.h)/2,fill:n?"rgba(29, 78, 216, 1)":"rgba(37, 99, 235, 0.92)",stroke:"rgba(255,255,255,0.96)",strokeWidth:n?1.5*e:e,style:{cursor:t.cursor??"grab",pointerEvents:"auto"}})}function OT(t,e){const o=n();r(o.state.shapeEditingSession);const i=lT(o),s=GI(t,e);return!!i&&!!s&&hT(i,s.subpathId,s.nodeId)}var WT=class{editor;deactivateHistoryScope=null;session=null;subscribers=new Set;constructor(t){this.editor=t}start(t,e,n){const r=this.editor.shapes.get(e);if(!nM(r))return!1;if(this.session?.mode===t&&this.session.shapeId===e)return!0;this.clear();const o=[HT(this.editor,r,t)];this.session={mode:t,shapeId:e,snapshots:o,index:o.length-1,initialShapeSignature:DT(r),onApply:n?.onApply,onBoundaryUndo:n?.onBoundaryUndo};const i={getState:()=>this.getState(),subscribe:t=>this.subscribe(t),undo:()=>this.undo(),redo:()=>this.redo()};return this.deactivateHistoryScope=this.editor.history.activateScope(i),this.notify(),!0}record(t){const e=this.session,n=this.editor.shapes.get(t);if(!e||e.shapeId!==t||!nM(n))return!1;const r=HT(this.editor,n,e.mode);return e.snapshots[e.index]?.signature===r.signature?(e.snapshots[e.index]=r,!1):(e.snapshots=[...e.snapshots.slice(0,e.index+1),r],e.index=e.snapshots.length-1,this.notify(),!0)}replaceCurrent(t){const e=this.session,n=this.editor.shapes.get(t);if(!e||e.shapeId!==t||!nM(n))return!1;const r=HT(this.editor,n,e.mode),o=e.snapshots[e.index];return e.snapshots[e.index]=r,o?.signature!==r.signature&&(this.notify(),!0)}end(t,e){return this.session?.mode===t&&this.session.shapeId===e&&(this.clear(),!0)}hasNetChanges(t,e){const n=this.session,r=this.editor.shapes.get(e);return!(!n||n.mode!==t||n.shapeId!==e)&&(!nM(r)||n.initialShapeSignature!==DT(r))}undo(){const t=this.session;return!!t&&(t.index<=0?t.onBoundaryUndo?.()??!1:this.applySnapshot(t.index-1))}redo(){const t=this.session;return!(!t||t.index>=t.snapshots.length-1)&&this.applySnapshot(t.index+1)}applySnapshot(t){const e=this.session,n=e?.snapshots[t];if(!e||!n)return!1;const r=this.editor.shapes.get(e.shapeId);if(!nM(r))return this.clear(),!1;e.index=t;const o=lT(this.editor);this.editor.commands.updateShapes([{id:e.shapeId,..."create"===e.mode&&n.draftMeta?{meta:bT(r.meta,n.draftMeta)}:{},props:{subpaths:wM(n.subpaths)}}],{source:"user"});const i=this.editor.shapes.get(e.shapeId);nM(i)&&e.onApply?.(i);const s=n.selection??o;return s&&nM(i)&&this.editor.state.shapeEditingSession.get()?.shapeId===e.shapeId?pT(this.editor,i,s.nodes,s.primary):dT(this.editor),this.notify(),!0}getState(){const t=this.session?.index??0,e=(this.session?.snapshots.length??1)-1;return{canUndo:t+(this.session?.onBoundaryUndo?1:0)>0,canRedo:t<e}}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}clear(){(this.session||this.deactivateHistoryScope)&&(this.session=null,this.deactivateHistoryScope?.(),this.deactivateHistoryScope=null,this.notify())}notify(){for(const t of this.subscribers)t()}};function HT(t,e,n){const r=wM(e.props.subpaths),o="create"===n?wT(e):null;return{subpaths:r,draftMeta:o,selection:lT(t),signature:JSON.stringify({subpaths:r,draftMeta:o})}}function DT(t){return JSON.stringify(function(t){return{...t,meta:{...t.meta},props:{...t.props,fill:{...t.props.fill},stroke:{...t.props.stroke},subpaths:wM(t.props.subpaths)}}}(t))}var FT=new WeakMap;function jT(t){const e=FT.get(t);if(e)return e;const n=new WT(t);return FT.set(t,n),n}function UT(t,e,n,r){return jT(t).start(e,n,r)}function XT(t,e){return jT(t).record(e)}function YT(t,e,n){return jT(t).end(e,n)}var KT=new WeakMap;function _T(t){return KT.get(t)??!1}function qT(t){return function(t,e){const n=t.state.shapeEditingSession.get(),r=n?t.shapes.get(n.shapeId):null;return!(!n||!nM(r))&&(_T(t)===e||(KT.set(t,e),e||t.snaps.clearIndicators(),t.session.update({shapeEditingSession:{...n}},"system")),e)}(t,!_T(t))}function VT(t){KT.delete(t),t.snaps.clearIndicators()}function GT(t){let e=null;const n=me("path.editSnap.lifecycle",t.state.shapeEditingSession,()=>{const n=t.state.shapeEditingSession.get(),r=n?t.shapes.get(n.shapeId):null,o=nM(r)?r.id:null;if(o!==e){if(e){const n=function(t,e,n){return jT(t).hasNetChanges(e,n)}(t,"edit",e);YT(t,"edit",e),n||t.editing.cancelOperation()}e=o,dT(t),VT(t),o&&UT(t,"edit",o,{onBoundaryUndo:()=>{if(t.state.shapeEditingSession.get()?.shapeId!==o)return!1;const e=t.editing.complete("user");return e&&"select"!==t.state.tool.get().activeToolId&&t.commands.setActiveTool("select",{source:"system"}),e}})}});return()=>{n(),e&&YT(t,"edit",e),dT(t),VT(t)}}var JT="path.edit",ZT=Math.PI/4,QT={propagation:"stop"},tC=1,eC=new WeakMap,nC=new WeakMap;function rC(t){const e=t.state.shapeEditingSession.get();if(!e)return null;const n=t.shapes.get(e.shapeId);return nM(n)?n:null}function oC(t,e,n){return t.shapes.computeLocalToPageTransform(e).invert().applyToPoint(n)}function iC(t){ZI(t,null)}function sC(t){iC(t),dT(t)}function aC(t){return t.shiftKey}function lC(t){return JSON.stringify([t.subpathId,t.nodeId])}function cC(t,e){const n=eC.get(t);if(!n)return;if(e.pointerId!==n.pointerId)return;const r=t.shapes.get(n.shapeId);if(!nM(r))return void dC(t);if(!(n.isActive||(o=n.originScreenPoint,i=e.screenPoint,o.dist2(i)>=9)))return;var o,i;n.isActive=!0;const s=function(t,e){const n=Math.min(t.x,e.x),r=Math.min(t.y,e.y),o=Math.max(t.x,e.x),i=Math.max(t.y,e.y);return new vt(n,r,o-n,i-r)}(n.originPagePoint,e.pagePoint),a=function(t,e,n){const r=t.shapes.computeLocalToPageTransform(e);return e.props.subpaths.flatMap(t=>t.nodes.flatMap(e=>{const o=r.applyToPoint(bM(e));return n.containsPoint(o)?[{subpathId:t.id,nodeId:e.id}]:[]}))}(t,r,s),l=aC(e)?function(t,e){const n=new Map(t.map(t=>[lC(t),{...t}]));for(const r of e){const t=lC(r);n.has(t)?n.delete(t):n.set(t,{...r})}return Array.from(n.values())}(n.previousEntries,a):a;t.interaction.setBrushBox(s),pT(t,r,l,l.at(-1)??null)}function dC(t){const e=eC.get(t);if(!e)return;const n=t.shapes.get(e.shapeId);nM(n)&&t.state.shapeEditingSession.get()?.shapeId===e.shapeId?pT(t,n,e.previousEntries,e.previousPrimary):dT(t),eC.delete(t),t.interaction.setBrushBox(null)}function uC(t,e,n,r){const o=t.shapes.get(e);nM(o)&&pT(t,o,n,r)}function pC(t){return t.filter(t=>t.nodes.length>=2)}function hC(t,e){t.editing.complete("user"),t.shapes.get(e.id)&&t.operations.run({kind:"path.shape-delete",label:"shape.delete",source:"user",history:"record"},()=>{t.commands.deleteShapes([e.id],{source:"user"})})}function fC(t,e,n){const r=pC(function(t,e){const n=_M(e);return 0===n.size?wM(t):t.map(t=>{const e=n.get(t.id);if(!e)return xM(t);const r=t.nodes.filter(t=>!e.has(t.id)).map(yM),o=t.closed&&r.length>=3;return t.closed&&!o&&tT(r),{...t,closed:o,nodes:r}}).filter(t=>t.nodes.length>0)}(e.props.subpaths,n));0!==r.length?(t.commands.updateShapes([{id:e.id,props:{subpaths:r}}],{source:"user"}),dT(t),XT(t,e.id)):hC(t,e)}function gC(t,e){const n=cT(t);if(!n||n.shape.isLocked)return!1;const{shape:r,selection:o}=n,i=KM(r.props.subpaths,o.nodes,e,o.primary);if(!i)return!1;const s=pC(i.subpaths);return 0===s.length?(hC(t,r),!0):(t.operations.run({kind:"path.node-operation",label:"shape.edit",source:"user",history:"record"},()=>{t.commands.updateShapes([{id:r.id,props:{subpaths:s}}],{source:"user"}),uC(t,r.id,i.selectedNodes,i.primaryNode)}),XT(t,r.id),!0)}function mC(t,e){const n=cT(t);if(!n||n.shape.isLocked)return!1;const{shape:r,selection:o}=n,i=function(t,e,n){const r=t.shapes.computeLocalToPageTransform(e).invert(),o=r.applyToPoint(new bt(0,0));return r.applyToPoint(n).sub(o)}(t,r,e),s=jM(r.props.subpaths,o.nodes,t=>bC(t,i));return t.operations.run({kind:"path.node-nudge",label:"shape.edit",source:"user",history:"record"},()=>{t.commands.updateShapes([{id:r.id,props:{subpaths:s}}],{source:"user"}),uC(t,r.id,o.nodes,o.primary)}),XT(t,r.id),!0}function yC(t,e,n){const r=rC(t);if(r&&t.tools.isInInitialState()&&("Enter"===e.key||"Escape"===e.key)&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.accelKey)return t.editing.complete("user");if(!(r||"Enter"!==e.key||e.altKey||e.ctrlKey||e.metaKey||e.accelKey))return function(t){if(t.state.shapeEditingSession.get()||"select"!==t.state.tool.get().activeToolId||!t.tools.isInInitialState())return!1;const e=t.selection.getIds(),[n]=t.state.selectedShapes.get();return!(1!==e.length||!nM(n)||!t.editing.canEditShape(n)||(sC(t),VT(t),!t.editing.start({shapeId:n.id,operationKind:JT,entryMode:"focusEnd"},"user")))}(t);if(r&&e.accelKey&&"z"===e.key.toLowerCase()&&!e.altKey)return e.shiftKey?t.history.redo():t.history.undo();if(e.accelKey&&("'"===e.key||"Quote"===e.code)&&r&&!r.isLocked)return qT(t),t.inputs.state.get().isPointing&&t.tools.dispatch(e,n),!0;if(e.accelKey&&"j"===e.key.toLowerCase()&&!e.altKey&&r&&!r.isLocked)return gC(t,"merge");const o=function(t){if(t.altKey||t.ctrlKey||t.metaKey||t.accelKey)return null;const e=t.shiftKey?10:1;switch(t.key){case"ArrowLeft":return new bt(-e,0);case"ArrowRight":return new bt(e,0);case"ArrowUp":return new bt(0,-e);case"ArrowDown":return new bt(0,e);default:return null}}(e);if(o)return mC(t,o);if(e.altKey||e.ctrlKey||e.metaKey||e.accelKey)return!1;const i=cT(t);if(!i||i.shape.isLocked)return!1;const s=e.key.toLowerCase();return"backspace"===s||"delete"===s?(fC(t,i.shape,i.selection.nodes),!0):"c"===s?function(t,e,n){const r=n.filter(t=>{const n=DM(e.props.subpaths,t.subpathId,t.nodeId);return!!n&&!n.in&&!n.out});if(0===r.length)return!1;const o=r.reduce((t,e)=>UM(t,e.subpathId,e.nodeId),e.props.subpaths);return t.commands.updateShapes([{id:e.id,props:{subpaths:o}}],{source:"user"}),uC(t,e.id,n,n.at(-1)??null),XT(t,e.id),!0}(t,i.shape,i.selection.nodes):"x"===s?(function(t,e,n){const r=n.reduce((t,e)=>XM(t,e.subpathId,e.nodeId),e.props.subpaths);t.commands.updateShapes([{id:e.id,props:{subpaths:r}}],{source:"user"}),uC(t,e.id,n,n.at(-1)??null),XT(t,e.id)}(t,i.shape,i.selection.nodes),!0):"j"===s?gC(t,"join"):"k"===s&&gC(t,"separate")}function xC(t,e,n){const r=n?t.len():e?.len()??t.len();if(0===r)return null;const o=t.normalize().mul(-r);return{dx:o.x,dy:o.y}}function wC(t,e){const n=e.sub(t),r=n.len();if(0===r)return e.clone();const o=Math.round(Math.atan2(n.y,n.x)/ZT)*ZT;return t.add(new bt(Math.cos(o)*r,Math.sin(o)*r))}function bC(t,e){return{...t,x:t.x+e.x,y:t.y+e.y}}function vC(){return{createSession(t,{handle:e,shape:n,originPagePoint:r}){if(!nM(n)||"custom"!==e.kind)return null;const o=GI(e.type,e.id);if(!o)return null;if(t.state.shapeEditingSession.get()?.shapeId!==n.id)return null;const i=nC.get(t),s="path.node"===o.type&&i?.shapeId===n.id&&i.nodeId===o.nodeId;s&&nC.delete(t);const a=n,l=DM(a.props.subpaths,o.subpathId,o.nodeId),c=oC(t,a,r),d=cT(t),u=d?.selection.shapeId===n.id?d.selection.nodes.map(t=>({...t})):[],p=d?.selection.shapeId===n.id?{...d.selection.primary}:null,h={subpathId:o.subpathId,nodeId:o.nodeId},f=!!d&&d.selection.shapeId===n.id&&hT(d.selection,o.subpathId,o.nodeId),g="path.node"===o.type&&f,m="path.node"===o.type&&t.inputs.state.get().shiftKey,y=m&&!g?[...d?.selection.shapeId===n.id?d.selection.nodes:[],h]:null;y?pT(t,n,y,h):t.inputs.state.get().shiftKey||f||uT(t,n,o.subpathId,o.nodeId);const x="path.node"===o.type&&(y||g)?y??d.selection.nodes:[h],w=t.shapes.computeLocalToPageTransform(a),b=l?w.applyToPoint(bM(l)):r,v=e.point.sub(r),k="path.node"===o.type?x.flatMap(t=>{const e=DM(a.props.subpaths,t.subpathId,t.nodeId);return e?[w.applyToPoint(bM(e))]:[]}):[e.point],P=(k.length>0?k:[e.point]).map(t=>t.sub(r)),S=function(t,e,n){const r=new Set(n.map(lC)),o=t.shapes.computeLocalToPageTransform(e);return{points:e.props.subpaths.flatMap(t=>t.nodes.flatMap(n=>{const i={subpathId:t.id,nodeId:n.id};return r.has(lC(i))?[]:[{id:`${e.id}:${t.id}:${n.id}`,nodeId:e.id,point:o.applyToPoint(bM(n)),kind:"custom"}]})),outlines:[]}}(t,a,"path.node"===o.type?x:[]);return{shapeId:n.id,operationKind:"path.handle",onClick:m&&g?({editor:t})=>{const e=t.shapes.get(n.id);nM(e)&&function(t,e,n,r){const o=lT(t);if(!o||o.shapeId!==e.id)return void uT(t,e,n,r);const i={subpathId:n,nodeId:r},s=hT(o,n,r),a=s?o.nodes.filter(t=>!mT(t,i)):[...o.nodes,i];pT(t,e,a,s?a.at(-1)??null:i)}(t,e,o.subpathId,o.nodeId)}:void 0,onCancel({editor:t,reason:e}){if("pointer_cancel"!==e&&"escape"!==e)return;const r=t.shapes.get(n.id);nM(r)&&t.state.shapeEditingSession.get()?.shapeId===n.id&&(0!==u.length?pT(t,r,u,p):dT(t))},onComplete({editor:t}){s?function(t,e){jT(t).replaceCurrent(e)}(t,n.id):XT(t,n.id)},update({editor:t,pagePoint:e,accelKey:i,source:s}){if(!nM(t.shapes.get(n.id)))return"stop";const d=t.inputs.state.get(),u=d.shiftKey?"path.node"===o.type?wC(r,e):wC(b,e.add(v)).sub(v):e,p=_T(t)&&!i&&!d.shiftKey&&S.points.length>0,h=p?t.snaps.snapHandle({mode:"align",pagePoint:u,sourcePointOffsets:P,snapshot:S,threshold:10/t.state.camera.get().z}):null;p||t.snaps.clearIndicators();const f=h?.snappedPagePoint??u,g=oC(t,a,"path.node"===o.type?f:f.add(v)),m="path.node"===o.type?l?jM(a.props.subpaths,x,t=>bC(t,g.sub(c))):wM(a.props.subpaths):FM(a.props.subpaths,o.subpathId,o.nodeId,t=>function(t,e,n,r){const o=bM(t),i=r.altKey?{...t,kind:"corner"}:{...t},s=n.sub(o);return"in"===e?(i.in={dx:s.x,dy:s.y},r.altKey||"corner"===t.kind||(i.out=xC(s,t.out?kM(t).sub(o):null,"symmetric"===t.kind))):(i.out={dx:s.x,dy:s.y},r.altKey||"corner"===t.kind||(i.in=xC(s,t.in?vM(t).sub(o):null,"symmetric"===t.kind))),i}(t,o.handle,g,{altKey:d.altKey}));if(t.commands.updateShapes([{id:n.id,props:{subpaths:m}}],{source:s}),"path.node"===o.type){const e=t.shapes.get(n.id);nM(e)&&pT(t,e,x,{subpathId:o.subpathId,nodeId:o.nodeId})}return"continue"}}}}}function kC(){return{id:"land.path.interactions",editorEvent:{handleEvent(t,e,n){if("pointer"===e.type&&"pointer_move"===e.name&&eC.get(t)?.pointerId===e.pointerId)return iC(t),cC(t,e),QT;if("pointer"===e.type&&"pointer_up"===e.name&&(nC.delete(t),iC(t),eC.get(t)?.pointerId===e.pointerId))return function(t,e){const n=eC.get(t);n&&(n.isActive?cC(t,e):aC(e)||dT(t),eC.delete(t),t.interaction.setBrushBox(null))}(t,e),QT;if("pointer"===e.type&&"pointer_cancel"===e.name&&(nC.delete(t),iC(t),eC.get(t)?.pointerId===e.pointerId))return dC(t),QT;if("double_click"===e.type&&!e.shiftKey&&!e.altKey&&!e.accelKey){sC(t);const n=t.shapes.hitTest(e.pagePoint);if(nM(n))return VT(t),t.editing.start({shapeId:n.id,operationKind:JT,entryMode:"focusEnd"},"user"),QT}if("cancel"===e.type)return nC.delete(t),eC.has(t)?(dC(t),QT):"command"===e.reason?void iC(t):"escape"===e.reason&&t.tools.isInInitialState()&&rC(t)&&t.editing.complete("user")?QT:void sC(t);if("keyboard"===e.type&&"key_down"===e.name)return yC(t,e,n)?QT:void 0;if("pointer"!==e.type||"pointer_move"!==e.name){if("pointer"===e.type&&"pointer_down"===e.name&&0===e.button&&e.altKey){iC(t);const n=rC(t);if(!n)return;const r=t.selection.hitTestHandle(e.pagePoint);if("custom"===r?.kind&&"path.node"===r.type){const e=GI(r.type,r.id);if("path.node"===e?.type){const r=cT(t);return fC(t,n,r?.selection.shapeId===n.id&&hT(r.selection,e.subpathId,e.nodeId)?r.selection.nodes:[{subpathId:e.subpathId,nodeId:e.nodeId}]),QT}}}if("pointer"===e.type&&"pointer_down"===e.name&&0===e.button&&!e.altKey){iC(t);const n=rC(t);if(!n)return;const r=t.selection.hitTestHandle(e.pagePoint);if("custom"===r?.kind)return void(GI(r.type,r.id)||dT(t));const o=oC(t,n,e.pagePoint),i=WM(n.props.subpaths,o,7/t.state.camera.get().z);if(!i)return function(t,e,n){const r=cT(t);eC.set(t,{shapeId:e.id,pointerId:n.pointerId,originPagePoint:n.pagePoint.clone(),originScreenPoint:n.screenPoint.clone(),previousEntries:r?.selection.shapeId===e.id?r.selection.nodes.map(t=>({...t})):[],previousPrimary:r?.selection.shapeId===e.id?{...r.selection.primary}:null,isActive:!1})}(t,n,e),QT;const s=`insert-node:${tC+=1}`;return t.operations.run({kind:"path.insert-node",label:"shape.edit",source:"user",history:"record"},()=>{const e=sT(n.props.subpaths,i,s);t.commands.updateShapes([{id:n.id,props:{subpaths:e}}],{source:"user"});const r=t.shapes.get(n.id);nM(r)&&uT(t,r,i.subpathId,s)}),XT(t,n.id),void nC.set(t,{shapeId:n.id,nodeId:s})}}else"mouse"!==e.pointerType||0!==e.buttons||e.altKey?iC(t):function(t,e){const n=rC(t);if(!n||"select"!==t.state.tool.get().activeToolId||!t.tools.isInInitialState())return void iC(t);if("custom"===t.selection.hitTestHandle(e.pagePoint)?.kind)return void iC(t);const r=oC(t,n,e.pagePoint),o=WM(n.props.subpaths,r,7/t.state.camera.get().z);if(!o)return void iC(t);const i=t.shapes.computeLocalToPageTransform(n);ZI(t,{shapeId:n.id,subpathId:o.subpathId,startNodeId:o.startNodeId,endNodeId:o.endNodeId,t:o.t,pagePoint:i.applyToPoint(o.point)})}(t,e)}},selectionHandle:vC()}}function PC(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function SC(t){if(!t||"object"!=typeof t)return null;const e=t,n=PC(e.dx,NaN),r=PC(e.dy,NaN);return Number.isFinite(n)&&Number.isFinite(r)?e.dx===n&&e.dy===r?t:{dx:n,dy:r}:null}function IC(t,e,n){if(!t||"object"!=typeof t)return null;const r=t,o=new Set,i=Array.isArray(r.nodes)?r.nodes.map((t,e)=>function(t,e,n){if(!t||"object"!=typeof t)return null;const r=t,o=PC(r.x,NaN),i=PC(r.y,NaN);return Number.isFinite(o)&&Number.isFinite(i)?{id:TC("string"==typeof r.id&&r.id.length>0?r.id:`node:${e}`,n),x:o,y:i,kind:oM(r.kind)?r.kind:"corner",in:SC(r.in),out:SC(r.out)}:null}(t,e,o)).filter(t=>null!==t):[];return 0===i.length?null:{id:TC("string"==typeof r.id&&r.id.length>0?r.id:`subpath:${e}`,n),closed:"boolean"==typeof r.closed&&r.closed,nodes:i}}function MC(t,e){if(!Array.isArray(t))return e;const n=new Set,r=t.map((t,e)=>IC(t,e,n)).filter(t=>null!==t);return r.length>0?r:e}function TC(t,e){if(!e.has(t))return e.add(t),t;let n=2;for(;e.has(`${t}:${n}`);)n+=1;const r=`${t}:${n}`;return e.add(r),r}function CC(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist2(e);const i=t.sub(e),s=Math.max(0,Math.min(1,(i.x*r.x+i.y*r.y)/o));return t.dist2(e.add(r.mul(s)))}var AC=class extends pe{type="path";getDefaultProps(){return{subpaths:[{id:"subpath:default",closed:!1,nodes:[{id:"node:0",x:0,y:0,kind:"corner"},{id:"node:1",x:96,y:0,kind:"corner"}]}],fill:Lt("transparent"),stroke:Et("stroke-slate"),strokeWidth:3,fillRule:"nonzero"}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{subpaths:(r=MC(e.subpaths,n.subpaths),r.map(t=>({...t,nodes:t.nodes.filter(t=>gM(t.x)&&gM(t.y))})).filter(t=>t.nodes.length>0).map(xM)),fill:$t(e.fill,n.fill),stroke:$t(e.stroke,n.stroke),strokeWidth:Math.max(1,PC(e.strokeWidth,n.strokeWidth)),fillRule:rM(e.fillRule)?e.fillRule:n.fillRule};var r}getPositionedBounds(t){const e=EM(t).localBounds;return new vt(t.x+e.x,t.y+e.y,e.w,e.h)}getLocalBounds(t){return EM(t).localBounds}getRenderBounds(t){return EM(t).renderBounds}getExportBounds(t){return this.getRenderBounds(t)}getSelectionResizeLocalBounds(t){return EM(t).pointBounds}resizeSelectionBounds(t,e){const n=$M(t,this.getLocalTransform(t)).map(t=>({...t,nodes:t.nodes.map(t=>LC(t,t=>function(t,e){return 0===e.selectionRotation?t:bt.RotWith(t,e.selectionRotationCenter,-e.selectionRotation)}(t,e)))})),r=RM(function(t,e){const n=EM(t).pointBounds,r=0===n.w?1:e.w/Math.max(n.w,1e-6),o=0===n.h?1:e.h/Math.max(n.h,1e-6);return BM(t.props.subpaths,t=>new bt(0===n.w?e.center.x:e.x+(t.x-n.x)*r,0===n.h?e.center.y:e.y+(t.y-n.y)*o))}({...t,x:0,y:0,rotation:0,scaleX:1,scaleY:1,props:{...t.props,subpaths:n}},e.selectionLocalBounds).map(t=>({...t,nodes:t.nodes.map(t=>LC(t,t=>function(t,e){return 0===e.selectionRotation?t:bt.RotWith(t,e.selectionRotationCenter,e.selectionRotation)}(t,e)))})),t.props);return{id:t.id,x:r.x,y:r.y,rotation:0,scaleX:1,scaleY:1,props:{subpaths:r.subpaths}}}getPositionedOutlineVertices(t){return EM(t).outlineVertices.map(e=>new bt(t.x+e.x,t.y+e.y))}getTerminalBindingOutlines(t){return EM(t).flattenedSubpaths.filter(t=>t.points.length>0).map(e=>({points:e.points.map(e=>new bt(t.x+e.x,t.y+e.y)),closed:e.closed}))}resolveBindingPoint(t,e){const n=e.editor.shapes.computePositionedToPageTransform(t),r=n.tryInvert();if(!r)return e.rawPagePoint;const o=r.applyToPoint(e.rawPagePoint),i=r.applyToPoint(e.oppositePagePoint),s=i.sub(o);let a=Number.POSITIVE_INFINITY;for(const l of this.getTerminalBindingOutlines(t)){const t=l.closed?l.points.length:Math.max(0,l.points.length-1);for(let e=0;e<t;e+=1){const t=l.points[e],n=l.points[(e+1)%l.points.length];if(!t||!n)continue;const r=EC(o,i,t,n);null!==r&&r>1e-6&&r<a&&(a=r)}}return Number.isFinite(a)?n.applyToPoint(o.add(s.mul(a))):e.rawPagePoint}getHandleSnapGeometry(t){return{points:t.props.subpaths.flatMap(t=>t.nodes.flatMap(t=>[{point:bM(t),kind:"custom"},...t.in?[{point:vM(t),kind:"custom"}]:[],...t.out?[{point:kM(t),kind:"custom"}]:[]])),outline:EM(t).outlineVertices}}canReceiveTerminalBinding(t){return!0}canEdit(t){return!0}canUseSelectionResizeHandles(t,e){return e.editor.state.shapeEditingSession.get()?.shapeId!==t.id}canUseSelectionRotateHandle(t,e){return e.editor.state.shapeEditingSession.get()?.shapeId!==t.id}getSelectionHandleAnchors(t,e){const n={terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:[]};if(!e.isOnlySelected)return n;const r=e.editor.state.shapeEditingSession.get();if(!r||r.shapeId!==t.id)return n;const o=e.editor.shapes.computeLocalToPageTransform(t);return{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:t.props.subpaths.flatMap(t=>t.nodes.flatMap(e=>{const n=[{kind:"custom",type:KI,id:qI(t.id,e.id),point:o.applyToPoint(bM(e)),cursor:"grab"}];return e.in&&n.push({kind:"custom",type:_I,id:VI(t.id,e.id,"in"),point:o.applyToPoint(vM(e)),cursor:"grab"}),e.out&&n.push({kind:"custom",type:_I,id:VI(t.id,e.id,"out"),point:o.applyToPoint(kM(e)),cursor:"grab"}),n}))}}getSelectionOverlayInfo(t,e){const n=e.editor.state.shapeEditingSession.get();return n&&n.shapeId===t.id?{usesSelectionPathOverlay:!0,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:NM(t,e.editor.shapes.computeLocalToPageTransform(t)),pathStyle:null,bindingSegments:[]}:{usesSelectionPathOverlay:!1,startPagePoint:null,endPagePoint:null,middlePagePoint:null,path:null,pathStyle:null,bindingSegments:[]}}hitTest(t,e,n){const r=new bt(e.x-t.x,e.y-t.y),o=EM(t);return!Ot(t.props.fill)&&function(t,e,n){let r=0,o=0;for(const i of t)if(i.closed&&!(i.points.length<3))for(let t=0;t<i.points.length;t+=1){const n=i.points[t],s=i.points[(t+1)%i.points.length];n&&s&&(n.y<=e.y&&s.y>e.y||n.y>e.y&&s.y<=e.y)&&n.x+(e.y-n.y)/(s.y-n.y)*(s.x-n.x)>e.x&&(o+=1,r+=s.y>n.y?1:-1)}return"evenodd"===n?o%2==1:0!==r}(o.flattenedSubpaths,r,t.props.fillRule)||function(t,e,n){const r=n*n;for(const o of t)for(let t=1;t<o.points.length;t+=1){const n=o.points[t-1],i=o.points[t];if(n&&i&&OM(e,n,i)<=r)return!0}return!1}(o.flattenedSubpaths,r,t.props.strokeWidth/2+6)}hitTestLineSegment(t,e){const n=new bt(e.positionedStart.x-t.x,e.positionedStart.y-t.y),r=new bt(e.positionedEnd.x-t.x,e.positionedEnd.y-t.y),o=e.positionedMargin+t.props.strokeWidth/2;return EM(t).flattenedSubpaths.some(t=>function(t,e,n,r){const o=r*r;for(let i=1;i<n.length;i+=1){const r=n[i-1],s=n[i];if(r&&s&&(CC(r,t,e)<=o||CC(s,t,e)<=o||CC(t,r,s)<=o||CC(e,r,s)<=o))return!0}return!1}(n,r,t.points,o))}isWrappedByBrush(t,e){const n=e.pageOutlineVertices;return 0===n.length?!!e.pageBounds&&e.brushBounds.containsBox(e.pageBounds):n.every(t=>e.brushBounds.containsPoint(t))}canSelectByBrush(t,e){return e.isWrapping?this.isWrappedByBrush(t,e):e.pageBounds?.intersects(e.brushBounds)??!1}onEditEnd(t){if(t.props.subpaths.every(t=>t.nodes.length<2))return{deleteShapeIds:[t.id]}}};function EC(t,e,n,r){const o=e.sub(t),i=r.sub(n),s=o.x*i.y-o.y*i.x;if(Math.abs(s)<1e-8)return null;const a=n.sub(t),l=(a.x*i.y-a.y*i.x)/s,c=(a.x*o.y-a.y*o.x)/s;return l>=0&&l<=1&&c>=0&&c<=1?l:null}function LC(t,e){const n=e(bM(t)),r=t.in?e(vM(t)):null,o=t.out?e(kM(t)):null;return{...yM(t),x:n.x,y:n.y,in:r?{dx:r.x-n.x,dy:r.y-n.y}:null,out:o?{dx:o.x-n.x,dy:o.y-n.y}:null}}var BC=Math.PI/4,RC=1,$C=1;function NC(){return`node:${RC+=1}`}function zC(t,e,n){return t.shapes.computeLocalToPageTransform(e).invert().applyToPoint(n)}function OC(t,e,n,r){const o=(HM(e.props.subpaths,n)?.nodes.filter(t=>t.id!==r))?.at(-1);return o?t.shapes.computeLocalToPageTransform(e).applyToPoint(new bt(o.x,o.y)):null}function WC(t,e){const n=e.sub(t),r=n.len();if(0===r)return e.clone();const o=Math.round(Math.atan2(n.y,n.x)/BC)*BC;return t.add(new bt(Math.cos(o)*r,Math.sin(o)*r))}function HC(t,e,n,r,o){const i=function(t,e,n){const r=HM(e.props.subpaths,n)?.nodes[0];return r?t.shapes.computeLocalToPageTransform(e).applyToPoint(new bt(r.x,r.y)):null}(t,e,n),s=HM(e.props.subpaths,n),a=s?.nodes.filter(t=>t.id!==r).length??0;return!(!i||!s||a<3)&&i.dist(o)<=10/t.state.camera.get().z}function DC(t,e){return e.previewNodeId?t.map(t=>t.id===e.subpathId?{...t,nodes:t.nodes.filter(t=>t.id!==e.previewNodeId)}:t):wM(t)}function FC(t,e){return HM(t.props.subpaths,e.subpathId)?.nodes.filter(t=>t.id!==e.previewNodeId).length??0}var jC=class extends he{draft=null;operation=null;constructor(t){super(t,"path"),this.initial="idle",this.addChild(new UC(t,this)),this.addChild(new XC(t,this))}onEnter(){this.editor.interaction.clearSelection()}onExit(){this.draft&&(this.canFinishDraft()?this.finishDraft({switchToSelect:!1}):this.cancelDraft())}isInInitialState(){return!this.hasDraft()&&super.isInInitialState()}startOrExtend(t,e,n){if(!this.draft){this.operation=this.editor.operations.begin({kind:"path.create",label:"shape.create",source:"user",history:"record"});const n=this.editor.shapes.getDefaultProps("path"),r=`subpath:${$C+=1}`,o=NC(),i={id:o,x:0,y:0,kind:"corner"},[s]=this.editor.commands.createShapes([{type:"path",x:t.x,y:t.y,meta:bT({},{subpathId:r,previewNodeId:null}),props:{...n,subpaths:[{id:r,closed:!1,nodes:[i]}]}}],{source:"user",autoReparent:!1});if(!nM(s))throw this.cancelOperation(),new Error("Failed to create path shape");return this.editor.commands.setSelectedShapeIds([s.id],{source:"system"}),this.draft={shapeId:s.id,subpathId:r,lastNodeId:o,createdShape:!0,previewNodeId:null},UT(this.editor,"create",s.id,{onBoundaryUndo:()=>this.draft?.shapeId===s.id&&(this.cancelDraft(),this.editor.commands.setActiveTool("select",{source:"system"}),!0),onApply:t=>{const e=this.draft;if(!e||e.shapeId!==t.id)return;const n=HM(t.props.subpaths,e.subpathId);this.draft={...e,lastNodeId:n?.nodes.at(-1)?.id??e.lastNodeId,previewNodeId:null}}}),{shapeId:s.id,subpathId:r,nodeId:o,originPagePoint:t.clone(),originScreenPoint:e.clone(),startNode:yM(i),finishOnPointerUp:!1}}const r=this.editor.shapes.get(this.draft.shapeId);if(!nM(r))return this.cancelDraft(),null;const o=n.shiftKey?OC(this.editor,r,this.draft.subpathId,this.draft.previewNodeId)??t:t,i=n.shiftKey?WC(o,t):t;if(HC(this.editor,r,this.draft.subpathId,this.draft.previewNodeId,t)){const n=this.draft,o=HM(r.props.subpaths,n.subpathId)?.nodes.find(t=>t.id!==n.previewNodeId);return o?(this.editor.commands.updateShapes([{id:r.id,meta:bT(r.meta,{subpathId:n.subpathId,previewNodeId:null}),props:{subpaths:DC(r.props.subpaths,n).map(t=>t.id===n.subpathId?{...t,closed:!0}:t)}}],{source:"user"}),this.draft={...n,previewNodeId:null},{shapeId:r.id,subpathId:n.subpathId,nodeId:o.id,originPagePoint:t.clone(),originScreenPoint:e.clone(),startNode:yM(o),finishOnPointerUp:!0}):null}const s=zC(this.editor,r,i),a=this.draft.previewNodeId??NC(),l=r.props.subpaths.map(t=>t.id===this.draft?.subpathId?this.draft.previewNodeId?{...t,nodes:t.nodes.map(t=>t.id===this.draft?.previewNodeId?{id:a,x:s.x,y:s.y,kind:"corner"}:t)}:{...t,nodes:[...t.nodes,{id:a,x:s.x,y:s.y,kind:"corner"}]}:t);return this.editor.commands.updateShapes([{id:r.id,meta:bT(r.meta,{subpathId:this.draft.subpathId,previewNodeId:null}),props:{subpaths:l}}],{source:"user"}),this.draft={...this.draft,lastNodeId:a,previewNodeId:null},{shapeId:r.id,subpathId:this.draft.subpathId,nodeId:a,originPagePoint:t.clone(),originScreenPoint:e.clone(),startNode:{id:a,x:s.x,y:s.y,kind:"corner"},finishOnPointerUp:!1}}updateNodeDrag(t,e,n,r){const o=this.editor.shapes.get(t.shapeId);if(!nM(o))return;const i=r.shiftKey?WC(t.originPagePoint,e):e,s=zC(this.editor,o,t.originPagePoint),a=zC(this.editor,o,i),l=t.originScreenPoint.dist(n)>=3,c=FM(o.props.subpaths,t.subpathId,t.nodeId,()=>l?function(t,e,n){return{...t,kind:n.altKey?"smooth":"symmetric",in:{dx:-e.x,dy:-e.y},out:{dx:e.x,dy:e.y}}}(t.startNode,a.sub(s),r):yM(t.startNode));this.editor.commands.updateShapes([{id:o.id,meta:bT(o.meta,{subpathId:t.subpathId,previewNodeId:this.draft?.previewNodeId??null}),props:{subpaths:c}}],{source:"user"})}updatePreview(t,e){if(!this.draft)return;const n=this.editor.shapes.get(this.draft.shapeId);if(!nM(n)||FC(n,this.draft)<1)return;const r=e.shiftKey?OC(this.editor,n,this.draft.subpathId,this.draft.previewNodeId):null,o=r?WC(r,t):t,i=zC(this.editor,n,o),s=this.draft.previewNodeId??NC(),a=n.props.subpaths.map(t=>t.id!==this.draft?.subpathId?t:this.draft.previewNodeId?{...t,nodes:t.nodes.map(t=>t.id===this.draft?.previewNodeId?{id:s,x:i.x,y:i.y,kind:"corner"}:t)}:{...t,nodes:[...t.nodes,{id:s,x:i.x,y:i.y,kind:"corner"}]});this.editor.commands.updateShapes([{id:n.id,meta:bT(n.meta,{subpathId:this.draft.subpathId,previewNodeId:s}),props:{subpaths:a}}],{source:"user"}),this.draft={...this.draft,previewNodeId:s}}canFinishDraft(){if(!this.draft)return!1;const t=this.editor.shapes.get(this.draft.shapeId);return!!nM(t)&&FC(t,this.draft)>=2}finishDraft(t={}){if(!this.draft)return;const e=t.switchToSelect??!0,n=this.editor.shapes.get(this.draft.shapeId);if(nM(n)){const t=DC(n.props.subpaths,this.draft),e=RM($M({...n,props:{...n.props,subpaths:t}},this.editor.shapes.computeLocalToPageTransform(n)),n.props);this.editor.commands.updateShapes([{id:n.id,x:e.x,y:e.y,rotation:0,scaleX:1,scaleY:1,meta:vT(n.meta),props:{subpaths:e.subpaths}}],{source:"user"}),this.draft.createdShape&&Yt(this.editor,n.id,{source:"user"})}YT(this.editor,"create",this.draft.shapeId),this.commitOperation(),this.draft=null,e&&!this.editor.state.tool.get().isToolLocked&&this.editor.commands.setActiveTool("select",{source:"system"})}finishDraftAndEdit(){const t=this.draft?.shapeId;if(t){if(!this.canFinishDraft())return this.cancelDraft(),void(this.editor.state.tool.get().isToolLocked||this.editor.commands.setActiveTool("select",{source:"system"}));this.finishDraft({switchToSelect:!1}),nM(this.editor.shapes.get(t))&&(this.editor.commands.setActiveTool("select",{source:"system"}),this.editor.editing.start({shapeId:t,operationKind:"path.edit",entryMode:"focusEnd"},"user"))}}cancelDraft(){this.draft&&(YT(this.editor,"create",this.draft.shapeId),this.cancelOperation(),this.draft=null)}hasDraft(){return null!==this.draft}commitOperation(){const t=this.operation;this.operation=null,t?.commit()}cancelOperation(){const t=this.operation;this.operation=null,t?.isActive&&t.cancel()}},UC=class extends he{tool;constructor(t,e){super(t,"idle",e),this.tool=e}onPointerDown(t){if(0!==t.button)return;const e=this.tool.startOrExtend(t.pagePoint,t.screenPoint,{altKey:t.altKey,shiftKey:t.shiftKey});e&&this.transition("dragging_node",e)}onPointerMove(t){this.tool.updatePreview(t.pagePoint,{shiftKey:t.shiftKey})}onKeyDown(t){("Enter"===t.key&&this.tool.hasDraft()||"Escape"===t.key&&this.tool.hasDraft())&&this.tool.finishDraftAndEdit()}onCancel(t){"escape"===t.reason&&this.tool.hasDraft()&&this.tool.finishDraftAndEdit()}},XC=class extends he{tool;info=null;constructor(t,e){super(t,"dragging_node",e),this.tool=e}onEnter(t){this.info=t}onPointerMove(t){this.info&&this.tool.updateNodeDrag(this.info,t.pagePoint,t.screenPoint,{altKey:t.altKey,shiftKey:t.shiftKey})}onPointerUp(t){const e=this.info;e&&(this.tool.updateNodeDrag(e,t.pagePoint,t.screenPoint,{altKey:t.altKey,shiftKey:t.shiftKey}),XT(this.editor,e.shapeId)),this.transition("idle"),e?.finishOnPointerUp&&this.tool.finishDraft()}onCancel(){this.tool.cancelDraft(),this.transition("idle")}onExit(){this.info=null}},YC=class{type="path";toSvg(t,e){const n=EM(t);return n.path?{tag:"path",attrs:{d:n.path,fill:Ot(t.props.fill)?"none":e.resolveColor(t.props.fill),"fill-rule":t.props.fillRule,"clip-rule":t.props.fillRule,stroke:e.resolveColor(t.props.stroke),"stroke-width":t.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round"}}:null}};function KC(){return{id:"land.path",shapeUtils:[new AC],shapeSvgExporters:[new YC],interactionHandlers:[kC()],setup(t){const e=GT(t);return t.tools.register("path",t=>new jC(t)),e}}}var{difference:_C,intersection:qC,union:VC,xor:GC}=gt,JC=1,ZC=1;function QC(t,e){return Math.abs(t[0]-e[0])<1e-6&&Math.abs(t[1]-e[1])<1e-6}function tA(t){return $M(t.shape,t.localToPage).filter(t=>t.closed&&t.nodes.length>=3).map(t=>function(t){const e=[];for(const n of t){const t=[n.x,n.y],r=e[e.length-1];r&&QC(r,t)||e.push(t)}return e.length>1&&QC(e[0],e[e.length-1])&&e.pop(),e.length>=3?e:null}(AM(t).points)).filter(t=>null!==t).map(t=>[t])}function eA(t){const e=t.length>1&&QC(t[0],t[t.length-1])?t.slice(0,-1):t;return e.length<3?null:{id:`boolean-subpath:${JC+=1}`,closed:!0,nodes:e.map(([t,e])=>({id:`boolean-node:${ZC+=1}`,x:t,y:e,kind:"corner"}))}}function nA(t,e){const n=e.map(tA).filter(t=>t.length>0);return 0===n.length?[]:function(t,e){const[n,...r]=e;if(!n)return[];if(0===r.length)return n;switch(t){case"union":return VC(n,...r);case"subtract":return _C(n,...r);case"intersect":return qC(n,...r);case"xor":return GC(n,...r)}}(t,n).flatMap(t=>t).map(eA).filter(t=>null!==t)}var rA=bn("plugin-path.api");function oA({editor:t}){return function({editor:t}){return{getSelectionStyle:()=>function(t){const e=t.state.selectedShapes.get().filter(nM);return 0===e.length?null:{fill:uA(e.map(t=>t.props.fill)),stroke:uA(e.map(t=>t.props.stroke)),strokeWidth:dA(e.map(t=>t.props.strokeWidth))}}(t),setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(nM).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)},getToolDefaults:()=>t.shapes.getDefaultProps("path"),setToolDefaults:e=>(t.shapes.updateDefaultProps("path",e),t.shapes.getDefaultProps("path")),canBeginEdit:()=>null!==iA(t),beginEdit(){const e=iA(t);return!!e&&(dT(t),VT(t),t.editing.start({shapeId:e.id,operationKind:"path.edit",entryMode:"focusEnd"},"user"),!0)},isEditing:()=>null!==sA(t),completeEdit:()=>!!sA(t)&&(t.editing.complete("user"),!0),isNodeSnapEnabled:()=>_T(t),canToggleNodeSnap:()=>{const e=sA(t);return!!e&&!e.isLocked},toggleNodeSnap(){const e=sA(t);return!(!e||e.isLocked)&&(qT(t),!0)},canDeleteSelectedNodes:()=>aA(t,()=>!0),deleteSelectedNodes(){const e=cT(t);return!(!e||e.shape.isLocked)&&(fC(t,e.shape,e.selection.nodes),!0)},canMakeSelectedNodesCurve:()=>aA(t,t=>t.entries.some(({node:t})=>!t.in&&!t.out)),makeSelectedNodesCurve:()=>lA(t,"make-curve"),canRemoveSelectedNodeHandles:()=>aA(t,t=>t.entries.some(({node:t})=>!!t.in||!!t.out)),removeSelectedNodeHandles:()=>lA(t,"remove-handles"),canRunSelectedNodeOperation:e=>aA(t,t=>YM(t.shape.props.subpaths,t.selection.nodes,e)),runSelectedNodeOperation(e){const n=cT(t);return!(!n||n.shape.isLocked||!YM(n.shape.props.subpaths,n.selection.nodes,e))&&(gC(t,e),!0)},canRunBooleanOperation:()=>cA(t).length>=2,runBooleanOperation:e=>function(t,e){const n=cA(t),r=n[0];if(!r||n.length<2)return null;const o=function(t,e,n){const r=nA(t,e);return 0===r.length?null:RM(r,{...n,fillRule:"evenodd"})}(e,n.map(e=>({shape:e,localToPage:t.shapes.computeLocalToPageTransform(e)})),{fill:r.props.fill,stroke:r.props.stroke,strokeWidth:r.props.strokeWidth});if(!o)return null;let i=null;return t.operations.run({kind:`path.boolean.${e}`,label:"shape.boolean",source:"user",history:"record"},()=>{const[e]=t.commands.createShapes([{type:"path",x:o.x,y:o.y,parentId:r.parentId,props:{...r.props,subpaths:o.subpaths,fillRule:"evenodd"}}],{source:"user"});t.commands.deleteShapes(n.map(t=>t.id),{source:"user"}),e&&(i=e.id,t.commands.setSelectedShapeIds([e.id],{source:"system"}))}),i}(t,e)}}({editor:t})}function iA(t){const e=t.state.selectedShapes.get(),n=1===e.length?e[0]:null;return nM(n)&&!n.isLocked?n:null}function sA(t){const e=t.state.shapeEditingSession.get(),n=e?t.shapes.get(e.shapeId):null;return nM(n)?n:null}function aA(t,e){const n=cT(t);return!!n&&!n.shape.isLocked&&e(n)}function lA(t,e){const n=cT(t);if(!n||n.shape.isLocked)return!1;const r="make-curve"===e?n.entries.filter(({node:t})=>!t.in&&!t.out).reduce((t,{ref:e})=>UM(t,e.subpathId,e.nodeId),n.shape.props.subpaths):n.selection.nodes.reduce((t,e)=>XM(t,e.subpathId,e.nodeId),n.shape.props.subpaths);t.commands.updateShapes([{id:n.shape.id,props:{subpaths:r}}],{source:"user"});const o=t.shapes.get(n.shape.id);return nM(o)&&pT(t,o,n.selection.nodes,n.selection.primary),XT(t,n.shape.id),!0}function cA(t){return t.state.selectedShapes.get().filter(nM).filter(t=>!t.isLocked&&!t.isHidden)}function dA(t){const[e,...n]=t;return void 0!==e&&n.every(t=>t===e)?e:null}function uA(t){const[e,...n]=t;return void 0!==e&&n.every(t=>Wt(e,t))?e:null}var pA={id:"path",editor:KC(),render:BT(),api:rA,setup:({editor:t})=>({api:oA({editor:t})})},hA=bn("canvas-kit.clipboard");function fA({clipboard:t,editor:e,tasks:n}){return function({clipboard:t,editor:e,tasks:n}){return{hasContent:()=>null!==t.getMemoryPayload(),copy:()=>n.run(async n=>{const r=e.selection.createClipboardPayload();return r?(await t.write(r),n.throwIfAborted(),r):null}),cut:()=>n.run(async n=>{const r=e.selection.createClipboardPayload();return!!r&&(await t.write(r),n.throwIfAborted(),e.selection.delete("user"),!0)}),paste:(r={})=>n.run(async n=>{const o=await t.read();return n.throwIfAborted(),!!o&&(e.selection.pasteClipboardPayload({payload:o,pagePoint:r.pagePoint?gA(r.pagePoint):e.state.viewportPageBounds.get()?.center??void 0,source:"user"}),!0)})}}({clipboard:t,editor:e,tasks:n})}function gA(t){return new bt(t.x,t.y)}function mA(){let t=null;const e=new Set;return{value:{async write(n){t=n;for(const t of e)t()},read:async()=>t,getMemoryPayload:()=>t,subscribe:t=>(e.add(t),()=>e.delete(t))},dispose(){e.clear(),t=null}}}function yA(t={}){return{id:"canvas-kit.clipboard-runtime",api:hA,setup({editor:e,tasks:n}){const r=t.createClipboard?.()??mA();try{return{api:fA({clipboard:r.value,editor:e,tasks:n}),dispose:()=>r.dispose?.()}}catch(o){throw Promise.resolve(r.dispose?.()).catch(()=>{}),o}}}}var xA=yA();function wA(t){return new Promise((e,n)=>{const r=new FileReader;r.addEventListener("load",()=>{e("string"==typeof r.result?r.result:null)}),r.addEventListener("error",()=>{n(r.error)}),r.readAsDataURL(t)})}async function bA({assetInliners:t=[],editor:e,padding:n=16,resolveThemeColor:r,shapeIds:o}){e.exports.repairIntegrity(o);const i=Array.from(e.shapeSvgExporters.values(),t=>t.type).sort();let s,a=e.exports.getIntegrityReport(o);try{s=await async function({assetInliners:t,editor:e,padding:n,resolveThemeColor:r,shapeIds:o}){const i=3;for(let a=0;a<i;a+=1){const i=e.store.getRevision();try{for(const n of t)await(n.prepare?.({editor:e,requestedShapeIds:o}))}catch(s){if(e.store.getRevision()!==i)continue;throw s}if(e.store.getRevision()!==i)continue;const a=e.exports.getSvgString(o,{padding:n,resolveThemeColor:r}),l=a?.exportedShapeIds.flatMap(t=>{const n=e.shapes.get(t);return n?[n]:[]})??[];if(e.store.getRevision()===i)return{exportedShapes:l,result:a}}throw new Error("The document changed repeatedly during SVG export.")}({assetInliners:t,editor:e,padding:n,resolveThemeColor:r,shapeIds:o})}catch(p){return a=e.exports.getIntegrityReport(o),vA({cause:p,integrity:a,supportedShapeTypes:i})}a=e.exports.getIntegrityReport(o);const l=function({integrity:t,supportedShapeTypes:e}){const n=function(t){const e=Object.entries(t).filter(t=>"number"==typeof t[1]);return 0===e.length?"none":e.map(([t,e])=>`${t} ${e}`).join(", ")}(function(t){const e={};for(const n of t.issues)e[n.kind]=(e[n.kind]??0)+1;return e}(t));return 0===t.fatalIssueCount&&0===t.issues.length?{tone:"success",title:"SVG export ready",details:`${t.requestedShapeIds.length} shape(s) ready. Issues: ${n}.`,integrity:t,supportedShapeTypes:e}:t.canExport?{tone:"warning",title:"SVG export repaired",details:`${t.requestedShapeIds.length} shape(s) exportable. Issues: ${n}.`,integrity:t,supportedShapeTypes:e}:{tone:"error",title:"SVG export blocked",details:`Fatal export issue(s): ${n}.`,integrity:t,supportedShapeTypes:e}}({integrity:a,supportedShapeTypes:i}),{exportedShapes:c,result:d}=s;if(!d)return{status:{...l,tone:"error",title:"SVG export blocked",details:`${l.details} No exportable SVG content was produced.`},svg:null,width:null,height:null,exportedShapeIds:[],skippedShapes:[]};let u=d.svg;try{for(const n of t)u=await n.inline({editor:e,exportedShapes:c,exportedShapeIds:d.exportedShapeIds,svg:u});!function(t){const e=new Set,n=/<([a-z][\w:-]*)\b([^>]*)>/giu,r=/<style\b[^>]*>([\s\S]*?)<\/style>/giu,o=/\burl\(\s*(["']?)(.*?)\1\s*\)/giu,i=Array.from(t.matchAll(n));for(const a of i){const t=IA(a[1]??""),n=TA(a[2]??"");for(const r of MA(t)){const t=n.get(r)?.trim();if(!t)continue;const o="srcset"===r?CA(t):[t];for(const n of o)AA(n)||e.add(n)}}const s=[...i.map(t=>t[0]),...Array.from(t.matchAll(r),t=>t[1]??"")];for(const a of s){for(const t of a.matchAll(o)){const n=t[2]?.trim();n&&!AA(n)&&e.add(n)}/@import\b/iu.test(a)&&e.add("CSS @import"),/\blocal\(/iu.test(a)&&e.add("CSS local() font source")}if(e.size>0)throw new Error(`${e.size} external SVG resource(s) remain after embedding.`)}(u)}catch(p){return vA({cause:p,exportedShapeIds:d.exportedShapeIds,integrity:a,skippedShapes:d.skippedShapes,supportedShapeTypes:i})}return{status:l,svg:u,width:d.width,height:d.height,exportedShapeIds:d.exportedShapeIds,skippedShapes:d.skippedShapes}}function vA({cause:t,exportedShapeIds:e=[],integrity:n,skippedShapes:r=[],supportedShapeTypes:o}){return{status:{tone:"error",title:"SVG export blocked",details:`Resource embedding failed: ${t instanceof Error&&t.message.trim().length>0?t.message:"An SVG resource could not be embedded."}`,integrity:n,supportedShapeTypes:o},svg:null,width:null,height:null,exportedShapeIds:e,skippedShapes:r}}var kA={audio:["src"],embed:["src"],iframe:["src"],img:["src","srcset"],input:["src"],object:["data"],script:["src"],source:["src","srcset"],track:["src"],video:["poster","src"]},PA=["href","xlink:href"],SA=new Set(["a","area"]);function IA(t){return(t.split(":").pop()??t).toLowerCase()}function MA(t){const e=kA[t]??[];return SA.has(t)?e:[...PA,...e]}function TA(t){const e=new Map;for(const n of t.matchAll(/([^\s=/>]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/gu)){const t=n[1]?.toLowerCase(),r=n[2]??n[3]??n[4];t&&void 0!==r&&e.set(t,r)}return e}function CA(t){const e=[];let n=0;for(;n<t.length;){for(;n<t.length&&(","===t[n]||/\s/u.test(t[n]??""));)n+=1;if(n>=t.length)break;const r="data:"===t.slice(n,n+5).toLowerCase(),o=n;for(;n<t.length&&!/\s/u.test(t[n]??"")&&(r||","!==t[n]);)n+=1;let i=t.slice(o,n);const s=r&&i.endsWith(",");if(s&&(i=i.replace(/,+$/u,"")),i&&e.push(i),!s)for(;n<t.length&&","!==t[n];)n+=1}return e}function AA(t){return t.startsWith("#")||/^data:/iu.test(t)}var EA=16384,LA=67108864;async function BA({background:t,pixelRatio:e=2,...n}){const r=await bA(n);if(!r.svg||null===r.width||null===r.height)return{status:"error"===r.status.tone?$A(r.status):{...r.status,tone:"error",title:"PNG export blocked",details:`${r.status.details} No exportable SVG content was produced.`},blob:null,width:null,height:null,exportedShapeIds:r.exportedShapeIds,skippedShapes:r.skippedShapes};try{const n=await async function({background:t,height:e,pixelRatio:n,svg:r,width:o}){const i=Math.ceil(o*n),s=Math.ceil(e*n);if(function({height:t,pixelRatio:e,sourceHeight:n,sourceWidth:r,width:o}){if(!Number.isFinite(e)||e<=0||!Number.isFinite(r)||r<=0||!Number.isFinite(n)||n<=0)throw new Error("PNG dimensions and pixel ratio must be positive numbers.");if(o>EA||t>EA||o*t>LA)throw new Error(`PNG dimensions ${o}×${t} exceed the browser export limit.`)}({height:s,pixelRatio:n,sourceHeight:e,sourceWidth:o,width:i}),"undefined"==typeof document||"undefined"==typeof Image||"undefined"==typeof FileReader)throw new Error("PNG export requires a browser environment.");const a=await wA(new Blob([r],{type:"image/svg+xml;charset=utf-8"}));if(!a)throw new Error("The exported SVG could not be encoded as a data URL.");const l=await(d=a,new Promise((t,e)=>{const n=new Image;n.onload=()=>t(n),n.onerror=()=>e(new Error("The exported SVG could not be decoded.")),n.src=d})),c=document.createElement("canvas");var d;c.width=i,c.height=s;const u=c.getContext("2d");if(!u)throw new Error("A 2D canvas context is unavailable.");t&&(u.fillStyle=t,u.fillRect(0,0,i,s));return u.drawImage(l,0,0,i,s),{blob:await RA(c),width:i,height:s}}({background:t,height:r.height,pixelRatio:e,svg:r.svg,width:r.width});return{status:$A(r.status,`${n.width}×${n.height} px.`),blob:n.blob,width:n.width,height:n.height,exportedShapeIds:r.exportedShapeIds,skippedShapes:r.skippedShapes}}catch(o){const t=o instanceof Error&&o.message.trim().length>0?o.message:"The SVG could not be rasterized.";return{status:{...r.status,tone:"error",title:"PNG export blocked",details:`Rasterization failed: ${t}`},blob:null,width:null,height:null,exportedShapeIds:r.exportedShapeIds,skippedShapes:r.skippedShapes}}}function RA(t){return new Promise((e,n)=>{t.toBlob(t=>{t?e(t):n(new Error("The browser did not produce a PNG blob."))},"image/png")})}function $A(t,e){return{...t,title:"success"===t.tone?"PNG export ready":"warning"===t.tone?"PNG export repaired":"PNG export blocked",details:e?`${t.details} ${e}`:t.details}}async function NA(t,e){return(await t.export("svg",{...DA(e),options:e})).result}async function zA(t,e){return(await t.export("png",{...DA(e),options:e})).result}function OA(){return{kind:"provider",id:"canvas-kit.export.svg",format:"svg",label:"SVG",mimeType:"image/svg+xml;charset=utf-8",fileExtension:"svg",async export({editor:t,options:e,shapeIds:n},r){const o=e??{},i=await bA({assetInliners:[HA(n,r.inlineSvg)],editor:t,padding:o.padding,resolveThemeColor:o.appearance?.resolveThemeColor,shapeIds:n});return{data:i.svg,result:i,status:i.status}}}}function WA(){return{kind:"provider",id:"canvas-kit.export.png",format:"png",label:"PNG",mimeType:"image/png",fileExtension:"png",async export({editor:t,options:e,shapeIds:n},r){const o=e??{},i=await BA({assetInliners:[HA(n,r.inlineSvg)],background:o.background,editor:t,padding:o.padding,pixelRatio:o.pixelRatio,resolveThemeColor:o.appearance?.resolveThemeColor,shapeIds:n});return{data:i.blob,result:i,status:i.status}}}}function HA(t,e){return{inline:n=>e({...n,requestedShapeIds:t})}}function DA(t){return t.scope?{scope:t.scope}:{shapeIds:t.shapeIds}}function FA(){return{id:"canvas-kit.export",setup:()=>({exports:[OA(),WA()]})}}function jA(t,e=0){return Math.max(0,"number"==typeof t&&Number.isFinite(t)?t:e)}function UA({cornerRadius:t,h:e,w:n}){return Math.min(jA(t),Math.max(0,n)/2,Math.max(0,e)/2)}function XA(t){return xt(t)&&"video"===t.type}function YA(t){return yt(t)&&"video"===t.type}var KA=bn("plugin-video.api");function _A({editor:t}){return{getSelectionState(){if(1!==t.selection.getIds().length)return null;const[e]=t.state.selectedShapes.get();return YA(e)?{shapeId:e.id,cornerRadius:jA(e.props.cornerRadius),loop:e.props.loop}:null},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(YA).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...void 0===e.cornerRadius?{}:{cornerRadius:jA(e.cornerRadius)},...void 0===e.loop?{}:{loop:e.loop}}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)}}}function qA(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}var VA=class extends pe{type="video";getDefaultProps(){return{w:320,h:180,assetId:null,name:"",loop:!1,cornerRadius:0}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Math.max(64,qA(e.w,n.w)),h:Math.max(36,qA(e.h,n.h)),assetId:(r=e.assetId,"string"==typeof r&&r.startsWith("asset:")?e.assetId:null),name:"string"==typeof e.name?e.name:"",loop:!0===e.loop,cornerRadius:jA(e.cornerRadius)};var r}getLocalBounds(t){return new vt(0,0,t.props.w,t.props.h)}getRenderBounds(t){return QA(t)}getExportBounds(t){return this.getLocalBounds(t)}getPointHitTestBounds(t){const e=QA(t);return new vt(e.x+t.x,e.y+t.y,e.w,e.h)}canEdit(t){return!0}hitTest(t,e){return this.getPointHitTestBounds(t).containsPoint(e)}hitTestBindingTarget(t,e){return this.getPositionedBounds(t).containsPoint(e)}canReceiveTerminalBinding(t){return!0}getAllowedSelectionResizeModes(t,e){return Gt}},GA="Video",JA=34;function ZA(t){return/^\s*$/.test(t)?GA:t}function QA(t){return new vt(0,-34,t.props.w,t.props.h+34)}function tE(){return{id:"land.video",shapeUtils:[new VA]}}var eE='[data-ui="video-shape-player"]',nE=new Set(["key_down","key_up","pointer_cancel","pointer_down","pointer_move","pointer_up"]),rE=["Inter","ui-sans-serif","system-ui","-apple-system","BlinkMacSystemFont","'Segoe UI'","sans-serif"].join(", "),oE={id:"land.video.player.dom-events",handle({event:t,name:e}){if(!nE.has(e))return"continue";const n=t.target;return n instanceof Element&&n.closest(eE)?"handled":"continue"},getCursor:({element:t})=>t?.closest(eE)?"default":void 0},iE=a({id:"land.video.name.dom-events",selector:'[data-ui="video-canvas-name"]'});function sE(){return{id:"land.video.react",domEventGuards:[oE,iE],shapeRenderers:[{type:"video",component:aE,hoverComponent:lE}]}}function aE({editor:t,isSelected:e,shape:n,shapeEditingSession:r}){const{assetId:o,h:i,loop:s,name:a,w:l}=n.props,c=o?t.assets.resolveUrl(o):null,p=r?.shapeId===n.id;
75
+ return u("div",{style:{height:"100%",overflow:"visible",pointerEvents:"none",position:"relative",width:"100%"},children:[d("div",{"data-ui":"video-shape",style:{background:"#000",borderRadius:UA(n.props),display:"block",height:i,left:0,overflow:"hidden",pointerEvents:"none",position:"absolute",top:34,width:l},children:c?d("video",{"aria-label":ZA(a),controls:e,"data-ui":"video-shape-player",draggable:!1,loop:s,playsInline:!0,preload:"metadata",src:c,style:{display:"block",height:i,objectFit:"contain",pointerEvents:e?"auto":"none",userSelect:"none",width:l}}):d("div",{"data-ui":"video-shape-missing-asset",style:{alignItems:"center",background:"#0f172a",border:"1px solid #334155",boxSizing:"border-box",color:"#cbd5e1",display:"flex",fontFamily:rE,fontSize:12,height:i,justifyContent:"center",overflow:"hidden",width:l},children:"Missing video"})}),d(cE,{editor:t,shape:n,isEditing:p})]})}function lE({shape:t,strokeWidth:e}){const n=QA(t);
76
+ return d("svg",{"aria-hidden":"true","data-ui":"video-hover-outline",width:"100%",height:"100%",viewBox:`${n.x} ${n.y} ${n.w} ${n.h}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},children:d("rect",{x:0,y:0,width:t.props.w,height:t.props.h,rx:UA(t.props),ry:UA(t.props),fill:"none",stroke:o,strokeWidth:e,vectorEffect:"non-scaling-stroke"})})}function cE({editor:t,shape:e,isEditing:n}){
77
+ return d(s,{editor:t,shape:e,isEditing:n,value:e.props.name,fallback:ZA(""),bodyWidth:e.props.w,bodyHeight:e.props.h,renderHeight:34,operationKind:"video.edit",editAriaLabel:"Edit video name",inputAriaLabel:"Video name",dataUi:{heading:"video-canvas-heading",dragHandle:"video-drag-handle",name:"video-canvas-name",input:"video-canvas-name-input"},onValueChange:n=>{t.commands.updateShapes([{id:e.id,props:{name:n}}],{source:"user"})}})}var dE={id:"video",editor:tE(),render:sE(),api:KA,setup:({editor:t})=>({api:_A({editor:t})})},uE=bn("video.host-api"),pE="blobs",hE=null;function fE(){return"undefined"==typeof indexedDB?Promise.resolve(null):(hE||(hE=new Promise((t,e)=>{const n=indexedDB.open("land.plugin-video",1);n.addEventListener("upgradeneeded",()=>{n.result.objectStoreNames.contains(pE)||n.result.createObjectStore(pE)}),n.addEventListener("success",()=>{const e=n.result;e.addEventListener("versionchange",()=>{e.close(),hE=null}),t(e)}),n.addEventListener("error",()=>{hE=null,e(n.error)})})),hE)}var gE="video-blob:";function mE(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?`${gE}${crypto.randomUUID()}`:`${gE}${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}async function yE(t){if("undefined"==typeof indexedDB)throw new Error("IndexedDB is not available for video storage.");const e=mE();return await async function(t,e){const n=await fE();n&&await new Promise((r,o)=>{const i=n.transaction(pE,"readwrite");i.addEventListener("complete",()=>r()),i.addEventListener("abort",()=>o(i.error)),i.addEventListener("error",()=>o(i.error)),i.objectStore(pE).put(e,t)})}(e,t),{storageKey:e}}async function xE(t){const e=await async function(t){const e=await fE();return e?new Promise((n,r)=>{const o=e.transaction(pE,"readonly").objectStore(pE).get(t);o.addEventListener("success",()=>n(o.result??null)),o.addEventListener("error",()=>r(o.error))}):null}(t);return e instanceof Blob?e:null}async function wE(t){await async function(t){const e=await fE();e&&await new Promise((n,r)=>{const o=e.transaction(pE,"readwrite");o.addEventListener("complete",()=>n()),o.addEventListener("abort",()=>r(o.error)),o.addEventListener("error",()=>r(o.error)),o.objectStore(pE).delete(t)})}(t)}async function bE(){return(await async function(){const t=await fE();return t?new Promise((e,n)=>{const r=t.transaction(pE,"readonly").objectStore(pE).getAllKeys();r.addEventListener("success",()=>e([...r.result])),r.addEventListener("error",()=>n(r.error))}):null}())?.map(String)??[]}function vE(t,e){const n=t.assets.get(e);return XA(n)&&"local"===n.props.source.kind&&n.props.source.storageKey||null}function kE(t,e){const n=t.assets.get(e);return XA(n)&&"remote"===n.props.source.kind&&n.props.source.url||null}function PE(t){const e=new Set;for(const n of t.assets.getAll())XA(n)&&"local"===n.props.source.kind&&n.props.source.storageKey&&e.add(n.props.source.storageKey);return e}async function SE({editor:t,objectUrls:e}){const n=PE(t),r=await bE(),o=[];for(const i of r)n.has(i)||(e?.release(i),await wE(i),o.push(i));return o}function IE(){const t=new Map,e=new Map;let n=0,r=!1;const o=async(o,i={})=>{if(i.signal?.throwIfAborted(),r)return null;const s=t.get(o);if(s)return s;const a=e.get(o);if(a)return a;const l=n,c=xE(o).then(e=>{if(i.signal?.throwIfAborted(),!e||r||l!==n)return null;const s=URL.createObjectURL(e);return t.set(o,s),s}).finally(()=>{e.delete(o)});return e.set(o,c),c};return{async preloadForEditor(t,e={}){e.signal?.throwIfAborted(),await Promise.all(Array.from(PE(t)).map(t=>o(t,e)))},preload:o,resolve:e=>t.get(e)??null,resolveAssetUrl(e,n){const r=kE(e,n);if(r)return r;const o=vE(e,n);return o?t.get(o)??null:null},release(n){const r=t.get(n);r&&(URL.revokeObjectURL(r),t.delete(n)),e.delete(n)},releaseAll(){r=!0,n+=1;for(const e of t.values())URL.revokeObjectURL(e);t.clear(),e.clear()}}}async function ME(t,{signal:e}){if("url"===t.type)return{...await TE(t.url,{signal:e}),name:t.name||RE(t.url)||"Video",source:{kind:"remote",url:t.url},mimeType:null};const n="file"===t.type?t.file:t.blob;if(!EE(n))throw new Error("The selected file is not a video.");const r=URL.createObjectURL(n),o=await TE(r,{signal:e}).finally(()=>URL.revokeObjectURL(r));e.throwIfAborted();const{storageKey:i}=await yE(n);try{e.throwIfAborted()}catch(s){throw await wE(i),s}return{...o,name:"file"===t.type?t.file.name||"Video":t.name||"Video",source:{kind:"local",storageKey:i},mimeType:"file"===t.type?t.file.type||"video/mp4":t.mimeType||t.blob.type||"video/mp4",fileSize:n.size}}function TE(t,{signal:e}={}){return e?.throwIfAborted(),new Promise((n,r)=>{const o=document.createElement("video"),i=()=>{o.removeEventListener("loadedmetadata",s),o.removeEventListener("error",a),e?.removeEventListener("abort",l),o.removeAttribute("src"),o.load()},s=()=>{const t=o.videoWidth||320,e=o.videoHeight||180,r=Number.isFinite(o.duration)&&o.duration>=0?o.duration:null;i(),n({width:t,height:e,duration:r})},a=()=>{i(),r(new Error("Could not decode video metadata."))},l=()=>{i(),r(e?.reason??new Error("Video metadata decoding aborted."))};o.preload="metadata",o.addEventListener("loadedmetadata",s),o.addEventListener("error",a),e?.addEventListener("abort",l,{once:!0}),o.src=t,o.load(),e?.aborted&&l()})}function CE({height:t,width:e}){const n=e>0&&Number.isFinite(e)?e:320,r=t>0&&Number.isFinite(t)?t:180,o=Math.min(1,480/Math.max(n,r));return{w:Math.max(64,Math.round(n*o)),h:Math.max(36,Math.round(r*o))}}function AE(t){for(const e of t)if(e.type.startsWith("video/"))return e;return null}function EE(t){return!t.type||t.type.startsWith("video/")}function LE({filename:t,url:e}){const n=document.createElement("a");n.href=e,n.download=t,n.click()}async function BE({blob:t,filename:e}){const n=URL.createObjectURL(t);try{LE({filename:e,url:n})}finally{window.setTimeout(()=>URL.revokeObjectURL(n),0)}}function RE(t){try{const e=new URL(t).pathname.split("/").filter(Boolean).at(-1);return e?decodeURIComponent(e):null}catch{return null}}var $E=1;function NE(t,e){return t.commands.createAsset({type:"video",props:{w:e.width,h:e.height,duration:e.duration,name:e.name,source:e.source,mimeType:e.mimeType,fileSize:e.fileSize}},{source:"user"})}async function zE({editor:t,objectUrls:e,pagePoint:n,signal:r,size:o,source:i}){return OE({editor:t,input:await ME(i,{signal:r}),objectUrls:e,pagePoint:n,signal:r,size:o})}async function OE({editor:t,input:e,objectUrls:n,pagePoint:r,signal:o,size:i}){const s="local"===e.source.kind?e.source.storageKey:null;try{s&&await n.preload(s,{signal:o}),o.throwIfAborted()}catch(l){throw await DE({objectUrls:n,storageKey:s}),l}let a=null;try{const o=NE(t,e);a=o.id;const l=function(t){return!t||!Number.isFinite(t.w)||!Number.isFinite(t.h)||t.w<=0||t.h<=0?null:{w:Math.max(64,t.w),h:Math.max(36,t.h)}}(i)??CE({width:o.props.w,height:o.props.h}),c=t.state.viewportPageBounds.get(),d=r??c?.center??t.viewport.screenToPage(new bt(360,240)),[u]=t.commands.createShapes([{type:"video",x:Math.round(d.x-l.w/2),y:Math.round(d.y-l.h/2),props:{...l,assetId:o.id,name:e.name}}],{source:"user"});return u?(t.commands.setSelectedShapeIds([u.id],{source:"user"}),u.id):(t.commands.deleteAsset(o.id,{source:"system"}),a=null,await DE({objectUrls:n,storageKey:s}),null)}catch(l){throw a&&t.commands.deleteAsset(a,{source:"system"}),await DE({objectUrls:n,storageKey:s}),l}}async function WE({editor:t,file:e,objectUrls:n,signal:r}){if(!EE(e))return!1;const[o]=t.state.selectedShapes.get();return!(1!==t.selection.getIds().length||!YA(o)||o.isLocked)&&async function({editor:t,input:e,objectUrls:n,shape:r,signal:o}){const i=r.props.assetId,s="local"===e.source.kind?e.source.storageKey:null;try{o.throwIfAborted(),s&&await n.preload(s,{signal:o}),o.throwIfAborted()}catch(a){throw await DE({objectUrls:n,storageKey:s}),a}try{const o=t.shapes.get(r.id);if(!YA(o)||o.isLocked||o.props.assetId!==i)return await DE({objectUrls:n,storageKey:s}),!1;const l=t.operations.begin({kind:`video.asset.replace:${r.id}:${$E++}`,label:"video.asset.replace",source:"user",history:"record"});try{const n=NE(t,e);return t.commands.updateShapes([{id:r.id,props:{assetId:n.id,name:e.name}}],{source:"user"}),i&&!function(t,e){return t.snapshots.getDocument().records.some(t=>"shape"===t.typeName&&t.props.assetId===e)}(t,i)&&t.commands.deleteAsset(i,{source:"user"}),l.commit(),!0}catch(a){throw l.isActive&&l.cancel(),a}}catch(a){throw await DE({objectUrls:n,storageKey:s}),a}}({editor:t,input:await ME({type:"file",file:e},{signal:r}),objectUrls:n,shape:o,signal:r})}async function HE({editor:t,objectUrls:e,onError:n}){if(1!==t.selection.getIds().length)return;const[r]=t.state.selectedShapes.get();if(!YA(r)||!r.props.assetId)return;const o=t.assets.get(r.props.assetId);if(!XA(o))return;const i=o.props.name||"land-video";if("remote"===o.props.source.kind)return void(await async function({filename:t,onError:e,url:n}){try{const e=await fetch(n);if(!e.ok)throw new Error(`Could not download video URL (${e.status}).`);await BE({blob:await e.blob(),filename:t})}catch(r){e?.(new Error("Could not download remote video; opening URL instead.",{cause:r})),function(t){const e=document.createElement("a");e.href=t,e.rel="noreferrer",e.target="_blank",e.click()}(n)}}({filename:i,onError:n,url:o.props.source.url}));const s=o.props.source.storageKey,a=await xE(s);if(a)return void(await BE({blob:a,filename:i}));const l=e.resolve(s);l&&LE({filename:i,url:l})}async function DE({objectUrls:t,storageKey:e}){e&&(t.release(e),await wE(e))}function FE({editor:t,onError:e,tasks:n,videoAssetService:r}){let o;const i=jE(t=>o.insert({source:{type:"file",file:t}}),e),s=jE(t=>o.replaceSelection({file:t}),e);return o={openInsertFilePicker(){i.open()},openReplaceFilePicker(){s.open()},insert:({pagePoint:e,size:o,source:i})=>n.run(async n=>{n.throwIfAborted();const s=await zE({editor:t,objectUrls:r.objectUrls,pagePoint:e,signal:n,size:o,source:i});return n.throwIfAborted(),s}),replaceSelection:({file:e})=>n.run(async n=>{if(!e.type.startsWith("video/"))return!1;const[o]=t.state.selectedShapes.get();if(!YA(o)||o.isLocked)return!1;const i=await WE({editor:t,file:e,objectUrls:r.objectUrls,signal:n});return n.throwIfAborted(),i}),downloadSelectionOriginal:()=>n.run(async n=>{await HE({editor:t,objectUrls:r.objectUrls,onError:e}),n.throwIfAborted()})},{value:o,dispose(){i.dispose(),s.dispose()}}}function jE(t,e){let n=null,r=!1;return{open(){if(!r){if(!globalThis.document)throw new Error("Video file selection requires a browser document.");n??=function(){const n=document.createElement("input");return n.type="file",n.accept="video/*",n.hidden=!0,n.onchange=()=>{const o=n.files?.[0]??null;n.value="",o&&!r&&t(o).catch(t=>{e?.(new Error("Video file selection failed.",{cause:t}))})},n}(),n.click()}},dispose(){r=!0,n&&(n.onchange=null),n=null}}}function UE(){const t=IE();return{value:{objectUrls:t,async cleanupAfterRestore(e,{signal:n}){n.throwIfAborted(),await SE({editor:e,objectUrls:t}),n.throwIfAborted()},preloadForEditor:(e,{signal:n})=>t.preloadForEditor(e,{signal:n}),resolveAssetUrl:(e,n)=>t.resolveAssetUrl(e,n)},dispose(){t.releaseAll()}}}function XE(t={}){return{id:"video.host",requires:[dE],api:uE,setup({editor:e,tasks:n}){const r=(t.createAssetService??UE)();let o=null;try{const i=FE({editor:e,onError:t.onError,tasks:n,videoAssetService:r.value});return o=i.dispose,{api:i.value,imports:[{id:"video.host-import",order:100,acceptsPreview:t=>t.fileTypes.some(t=>t.startsWith("video/"))||t.dataTypes.some(t=>{const e=t.toLowerCase();return"files"===e||"text/uri-list"===e}),accepts:t=>null!==AE(t.files)||(t.urls?.some(YE)??!1),async import(t){const e=AE(t.files),n=t.urls?.find(YE);return(e||n)&&await i.value.insert({source:e?{type:"file",file:e}:{type:"url",url:n},pagePoint:t.pagePoint})?"handled":"ignored"}}],assetResolvers:[{id:"video.host.asset-resolver",resolve:t=>r.value.resolveAssetUrl(e,t),preload:({signal:t})=>r.value.preloadForEditor(e,{signal:t}),cleanupAfterRestore:({signal:t})=>r.value.cleanupAfterRestore(e,{signal:t})}],dispose(){o?.(),r.dispose()}}}catch(i){throw o?.(),r.dispose(),i}}}}function YE(t){return t.startsWith("data:video/")||/\.(?:m4v|mov|mp4|ogv|webm)(?:[?#].*)?$/i.test(t)}function KE({toolIds:t,shortcutOverrides:e}){return mt([...t.map(_E),{id:"standard.history.undo",shortcut:{key:"z",accelKey:!0},isEnabled:t=>VE(t)&&t.history.state.getSnapshot().canUndo,run:t=>{t.history.undo()}},{id:"standard.history.redo",shortcut:{key:"z",accelKey:!0,shiftKey:!0},isEnabled:t=>VE(t)&&t.history.state.getSnapshot().canRedo,run:t=>{t.history.redo()}},{id:"standard.selection.select-all",shortcut:{key:"a",accelKey:!0},isEnabled:t=>t.pages.state.getSnapshot().currentPageShapeIds.length>0,run:t=>t.selection.selectAll()},{id:"standard.selection.duplicate",shortcut:{key:"d",accelKey:!0},isEnabled:t=>VE(t)&&GE(t),run:t=>{t.selection.duplicate()}},{id:"standard.selection.delete",shortcut:["Backspace","Delete"],isEnabled:t=>VE(t)&&GE(t),run:t=>t.selection.delete()},{id:"standard.layer.move-selection-backward",shortcut:{key:"ArrowDown",altKey:!0},isEnabled:t=>VE(t)&&JE(t).canMoveBackward,run:t=>{t.layers.move(t.selection.state.getSnapshot().ids,"backward")}},{id:"standard.layer.move-selection-forward",shortcut:{key:"ArrowUp",altKey:!0},isEnabled:t=>VE(t)&&JE(t).canMoveForward,run:t=>{t.layers.move(t.selection.state.getSnapshot().ids,"forward")}},{id:"standard.clipboard.copy",shortcut:{key:"c",accelKey:!0},isEnabled:GE,run:async t=>{await(t.api(hA)?.copy())}},{id:"standard.clipboard.cut",shortcut:{key:"x",accelKey:!0},isEnabled:t=>VE(t)&&GE(t),run:async t=>{await(t.api(hA)?.cut())}},{id:"standard.clipboard.paste",shortcut:{key:"v",accelKey:!0},isEnabled:t=>VE(t)&&(t.api(hA)?.hasContent()??!1),run:async t=>{await(t.api(hA)?.paste())}},{id:"standard.view.zoom-in",shortcut:{key:"="},isEnabled:()=>!0,run:t=>t.viewport.zoomIn()},{id:"standard.view.zoom-out",shortcut:{key:"-"},isEnabled:()=>!0,run:t=>t.viewport.zoomOut()},{id:"standard.view.reset-zoom",shortcut:{key:"0",accelKey:!0},isEnabled:()=>!0,run:t=>t.viewport.resetZoom()}],e)}function _E(t){return{id:`standard.tool.${t}`,shortcut:ZE(t),isEnabled:e=>VE(e)||qE.has(t),run:e=>e.tools.setCurrent(t)}}var qE=new Set(["select","hand","laser"]);function VE(t){return!t.document.readonlyState.getSnapshot()}function GE(t){return t.selection.state.getSnapshot().ids.length>0}function JE(t){return t.layers.getActionState(t.selection.state.getSnapshot().ids)}function ZE(t){const e=QE[t];return e?{key:e}:void 0}var QE={select:"v",hand:"h",rectangle:"r",ellipse:"o",rhombus:"d",triangle:"3",pentagon:"5",hexagon:"6",star:"8",draw:"p",arrow:"a",eraser:"e",laser:"l",path:"b",text:"t",frame:"f"};function tL(t={}){const e=!1!==t.geo&&!1!==t.connector,n=e&&!1!==t.flow&&!1!==t.image&&!1!==t.text,r="object"==typeof t.connector?nc(t.connector):rc,o="object"==typeof t.flow?IS(t.flow):MS,i="object"==typeof t.text?{...lm(),...t.text}:lm(),s=dm(i),a=CP({...i,fontCatalog:s}),l=!1===t.image?null:og({onError:t.onError}),c=!1===t.video?null:XE({onError:t.onError}),d=["select","hand",...!1===t.geo?[]:zi,...!1===t.draw?[]:["draw"],...!1===t.arrow?[]:["arrow"],...e?["connector"]:[],...!1===t.eraser?[]:["eraser"],...!1===t.laser?[]:["laser"],...!1===t.path?[]:["path"],...!1===t.text?[]:["text"],...!1===t.frame?[]:["frame"]];return{plugins:[...!1===t.geo?[]:[Wa],...!1===t.draw?[]:[jd],...!1===t.arrow?[]:[er],...e?[r]:[],...!1===t.eraser?[]:[qu],...!1===t.laser?[]:[YI],...!1===t.path?[]:[pA],...!1===t.html?[]:[JS],...l?[sf,l]:[],...c?[dE,c]:[],...!1===t.text?[]:[a,OP({fontCatalog:s})],...n?[o]:[],...!1===t.frame?[]:[xp],...!1===t.group?[]:[NS],xA,FA()],actions:KE({toolIds:d,shortcutOverrides:t.shortcutOverrides})}}export{Ye as ARROW_STROKE_STYLES,er as Arrow,wn as ArrowBindingUtil,is as ArrowLeftTool,ss as ArrowRightTool,qn as ArrowShapeSvgExporter,Nn as ArrowShapeUtil,jn as ArrowTool,Zi as BurstTool,uo as CONNECTOR_ARROW_TERMINAL_PADDING,wr as CONNECTOR_CLICK_DRAG_THRESHOLD_SCREEN,li as CONNECTOR_CURVE_INSERT_HANDLE_TYPE,ai as CONNECTOR_CURVE_WAYPOINT_HANDLE_TYPE,Mr as CONNECTOR_DASH_ARRAY,xr as CONNECTOR_LINE_HIT_RADIUS_SCREEN,ur as CONNECTOR_ORTHOGONAL_OBSTACLE_CLEARANCE_PAGE,ci as CONNECTOR_ORTHOGONAL_SEGMENT_HANDLE_TYPE,vr as CONNECTOR_ORTHOGONAL_SEGMENT_SNAP_SCREEN,dr as CONNECTOR_ORTHOGONAL_STUB_PAGE,br as CONNECTOR_ORTHOGONAL_TERMINAL_SNAP_SCREEN,mr as CONNECTOR_PORT_HIT_RADIUS_SCREEN,fr as CONNECTOR_PORT_HOVER_GAP_SCREEN,gr as CONNECTOR_PORT_HOVER_ICON_SCREEN,hr as CONNECTOR_PORT_HOVER_RADIUS_SCREEN,yr as CONNECTOR_PORT_VISUAL_OFFSET_SCREEN,pr as CONNECTOR_PORT_VISUAL_RADIUS_SCREEN,Pr as CONNECTOR_QUICK_CONNECT_CROSS_AXIS_PAGE,kr as CONNECTOR_QUICK_CONNECT_DISTANCE_PAGE,Ir as CONNECTOR_QUICK_CREATE_CROSS_GAP_PAGE,Sr as CONNECTOR_QUICK_CREATE_GAP_PAGE,rc as Connector,bl as ConnectorBindingUtil,Vl as ConnectorShapeSvgExporter,Ul as ConnectorShapeUtil,ql as ConnectorTool,_S as DEFAULT_HTML_IFRAME_SANDBOX,oh as DEFAULT_IMAGE_SMUDGE_BRUSH_COLOR,rh as DEFAULT_IMAGE_SMUDGE_BRUSH_SIZE,sm as DEFAULT_TEXT_FONT,xA as DefaultClipboardRuntimePlugin,jd as Draw,Od as DrawShapeSvg,Nd as DrawShapeSvgExporter,$d as DrawShapeUtil,pd as DrawTool,qi as EllipseTool,qu as Eraser,au as EraserTool,_P as FLOW_NODE_GAP_PAGE,GP as FLOW_NODE_TITLE_RENDER_HEIGHT,MS as Flow,nS as FlowNodeShapeUtil,PS as FlowNodeSvgExporter,xp as Frame,cp as FrameShapeSvgExporter,tp as FrameShapeUtil,sp as FrameTool,zi as GEO_SHAPE_KINDS,Oi as GEO_STROKE_STYLES,Wa as Geo,Aa as GeoShapeSvgExporter,Ta as GeoShapeUtil,NS as Group,AS as GroupShapeSvgExporter,CS as GroupShapeUtil,am as HOST_TEXT_FONT,OS as HTML_INTERACTION_OPERATION_KIND,ns as HexagonTool,JS as Html,XS as HtmlShapeUtil,kp as IMAGE_CROP_ASPECT_RATIO_PRESETS,sh as IMAGE_SMUDGE_BRUSH_SIZE_MAX,ih as IMAGE_SMUDGE_BRUSH_SIZE_MIN,sf as Image,Lh as ImageShapeSvgExporter,Eh as ImageShapeUtil,YI as Laser,nI as LaserTool,Vi as MessageCircleTool,_I as PATH_CONTROL_HANDLE_TYPE,tM as PATH_FILL_RULES,KI as PATH_NODE_HANDLE_TYPE,eM as PATH_NODE_KINDS,pA as Path,YC as PathShapeSvgExporter,AC as PathShapeUtil,jC as PathTool,es as PentagonTool,_i as RectangleTool,Qi as RhombusTool,rs as StarTool,Ji as SummaryLeftTool,Gi as SummaryTool,Tv as TEXT_SIZE_PRESETS,AP as Text,vk as TextLinkPopoverPresenterProvider,Pk as TextSearchHighlightProvider,os as TrapezoidTool,ts as TriangleTool,GA as VIDEO_NAME_FALLBACK,JA as VIDEO_NAME_RENDER_HEIGHT,dE as Video,VA as VideoShapeUtil,Pn as arrowApiToken,Ml as beginConnectorPortDrag,xh as cancelImageSmudgeSession,bh as cancelImageSmudgeSessionIfActive,hA as canvasClipboardApiToken,Ka as chooseFacingPort,_a as chooseOpposingPort,kf as cleanupUnreferencedImageBlobs,SE as cleanupUnreferencedVideoBlobs,Th as cloneImageSmudgeStrokes,bi as commitConnectorCreation,wh as completeImageSmudgeSession,Xf as confirmImageSmudgeSession,Zl as connectorApiToken,vn as createArrow,Jn as createArrowCanvasRenderPlugin,Vn as createArrowEditorPlugin,_n as createArrowInteractionHandler,Kn as createArrowSelectionHandleInteractionHandler,ug as createCanvasShapeLinkHref,yA as createClipboardRuntimePlugin,yi as createConnectorBoundEndpoint,ol as createConnectorCanvasRenderPlugin,ui as createConnectorCurveInsertHandleId,di as createConnectorCurveWaypointHandleId,Gl as createConnectorEditorPlugin,pi as createConnectorOrthogonalSegmentHandleId,nc as createConnectorPlugin,Mo as createConnectorTerminalOffsetMapper,FA as createDefaultCanvasExportPlugin,qa as createDefaultConnectorQuickCreateNodeFactory,cm as createDefaultTextFontCatalog,lm as createDefaultTextPluginOptions,Hd as createDrawCanvasRenderPlugin,zd as createDrawEditorPlugin,pu as createEraserCanvasRenderPlugin,_u as createEraserEditorPlugin,sS as createFlowCanvasRenderPlugin,SS as createFlowEditorPlugin,qP as createFlowNodeFromPort,IS as createFlowPlugin,hp as createFrameCanvasRenderPlugin,dp as createFrameEditorPlugin,Ba as createGeoCanvasRenderPlugin,Ea as createGeoEditorPlugin,LS as createGroupCanvasRenderPlugin,ES as createGroupEditorPlugin,qS as createHtmlCanvasRenderPlugin,KS as createHtmlEditorPlugin,DS as createHtmlInteractionHandler,GS as createHtmlPlugin,jS as createHtmlPluginApi,Xh as createImageCanvasRenderPlugin,Zp as createImageCropInteractionHandler,Jp as createImageCropSelectionHandleInteractionHandler,Fh as createImageEditorPlugin,Jf as createImageHostApi,og as createImageHostPlugin,Pf as createImageObjectUrlStore,Rh as createImageSmudgeInteractionHandler,hf as createImageStorageKey,Qf as createImageSvgAssetInliner,sI as createLaserCanvasRenderPlugin,XI as createLaserEditorPlugin,Sf as createLocalImageAssetService,UE as createLocalVideoAssetService,mA as createMemoryCanvasClipboard,BT as createPathCanvasRenderPlugin,VI as createPathControlHandleId,KC as createPathEditorPlugin,qI as createPathNodeHandleId,WA as createPngExportFormatProvider,yg as createRichTextFromPlainText,KE as createStandardCanvasActions,tL as createStandardCanvasKitProfile,OA as createSvgExportFormatProvider,Tk as createTextCanvasRenderPlugin,PP as createTextEditorPlugin,dm as createTextFontCatalog,CP as createTextPlugin,OP as createTextSvgExportPlugin,sE as createVideoCanvasRenderPlugin,tE as createVideoEditorPlugin,FE as createVideoHostApi,XE as createVideoHostPlugin,IE as createVideoObjectUrlStore,mE as createVideoStorageKey,TE as decodeVideoMetadata,yf as deleteImageBlob,wE as deleteVideoBlob,Wf as downloadSelectedImageOriginal,HE as downloadSelectedVideoOriginal,vd as drawApiToken,zA as exportCanvasPng,NA as exportCanvasSvg,BA as exportEditorPng,bA as exportEditorSvg,Ya as findQuickConnectTargets,Sk as findRichTextSearchMatches,CE as fitVideoSize,cd as flipDrawShapeInSelectionBounds,YP as flowApiToken,ep as frameApiToken,as as geoApiToken,kh as getActiveImageSmudgeSession,xf as getAllImageBlobStorageKeys,bE as getAllVideoBlobStorageKeys,xe as getArrowBindingAnchorPagePoint,ke as getArrowTerminalPagePoint,Xa as getBalancedConnectorBranchNodeInput,fo as getConnectorArrowGlyphLength,ho as getConnectorArrowLength,po as getConnectorArrowMagnification,wi as getConnectorCreationInvalidReason,Lo as getConnectorInfo,mo as getConnectorMarkerPath,go as getConnectorMarkerRefX,Li as getConnectorParentId,el as getConnectorPortInteractionState,yo as getConnectorSegmentPoint,Ha as getConnectorVisualPortPoint,HP as getDefaultFlowNodeTitle,ud as getDrawShapeDiagnostics,sd as getDrawShapeParentPoints,ad as getDrawShapeParentSegments,Gd as getEraserRuntime,Ef as getFirstImageFile,AE as getFirstVideoFile,tS as getFlowNodeDisplayTitle,eS as getFlowNodeRenderBounds,YS as getHtmlDisplayTitle,Hp as getImageCropModeOperationKind,Lp as getImageCropRectOrDefault,fh as getImageSmudgeModeOperationKind,QS as getLaserRuntime,wf as getLocalImageAssetStorageKey,vE as getLocalVideoAssetStorageKey,Fa as getNearestConnectorPortAtPoint,xg as getPlainTextFromRichText,vf as getReferencedImageStorageKeys,PE as getReferencedVideoStorageKeys,bf as getRemoteImageAssetUrl,kE as getRemoteVideoAssetUrl,Eo as getResolvedConnectorLocalInfo,To as getResolvedConnectorPageInfo,ZA as getVideoDisplayName,QA as getVideoRenderBounds,nl as getVisibleConnectorSourcePortAtPoint,Ai as hasDirectedConnector,FS as htmlApiToken,Qh as imageApiToken,af as imageHostApiToken,Nf as insertImageIntoEditor,OE as insertPreparedVideoIntoEditor,zE as insertVideoIntoEditor,_d as interpolateDrawShapeRecords,cg as isAllowedRichTextLinkHref,qe as isArrowBindingRecord,_e as isArrowShapeRecord,Ke as isArrowStrokeStyle,Cr as isConnectorBindingRecord,Tr as isConnectorShapeRecord,bd as isDrawShapeRecord,dg as isExternalRichTextLinkHref,UP as isFlowNodeShape,Hi as isGeoShapeKind,Wi as isGeoShapeRecord,Di as isGeoStrokeStyle,zS as isHtmlShapeRecord,_p as isImageAssetRecord,qp as isImageShapeRecord,gh as isImageSmudgeModeForShape,rM as isPathFillRule,oM as isPathNodeKind,nM as isPathShapeRecord,Dg as isTextShapeRecord,XA as isVideoAssetRecord,EE as isVideoBlob,YA as isVideoShapeRecord,lg as normalizeRichTextLinkHref,WP as openBrowserRichTextLink,hg as openRichTextLink,pg as parseCanvasShapeLinkHref,hi as parseConnectorIndexedHandleId,fi as parseConnectorOrthogonalSegmentHandleId,GI as parsePathHandle,rA as pathApiToken,ME as prepareVideoAssetInput,ja as quickConnectFromPort,wA as readBlobAsDataUrl,gf as readImageBlob,mf as readImageBlobAsDataUrl,xE as readVideoBlob,Sh as redoImageSmudgeStroke,Ih as registerImageSmudgeConfirmHandler,Of as replaceSelectedImageFromFile,WE as replaceSelectedVideoFromFile,Mh as requestImageSmudgeConfirm,we as resolveArrowBindingPagePoint,On as resolveArrowTerminalBindingAtPoint,Wn as resolveArrowTerminalBindingAtStartPoint,Hn as resolveArrowTerminalBindingForArrow,xi as resolveConnectorDraftEndpoint,Bi as resolveConnectorDraftParentId,ki as setConnectorTerminalPagePoint,yh as startImageSmudgeSession,HS as startInteractingWithHtmlShape,SP as textApiToken,Ph as undoImageSmudgeStroke,jP as unwrapFlowNode,vh as updateImageSmudgeBrush,Xg as updateTextShapeRichText,wg as validateRichTextDocument,KA as videoApiToken,uE as videoHostApiToken,FP as wrapShapeAsFlowNode,ff as writeImageBlob,yE as writeVideoBlob};