@yuzhouu/canvas-standard 0.1.10 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/_vendor/plugin-draw/api.d.ts +1 -2
- package/_vendor/plugin-eraser/_vendor/signals/atom.d.ts +1 -1
- package/_vendor/plugin-eraser/_vendor/signals/computed.d.ts +1 -1
- package/_vendor/plugin-eraser/_vendor/signals/core.d.ts +3 -3
- package/_vendor/plugin-eraser/_vendor/signals/effect.d.ts +1 -1
- package/_vendor/plugin-eraser/_vendor/signals/types.d.ts +5 -3
- package/_vendor/plugin-eraser/eraserRuntime.d.ts +4 -4
- package/_vendor/plugin-flow/_vendor/plugin-image/image/api.d.ts +1 -2
- package/_vendor/plugin-flow/_vendor/plugin-image/image/mediaPresentation.d.ts +1 -2
- package/_vendor/plugin-flow/_vendor/plugin-text/api.d.ts +1 -2
- package/_vendor/plugin-flow/_vendor/plugin-text/geoLabelApi.d.ts +1 -2
- package/_vendor/plugin-flow/_vendor/plugin-text/host/textShapeRendererRuntime.d.ts +1 -1
- package/_vendor/plugin-flow/_vendor/plugin-text/host/useTextLabelLayout.d.ts +1 -1
- package/_vendor/plugin-flow/_vendor/plugin-text/textShapeHelpers.d.ts +1 -1
- package/_vendor/plugin-flow/_vendor/plugin-text/textShapeUtil.d.ts +2 -3
- package/_vendor/plugin-flow/api.d.ts +1 -2
- package/_vendor/plugin-flow/flowEdgeRuntime.d.ts +2 -2
- package/_vendor/plugin-flow/flowEdgeShapeUtil.d.ts +3 -7
- package/_vendor/plugin-flow/types.d.ts +1 -2
- package/_vendor/plugin-frame/api.d.ts +1 -2
- package/_vendor/plugin-frame/frameCreationRuntime.d.ts +1 -1
- package/_vendor/plugin-geo/_vendor/plugin-text/api.d.ts +1 -2
- package/_vendor/plugin-geo/_vendor/plugin-text/geoLabelApi.d.ts +1 -2
- package/_vendor/plugin-geo/_vendor/plugin-text/host/textShapeRendererRuntime.d.ts +1 -1
- package/_vendor/plugin-geo/_vendor/plugin-text/host/useTextLabelLayout.d.ts +1 -1
- package/_vendor/plugin-geo/_vendor/plugin-text/textShapeHelpers.d.ts +1 -1
- package/_vendor/plugin-geo/_vendor/plugin-text/textShapeUtil.d.ts +2 -3
- package/_vendor/plugin-geo/api.d.ts +1 -2
- package/_vendor/plugin-geo/geoCreationRuntime.d.ts +1 -1
- package/_vendor/plugin-html/api.d.ts +1 -2
- package/_vendor/plugin-image/image/api.d.ts +1 -2
- package/_vendor/plugin-image/image/mediaPresentation.d.ts +1 -2
- package/_vendor/plugin-laser/_vendor/signals/atom.d.ts +1 -1
- package/_vendor/plugin-laser/_vendor/signals/computed.d.ts +1 -1
- package/_vendor/plugin-laser/_vendor/signals/core.d.ts +3 -3
- package/_vendor/plugin-laser/_vendor/signals/effect.d.ts +1 -1
- package/_vendor/plugin-laser/_vendor/signals/types.d.ts +5 -3
- package/_vendor/plugin-laser/laserRuntime.d.ts +2 -2
- package/_vendor/plugin-path/api.d.ts +1 -2
- package/_vendor/plugin-path/pathShapeUtil.d.ts +2 -3
- package/_vendor/plugin-text/api.d.ts +1 -2
- package/_vendor/plugin-text/geoLabelApi.d.ts +1 -2
- package/_vendor/plugin-text/host/textShapeRendererRuntime.d.ts +1 -1
- package/_vendor/plugin-text/host/useTextLabelLayout.d.ts +1 -1
- package/_vendor/plugin-text/textShapeHelpers.d.ts +1 -1
- package/_vendor/plugin-text/textShapeUtil.d.ts +2 -3
- package/_vendor/plugin-video/video/api.d.ts +1 -2
- package/_vendor/plugin-video/video/mediaPresentation.d.ts +1 -2
- package/index.mjs +67 -67
- package/package.json +3 -3
- package/_vendor/canvas-export/_vendor/signals/atom.d.ts +0 -11
- package/_vendor/canvas-export/_vendor/signals/computed.d.ts +0 -13
- package/_vendor/canvas-export/_vendor/signals/core.d.ts +0 -35
- package/_vendor/canvas-export/_vendor/signals/effect.d.ts +0 -5
- package/_vendor/canvas-export/_vendor/signals/index.d.ts +0 -8
- package/_vendor/canvas-export/_vendor/signals/types.d.ts +0 -22
- package/_vendor/canvas-export/_vendor/store/diff.d.ts +0 -9
- package/_vendor/canvas-export/_vendor/store/history.d.ts +0 -22
- package/_vendor/canvas-export/_vendor/store/index.d.ts +0 -5
- package/_vendor/canvas-export/_vendor/store/store.d.ts +0 -40
- package/_vendor/canvas-export/_vendor/store/types.d.ts +0 -27
- package/_vendor/plugin-draw/_vendor/signals/atom.d.ts +0 -11
- package/_vendor/plugin-draw/_vendor/signals/computed.d.ts +0 -13
- package/_vendor/plugin-draw/_vendor/signals/core.d.ts +0 -35
- package/_vendor/plugin-draw/_vendor/signals/effect.d.ts +0 -5
- package/_vendor/plugin-draw/_vendor/signals/index.d.ts +0 -8
- package/_vendor/plugin-draw/_vendor/signals/types.d.ts +0 -22
- package/_vendor/plugin-draw/_vendor/store/diff.d.ts +0 -9
- package/_vendor/plugin-draw/_vendor/store/history.d.ts +0 -22
- package/_vendor/plugin-draw/_vendor/store/index.d.ts +0 -5
- package/_vendor/plugin-draw/_vendor/store/store.d.ts +0 -40
- package/_vendor/plugin-draw/_vendor/store/types.d.ts +0 -27
- package/_vendor/plugin-eraser/_vendor/store/diff.d.ts +0 -9
- package/_vendor/plugin-eraser/_vendor/store/history.d.ts +0 -22
- package/_vendor/plugin-eraser/_vendor/store/index.d.ts +0 -5
- package/_vendor/plugin-eraser/_vendor/store/store.d.ts +0 -40
- package/_vendor/plugin-eraser/_vendor/store/types.d.ts +0 -27
- package/_vendor/plugin-flow/_vendor/signals/atom.d.ts +0 -11
- package/_vendor/plugin-flow/_vendor/signals/computed.d.ts +0 -13
- package/_vendor/plugin-flow/_vendor/signals/core.d.ts +0 -35
- package/_vendor/plugin-flow/_vendor/signals/effect.d.ts +0 -5
- package/_vendor/plugin-flow/_vendor/signals/index.d.ts +0 -8
- package/_vendor/plugin-flow/_vendor/signals/types.d.ts +0 -22
- package/_vendor/plugin-flow/_vendor/store/diff.d.ts +0 -9
- package/_vendor/plugin-flow/_vendor/store/history.d.ts +0 -22
- package/_vendor/plugin-flow/_vendor/store/index.d.ts +0 -5
- package/_vendor/plugin-flow/_vendor/store/store.d.ts +0 -40
- package/_vendor/plugin-flow/_vendor/store/types.d.ts +0 -27
- package/_vendor/plugin-frame/_vendor/signals/atom.d.ts +0 -11
- package/_vendor/plugin-frame/_vendor/signals/computed.d.ts +0 -13
- package/_vendor/plugin-frame/_vendor/signals/core.d.ts +0 -35
- package/_vendor/plugin-frame/_vendor/signals/effect.d.ts +0 -5
- package/_vendor/plugin-frame/_vendor/signals/index.d.ts +0 -8
- package/_vendor/plugin-frame/_vendor/signals/types.d.ts +0 -22
- package/_vendor/plugin-frame/_vendor/store/diff.d.ts +0 -9
- package/_vendor/plugin-frame/_vendor/store/history.d.ts +0 -22
- package/_vendor/plugin-frame/_vendor/store/index.d.ts +0 -5
- package/_vendor/plugin-frame/_vendor/store/store.d.ts +0 -40
- package/_vendor/plugin-frame/_vendor/store/types.d.ts +0 -27
- package/_vendor/plugin-geo/_vendor/signals/atom.d.ts +0 -11
- package/_vendor/plugin-geo/_vendor/signals/computed.d.ts +0 -13
- package/_vendor/plugin-geo/_vendor/signals/core.d.ts +0 -35
- package/_vendor/plugin-geo/_vendor/signals/effect.d.ts +0 -5
- package/_vendor/plugin-geo/_vendor/signals/index.d.ts +0 -8
- package/_vendor/plugin-geo/_vendor/signals/types.d.ts +0 -22
- package/_vendor/plugin-geo/_vendor/store/diff.d.ts +0 -9
- package/_vendor/plugin-geo/_vendor/store/history.d.ts +0 -22
- package/_vendor/plugin-geo/_vendor/store/index.d.ts +0 -5
- package/_vendor/plugin-geo/_vendor/store/store.d.ts +0 -40
- package/_vendor/plugin-geo/_vendor/store/types.d.ts +0 -27
- package/_vendor/plugin-group/_vendor/signals/atom.d.ts +0 -11
- package/_vendor/plugin-group/_vendor/signals/computed.d.ts +0 -13
- package/_vendor/plugin-group/_vendor/signals/core.d.ts +0 -35
- package/_vendor/plugin-group/_vendor/signals/effect.d.ts +0 -5
- package/_vendor/plugin-group/_vendor/signals/index.d.ts +0 -8
- package/_vendor/plugin-group/_vendor/signals/types.d.ts +0 -22
- package/_vendor/plugin-group/_vendor/store/diff.d.ts +0 -9
- package/_vendor/plugin-group/_vendor/store/history.d.ts +0 -22
- package/_vendor/plugin-group/_vendor/store/index.d.ts +0 -5
- package/_vendor/plugin-group/_vendor/store/store.d.ts +0 -40
- package/_vendor/plugin-group/_vendor/store/types.d.ts +0 -27
- package/_vendor/plugin-html/_vendor/signals/atom.d.ts +0 -11
- package/_vendor/plugin-html/_vendor/signals/computed.d.ts +0 -13
- package/_vendor/plugin-html/_vendor/signals/core.d.ts +0 -35
- package/_vendor/plugin-html/_vendor/signals/effect.d.ts +0 -5
- package/_vendor/plugin-html/_vendor/signals/index.d.ts +0 -8
- package/_vendor/plugin-html/_vendor/signals/types.d.ts +0 -22
- package/_vendor/plugin-html/_vendor/store/diff.d.ts +0 -9
- package/_vendor/plugin-html/_vendor/store/history.d.ts +0 -22
- package/_vendor/plugin-html/_vendor/store/index.d.ts +0 -5
- package/_vendor/plugin-html/_vendor/store/store.d.ts +0 -40
- package/_vendor/plugin-html/_vendor/store/types.d.ts +0 -27
- package/_vendor/plugin-image/_vendor/signals/atom.d.ts +0 -11
- package/_vendor/plugin-image/_vendor/signals/computed.d.ts +0 -13
- package/_vendor/plugin-image/_vendor/signals/core.d.ts +0 -35
- package/_vendor/plugin-image/_vendor/signals/effect.d.ts +0 -5
- package/_vendor/plugin-image/_vendor/signals/index.d.ts +0 -8
- package/_vendor/plugin-image/_vendor/signals/types.d.ts +0 -22
- package/_vendor/plugin-image/_vendor/store/diff.d.ts +0 -9
- package/_vendor/plugin-image/_vendor/store/history.d.ts +0 -22
- package/_vendor/plugin-image/_vendor/store/index.d.ts +0 -5
- package/_vendor/plugin-image/_vendor/store/store.d.ts +0 -40
- package/_vendor/plugin-image/_vendor/store/types.d.ts +0 -27
- package/_vendor/plugin-laser/_vendor/store/diff.d.ts +0 -9
- package/_vendor/plugin-laser/_vendor/store/history.d.ts +0 -22
- package/_vendor/plugin-laser/_vendor/store/index.d.ts +0 -5
- package/_vendor/plugin-laser/_vendor/store/store.d.ts +0 -40
- package/_vendor/plugin-laser/_vendor/store/types.d.ts +0 -27
- package/_vendor/plugin-path/_vendor/signals/atom.d.ts +0 -11
- package/_vendor/plugin-path/_vendor/signals/computed.d.ts +0 -13
- package/_vendor/plugin-path/_vendor/signals/core.d.ts +0 -35
- package/_vendor/plugin-path/_vendor/signals/effect.d.ts +0 -5
- package/_vendor/plugin-path/_vendor/signals/index.d.ts +0 -8
- package/_vendor/plugin-path/_vendor/signals/types.d.ts +0 -22
- package/_vendor/plugin-path/_vendor/store/diff.d.ts +0 -9
- package/_vendor/plugin-path/_vendor/store/history.d.ts +0 -22
- package/_vendor/plugin-path/_vendor/store/index.d.ts +0 -5
- package/_vendor/plugin-path/_vendor/store/store.d.ts +0 -40
- package/_vendor/plugin-path/_vendor/store/types.d.ts +0 -27
- package/_vendor/plugin-text/_vendor/signals/atom.d.ts +0 -11
- package/_vendor/plugin-text/_vendor/signals/computed.d.ts +0 -13
- package/_vendor/plugin-text/_vendor/signals/core.d.ts +0 -35
- package/_vendor/plugin-text/_vendor/signals/effect.d.ts +0 -5
- package/_vendor/plugin-text/_vendor/signals/index.d.ts +0 -8
- package/_vendor/plugin-text/_vendor/signals/types.d.ts +0 -22
- package/_vendor/plugin-text/_vendor/store/diff.d.ts +0 -9
- package/_vendor/plugin-text/_vendor/store/history.d.ts +0 -22
- package/_vendor/plugin-text/_vendor/store/index.d.ts +0 -5
- package/_vendor/plugin-text/_vendor/store/store.d.ts +0 -40
- package/_vendor/plugin-text/_vendor/store/types.d.ts +0 -27
- package/_vendor/plugin-video/_vendor/signals/atom.d.ts +0 -11
- package/_vendor/plugin-video/_vendor/signals/computed.d.ts +0 -13
- package/_vendor/plugin-video/_vendor/signals/core.d.ts +0 -35
- package/_vendor/plugin-video/_vendor/signals/effect.d.ts +0 -5
- package/_vendor/plugin-video/_vendor/signals/index.d.ts +0 -8
- package/_vendor/plugin-video/_vendor/signals/types.d.ts +0 -22
- package/_vendor/plugin-video/_vendor/store/diff.d.ts +0 -9
- package/_vendor/plugin-video/_vendor/store/history.d.ts +0 -22
- package/_vendor/plugin-video/_vendor/store/index.d.ts +0 -5
- package/_vendor/plugin-video/_vendor/store/store.d.ts +0 -40
- package/_vendor/plugin-video/_vendor/store/types.d.ts +0 -27
package/index.mjs
CHANGED
|
@@ -1,68 +1,68 @@
|
|
|
1
1
|
import "./styles.css";
|
|
2
|
-
import{CanvasMedia as t,SHAPE_HOVER_STROKE as e,ShapeHeadingControl as n,ShapeHoverRect as r,createCanvasReadable as o,createShapeHeadingDomEventGuard as i,defineCanvasPlugin as s,useEditor as a,useValue as l}from"@yuzhouu/canvas-kit/plugin";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 w,useId as x,useLayoutEffect as b,useMemo as v,useRef as k,useState as S,useSyncExternalStore as I}from"react";import{EditorContent as P,useEditor as M}from"@tiptap/react";import{Extension as T,Mark as C,Node as E,callOrReturn as A,canInsertNode as L,combineTransactionSteps as R,createStyleTag as $,findChildrenInRange as N,getAttributes as B,getChangedRanges as O,getExtensionField as z,getMarksBetween as H,getNodeAtPosition as D,getNodeType as F,getRenderedAttributes as W,getStyleProperty as j,isAtEndOfNode as U,isAtStartOfNode as K,isNodeActive as X,isNodeEmpty as Y,isNodeSelection as _,markInputRule as q,markPasteRule as G,mergeAttributes as V,nodeInputRule as J,parseIndentedBlocks as Z,renderNestedMarkdownContent as Q,textblockTypeInputRule as tt,wrappingInputRule as et}from"@tiptap/core";import{jsx as nt}from"@tiptap/core/jsx-runtime";import{NodeSelection as rt,Plugin as ot,PluginKey as it,Selection as st,TextSelection as at}from"@tiptap/pm/state";import{Decoration as lt,DecorationSet as ct}from"@tiptap/pm/view";import{Fragment as dt}from"@tiptap/pm/model";import{dropCursor as ut}from"@tiptap/pm/dropcursor";import{gapCursor as pt}from"@tiptap/pm/gapcursor";import{history as ht,redo as ft,undo as gt}from"@tiptap/pm/history";import{createCanvasMediaPresenter as mt,defineCanvasHostModule as yt,waitForEditorIdle as wt}from"@yuzhouu/canvas-host/module";import xt from"polygon-clipping";import{DefaultClipboardHostModule as bt}from"@yuzhouu/canvas-host/clipboard";import{getCanvasHost as vt}from"@yuzhouu/canvas-host";import{applyCanvasActionShortcutOverrides as kt}from"@yuzhouu/canvas-kit";export*from"@yuzhouu/canvas-host/clipboard";var St="document:main";function It(t){return!!t&&"shape"===t.typeName}function Pt(t){return!!t&&"asset"===t.typeName}var Mt=class{},Tt=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)}},Ct=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 Tt(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 Et(t,e,n){return t.dist(function(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 Tt(t.x+r.x*s,t.y+r.y*s)}(e,n,t))}function At(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 Lt(t,e,n,r){return At(t,e,n,r)?0:Math.min(Et(t,n,r),Et(e,n,r),Et(n,t,e),Et(r,t,e))}var Rt=["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"],$t=Object.fromEntries(Rt.map(t=>[t,`--land-shape-${t}`])),Nt={"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 Bt(t){return{kind:"theme",slot:t}}function Ot(t){return{kind:"custom",value:t}}function zt(t){return function(t){return!!t&&"object"==typeof t&&"theme"===t.kind&&Rt.includes(t.slot)}(t)||function(t){return!!t&&"object"==typeof t&&"custom"===t.kind&&"string"==typeof t.value}(t)}function Ht(t){return $t[t]}function Dt(t,e){return zt(t)?t:e}function Ft(t){return"custom"===t.kind?t.value:`var(${Ht(t.slot)}, ${Nt[t.slot]})`}function Wt(t,e){if("custom"===t.kind)return t.value;const n=Ht(t.slot),r=Nt[t.slot];return e?.(n,r)??r}function jt(t){if("custom"!==t.kind)return!1;const e=t.value.trim().toLowerCase();return"transparent"===e||/^#[0-9a-f]{6}00$/.test(e)}function Ut(t,e){return t===e||!(!t||!e)&&(t.kind===e.kind&&("theme"===t.kind?t.slot===e.slot:t.value===e.value))}var Kt=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 Tt(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 Xt(t){return void 0!==t&&t<0?-1:1}function Yt(t,e){if(void 0===e)return t;const n=2*Math.PI;return t+Math.round((e-t)/n)*n}function _t(t,e){const n=2*Math.PI,r=((t-e+Math.PI)%n+n)%n-Math.PI;return Math.abs(r)}function qt(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*Xt(n.preferredScaleYSign);return a({rotation:Yt(Math.atan2(-t.c/e,t.d/e),n.preferredRotation),scaleX:0,scaleY:e})}const e=o*Xt(n.preferredScaleXSign);return a({rotation:Yt(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:Yt(u,n.preferredRotation),scaleX:p,scaleY:h},{rotation:Yt(u+Math.PI,n.preferredRotation),scaleX:-p,scaleY:-h}],g=Xt(n.preferredScaleXSign),m=Xt(n.preferredScaleYSign),y=t=>{let e=0;return void 0!==n.preferredScaleXSign&&Xt(t.scaleX)===g&&(e+=1),void 0!==n.preferredScaleYSign&&Xt(t.scaleY)===m&&(e+=1),{signMatches:e,rotationDistance:void 0===n.preferredRotation?0:_t(t.rotation,n.preferredRotation)}},w=y(f[0]),x=y(f[1]),b=x.signMatches>w.signMatches||x.signMatches===w.signMatches&&x.rotationDistance<w.rotationDistance?f[1]:f[0];return a({rotation:b.rotation,scaleX:b.scaleX,scaleY:b.scaleY})}new Tt(24,24);function Gt(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 Vt=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],Jt=["top_left","top_right","bottom_right","bottom_left"],Zt=["free","aspect_ratio_locked"],Qt=["free"],te=["aspect_ratio_locked"];function ee(t,e){return 0===e.rotation?t.clone():Tt.RotWith(t,e.rotationCenter,e.rotation)}function ne({axis:t,bounds:e,point:n}){return"horizontal"===t?new Tt(e.minX+e.maxX-n.x,n.y):new Tt(n.x,e.minY+e.maxY-n.y)}function re({width:t,height:e,preserveAspectRatio:n=!1}){const r=n&&t>0&&e>0?Math.max(1,1/t,1/e):1;return{width:Math.max(1,t*r),height:Math.max(1,e*r)}}function oe({localWidth:t,localHeight:e,scaleX:n,scaleY:r}){return{width:Math.abs(n)*t,height:Math.abs(r)*e}}function ie({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 se({requestedBounds:t,handleId:e,actualWidth:n,actualHeight:r,scaleX:o,scaleY:i,isResizingFromCenter:s}){return new Ct(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)}var ae=[{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 le(t,e){return t.shapes.getUtil(e).getTerminalBindingPorts(e,{editor:t}).flatMap(n=>{const r=de(t,e,n);return r?[r]:[]})}function ce(t,e,n){const r=t.shapes.getUtil(e).getTerminalBindingPorts(e,{editor:t}).find(t=>t.id===n);return r?de(t,e,r):null}function de(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?Tt.Zero():new Tt((t.d*e.x-t.b*e.y)/n,(-t.c*e.x+t.a*e.y)/n).normalize()}(i,new Tt(n.outwardNormal.x,n.outwardNormal.y));if(s.len2()<1e-12)return null;const a=new Tt(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 ue(t){return[new Tt(t.minX,t.minY),new Tt(t.maxX,t.minY),new Tt(t.maxX,t.maxY),new Tt(t.minX,t.maxY)]}function pe(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 he(t,e,n){const r=t[e];return"number"==typeof r&&Number.isFinite(r)?r:n}var fe=class{getPositionedBounds(t){const e=this.getLocalBounds(t);return new Ct(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?[ue(e)]:null}getChildExportClipLocalBounds(t){return this.getChildClipLocalBounds(t)}getChildExportClipLocalPolygons(t){const e=this.getChildExportClipLocalBounds(t);return e?[ue(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=ie({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=he(i,"w",r.width),a=he(i,"h",r.height),l=oe({localWidth:s,localHeight:a,scaleX:t.scaleX,scaleY:t.scaleY}),c=ee(se({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 Zt}getSelectionResizeHandleIds(t,e){return Vt}flipSelectionBounds(t,e){const n=this.getSelectionPagePoints(t);if(n){const r=n.map(t=>{const n=0===e.selectionRotation?t.clone():Tt.RotWith(t,e.selectionRotationCenter,-e.selectionRotation),r=ne({axis:e.axis,bounds:e.selectionBounds,point:n});return 0===e.selectionRotation?r:Tt.RotWith(r,e.selectionRotationCenter,e.selectionRotation)}),o=this.getSelectionPageMiddlePoint(t),i=o?(()=>{const t=0===e.selectionRotation?o.clone():Tt.RotWith(o,e.selectionRotationCenter,-e.selectionRotation),n=ne({axis:e.axis,bounds:e.selectionBounds,point:t});return 0===e.selectionRotation?n:Tt.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:Tt.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:ue(this.getLocalBounds(t))}}getPositionedOutlineVertices(t){const e=this.getPositionedBounds(t);return[new Tt(e.minX,e.minY),new Tt(e.maxX,e.minY),new Tt(e.maxX,e.maxY),new Tt(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 Kt.Translate(t.x+e.x,t.y+e.y).compose(Kt.Rotate(t.rotation)).compose(Kt.Scale(t.scaleX,t.scaleY)).compose(Kt.Translate(-e.x,-e.y))}getPositionedTransform(t){const e=this.getLocalBounds(t).center,n=new Tt(t.x+e.x,t.y+e.y);return Kt.Translate(n.x,n.y).compose(Kt.Rotate(t.rotation)).compose(Kt.Scale(t.scaleX,t.scaleY)).compose(Kt.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)?ae:[]}getTerminalBindingOutlines(t,e){return this.canReceiveTerminalBinding(t,e)?[{points:this.getPositionedOutlineVertices(t),closed:!0}]:[]}canCopyToClipboard(t,e){return!0}isValidAfterBindingLoad(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=ue(n);for(let o=0;o<r.length;o+=1){const n=r[o],i=r[(o+1)%r.length];if(n&&i&&null!==pe(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=pe(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}};function ge(t){const e=2*Math.PI,n=(t%e+e)%e;return Math.floor(2*(n+Math.PI/4)/Math.PI%4)}function me({bodyHeight:t,bodyWidth:e,editor:n,headingHeight:r,shape:o}){const i=n.shapes.computeLocalToPageTransform(o),s=Math.atan2(i.b,i.a),a=function({bodyHeight:t,bodyWidth:e,headingHeight:n,side:r}){switch(r){case 0:return new Ct(0,-n,e,n);case 1:return new Ct(-n,0,n,t);case 2:return new Ct(0,t,e,n);case 3:return new Ct(e,0,n,t)}}({bodyHeight:t,bodyWidth:e,headingHeight:r*(l=n.state.cameraZoom.get(),Math.min(1/Math.max(l,1e-4),3.5)),side:ge(s)});var l;return new Ct(a.x+o.x,a.y+o.y,a.w,a.h)}function ye({bodyHeight:t,bodyWidth:e,headingHeight:n,shape:r}){const o=3.5*n;return new Ct(r.x-o,r.y-o,e+2*o,t+2*o)}var we=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 xe(t){return Math.min(1,Math.max(0,(96-t)/96))}Math.PI,Math.PI,Math.PI;function be(t,e,n,r={}){let o=!0;return e.graph.effect(t,()=>{e.get(),o&&!1===r.fireImmediately?o=!1:(o=!1,n())})}function ve(t){return Number.isInteger(t)?`${t}`:`${Number(t.toFixed(2))}`}function ke(t,e,n){return Math.max(e,Math.min(n,t))}function Se(t){return t?640:480}function Ie(t,e){return t.x===e.x&&t.y===e.y&&t.pressure===e.pressure&&t.segment===e.segment}function Pe(t){return new Tt(t.x,t.y)}function Me(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 Te(t){const e=[];for(const n of t)e.push(...n.points.map(Me));return e}function Ce(t){return[{points:t.map(Me)}]}function Ee(t){if(void 0!==t&&Number.isFinite(t))return ke(t,0,1)}function Ae(t,e,n,r,o={}){const i=Me(e),s=t[t.length-1];if(!s)return t.push(i),{anchorPoint:Me(i),hasProvisionalPoint:!1};if(Ie(s,i))return o.force&&r.hasProvisionalPoint?{anchorPoint:Me(i),hasProvisionalPoint:!1}:r;if(Ie(r.anchorPoint,i))return r.hasProvisionalPoint&&t.pop(),{anchorPoint:Me(r.anchorPoint),hasProvisionalPoint:!1};const a=function(t,e){if(t<=e.softMaxPointCount)return e.minPointDistance;const n=ke((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:Me(i),hasProvisionalPoint:!1}:{anchorPoint:Me(r.anchorPoint),hasProvisionalPoint:!0}}function Le(t,e){const n=Math.max(2,Math.floor(e));if(t.length<=n)return t.map(Me);const r=function(t,e){let n=Re(t,!0);n.length<e&&(n=Re(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(Me)}function Re(t,e){const n=[];for(let r=1;r<t.length-1;r+=1){if(e&&$e(t,r))continue;const o=t[r],i=t[r-1],s=t[r+1];o&&i&&s&&n.push({index:r,score:Ne(o,i,s)})}return n.sort((t,e)=>t.score-e.score||t.index-e.index),n}function $e(t,e){return"straight"===t[e]?.segment||"straight"===t[e+1]?.segment}function Ne(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=ke(((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 Be(t){if(0===t.length)return null;if(1===t.length){const e=t[0];return`M ${ve(e.x)} ${ve(e.y)}`}if(2===t.length){const e=t[0],n=t[1];return[`M ${ve(e.x)} ${ve(e.y)}`,`L ${ve(n.x)} ${ve(n.y)}`].join(" ")}const e=[],n=t[0];e.push(`M ${ve(n.x)} ${ve(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 ${ve(n.x)} ${ve(n.y)}`);continue}const o=t[r+1];if(!o||"straight"===o.segment){if(Oe(t,r)){const o=t[r-1];e.push(`Q ${ve(o.x)} ${ve(o.y)} ${ve(n.x)} ${ve(n.y)}`)}else e.push(`L ${ve(n.x)} ${ve(n.y)}`);continue}const i=Tt.Med(Pe(n),Pe(o));e.push(`Q ${ve(n.x)} ${ve(n.y)} ${ve(i.x)} ${ve(i.y)}`)}return e.join(" ")}function Oe(t,e){return e>=2&&"straight"!==t[e-1]?.segment&&"straight"!==t[e-2]?.segment}function ze(t){if(t.length<3)return function(t){if(0===t.length)return null;const[e,...n]=t;return e?[`M ${ve(e.x)} ${ve(e.y)}`,...n.map(t=>`L ${ve(t.x)} ${ve(t.y)}`),"Z"].join(" "):null}(t);const e=t[0],n=t[t.length-1];if(!e||!n)return null;const r=Tt.Med(n,e),o=[`M ${ve(r.x)} ${ve(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=Tt.Med(e,n);o.push(`Q ${ve(e.x)} ${ve(e.y)} ${ve(r.x)} ${ve(r.y)}`)}return o.push("Z"),o.join(" ")}function He(t){return t.map(Me)}function De(t){return t.map(Fe)}function Fe(t){return function(t){return{points:t.points.map(Me)}}(t)}function We(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 je(t,e,n){return t.map(t=>({points:We(t.points,e,n)}))}function Ue(t,e){return t.map((t,n)=>({points:t.points.map((t,r)=>{const o=e(Pe(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 Ke(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 Xe(t,e,n){return t.map(t=>({points:Ke(t.points,e,n)}))}function Ye(t){return{rotation:t.selectionRotation,rotationCenter:t.selectionRotationCenter}}function _e(t,e){const n=Ye(e);return Ue(t,t=>function(t,e){return 0===e.rotation?t.clone():Tt.RotWith(t,e.rotationCenter,-e.rotation)}(t,n))}function qe(t,e){const n=Ye(e);return Ue(t,t=>ee(t,n))}function Ge(t,e){return Ue(t,t=>ne({axis:e.axis,bounds:e.selectionMirrorBounds,point:t}))}var{PI:Ve}=Math,Je=Ve+1e-4,Ze=[1,1];function Qe(t,e,n,r=t=>t){return t*r(.5-e*(.5-n))}var{min:tn}=Math;function en(t,e,n){let r=tn(1,e/n);return tn(1,t+(tn(1,1-r)-t)*(.275*r))}function nn(t,e){return[t[0]+e[0],t[1]+e[1]]}function rn(t,e,n){return t[0]=e[0]+n[0],t[1]=e[1]+n[1],t}function on(t,e){return[t[0]-e[0],t[1]-e[1]]}function sn(t,e,n){return t[0]=e[0]-n[0],t[1]=e[1]-n[1],t}function an(t,e){return[t[0]*e,t[1]*e]}function ln(t,e,n){return t[0]=e[0]*n,t[1]=e[1]*n,t}function cn(t){return[t[1],-t[0]]}function dn(t,e){let n=e[0];return t[0]=e[1],t[1]=-n,t}function un(t,e){return t[0]*e[0]+t[1]*e[1]}function pn(t,e){return t[0]===e[0]&&t[1]===e[1]}function hn(t,e){let n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function fn(t){return function(t,e){return[t[0]/e,t[1]/e]}(t,function(t){return Math.hypot(t[0],t[1])}(t))}function gn(t,e){return Math.hypot(t[1]-e[1],t[0]-e[0])}function mn(t,e,n){let r=Math.sin(n),o=Math.cos(n),i=t[0]-e[0],s=t[1]-e[1],a=i*r+s*o;return[i*o-s*r+e[0],a+e[1]]}function yn(t,e,n,r){let o=Math.sin(r),i=Math.cos(r),s=e[0]-n[0],a=e[1]-n[1],l=s*i-a*o,c=s*o+a*i;return t[0]=l+n[0],t[1]=c+n[1],t}function wn(t,e,n){return nn(t,an(on(e,t),n))}function xn(t,e,n,r){let o=n[0]-e[0],i=n[1]-e[1];return t[0]=e[0]+o*r,t[1]=e[1]+i*r,t}function bn(t,e,n){return nn(t,an(e,n))}var vn=[0,0],kn=[0,0],Sn=[0,0];function In(t,e){let n=bn(t,fn(cn(on(t,nn(t,[1,1])))),-e),r=[],o=1/13;for(let i=o;i<=1;i+=o)r.push(mn(n,t,2*Je*i));return r}function Pn(t,e,n){let r=[],o=1/n;for(let i=o;i<=1;i+=o)r.push(mn(e,t,Je*i));return r}function Mn(t,e,n){let r=on(e,n),o=an(r,.5),i=an(r,.51);return[on(t,o),on(t,i),nn(t,i),nn(t,o)]}function Tn(t,e,n,r){let o=[],i=bn(t,e,n),s=1/r;for(let a=s;a<1;a+=s)o.push(mn(i,t,3*Je*a));return o}function Cn(t,e,n){return[nn(t,an(e,n)),nn(t,an(e,.99*n)),on(t,an(e,.99*n)),on(t,an(e,n))]}function En(t,e,n){return!1===t||void 0===t?0:!0===t?Math.max(e,n):t}function An(t,e={}){let{size:n=16,smoothing:r=.5,thinning:o=.5,simulatePressure:i=!0,easing:s=t=>t,start:a={},end:l={},last:c=!1}=e,{cap:d=!0,easing:u=t=>t*(2-t)}=a,{cap:p=!0,easing:h=t=>--t*t*t+1}=l;if(0===t.length||n<=0)return[];let f,g=t[t.length-1].runningLength,m=En(a.taper,n,g),y=En(l.taper,n,g),w=(n*r)**2,x=[],b=[],v=function(t,e,n){return t.slice(0,10).reduce((t,r)=>{let o=r.pressure;return e&&(o=en(t,r.distance,n)),(t+o)/2},t[0].pressure)}(t,i,n),k=Qe(n,o,t[t.length-1].pressure,s),S=t[0].vector,I=t[0].point,P=I,M=I,T=P,C=!1;for(let $=0;$<t.length;$++){let{pressure:e}=t[$],{point:r,vector:a,distance:l,runningLength:c}=t[$],d=$===t.length-1;if(!d&&g-c<3)continue;o?(i&&(e=en(v,l,n)),k=Qe(n,o,e,s)):k=n/2,void 0===f&&(f=k);let p=c<m?u(c/m):1,E=g-c<y?h((g-c)/y):1;k=Math.max(.01,k*Math.min(p,E));let A=(d?t[$]:t[$+1]).vector,L=d?1:un(a,A),R=null!==L&&L<0;if(un(a,S)<0&&!C||R){dn(vn,S),ln(vn,vn,k);for(let t=0;t<=1;t+=.07692307692307693)sn(kn,r,vn),yn(kn,kn,r,Je*t),M=[kn[0],kn[1]],x.push(M),rn(Sn,r,vn),yn(Sn,Sn,r,Je*-t),T=[Sn[0],Sn[1]],b.push(T);I=M,P=T,R&&(C=!0)}else C=!1,d?(dn(vn,a),ln(vn,vn,k),x.push(on(r,vn)),b.push(nn(r,vn))):(xn(vn,A,a,L),dn(vn,vn),ln(vn,vn,k),sn(kn,r,vn),M=[kn[0],kn[1]],($<=1||hn(I,M)>w)&&(x.push(M),I=M),rn(Sn,r,vn),T=[Sn[0],Sn[1]],($<=1||hn(P,T)>w)&&(b.push(T),P=T),v=e,S=a)}let E=[t[0].point[0],t[0].point[1]],A=t.length>1?[t[t.length-1].point[0],t[t.length-1].point[1]]:nn(t[0].point,[1,1]),L=[],R=[];if(1===t.length){if(!m&&!y||c)return In(E,f||k)}else{m||y&&1===t.length||(d?L.push(...Pn(E,b[0],13)):L.push(...Mn(E,x[0],b[0])));let e=cn(function(t){return[-t[0],-t[1]]}(t[t.length-1].vector));y||m&&1===t.length?R.push(A):p?R.push(...Tn(A,e,k,29)):R.push(...Cn(A,e,k))}return x.concat(R,b.reverse(),L)}var Ln=[0,0];function Rn(t){return null!=t&&t>=0}function $n(t,e={}){return An(function(t,e={}){let{streamline:n=.5,size:r=16,last:o=!1}=e;if(0===t.length)return[];let i=.15+.85*(1-n),s=Array.isArray(t[0])?t:t.map(({x:t,y:e,pressure:n=.5})=>[t,e,n]);if(2===s.length){let t=s[1];s=s.slice(0,-1);for(let e=1;e<5;e++)s.push(wn(s[0],t,e/4))}1===s.length&&(s=[...s,[...nn(s[0],Ze),...s[0].slice(2)]]);let a=[{point:[s[0][0],s[0][1]],pressure:Rn(s[0][2])?s[0][2]:.25,vector:[...Ze],distance:0,runningLength:0}],l=!1,c=0,d=a[0],u=s.length-1;for(let p=1;p<s.length;p++){let t=o&&p===u?[s[p][0],s[p][1]]:wn(d.point,s[p],i);if(pn(d.point,t))continue;let e=gn(t,d.point);if(c+=e,p<u&&!l){if(c<r)continue;l=!0}sn(Ln,d.point,t),d={point:t,pressure:Rn(s[p][2])?s[p][2]:.5,vector:fn(Ln),distance:e,runningLength:c},a.push(d)}return a[0].vector=a[1]?.vector||[0,0],a}(t,e),e)}var Nn=new WeakMap;function Bn(t){return{...t}}function On(t,e,n){return t.map(t=>new Tt(t.x+e,t.y+n))}function zn(t,e,n){return t.map(t=>On(t,e,n))}function Hn({segments:t,outlineVertices:e,outlinePolygons:n,strokeWidth:r,sampling:o,isClosed:i}){const s=Te(t),a=s.map(Pe),l=a.length>0?Ct.FromPoints(a):new Ct(0,0,1,1),c=i||0===e.length?l.expand(Math.max(r/2,1)):Ct.FromPoints([...e]),d=i&&s.length>=3?function(t){if(t.length<3)return null;const e=Be(t);return e?`${e} Z`:null}(s):null,u=void 0!==n?function(t){const e=t.map(t=>ze(t)).filter(t=>null!==t);return e.length>0?e.join(" "):null}(n):ze(e);return{normalizedSegments:De(t),normalizedPoints:He(s),pointBounds:l,path:u,selectionPath:d??Be(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:Bn(o)}}function Dn(t,e,n,r){const o=function({strokeWidth:t,isPen:e}){return[t,e?"pen":"pointer"].join(":")}({strokeWidth:n,isPen:r}),i=Nn.get(t),s=i?.get(o);if(s)return{normalizedSegment:Fe(s.normalizedSegment),sampling:Bn(s.sampling)};const a=function(t,e){if(t.length<=1)return{points:t.map(Me),rawPointCount:t.length,sampledPointCount:t.length,maxPointCount:e.maxPointCount,reduced:!1,capped:!1};const n=[Me(t[0])];for(let i=1;i<t.length;i+=1){const e=t[i];if(!e)continue;const r=Ee(e.pressure),o={x:e.x,y:e.y,...void 0===r?null:{pressure:r},...void 0===e.segment?null:{segment:e.segment}},s=n[n.length-1];s&&Ie(s,o)||n.push(o)}const r=n.length>e.maxPointCount,o=Le(n,e.maxPointCount);return{points:o,rawPointCount:t.length,sampledPointCount:o.length,maxPointCount:e.maxPointCount,reduced:o.length<t.length,capped:r}}(t.points,e),l={normalizedSegment:{points:He(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:Fe(l.normalizedSegment),sampling:Bn(l.sampling)}),i||Nn.set(t,c),l}function Fn(t,e,n=!1,r=!1,{brush:o="pencil"}={}){const i=function(t){return{maxPointCount:Se(t)}}(n),s=[],a=[],l=t.filter(t=>t.points.length>0);for(let h=0;h<l.length;h+=1){const t=Dn(l[h],i,e,n);s.push(Fe(t.normalizedSegment)),a.push(Bn(t.sampling))}const c=function({points:t,strokeWidth:e,isPen:n,isClosed:r,constantWidth:o}){const i=r&&t.length>2?[...t,t[0]]:t,s=i.filter((t,e)=>{const n=i[e-1];return!n||t.x!==n.x||t.y!==n.y||t.pressure!==n.pressure||t.segment!==n.segment}),a=[],l=(t,{straight:i=!1}={})=>{const s=$n(t.map(({x:t,y:e,pressure:n})=>[t,e,n??.5]),{size:e,thinning:n&&!o?.4:0,simulatePressure:!1,streamline:i||r?0:.5,last:!0}).map(([t,e])=>new Tt(t,e));s.length>0&&a.push(s)};let c=[];for(const d of s){const t=c[c.length-1];"straight"===d.segment&&t?(c.length>1&&l(c),l([t,d],{straight:!0}),c=[d]):c.push(d)}return(c.length>1||0===a.length)&&l(c),a}({points:Te(s),strokeWidth:e,isPen:n,isClosed:r,constantWidth:"highlighter"===o||r}),d=(u=a,p=i.maxPointCount,{rawPointCount:u.reduce((t,e)=>t+e.rawPointCount,0),sampledPointCount:u.reduce((t,e)=>t+e.sampledPointCount,0),sampledPointLimit:p,reduced:u.some(t=>t.reduced),capped:u.some(t=>t.capped)});var u,p;return Hn({segments:s,outlineVertices:c.flat(),outlinePolygons:c,strokeWidth:e,sampling:d,isClosed:r})}var Wn=new WeakMap,jn=new WeakMap;function Un(t){return t.segments}function Kn(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 Ct(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 Xn(t){const e=t,n=Wn.get(e);if(n)return n;const r=Fn(Un(t.props),t.props.strokeWidth,t.props.isPen??!1,t.props.isClosed,{brush:t.props.brush});return Wn.set(e,r),r}function Yn(t,e,n=!1,r=!1,o={}){const i=Fn(t,e,n,r,o),s=i.pointBounds,a=Fn(Ue(i.normalizedSegments,t=>new Tt(t.x-s.x,t.y-s.y)),e,n,r,o);return{x:s.x,y:s.y,segments:a.normalizedSegments,pointBounds:a.pointBounds,localBounds:a.localBounds,renderBounds:a.renderBounds,path:a.path,selectionPath:a.selectionPath,fillPath:a.fillPath,outlineVertices:a.outlineVertices,outlinePolygons:a.outlinePolygons,sampling:a.sampling}}function _n(t,e,n=!1,r=!1,o={}){return function(t,e,n=!1,r=!1,o={}){return Yn(Ce(t),e,n,r,o)}(t,e,n,r,o)}function qn(t,e,n=!1,r=!1,o={}){return Yn(t,e,n,r,o)}function Gn(t){const e=t,n=jn.get(e);if(n)return n;const r=function(t,e,n,r,o){return Hn({segments:je(t.normalizedSegments,n,r),outlineVertices:On(t.outlineVertices,n,r),outlinePolygons:zn(t.outlinePolygons,n,r),strokeWidth:e,sampling:t.sampling,isClosed:o})}(Xn(t),t.props.strokeWidth,t.x,t.y,t.props.isClosed);return jn.set(e,r),r}function Vn(t){return Te(Jn(t))}function Jn(t){const e=function(t,e){return new Tt(t.x+e.localBounds.center.x,t.y+e.localBounds.center.y)}(t,Xn(t));return Ue(function(t){return je(Un(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 Tt(r.x*t.scaleX,r.y*t.scaleY);return n.add(o.rot(t.rotation))}(t,n,e))}function Zn(t,e){let n=function({segments:t,strokeWidth:e,isPen:n,isClosed:r,brush:o,targetSelectionStrokeBounds:i}){let s=De(t);for(let a=0;a<2;a+=1){const t=Fn(s,e,n,r,{brush:o}),a=Kn(t.pointBounds,t.localBounds,i);s=Xe(s,t.pointBounds,a)}return s}({segments:_e(Jn(t),e),strokeWidth:t.props.strokeWidth,isPen:t.props.isPen??!1,isClosed:t.props.isClosed,brush:t.props.brush,targetSelectionStrokeBounds:e.targetSelectionStrokeBounds});return e.scaleX<0&&(n=Ge(n,{axis:"horizontal",selectionMirrorBounds:e.targetSelectionStrokeBounds,selectionRotation:e.selectionRotation,selectionRotationCenter:e.selectionRotationCenter})),e.scaleY<0&&(n=Ge(n,{axis:"vertical",selectionMirrorBounds:e.targetSelectionStrokeBounds,selectionRotation:e.selectionRotation,selectionRotationCenter:e.selectionRotationCenter})),qn(qe(n,e),t.props.strokeWidth,t.props.isPen??!1,t.props.isClosed,{brush:t.props.brush})}function Qn(t,e){return qn(qe(Ge(_e(Jn(t),e),e),e),t.props.strokeWidth,t.props.isPen??!1,t.props.isClosed,{brush:t.props.brush})}function tr(t){return De(t)}function er(t){const e=Xn(t);return{...e.sampling,hasPath:null!==e.path,hasSelectionPath:null!==e.selectionPath,outlineVertexCount:e.outlineVertices.length}}var nr=class extends we{constructor(t){super(t,"draw"),this.initial="idle",this.addChild(new rr(t,this)),this.addChild(new or(t,this))}getDefaultProps(){return this.editor.shapes.getDefaultProps("draw")}},rr=class extends we{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=St;let r=null,o=1/0,i=-1;const s=t.state.shapeIds.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():Kt.Identity(),i=o.applyToPoint(t.pagePoint),s=ir(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,brush:e.brush,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,Math.min(.35,.04*a)),pressureDeltaThreshold:.035,softMaxPointCount:1600,hardMaxPointCount:3200,maxDistanceMultiplier:2.5}:{minPointDistance:Math.max(.2,Math.min(.5,.06*a)),pressureDeltaThreshold:.08,softMaxPointCount:900,hardMaxPointCount:2200,maxDistanceMultiplier:6}),pointGuardState:{anchorPoint:sr(s),hasProvisionalPoint:!1},lastPressure:t.pressure,straightSegmentAnchorPoint:null,preserveStraightEndpointOnNextFreePoint:!1,segments:[{points:[s]}]})}},or=class extends we{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:")||Gt(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;e||(this.info.lastPressure=t.pressure);const n=ir(this.info.pageToParent.applyToPoint(t.pagePoint),this.info.originParentPoint,this.info.lastPressure,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:cr(this.info.segments)}],{source:"user"})}createShape(){const t=this.tool.getDefaultProps(),e=function(t,e){return e&&t.layers.canReceiveChildren(e)?e:St}(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,brush:this.info?.brush??t.brush,stroke:this.info?.stroke??t.stroke,strokeWidth:this.info?.strokeWidth??t.strokeWidth,fill:this.info?.fill??t.fill,isClosed:this.info?.isClosed??t.isClosed,...cr(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=ar(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=sr(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=ar(this.info),n=e[e.length-1];return(!n||!function(t,e){return t.x===e.x&&t.y===e.y&&t.pressure===e.pressure&&t.segment===e.segment}(n,t))&&(this.replaceCurrentSegmentPoints([...e,sr(t)]),this.resetPointGuard(t),!0)}appendGuardedCurrentPoint(t,e={}){if(!this.info)return;const n=ar(this.info).map(sr);this.info.pointGuardState=Ae(n,t,this.info.pointGuard,this.info.pointGuardState,e),this.replaceCurrentSegmentPoints(n)}resetPointGuard(t){this.info&&(this.info.pointGuardState={anchorPoint:sr(t),hasProvisionalPoint:!1})}replaceCurrentSegmentPoints(t){if(!this.info)return;const e=lr(this.info.segments);this.info.segments=[...e.slice(0,-1),{points:t.map(sr)}]}splitCurrentSegmentAtLimit(){if(!this.info)return;const t=Se(this.info.isPen);let e=lr(this.info.segments),n=e[e.length-1];for(;n.points.length>t;){const r=n.points.slice(0,t).map(sr),o=r[r.length-1],i=n.points.slice(t).map(sr);if(!o||0===i.length)break;const s={points:[sr(o),...i]};e=[...e.slice(0,-1),{points:r},s],n=s}this.info.segments=e}};function ir(t,e,n,r){return{x:t.x-e.x,y:t.y-e.y,...r?{pressure:n}:null}}function sr(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 ar(t){const e=lr(t.segments),n=e[e.length-1];return n?n.points.map(sr):[]}function lr(t){return t.length>0?[...t]:[{points:[]}]}function cr(t){return{segments:tr(lr(t))}}function dr(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 Tt(e.x+r.x*i,e.y+r.y*i);return t.dist(s)}function ur(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(dr(t,n,r),dr(e,n,r),dr(n,t,e),dr(r,t,e))}function pr(t,e){let n=0;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;const a=(i.x-s.x)*(t.y-s.y)-(t.x-s.x)*(i.y-s.y);s.y<=t.y?i.y>t.y&&a>0&&(n+=1):i.y<=t.y&&a<0&&(n-=1)}return 0!==n}function hr(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,dr(t,o,i)))}return n}function fr(t,e,n,r){if(0===n.length)return!1;if(pr(t,n)||pr(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&&ur(t,e,i,s)<=r)return!0}return!1}function gr(t,e,n,r={}){if(r.isClosed&&void 0!==r.fill&&!jt(r.fill)&&t.normalizedPoints.length>=3&&pr(n,t.normalizedPoints.map(Pe)))return!0;if(r.isClosed&&function(t,e,n){if(0===e.length)return Number.POSITIVE_INFINITY;if(1===e.length)return t.dist(Pe(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,dr(t,Pe(n),Pe(i))))}return n&&e.length>=3&&(r=Math.min(r,dr(t,Pe(e[e.length-1]),Pe(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(pr(n,o))return!0;if(hr(n,o)<=Math.max(4,.5*e))return!0}return!1}function mr(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function yr(t){if(!t||"object"!=typeof t)return null;const e=t,n=mr(e.x,NaN),r=mr(e.y,NaN);if(!Number.isFinite(n)||!Number.isFinite(r))return null;const o=mr(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 wr(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=yr(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 xr(t,e){if(!Array.isArray(t))return e;let n=!1;const r=[];for(const o of t){const t=wr(o);t?(n=n||t!==o,r.push(t)):n=!0}return 0===r.length?e:n?r:t}var br=class extends fe{type="draw";getDefaultProps(){return{brush:"pencil",segments:Ce([{x:0,y:0},{x:24,y:12}]),stroke:Bt("stroke-slate"),strokeWidth:4,fill:Ot("transparent"),isClosed:!1,isPen:!1}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{segments:xr(e.segments,n.segments),brush:"highlighter"===e.brush?"highlighter":"pencil",stroke:Dt(e.stroke,n.stroke),strokeWidth:Math.max(4,mr(e.strokeWidth,n.strokeWidth)),fill:Dt(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=Xn(t);return new Ct(t.x+e.localBounds.x,t.y+e.localBounds.y,e.localBounds.w,e.localBounds.h)}getLocalBounds(t){return Xn(t).localBounds}getRenderBounds(t){return Xn(t).renderBounds}getExportBounds(t){return this.getRenderBounds(t)}canReceiveTerminalBinding(t){return!0}canUseTerminalBindingPortHandles(t){return!1}getSelectionResizeLocalBounds(t){return this.getLocalBounds(t)}resizeSelectionBounds(t,e){const n=Zn(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:tr(n.segments)}}}flipSelectionBounds(t,e){const n=Qn(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:tr(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 Tt(t.minX,t.minY),n=new Tt(t.maxX,t.minY),r=new Tt(t.maxX,t.maxY),o=new Tt(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&&At(t,e,o,i))return!0}return!1})}getPositionedOutlineVertices(t){return Gn(t).outlineVertices}hitTest(t,e){return gr(Gn(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&&!jt(o.fill)&&t.normalizedPoints.length>=3&&fr(n,r,t.normalizedPoints.map(Pe),i))||0!==t.outlineVertices.length&&t.outlinePolygons.some(t=>fr(n,r,t,i))}(Gn(t),t.props.strokeWidth,e.positionedStart,e.positionedEnd,{fill:t.props.fill,isClosed:t.props.isClosed,margin:e.positionedMargin})}},vr=class{type="draw";toSvg(t,e){const n=Xn(t);if(!n.path&&!n.selectionPath)return null;const r=[];return n.fillPath&&!jt(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",attrs:"highlighter"===t.props.brush?{opacity:.35}:void 0,children:r}}};function kr(){return{shapeUtils:[new br],shapeSvgExporters:[new vr],tools:{draw:t=>new nr(t)}}}function Sr({shape:t,stroke:e=t.props.stroke,strokeWidth:n=t.props.strokeWidth}){const{fillPath:r,renderBounds:o,path:i,selectionPath:s}=Xn({props:{...t.props,strokeWidth:n}});if(!i&&!s)return null;const a=Ft(e);
|
|
3
|
-
return
|
|
4
|
-
return
|
|
5
|
-
return d(Ir,{shape:t,strokeWidth:e})}function Cr(t){return It(t)&&"draw"===t.type}function Er({editor:t}){return function({editor:t}){const e=()=>t.shapes.getDefaultProps("draw"),{brush:n,stroke:r,strokeWidth:i,fill:s,isClosed:a}=e(),l={pencil:{brush:n,stroke:r,strokeWidth:i,fill:s,isClosed:a},highlighter:{brush:"highlighter",stroke:Ot("#f8de0d"),strokeWidth:24,fill:Ot("transparent"),isClosed:!1}};return{getSelectionStyle(){const e=t.state.selectedShapes.get().filter(Cr);return 0===e.length?null:{brush:Ar(e.map(t=>t.props.brush)),fill:Ar(e.map(t=>t.props.fill)),stroke:Ar(e.map(t=>t.props.stroke)),strokeWidth:Ar(e.map(t=>t.props.strokeWidth)),isClosed:Ar(e.map(t=>t.props.isClosed))}},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(Cr).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)},toolDefaultsState:o(t.signals.computed("Draw.toolDefaults",e)),getBrushDefaults(t){const n=e();return n.brush===t?n:l[t]},setToolDefaults(n){const r=e();if(n.brush&&n.brush!==r.brush){const{brush:e,stroke:o,strokeWidth:i,fill:s,isClosed:a}=r;l[e]={brush:e,stroke:o,strokeWidth:i,fill:s,isClosed:a},t.shapes.updateDefaultProps("draw",{...l[n.brush],...n})}else t.shapes.updateDefaultProps("draw",n);return e()}}}({editor:t})}function Ar(t){const[e,...n]=t;return void 0!==e&&n.every(t=>t===e)?e:void 0}var Lr=s({id:"draw",editor:kr(),render:Pr(),setup:({editor:t})=>({api:Er({editor:t})})});function Rr(t,e,n){return Math.max(e,Math.min(n,t))}function $r(t,e,n){return t+(e-t)*n}function Nr(t,e,n){if(void 0!==t||void 0!==e)return $r(t??e??0,e??t??0,n)}function Br(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:Me(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:Pe(e).dist(Pe(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:Pe(e).dist(Pe(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:Me(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:Rr(s/a.length,0,1),c=Pe(a.start),d=Pe(a.end),u=Tt.Lrp(c,d,l),p=Nr(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 Or(t,e,n,r={}){if(t.parentId!==e.parentId)throw new Error("Cannot interpolate draw shapes with different parents");const o=Rr(n,0,1),i=t.props.isClosed&&e.props.isClosed,s=Vn(t),a=Vn(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=Br(s,l,i),h=Br(a,l,i),f=p.map((t,e)=>{const n=h[e]??h[h.length-1]??t,r=Tt.Lrp(Pe(t.point),Pe(n.point),o),i=Nr(t.point.pressure,n.point.pressure,o),s=$r(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,$r(t.props.strokeWidth,e.props.strokeWidth,o)),w=_n(f,y,m,g,{brush:(o<.5?t:e).props.brush}),x=o<.5?t:e;return{...x,id:t.id,x:w.x,y:w.y,rotation:0,scaleX:1,scaleY:1,opacity:$r(t.opacity,e.opacity,o),props:{...x.props,segments:De(w.segments),strokeWidth:y,isClosed:g,isPen:m}}}var zr=new WeakMap;function Hr(t,e){if(t.length!==e.length)return!1;const n=new Set(e);return t.every(t=>n.has(t))}function Dr(t){const e=zr.get(t);if(!e)throw new Error("EraserRuntime is not initialized for this editor.");return e}function Fr(t){return 4/t.state.camera.get().z}function Wr(t,e,n,r){const o=[new Tt(e.minX,e.minY),new Tt(e.maxX,e.minY),new Tt(e.maxX,e.maxY),new Tt(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 jr(t,e){const n=new Set,r=Fr(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&&(Wr(e,s,t.shapes.computeLocalToPageTransform(o),r)&&n.add(o.id))}return n}function Ur(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 Kr(t,e,n,r){const o=r.topMostOnly?n.slice(0,1):n;for(const i of o){const n=Ur(t,i,e);n&&e.erasingShapeIds.add(n)}}function Xr(t,e,n){Kr(t,e,t.shapes.hitTestPoint(n.pagePoint),{topMostOnly:n.accelKey})}function Yr(t,e,n){Kr(t,e,t.shapes.hitTestLineSegment(e.previousPagePoint,n.pagePoint,{margin:Fr(t)}),{topMostOnly:n.accelKey})}function _r(t,e){const n=t.trail[t.trail.length-1];n&&n.dist2(e)<=1e-6||t.trail.push(e.clone())}function qr(t,e){Dr(t).setPreview(Array.from(e.erasingShapeIds),e.trail)}function Gr(t){Dr(t).clear()}var Vr=class extends we{constructor(t){super(t,"eraser"),this.initial="idle",this.addChild(new Jr(t,this)),this.addChild(new Zr(t,this)),this.addChild(new Qr(t,this))}onExit(){Gr(this.editor)}},Jr=class extends we{constructor(t,e){super(t,"idle",e)}onEnter(){Gr(this.editor)}onPointerDown(t){0===t.button&&this.transition("pointing",function(t,e){const n={originScreenPoint:e.screenPoint.clone(),previousPagePoint:e.pagePoint.clone(),protectedContainerIds:jr(t,e.pagePoint),erasingShapeIds:new Set,trail:[e.pagePoint.clone()]};return Xr(t,n,e),qr(t,n),n}(this.editor,t))}},Zr=class extends we{info=null;constructor(t,e){super(t,"pointing",e)}onEnter(t){this.info=t}onPointerMove(t){var e,n;this.info&&(e=this.info.originScreenPoint,n=t.screenPoint,e.dist2(n)>=9&&(Yr(this.editor,this.info,t),_r(this.info,t.pagePoint),this.info.previousPagePoint=t.pagePoint.clone(),qr(this.editor,this.info),this.transition("erasing",this.info)))}onPointerUp(t){this.info&&(Xr(this.editor,this.info,t),qr(this.editor,this.info),to(this.editor,this.info)),this.transition("idle")}onCancel(){Gr(this.editor),this.transition("idle")}onExit(){this.info=null}},Qr=class extends we{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&&to(this.editor,this.info),this.transition("idle")}onCancel(){Gr(this.editor),this.transition("idle")}onExit(){this.info=null}update(t){this.info&&(Yr(this.editor,this.info,t),_r(this.info,t.pagePoint),this.info.previousPagePoint=t.pagePoint.clone(),qr(this.editor,this.info))}};function to(t,e){const n=Array.from(e.erasingShapeIds);Gr(t),0!==n.length&&t.commands.deleteShapes(n,{source:"user"})}function eo(){return{canvasOverlays:[{id:"land.eraser.trail-overlay",component:no}],shapeOpacityModifiers:[{id:"land.eraser.preview-opacity",getOpacityValue(t,e){const n=Dr(t).erasingShapeIdSetSignal;return{graph:t.signals,get:()=>t.layers.isOrAncestorInSet(e,n.get())?.32:1}}}]}}var no=g(function(){return l(Dr(a()).trailActiveSignal)?d(ro,{}):null}),ro=g(function(){const t=a(),e=l(Dr(t).trailSignal),n=l(t.state.cameraZoom),r=Math.max(n,1e-4),o=function(){const[t,e]=S(()=>yo());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}(),i=k({samples:[],sourceLength:0}),s=Math.max(o,yo());!function(t,e,n,r){xo(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-po*i;for(let a=o;a<e.length;a++){const l=e[a],c=(a-o+1)/i;wo(t,{x:l.x,y:l.y},n,Lo(s,r,c))}t.sourceLength=e.length,xo(t,r)}(i.current,e,r,s);const c=function(t,e){const n=bo(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(Ao(r[r.length-1],t[o],n));return r}(n.length>io?n.slice(-48):n,lo)}(i.current.samples,s);if(0===c.length)return null;const u=(h=ao/r,0===(p=c).length||h<=0?null:1===p.length?No(So(p[0],h/2,uo))??"":No(function(t){if(0===t.length)return[];if(1===t.length)return So(t[0].point,Math.max(t[0].radius,.01),uo);const e=[],n=[];for(const a of t){const t=Mo(a.direction);$o(e,Co(a.point,Eo(t,a.radius))),$o(n,To(a.point,Eo(t,a.radius)))}const r=[];for(const a of e)$o(r,a);const o=t[t.length-1],i=Mo(o.direction),s=function({center:t,direction:e,normal:n,radius:r}){if(r<=0)return[];const o=[];for(let i=1;i<co;i++){const s=i/co;o.push(To(t,To(Eo(e,Math.sin(Math.PI*s)*r),Eo(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)$o(r,a);for(let a=n.length-1;a>=0;a--)$o(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]+Io(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=Ro(s/o,0,1);return{point:r,direction:ko(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:oo})}):null}),oo="rgba(142, 142, 142, 0.16)",io=48,so=1,ao=12,lo=.32,co=8,uo=13,po=16,ho=8,fo=180,go=180,mo=680;function yo(){return"undefined"==typeof performance?Date.now():performance.now()}function wo(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=so/n,s=Io(o,e);if(s<i)return void(t.samples[t.samples.length-1]={...o,...e,time:r});const a=s*n/Math.max(ho,r-o.time);t.samples.push({...e,time:r,velocity:Lo(o.velocity,a,.68)})}function xo(t,e){t.samples=bo(t.samples,e)}function bo(t,e){const n=t[t.length-1];if(!n)return[];const r=e-Ro(fo+n.velocity*go,fo,mo);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?[vo(s,a,Ro((r-s.time)/(a.time-s.time),0,1)),...i]:i}function vo(t,e,n){return{...Ao(t,e,n),time:Lo(t.time,e.time,n),velocity:Lo(t.velocity,e.velocity,n)}}function ko(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?Co(r,t[e]):e===t.length-1?Co(t[e],n):Co(r,n))}function So(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 Io(t,e){return Math.sqrt(Po(t,e))}function Po(t,e){const n=t.x-e.x,r=t.y-e.y;return n*n+r*r}function Mo(t){return{x:-t.y,y:t.x}}function To(t,e){return{x:t.x+e.x,y:t.y+e.y}}function Co(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Eo(t,e){return{x:t.x*e,y:t.y*e}}function Ao(t,e,n){return{x:Lo(t.x,e.x,n),y:Lo(t.y,e.y,n)}}function Lo(t,e,n){return t+(e-t)*n}function Ro(t,e,n){return Math.max(e,Math.min(n,t))}function $o(t,e){const n=t[t.length-1];!n||Po(n,e)>.04?t.push(e):t[t.length-1]=e}function No(t){if(t.length<2)return null;if(2===t.length)return`M ${Oo(t[0])} L ${Oo(t[1])} Z`;const e=[`M ${Oo(Bo(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 ${Oo(r)} ${Oo(Bo(r,o))}`)}return e.push("Z"),e.join(" ")}function Bo(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}function Oo(t){return`${zo(t.x)},${zo(t.y)}`}function zo(t){return Number.isInteger(t)?`${t}`:t.toFixed(3)}function Ho(){return{tools:{eraser:t=>new Vr(t)}}}var Do=s({id:"eraser",editor:Ho(),render:eo(),setup({editor:t}){!function(t){const{atom:e,computed:n}=t.signals,r=e("eraser.shapeIds",[],{isEqual:Hr}),o=n("eraser.shapeIdSet",()=>new Set(r.get())),i=e("eraser.trail",[]),s={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([])}};zr.set(t,s)}(t)}});function Fo(t){return/^\s*$/.test(t)?"Frame":t}function Wo(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function jo(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 Uo=class extends fe{type="frame";getDefaultProps(){return{w:640,h:360,name:"",fill:Ot("transparent"),stroke:Bt("stroke-muted"),strokeWidth:1}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Math.max(1,Wo(e.w,n.w)),h:Math.max(1,Wo(e.h,n.h)),name:"string"==typeof e.name?e.name:n.name,fill:Dt(e.fill,n.fill),stroke:Dt(e.stroke,n.stroke),strokeWidth:Math.max(0,Wo(e.strokeWidth,n.strokeWidth))}}getLocalBounds(t){return new Ct(0,0,t.props.w,t.props.h)}getExportBounds(t){return function(t){return new Ct(0,-34,t.props.w,t.props.h+34)}(t)}getPointHitTestBounds(t,e){const n=this.getPositionedBounds(t).expand(3),r=ye({bodyHeight:t.props.h,bodyWidth:t.props.w,headingHeight:34,shape:t});return Ct.FromPoints([new Tt(n.minX,n.minY),new Tt(n.maxX,n.maxY),new Tt(r.minX,r.minY),new Tt(r.maxX,r.maxY)])}canEdit(t){return!0}canReceiveChildren(t){return!0}canSnapChildrenToSelf(t){return!0}canReceiveTerminalBinding(t){return!0}getSelectionResizeHandleIds(t,e){return Jt}shouldRotateDescendants(t){return!0}getChildClipLocalBounds(t){return this.getLocalBounds(t)}canSelectByBrush(t,e){return super.isWrappedByBrush(t,e)}hitTest(t,e,n){return function(t,e){return e?me({bodyHeight:t.props.h,bodyWidth:t.props.w,editor:e.editor,headingHeight:34,shape:t}):new Ct(t.x,t.y-34,t.props.w,34)}(t,n).containsPoint(e)||jo(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(jo(t,e,r)||jo(t,n,r))return!0;const i=[new Tt(t.minX,t.minY),new Tt(t.maxX,t.minY),new Tt(t.maxX,t.maxY),new Tt(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&&Lt(e,n,t,r)<=o)return!0}return!1}(this.getPositionedBounds(t),e.positionedStart,e.positionedEnd,Math.max(6,e.positionedMargin))}},Ko=new WeakMap;function Xo(t){const e=t.shapes.getDefaultProps("frame"),n=t.signals.atom("frame.creation-config",{w:e.w,h:e.h,aspectRatio:null}),r=t.signals.atom("frame.creation-hover",null),o={preview:t.signals.computed("frame.creation-preview",()=>{const e=n.get(),o=r.get(),i=t.inputs.state.get();return null===e.aspectRatio||!o||t.state.readonly.get()||t.inputs.isSpacePressed.get()||i.isPointing||i.currentTimestamp!==o.timestamp||!i.currentPagePoint?.equals(o.pagePoint)||"frame"!==t.state.tool.get().activeToolId?null:{bounds:_o(o.pagePoint,e),props:{...t.shapes.getDefaultProps("frame"),w:e.w,h:e.h}}}),getConfig:()=>({...n.get()}),setConfig:t=>(n.set(function(t){if(!Number.isFinite(t.w)||t.w<=0)throw new RangeError("Frame creation width must be a positive number.");if(!Number.isFinite(t.h)||t.h<=0)throw new RangeError("Frame creation height must be a positive number.");if(null!==t.aspectRatio&&(!Number.isFinite(t.aspectRatio)||t.aspectRatio<=0))throw new RangeError("Frame creation aspect ratio must be null or a positive number.");return{...t}}(t)),{...n.get()}),setHover(t){r.set({pagePoint:t.pagePoint.clone(),timestamp:t.timestamp})},clearHover(){r.set(null)}};return Ko.set(t,o),o}function Yo(t){const e=Ko.get(t);if(!e)throw new Error("FrameCreationRuntime is not initialized for this editor.");return e}function _o(t,e){return new Ct(t.x,t.y,e.w,e.h)}var qo=class extends we{constructor(t){super(t,"frame"),this.initial="idle",this.addChild(new Go(t,this)),this.addChild(new Vo(t,this))}getDefaultProps(){return this.editor.shapes.getDefaultProps("frame")}getCreationConfig(){return Yo(this.editor).getConfig()}},Go=class extends we{tool;constructor(t,e){super(t,"idle",e),this.tool=e}onEnter(){this.editor.interaction.clearSelection()}onExit(){Yo(this.editor).clearHover()}onPointerMove(t){const e=Yo(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,isDragCreating:!1,creationConfig:this.tool.getCreationConfig()})}},Vo=class extends we{tool;info=null;operation=null;constructor(t,e){super(t,"creating",e),this.tool=e}onEnter(t){if(this.info=t,this.operation=this.editor.operations.begin({kind:"frame.create",label:"shape.create",source:"user",history:"record"}),null!==this.info.creationConfig.aspectRatio)try{const t=this.createShape(_o(this.info.originPagePoint,this.info.creationConfig));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,!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;const o=this.info.originScreenPoint.dist(e);if(!this.info.isDragCreating){if(o<4){if(!this.info.shapeId&&r){const e=this.createShape(_o(t,this.info.creationConfig));this.info.shapeId=e.id}return}this.info.isDragCreating=!0}const i=function(t,e,n,r){let o=e.x-t.x,i=e.y-t.y;const s=r.aspectRatio??(n?r.w/r.h:null);if(null!==s){const t=Math.abs(o),e=Math.abs(i);0===e||t/Math.max(e,1)>=s?i=t/s*(i<0?-1:1):o=e*s*(o<0?-1:1)}const a=new Tt(t.x+o,t.y+i);return new Ct(Math.min(t.x,a.x),Math.min(t.y,a.y),Math.max(Math.abs(a.x-t.x),1),Math.max(Math.abs(a.y-t.y),1))}(this.info.originPagePoint,t,n,this.info.creationConfig);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 Jo=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:[Fo(a)]}]}}};function Zo(){return{shapeUtils:[new Uo],shapeSvgExporters:[new Jo],tools:{frame:t=>new qo(t)}}}var Qo="frame.edit";function ti({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},startEditingTitle(e){const n=t.selection.getIds(),r=e??(1===n.length?n[0]:void 0),o=r?t.shapes.get(r):null;return!(!o||"frame"!==o.type||!t.editing.canEditShape(o))&&(t.editing.start({shapeId:o.id,entryMode:"selectAll",operationKind:Qo},"user"),!0)},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(ei);return 0===e.length?null:{name:ni(e.map(t=>t.props.name)),fill:ri(e.map(t=>t.props.fill)),stroke:ri(e.map(t=>t.props.stroke)),strokeWidth:ni(e.map(t=>t.props.strokeWidth))}},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(ei).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)},toolDefaultsState:o(t.signals.computed("Frame.toolDefaults",()=>t.shapes.getDefaultProps("frame"))),setToolDefaults:e=>(t.shapes.updateDefaultProps("frame",e),t.shapes.getDefaultProps("frame")),getToolCreationConfig:()=>Yo(t).getConfig(),setToolCreationConfig:e=>Yo(t).setConfig(e),getSelectedChildOrderState(){const e=t.state.selectedShapeIds.get();if(1!==e.length)return null;const n=t.layers.getOrderState(e);if(!n||!n.parentId.startsWith("shape:"))return null;const r=t.shapes.get(n.parentId);return r&&"frame"===r.type?{index:t.layers.getChildIds(r.id).indexOf(e[0]),count:n.count,canMoveBackward:n.canMoveBackward,canMoveForward:n.canMoveForward}:null},moveSelectedChild:e=>t.layers.move(t.selection.getIds(),e,"user")}}({editor:t})}function ei(t){return"frame"===t.type}function ni(t){const e=t[0];return void 0!==e&&t.every(t=>t===e)?e:null}function ri(t){const e=t[0];return e&&t.every(t=>Ut(t,e))?e:null}function oi(){return{canvasOverlays:[{id:"land.frame.creation-preview",component:ai,order:10}],shapeRenderers:[{type:"frame",component:ii,hoverComponent:li}]}}function ii({editor:t,shape:e,shapeEditingSession:n}){
|
|
6
|
-
return
|
|
7
|
-
return
|
|
8
|
-
return
|
|
9
|
-
return d(n,{editor:t,shape:e,isEditing:r,value:e.props.name,fallback:Fo(""),bodyWidth:e.props.w,bodyHeight:e.props.h,renderHeight:0,operationKind:Qo,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"},offsetX:0,showDragHandle:!1,onValueChange:n=>{t.commands.updateShapes([{id:e.id,props:{name:n}}],{source:"user"})}})}var di=s({id:"frame",editor:Zo(),render:oi(),setup:({editor:t})=>(Xo(t),{api:ti({editor:t})})}),ui="flow-node",pi=["left","right"];function hi(t){return It(t)&&"flow-edge"===t.type}function fi(t){return("text"===t?.type||"image"===t?.type)&&"flow-node"===t.subType}function gi(t){return"text"===t.type?"文字生成":"图片生成"}function mi(t){return function(t){return!!t&&"binding"===t.typeName}(t)&&"flow-edge"===t.type}var yi={left:new Tt(-1,0),right:new Tt(1,0),top:new Tt(0,-1),bottom:new Tt(0,1)};function wi(t){const e=bi(t.sourceOutwardNormal),n=bi(t.targetOutwardNormal),r=ki(e,t.source,t.target,.25),o=ki(n,t.target,t.source,.25);return{path:`M${t.source.x},${t.source.y} C${r.x},${r.y} ${o.x},${o.y} ${t.target.x},${t.target.y}`,points:Array.from({length:25},(e,n)=>function(t,e,n,r,o){const i=1-o;return new Tt(i**3*t.x+3*i**2*o*e.x+3*i*o**2*n.x+o**3*r.x,i**3*t.y+3*i**2*o*e.y+3*i*o**2*n.y+o**3*r.y)}(t.source,r,o,t.target,n/24))}}function xi(t){const e=function(t){const e=yi[t.sourcePosition],n=yi[t.targetPosition],r=t.source.add(e.mul(t.offset)),o=t.target.add(n.mul(t.offset)),i=function(t){return"left"===t.sourcePosition||"right"===t.sourcePosition?t.source.x<t.target.x?new Tt(1,0):new Tt(-1,0):t.source.y<t.target.y?new Tt(0,1):new Tt(0,-1)}({source:r,sourcePosition:t.sourcePosition,target:o}),s=0!==i.x?"x":"y",a=i[s];let l;const c=new Tt(0,0),d=new Tt(0,0);if(e[s]*n[s]===-1){const n="x"===s?r.x+(o.x-r.x)*t.stepPosition:(r.x+o.x)/2,i="y"===s?r.y+(o.y-r.y)*t.stepPosition:(r.y+o.y)/2,c=[new Tt(n,r.y),new Tt(n,o.y)],d=[new Tt(r.x,i),new Tt(o.x,i)];l=e[s]===a?"x"===s?c:d:"x"===s?d:c}else{const i=[new Tt(r.x,o.y)],u=[new Tt(o.x,r.y)];if(l="x"===s?e.x===a?u:i:e.y===a?i:u,t.sourcePosition===t.targetPosition){const n=Math.abs(t.source[s]-t.target[s]);if(n<=t.offset){const i=Math.min(t.offset-1,t.offset-n);e[s]===a?c[s]=(r[s]>t.source[s]?-1:1)*i:d[s]=(o[s]>t.target[s]?-1:1)*i}}if(t.sourcePosition!==t.targetPosition){const t="x"===s?"y":"x",a=e[s]===n[t],c=r[t]>o[t],d=r[t]<o[t];(1===e[s]&&(!a&&c||a&&d)||1!==e[s]&&(!a&&d||a&&c))&&(l="x"===s?i:u)}}const u=r.add(c),p=o.add(d);return[t.source,...u.x!==l[0].x||u.y!==l[0].y?[u]:[],...l,...p.x!==l.at(-1).x||p.y!==l.at(-1).y?[p]:[],t.target]}({source:t.source,sourcePosition:bi(t.sourceOutwardNormal),target:t.target,targetPosition:bi(t.targetOutwardNormal),offset:20,stepPosition:.5});let n=`M${e[0].x} ${e[0].y}`;for(let r=1;r<e.length-1;r+=1)n+=Si(e[r-1],e[r],e[r+1],t.borderRadius);return n+=`L${e.at(-1).x} ${e.at(-1).y}`,{path:n,points:e}}function bi(t){return Math.abs(t.x)>=Math.abs(t.y)?t.x<0?"left":"right":t.y<0?"top":"bottom"}function vi(t,e){return t>=0?.5*t:25*e*Math.sqrt(-t)}function ki(t,e,n,r){switch(t){case"left":return new Tt(e.x-vi(e.x-n.x,r),e.y);case"right":return new Tt(e.x+vi(n.x-e.x,r),e.y);case"top":return new Tt(e.x,e.y-vi(e.y-n.y,r));case"bottom":return new Tt(e.x,e.y+vi(n.y-e.y,r))}}function Si(t,e,n,r){const o=Math.min(t.dist(e)/2,e.dist(n)/2,r),{x:i,y:s}=e;if(t.x===i&&i===n.x||t.y===s&&s===n.y)return`L${i} ${s}`;if(t.y===s){return`L ${i+o*(t.x<n.x?-1:1)},${s}Q ${i},${s} ${i},${s+o*(t.y<n.y?1:-1)}`}const a=t.x<n.x?1:-1;return`L ${i},${s+o*(t.y<n.y?-1:1)}Q ${i},${s} ${i+o*a},${s}`}var Ii="shape:flow-edge-preview";function Pi(t,e){return{kind:"bound",shapeId:t,attachment:{kind:"port",portId:e.id}}}function Mi(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||hi(n)||t.shapes.isHidden(n.id)||null===t.shapes.getClippedPageBounds(n.id)||!t.shapes.getUtil(n).canReceiveTerminalBinding(n,{editor:t}))return null;const r=ce(t,n,e.attachment.portId);return r?{draft:e,pagePoint:r.pagePoint.clone(),shape:n,port:r}:null}function Ti(t,e,n,r){if(e.shape&&e.port)return{point:e.pagePoint,outwardNormal:e.port.pageOutwardNormal};const o=n.pagePoint.sub(e.pagePoint).normalize();return{point:e.pagePoint,outwardNormal:o.len2()>0?o:new Tt("start"===r?1:-1,0)}}function Ci(t){return{portId:t.id}}function Ei(t,e,n){return ce(t,e,n.portId)}function Ai(t,e,n){const r=new Set(Hi(t,n));for(const o of Hi(t,e))if(r.has(o)&&t.layers.canReceiveChildren(o))return o;return St}function Li(t){const{editor:e,parentId:n,start:r,end:o,props:i}=t,s=n.startsWith("shape:")?e.shapes.get(n):null,a=(s?e.shapes.computeLocalToPageTransform(s):Kt.Identity()).tryInvert();if(!a)throw new Error("Flow edge parent transform is not invertible");const l=a.applyToPoint(r.point),c=a.applyToPoint(o.point),d=Oi({start:r,end:o,props:i}),u=Ct.FromPoints(d.points.map(t=>a.applyToPoint(t))),p=t=>({x:t.x-u.x,y:t.y-u.y});return{type:"flow-edge",parentId:n,x:u.x,y:u.y,rotation:0,props:{...i,w:Math.max(1,u.w),h:Math.max(1,u.h),start:p(l),end:p(c)}}}function Ri(t,e){return t.pagePoint.add(t.pageOutwardNormal.mul(20/Math.max(e,1e-4)))}function $i(t,e,n={}){const r=Math.max(t.state.cameraZoom.get(),1e-4),o=12/r,i=o+20/r;let s=null;for(const a of t.shapes.getInBounds(new Ct(e.x-i,e.y-i,2*i,2*i)))if(!hi(a)&&!t.shapes.isHidden(a.id)&&null!==t.shapes.getClippedPageBounds(a.id))for(const i of le(t,a)){const t={shape:a,port:i};if(n.portFilter&&!n.portFilter(t))continue;const l=Math.min(e.dist(i.pagePoint),e.dist(Ri(i,r)));l<=o&&(!s||l<s.distance||l===s.distance&&`${a.index}:${a.id}:${i.id}`<`${s.shape.index}:${s.shape.id}:${s.port.id}`)&&(s={...t,distance:l})}return s?{shape:s.shape,port:s.port}:null}function Ni(t,e){const n=t.shapes.computeLocalToPageTransform(e),r=n.tryInvert(),o=Bi(t,e);return r?function(t,e){const n=t.points.map(e),r=e(t.startPoint),o=e(t.endPoint);return{...t,path:Di(n),points:n,startPoint:r,endPoint:o,markerPath:t.markerPath?ji(o,n.at(-2),2):null,bounds:Ct.FromPoints(n)}}(o,t=>n.applyToPoint(t)):o}function Bi(t,e){const n=t.shapes.computeLocalToPageTransform(e).tryInvert(),r=new Tt(e.props.start.x,e.props.start.y),o=new Tt(e.props.end.x,e.props.end.y);if(!n)return Oi({start:{point:r,outwardNormal:new Tt(1,0)},end:{point:o,outwardNormal:new Tt(-1,0)},props:e.props});const i=t.bindings.getOwnedByShape(e.id).find(mi),s=(e,r,o)=>{const s=i?.endpoints.find(({slot:t})=>t===e),a=s?t.shapes.get(s.targetId):null,l=s&&a?Ei(t,a,s.props):null;if(!l||!a)return{point:r,outwardNormal:o};const c=l.pagePoint,d=c.add(l.pageOutwardNormal),u=n.applyToPoint(c);return{point:u,outwardNormal:n.applyToPoint(d).sub(u).normalize()}};return Oi({start:s("start",r,new Tt(1,0)),end:s("end",o,new Tt(-1,0)),props:e.props})}function Oi(t){const{start:e,end:n,props:r}=t,{path:o,points:i}="curved"===r.routing?wi({source:e.point,sourceOutwardNormal:e.outwardNormal,target:n.point,targetOutwardNormal:n.outwardNormal}):"orthogonal"===r.routing?xi({source:e.point,sourceOutwardNormal:e.outwardNormal,target:n.point,targetOutwardNormal:n.outwardNormal,borderRadius:r.cornerRadius}):(s=e.point,a=n.point,{path:`M ${s.x},${s.y}L ${a.x},${a.y}`,points:[s,a]});var s,a;const l="arrow"===r.headEnd?ji(i.at(-1),i.at(-2),r.strokeWidth):null,c=l?Wi(i.at(-1),i.at(-2),r.strokeWidth):[];return{path:o,points:[...i],startPoint:e.point,endPoint:n.point,markerPath:l,bounds:Ct.FromPoints([...i,...c]).expand(Math.max(r.strokeWidth/2,1))}}function zi(t,e,n,r){if(0===r.length)return n;const o=function(t,e){const n={id:Ii,typeName:"shape",scope:"document",type:e.type,subType:e.subType??null,parentId:e.parentId??"document:main",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)}}(t,n),i=t.shapes.computePageCenter(o),s=new Tt(-e.port.pageOutwardNormal.y,e.port.pageOutwardNormal.x).normalize();if(0===s.len2())return n;const a=Ki(e.port.pagePoint,s),l=Ui(t,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.at(-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<0&&e>0);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]}(r.map(e=>Ui(t,e,s,a)),c)-(Ki(i,s)-a);if(Math.abs(d)<=1e-6)return n;const u=n.parentId??e.shape.parentId,p=u.startsWith("shape:")?t.shapes.get(u):null,h=(p?t.shapes.computeLocalToPageTransform(p):Kt.Identity()).tryInvert();if(!h)return n;const f=i.add(s.mul(d)),g=h.applyToPoint(f).sub(h.applyToPoint(i));return{...n,x:n.x+g.x,y:n.y+g.y}}function Hi(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}function Di(t){return t.map((t,e)=>`${0===e?"M":"L"} ${Fi(t)}`).join(" ")}function Fi(t){return`${t.x.toFixed(3)} ${t.y.toFixed(3)}`}function Wi(t,e,n){const r=t.sub(e).normalize(),o=Math.max(8,4*n),i=t.sub(r.mul(o)),s=new Tt(-r.y,r.x).mul(.55*o);return[i.add(s),t,i.sub(s)]}function ji(t,e,n){const[r,o,i]=Wi(t,e,n);return`M ${Fi(r)} L ${Fi(o)} L ${Fi(i)}`}function Ui(t,e,n,r){const o=t.shapes.computePageCorners(e).map(t=>Ki(t,n)-r);return{min:Math.min(...o),max:Math.max(...o)}}function Ki(t,e){return t.x*e.x+t.y*e.y}var Xi=new WeakMap;function Yi(t){const e=Xi.get(t);if(!e)throw new Error("FlowEdgeRuntime is not initialized for this editor.");return e}var _i="left",qi="right";function Gi(t){return"right"===t.port.id&&("text"===t.shape.type||"image"===t.shape.type)}function Vi(t){return fi(t.shape)&&"left"===t.port.id}function Ji(t,e){return"start"===t?Gi(e):Vi(e)}function Zi(t,e,n,r){return!Yi(t).allowCycles&&function(t,e,n,r){const o=new Map;for(const a of t.state.shapeIds.get()){if(a===r)continue;const e=t.shapes.get(a);if(!hi(e))continue;const n=Qi(t,e.id);if(!n.start||!n.end)continue;const i=o.get(n.start.targetId)??[];i.push(n.end.targetId),o.set(n.start.targetId,i)}const i=[n],s=new Set;for(;i.length>0;){const t=i.pop();if(t===e)return!0;if(!s.has(t)){s.add(t);for(const e of o.get(t)??[])s.has(e)||i.push(e)}}return!1}(t,e,n,r)}function Qi(t,e){let n=null,r=null;for(const o of t.bindings.getOwnedByShape(e))if(mi(o)){n=o.endpoints.find(({slot:t})=>"start"===t)??null,r=o.endpoints.find(({slot:t})=>"end"===t)??null;break}return{start:n,end:r}}function ts(t,e){return t.bindings.getOwnedByShape(e).filter(mi)}function es(t,e,n,r){const o=Mi(t,e),i=Mi(t,n);return o?.shape&&o.port&&i?.shape&&i.port?Gi({shape:o.shape,port:o.port})?Vi({shape:i.shape,port:i.port})?(s=o.shape,a=i.shape,s.id!==a.id||Yi(t).allowCycles?t.layers.isOrAncestorLocked(o.shape.id)?"locked_source":ss(t,o.shape.id,o.port.id,i.shape.id,i.port.id,r)?"duplicate":Zi(t,o.shape.id,i.shape.id,r)?"cycle":Ai(t,o.shape,i.shape)?null:"invalid_parent":"self_loop"):"invalid_input":"invalid_output":"missing_endpoint";var s,a}function ns(t,e,n="user"){if(es(t,e.start,e.end))return null;const r=Mi(t,e.start),o=Mi(t,e.end);if(!(r?.shape&&r.port&&o?.shape&&o.port))return null;const i=Ai(t,r.shape,o.shape);if(!i)return null;const s={...t.shapes.getDefaultProps("flow-edge"),...e.props},a=Li({editor:t,parentId:i,start:Ti(0,r,o,"start"),end:Ti(0,o,r,"end"),props:s}),l=t.operations.begin({kind:"flow-edge.commit",label:"shape.create",source:n,history:"user"===n?"record":"ignore"});try{const i=t.commands.createShapes([a],{source:n,autoReparent:!1})[0];if(!hi(i))return l.cancel(),null;t.commands.createBinding({type:"flow-edge",ownerId:i.id,endpoints:[{slot:"start",targetId:r.shape.id,props:Ci(r.port)},{slot:"end",targetId:o.shape.id,props:Ci(o.port)}]},{source:n}),"none"!==e.selectionAfter&&t.commands.setSelectedShapeIds(Array.isArray(e.selectionAfter)?[...e.selectionAfter]:[i.id],{source:n});const s=t.shapes.get(i.id);return hi(s)?(l.commit(),s):(l.cancel(),null)}catch(c){throw l.isActive&&l.cancel(),c}}function rs(t,e,n,r){return is(t,e,{[n]:r})}function os(t,e,n,r,o="user"){const i=Mi(t,r),s=ts(t,e)[0];if(!i?.shape||!i.port||!s)return null;t.commands.setBindingEndpoint({bindingId:s.id,endpoint:{slot:n,targetId:i.shape.id,props:Ci(i.port)}},{source:o});const a=t.shapes.get(e);return hi(a)?a:null}function is(t,e,n={}){const r=Qi(t,e.id),o=t.shapes.computeLocalToPageTransform(e),i=o.applyToPoint(new Tt(e.props.start.x,e.props.start.y)),s=o.applyToPoint(new Tt(e.props.end.x,e.props.end.y)),a=as(t,r.start),l=as(t,r.end),c=n.start?Mi(t,{kind:"free",pagePoint:n.start}):a??Mi(t,{kind:"free",pagePoint:i}),d=n.end?Mi(t,{kind:"free",pagePoint:n.end}):l??Mi(t,{kind:"free",pagePoint:s});if(!c||!d)return null;const u=a&&l?Ai(t,a.shape,l.shape):e.parentId;if(!u||!t.layers.canReceiveChildren(u))return null;const p=Li({editor:t,parentId:u,start:Ti(0,c,d,"start"),end:Ti(0,d,c,"end"),props:e.props});return{...e,parentId:u,x:p.x??e.x,y:p.y??e.y,rotation:0,scaleX:1,scaleY:1,props:{...e.props,...p.props}}}function ss(t,e,n,r,o,i){for(const s of t.state.shapeIds.get()){if(s===i)continue;const a=t.shapes.get(s);if(!hi(a))continue;const l=Qi(t,a.id);if(l.start?.targetId===e&&l.start.props.portId===n&&l.end?.targetId===r&&l.end.props.portId===o)return!0}return!1}function as(t,e){if(!e)return null;const n=t.shapes.get(e.targetId);if(!n)return null;const r=Ei(t,n,e.props);return r&&Ji(e.slot,{shape:n,port:r})?Mi(t,Pi(n.id,r)):null}var ls="land:",cs="shape";function ds(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 us(n)?n:null}function us(t){return null!==fs(t)||ps(t)}function ps(t){try{const e=new URL(t);return"http:"===e.protocol||"https:"===e.protocol||"mailto:"===e.protocol}catch{return!1}}function hs(t){return`${ls}//${cs}/${encodeURIComponent(t)}`}function fs(t){try{const e=new URL(t);if(e.protocol!==ls||e.hostname!==cs||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 gs({href:t,openExternal:e,openInternal:n}){const r=fs(t);r?n?.(r):ps(t)&&e(t)}var ms=/[;{}<>\u0000-\u001f\u007f]/u,ys=/(?:url|expression)\s*\(|!\s*important|@\s*import|javascript\s*:/iu,ws=/^((?:\d+(?:\.\d{1,3})?)|(?:\.\d{1,3}))(px|em|rem|%)?$/iu;function xs(t){return{type:"doc",content:t.split("\n").map(t=>({type:"paragraph",content:t.length>0?[{type:"text",text:t}]:[]}))}}function bs(t){return t.content.map(t=>Cs(t)).join("\n")}function vs(t){return"taskItem"===t.type||(t.content?.some(vs)??!1)}function ks(t){return"taskList"===t.type||"taskItem"===t.type?"\n":""}function Ss(t){if(!t||"object"!=typeof t)return xs("");const e=t,n=Array.isArray(e.content)?e.content.map(t=>Ns(t,0)).filter(t=>null!==t):[];return{type:"doc",attrs:js(e.attrs),content:n}}function Is(t){return"text"===t.type&&"string"==typeof t.text}function Ps(t){if("paragraph"===t.type)return Ws(t.attrs?.textAlign)}function Ms(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=zs(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 Ts(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 Cs(t){return Is(t)?t.text:t.content?.map(t=>Cs(t)).join(ks(t))??""}function Es(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 As(t){const e=t.content?.map(t=>function(t){if(Is(t)){const e=Ms(t.marks),n=Ts(t.marks),r=Ls(t.text),o=e?`<span style="${Rs(Es(e))}">${r}</span>`:r;return n&&ps(n)?`<a href="${Rs(n)}" target="_blank" rel="noopener noreferrer">${o}</a>`:e?o:r}return"hardBreak"===t.type?"<br>":As(t)}(t)).join("")??"";if("taskList"===t.type)return`<ul data-type="taskList" style="margin:0;padding:0;list-style:none">${e}</ul>`;if("taskItem"===t.type){const n=!0===t.attrs?.checked;return`<li data-type="taskItem" data-checked="${n}" style="display:flex;align-items:flex-start;gap:0.625em;padding-block:0.18em"><label contenteditable="false" style="display:flex;align-items:center;flex:none;height:1lh;user-select:none"><input type="checkbox"${n?" checked":""} style="width:1em;height:1em;margin:0;font:inherit"></label><div style="flex:1;min-width:0">${e}</div></li>`}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=Ps(t);return`<p style="${n?`margin:0;text-align:${n}`:"margin:0"}">${e.length>0?e:"<br>"}</p>`}function Ls(t){return t.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function Rs(t){return Ls(t).replaceAll('"',""")}function $s(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(Bs).filter(t=>null!==t):void 0}}(n);return t.text.length>0?t:null}return Ns(n,e)}function Ns(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=>$s(t,e+1)).filter(t=>null!==t):[];return{type:r,attrs:Os(r,n.attrs),content:o}}function Bs(t){if(!t||"object"!=typeof t)return null;const e=t;if("string"!=typeof e.type)return null;if("link"===e.type){const t=js(e.attrs),n=t?.href;return"string"==typeof n&&us(n)?{type:"link",attrs:{...t,href:n}}:null}if("textStyle"===e.type){const t=zs(e.attrs);return t?{type:"textStyle",attrs:t}:null}return{type:e.type,attrs:js(e.attrs)}}function Os(t,e){const n=js(e);if("taskItem"===t)return{...n,checked:!0===n?.checked};if("paragraph"!==t)return n;const r={...n};delete r.textAlign;const o=e&&"object"==typeof e&&!Array.isArray(e)?Ws(e.textAlign):void 0;return void 0!==o&&(r.textAlign=o),Object.keys(r).length>0?r:void 0}function zs(t){if(!t||"object"!=typeof t||Array.isArray(t))return;const e=t,n={color:Hs(e.color,128),backgroundColor:Hs(e.backgroundColor,128),fontFamily:Hs(e.fontFamily,256),fontSize:Ds(e.fontSize),lineHeight:Fs(e.lineHeight)},r=Object.entries(n).filter(t=>void 0!==t[1]);return r.length>0?Object.fromEntries(r):void 0}function Hs(t,e){if("string"!=typeof t)return;const n=t.trim();return 0===n.length||n.length>e||ms.test(n)||ys.test(n)?void 0:n}function Ds(t){const e="string"==typeof t?ws.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 Fs(t){const e="string"==typeof t?ws.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 Ws(t){return"left"===t||"center"===t||"right"===t||"justify"===t?t:void 0}function js(t){if(!t||"object"!=typeof t)return;const e=Object.entries(t).map(([t,e])=>[t,Us(e)]).filter(t=>void 0!==t[1]);return e.length>0?Object.fromEntries(e):void 0}function Us(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=>Us(t,e+1)).filter(t=>void 0!==t);if(t&&"object"==typeof t){const n=Object.entries(t).map(([t,n])=>[t,Us(n,e+1)]).filter(t=>void 0!==t[1]);return Object.fromEntries(n)}}}function Ks(t){return It(t)&&"text"===t.type}function Xs(t){return{richText:t.richText,plainText:t.plainText,w:t.w,h:t.h,autoSize:t.autoSize,scale:t.scale,font:t.font,size:t.size,lineHeight:t.lineHeight,color:t.color,backgroundColor:t.backgroundColor,textAlign:t.textAlign,padding:t.padding,fill:t.fill,stroke:t.stroke,strokeWidth:t.strokeWidth,cornerRadius:t.cornerRadius,shadow:t.shadow}}function Ys(t){return Xs(t.shapes.getDefaultProps("text"))}function _s(t,e,n="user"){const r=Ys(t),o=e.props?.richText??xs(""),i={...r,...e.props,richText:o,plainText:bs(o)},[s]=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:i.richText,plainText:i.plainText,w:i.w,h:i.h,autoSize:i.autoSize,scale:i.scale,font:i.font,size:i.size,lineHeight:i.lineHeight,color:i.color,backgroundColor:i.backgroundColor,textAlign:i.textAlign,padding:i.padding,fill:i.fill,stroke:i.stroke,strokeWidth:i.strokeWidth,cornerRadius:i.cornerRadius,shadow:i.shadow}}],{source:n});if(!Ks(s))throw new Error("Failed to create text shape");return s}function qs(t,e,n,r,o="user"){const i=t.shapes.get(e);Ks(i)&&t.commands.updateShapes([{id:i.id,props:{richText:n,plainText:bs(n),..."number"==typeof r?.w?{w:r.w}:null,..."number"==typeof r?.h?{h:r.h}:null}}],{source:o})}var Gs="default",Vs={id:"host-default",label:"Host default",cssFamily:"inherit",source:{kind:"system"}};function Js(){return{defaultFont:Vs,defaultFontLabel:"Default",fonts:[]}}function Zs(){return Qs(Js())}function Qs(t){const e=new Map;for(const r of t.fonts)ta(r.id)&&"default"!==r.id&&e.set(r.id,r);const n={id:Gs,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 ta(t){return"string"==typeof t&&t.trim().length>0}function ea(t,e){return"default"===e?t.defaultFont:t.fontsById.get(e)??t.defaultFont}var na={s:14,m:16,l:20,xl:28},ra=na.m;function oa(t){return t.shadow?14*t.scale:0}function ia(t,e){const n=[...t.strokeWidth>0&&!jt(t.stroke)?[`inset 0 0 0 ${t.strokeWidth}px ${e(t.stroke)}`]:[],...t.shadow?["0 2px 8px rgba(0, 0, 0, 0.04)","0 1px 2px rgba(0, 0, 0, 0.02)"]:[]];return{backgroundColor:jt(t.fill)?(sa(t.padding).x>0||sa(t.padding).y>0)&&!jt(t.backgroundColor)?e(t.backgroundColor):void 0:e(t.fill),borderRadius:t.cornerRadius>0?`${t.cornerRadius}px`:void 0,boxShadow:n.length>0?n.join(", "):void 0}}function sa(t){return"number"==typeof t?{x:t,y:t}:t}function aa(t,e=0){const n=(t,e)=>"number"==typeof t&&Number.isFinite(t)?Math.max(0,t):e;if(t&&"object"==typeof t){const r=t,o=sa(e);return{x:n(r.x,o.x),y:n(r.y,o.y)}}return"number"==typeof t&&Number.isFinite(t)?Math.max(0,t):e}var la={[na.s]:20,[na.m]:24,[na.l]:28,[na.xl]:36};function ca(t,e=ra){return"number"==typeof t&&Number.isFinite(t)?Math.max(1,t):e}function da(t,e){return ea(e,t).cssFamily}function ua(t){return ca(t)}function pa(t,e=null){const n=ca(t);return"number"==typeof e?n*e:"string"==typeof e?e.endsWith("%")?n*Number.parseFloat(e)/100:Number.parseFloat(e):la[n]??Math.ceil(1.4*n)}function ha(t,e=null){return String(e??pa(t)/ca(t))}function fa(t,e=null){return Math.max(1,Math.ceil(pa(t,e)))}function ga(t){switch(t){case"middle":return"center";case"end":return"right";case"justify":return"justify";default:return"left"}}var ma="path-label",ya="geo-label";function wa(t={}){return{padding:sa(aa(t.padding,16)),verticalAlign:"top"===t.verticalAlign||"bottom"===t.verticalAlign?t.verticalAlign:"middle"}}function xa(t,e){return t.bindings.getTargetingShape(e).find(t=>"geo-label"===t.type&&t.endpoints.some(t=>"owner"===t.slot&&t.targetId===e))??null}function ba(t,e){const n=xa(t,e)?.endpoints.find(({slot:t})=>"owner"===t);return wa(n?.props)}function va(t,e){const n=Ca(t,e);return t.layers.isOrAncestorLocked(e)||null!==n&&t.layers.isOrAncestorLocked(n.ownerId)}var ka={[ma]:{selectionTarget:"owner",hoverTarget:"owner",hoverDecorationTarget:"owner",translateTarget:"owner",canSnap:!1,canReceiveTerminalBinding:!1,contributesToSelectionFrame:!0,canUseSelectionResizeHandles:!1,canUseSelectionRotateHandle:!1,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!0},[ya]:{selectionTarget:"owner",hoverTarget:"owner",hoverDecorationTarget:"label",translateTarget:"owner",canSnap:!1,canReceiveTerminalBinding:!1,contributesToSelectionFrame:!1,canUseSelectionResizeHandles:!0,canUseSelectionRotateHandle:!0,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!1}};function Sa(t,e){return t?Math.min(t.paddingInline,Math.max(0,(e-1)/2)):0}function Ia(t,e){return qt(t.shapes.computeLocalToPageTransform(e),t.shapes.computeLocalBounds(e),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY})?.rotation??e.rotation}function Pa(t,e,n,r){const o=t.shapes.getUtil(e),i=qt(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):Kt.Identity()).tryInvert();return l?qt(l.compose(o.getLocalTransform(s)),o.getLocalBounds(s),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY}):null}function Ma(t,e,n){const r=t.bindings.getTargetingShape(e).find(t=>t.type===n&&t.endpoints.some(({slot:t,targetId:n})=>"owner"===t&&n===e));if(!r)return null;const o=t.shapes.get(r.ownerId);return Ks(o)?o:null}function Ta(t,e){const n={...Ys(t),...e.layout.props,autoSize:!1,textAlign:"middle"},r=Pa(t,{id:"shape:draft-label",typeName:"shape",scope:"document",type:"text",subType:null,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=_s(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,ownerId:o.id,endpoints:[{slot:"owner",targetId:e.owner.id,props:e.bindingProps}]},{source:"user"}),o}catch(i){throw o.cancel(),i}}function Ca(t,e){const n=t.shapes.get(e);if(!Ks(n))return null;const r=t.bindings.getOwnedByShape(e).find(t=>t.type in ka);if(!r)return null;const o=r.type,i=r.endpoints.find(({slot:t})=>"owner"===t);return i?{label:n,ownerId:i.targetId,bindingType:o,behavior:ka[o]}:null}function Ea(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,l=Math.max(16,i.w*a/o);return{minWidth:l,maxWidth:l,paddingInline:ba(t,n.id).padding.x,normalizedCenterX:"summary-left"===s?1-a/2:a/2}}function Aa(t,e){const n=Ca(t,e.id);if(!n)return null;const r=t.shapes.get(n.ownerId);return r?Ea(t,e,r,n.bindingType):null}function La(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 Ra(t,e){return l(v(()=>t.signals.computed(`textLabelLayout(${e.id})`,()=>Aa(t,e)),[t,e]))}function $a(t,e={}){const n={offset:0};return t.content.map((t,r)=>(r>0&&(n.offset+=1),Na(t,`block:${r}`,n,e,[r])))}function Na(t,e,n,r,o){const i="codeBlock"===t.type?void 0:r.defaultBackgroundColor,s=function(t,e,n,r,o){return t.content?.map((i,s)=>(s>0&&(n.offset+=ks(t).length),function(t,e,n,r,o){if(Is(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=Ms(t.marks,r.defaultBackgroundColor),a=Ts(t.marks);return a&&us(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:Oa(s?.textDecorationLine)},children:i},e):d("span",{style:s,children:i},e)}return"hardBreak"===t.type?d("br",{},e):Na(t,e,n,{...r,defaultBackgroundColor:"codeBlock"===t.type?void 0:r.defaultBackgroundColor},o)}(i,`${e}:${s}`,n,r,[...o,s])))??[]}(t,e,n,{...r,defaultBackgroundColor:i},o);if("taskList"===t.type)return d("ul",{"data-type":"taskList",style:{listStyle:"none",margin:0,padding:0},children:s},e);if("taskItem"===t.type){const n=!0===t.attrs?.checked;
|
|
10
|
-
return
|
|
11
|
-
return nt("strong",{...V(this.options.HTMLAttributes,t),children:nt("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[q({find:za,type:this.type}),q({find:Da,type:this.type})]},addPasteRules(){return[G({find:Ha,type:this.type}),G({find:Fa,type:this.type})]}}),ja=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,Ua=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Ka=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Xa=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,Ya=C.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[q({find:ja,type:this.type}),q({find:Ka,type:this.type})]},addPasteRules(){return[G({find:Ua,type:this.type}),G({find:Xa,type:this.type})]}}),_a="numeric",qa="ascii",Ga="alpha",Va="asciinumeric",Ja="alphanumeric",Za="domain",Qa="emoji",tl="scheme",el="slashscheme",nl="whitespace";function rl(t,e){return t in e||(e[t]=[]),e[t]}function ol(t,e,n){e[_a]&&(e[Va]=!0,e[Ja]=!0),e[qa]&&(e[Va]=!0,e[Ga]=!0),e[Va]&&(e[Ja]=!0),e[Ga]&&(e[Ja]=!0),e[Ja]&&(e[Za]=!0),e[Qa]&&(e[Za]=!0);for(const r in e){const e=rl(r,n);e.indexOf(t)<0&&e.push(t)}}function il(t=null){this.j={},this.jr=[],this.jd=null,this.t=t}il.groups={},il.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||il.groups,e&&e.j?o=e:(o=new il(e),n&&r&&ol(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||il.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 il,Object.assign(s.j,a.j),s.jr.push.apply(s.jr,a.jr),s.jd=a.jd,s.t=a.t):s=new il,i&&(r&&(s.t&&"string"==typeof s.t?ol(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&&ol(i,n,r)),s.t=i),o.j[t]=s,s}};var sl=(t,e,n,r,o)=>t.ta(e,n,r,o),al=(t,e,n,r,o)=>t.tr(e,n,r,o),ll=(t,e,n,r,o)=>t.ts(e,n,r,o),cl=(t,e,n,r,o)=>t.tt(e,n,r,o),dl="WORD",ul="UWORD",pl="ASCIINUMERICAL",hl="ALPHANUMERICAL",fl="LOCALHOST",gl="TLD",ml="UTLD",yl="SCHEME",wl="SLASH_SCHEME",xl="NUM",bl="WS",vl="NL",kl="OPENBRACE",Sl="CLOSEBRACE",Il="OPENBRACKET",Pl="CLOSEBRACKET",Ml="OPENPAREN",Tl="CLOSEPAREN",Cl="OPENANGLEBRACKET",El="CLOSEANGLEBRACKET",Al="FULLWIDTHLEFTPAREN",Ll="FULLWIDTHRIGHTPAREN",Rl="LEFTCORNERBRACKET",$l="RIGHTCORNERBRACKET",Nl="LEFTWHITECORNERBRACKET",Bl="RIGHTWHITECORNERBRACKET",Ol="FULLWIDTHLESSTHAN",zl="FULLWIDTHGREATERTHAN",Hl="AMPERSAND",Dl="APOSTROPHE",Fl="ASTERISK",Wl="AT",jl="BACKSLASH",Ul="BACKTICK",Kl="CARET",Xl="COLON",Yl="COMMA",_l="DOLLAR",ql="DOT",Gl="EQUALS",Vl="EXCLAMATION",Jl="HYPHEN",Zl="PERCENT",Ql="PIPE",tc="PLUS",ec="POUND",nc="QUERY",rc="QUOTE",oc="FULLWIDTHMIDDLEDOT",ic="SEMI",sc="SLASH",ac="TILDE",lc="UNDERSCORE",cc="EMOJI",dc="SYM",uc=Object.freeze({__proto__:null,ALPHANUMERICAL:hl,AMPERSAND:Hl,APOSTROPHE:Dl,ASCIINUMERICAL:pl,ASTERISK:Fl,AT:Wl,BACKSLASH:jl,BACKTICK:Ul,CARET:Kl,CLOSEANGLEBRACKET:El,CLOSEBRACE:Sl,CLOSEBRACKET:Pl,CLOSEPAREN:Tl,COLON:Xl,COMMA:Yl,DOLLAR:_l,DOT:ql,EMOJI:cc,EQUALS:Gl,EXCLAMATION:Vl,FULLWIDTHGREATERTHAN:zl,FULLWIDTHLEFTPAREN:Al,FULLWIDTHLESSTHAN:Ol,FULLWIDTHMIDDLEDOT:oc,FULLWIDTHRIGHTPAREN:Ll,HYPHEN:Jl,LEFTCORNERBRACKET:Rl,LEFTWHITECORNERBRACKET:Nl,LOCALHOST:fl,NL:vl,NUM:xl,OPENANGLEBRACKET:Cl,OPENBRACE:kl,OPENBRACKET:Il,OPENPAREN:Ml,PERCENT:Zl,PIPE:Ql,PLUS:tc,POUND:ec,QUERY:nc,QUOTE:rc,RIGHTCORNERBRACKET:$l,RIGHTWHITECORNERBRACKET:Bl,SCHEME:yl,SEMI:ic,SLASH:sc,SLASH_SCHEME:wl,SYM:dc,TILDE:ac,TLD:gl,UNDERSCORE:lc,UTLD:ml,UWORD:ul,WORD:dl,WS:bl}),pc=/[a-z]/,hc=/\p{L}/u,fc=/\p{Emoji}/u,gc=/\d/,mc=/\s/,yc=null,wc=null;function xc(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 bc(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 il(r),i.jr=o.slice(),t.j[n]=i),t=i}return i=new il(n),i.jr=o.slice(),t.j[e[s-1]]=i,i}function vc(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 kc={defaultProtocol:"http",events:null,format:Ic,formatHref:Ic,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Sc(t,e=null){let n=Object.assign({},kc);t&&(n=Object.assign(n,t instanceof Sc?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 Ic(t){return t}function Pc(t,e){this.t="token",this.v=t,this.tk=e}function Mc(t,e){class n extends Pc{constructor(e,n){super(e,n),this.t=t}}for(const r in e)n.prototype[r]=e[r];return n.t=t,n}Sc.prototype={o:kc,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]:kc[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)}},Pc.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=kc.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 Tc=Mc("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),Cc=Mc("text"),Ec=Mc("nl"),Ac=Mc("url",{isLink:!0,toHref(t=kc.defaultProtocol){return this.hasProtocol()?this.v:`${t}://${this.v}`},hasProtocol(){const t=this.tk;return t.length>=2&&t[0].t!==fl&&t[1].t===Xl}}),Lc=t=>new il(t);function Rc(t,e,n){const r=n[0].s,o=n[n.length-1].e;return new t(e.slice(r,o),n)}var $c="undefined"!=typeof console&&console&&console.warn||(()=>{}),Nc={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function Bc(t,e=!1){if(Nc.initialized&&$c(`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');Nc.customSchemes.push([t,e])}function Oc(){Nc.scanner=function(t=[]){const e={};il.groups=e;const n=new il;null==yc&&(yc=vc("aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2")),null==wc&&(wc=vc("ελ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")),cl(n,"'",Dl),cl(n,"{",kl),cl(n,"}",Sl),cl(n,"[",Il),cl(n,"]",Pl),cl(n,"(",Ml),cl(n,")",Tl),cl(n,"<",Cl),cl(n,">",El),cl(n,"(",Al),cl(n,")",Ll),cl(n,"「",Rl),cl(n,"」",$l),cl(n,"『",Nl),cl(n,"』",Bl),cl(n,"<",Ol),cl(n,">",zl),cl(n,"&",Hl),cl(n,"*",Fl),cl(n,"@",Wl),cl(n,"`",Ul),cl(n,"^",Kl),cl(n,":",Xl),cl(n,",",Yl),cl(n,"$",_l),cl(n,".",ql),cl(n,"=",Gl),cl(n,"!",Vl),cl(n,"-",Jl),cl(n,"%",Zl),cl(n,"|",Ql),cl(n,"+",tc),cl(n,"#",ec),cl(n,"?",nc),cl(n,'"',rc),cl(n,"/",sc),cl(n,";",ic),cl(n,"~",ac),cl(n,"_",lc),cl(n,"\\",jl),cl(n,"・",oc);const r=al(n,gc,xl,{[_a]:!0});al(r,gc,r);const o=al(r,pc,pl,{[Va]:!0}),i=al(r,hc,hl,{[Ja]:!0}),s=al(n,pc,dl,{[qa]:!0});al(s,gc,o),al(s,pc,s),al(o,gc,o),al(o,pc,o);const a=al(n,hc,ul,{[Ga]:!0});al(a,pc),al(a,gc,i),al(a,hc,a),al(i,gc,i),al(i,pc),al(i,hc,i);const l=cl(n,"\n",vl,{[nl]:!0}),c=cl(n,"\r",bl,{[nl]:!0}),d=al(n,mc,bl,{[nl]:!0});cl(n,"",d),cl(c,"\n",l),cl(c,"",d),al(c,mc,d),cl(d,"\r"),cl(d,"\n"),al(d,mc,d),cl(d,"",d);const u=al(n,fc,cc,{[Qa]:!0});cl(u,"#"),al(u,fc,u),cl(u,"️",u);const p=cl(u,"");cl(p,"#"),al(p,fc,u);const h=[[pc,s],[gc,o]],f=[[pc,null],[hc,a],[gc,i]];for(let g=0;g<yc.length;g++)bc(n,yc[g],gl,dl,h);for(let g=0;g<wc.length;g++)bc(n,wc[g],ml,ul,f);ol(gl,{tld:!0,ascii:!0},e),ol(ml,{utld:!0,alpha:!0},e),bc(n,"file",yl,dl,h),bc(n,"mailto",yl,dl,h),bc(n,"http",wl,dl,h),bc(n,"https",wl,dl,h),bc(n,"ftp",wl,dl,h),bc(n,"ftps",wl,dl,h),ol(yl,{scheme:!0,ascii:!0},e),ol(wl,{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]?{[tl]:!0}:{[el]:!0};e.indexOf("-")>=0?r[Za]=!0:pc.test(e)?gc.test(e)?r[Va]=!0:r[qa]=!0:r[_a]=!0,ll(n,e,e,r)}return ll(n,"localhost",fl,{ascii:!0}),n.jd=new il(dc),{start:n,tokens:Object.assign({groups:e},uc)}}(Nc.customSchemes);for(let t=0;t<Nc.tokenQueue.length;t++)Nc.tokenQueue[t][1]({scanner:Nc.scanner});Nc.parser=function({groups:t}){const e=t.domain.concat([Hl,Fl,Wl,jl,Ul,Kl,_l,Gl,Jl,xl,Zl,Ql,tc,ec,sc,dc,ac,lc]),n=[Dl,Xl,Yl,ql,Vl,Zl,nc,rc,ic,Cl,El,kl,Sl,Pl,Il,Ml,Tl,Al,Ll,Rl,$l,Nl,Bl,Ol,zl],r=[Hl,Dl,Fl,jl,Ul,Kl,_l,Gl,Jl,kl,Sl,Zl,Ql,tc,ec,nc,sc,dc,ac,lc],o=Lc(),i=cl(o,ac);sl(i,r,i),sl(i,t.domain,i);const s=Lc(),a=Lc(),l=Lc();sl(o,t.domain,s),sl(o,t.scheme,a),sl(o,t.slashscheme,l),sl(s,r,i),sl(s,t.domain,s);const c=cl(s,Wl);cl(i,Wl,c),cl(a,Wl,c),cl(l,Wl,c);const d=cl(i,ql);sl(d,r,i),sl(d,t.domain,i);const u=Lc();sl(c,t.domain,u),sl(u,t.domain,u);const p=cl(u,ql);sl(p,t.domain,u);const h=Lc(Tc);sl(p,t.tld,h),sl(p,t.utld,h),cl(c,fl,h);const f=cl(u,Jl);cl(f,Jl,f),sl(f,t.domain,u),sl(h,t.domain,u),cl(h,ql,p),cl(h,Jl,f);const g=cl(s,Jl),m=cl(s,ql);cl(g,Jl,g),sl(g,t.domain,s),sl(m,r,i),sl(m,t.domain,s);const y=Lc(Ac);sl(m,t.tld,y),sl(m,t.utld,y),sl(y,t.domain,s),sl(y,r,i),cl(y,ql,m),cl(y,Jl,g),cl(y,Wl,c);const w=cl(y,Xl),x=Lc(Ac);sl(w,t.numeric,x);const b=Lc(Ac),v=Lc();sl(b,e,b),sl(b,n,v),sl(v,e,b),sl(v,n,v),cl(y,sc,b),cl(x,sc,b);const k=cl(a,Xl),S=cl(cl(cl(l,Xl),sc),sc);sl(a,t.domain,s),cl(a,ql,m),cl(a,Jl,g),sl(l,t.domain,s),cl(l,ql,m),cl(l,Jl,g),sl(k,t.domain,b),cl(k,sc,b),cl(k,nc,b),sl(S,t.domain,b),sl(S,e,b),cl(S,sc,b);const I=[[kl,Sl],[Il,Pl],[Ml,Tl],[Cl,El],[Al,Ll],[Rl,$l],[Nl,Bl],[Ol,zl]];for(let P=0;P<I.length;P++){const[t,r]=I[P],o=cl(b,t);cl(v,t,o);const i=Lc(Ac);sl(o,e,i);const s=Lc();sl(o,n,s),cl(o,r,b),sl(i,e,i),sl(i,n,s),sl(s,e,i),sl(s,n,s),cl(i,r,b),cl(s,r,b)}return cl(o,fl,y),cl(o,vl,Ec),{start:o,tokens:uc}}(Nc.scanner.tokens);for(let t=0;t<Nc.pluginQueue.length;t++)Nc.pluginQueue[t][1]({scanner:Nc.scanner,parser:Nc.parser});return Nc.initialized=!0,Nc}function zc(t){return Nc.initialized||Oc(),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(Rc(Cc,e,s)),s=[]),o-=p,d-=p;const t=u.t,r=n.slice(o-d,o);i.push(Rc(t,e,r))}}return s.length>0&&i.push(Rc(Cc,e,s)),i}(Nc.parser.start,t,xc(Nc.scanner.start,t))}function Hc(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 Sc(n),o=zc(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}zc.scan=xc;var Dc="[\0- -\u2029 ]",Fc=new RegExp(Dc),Wc=new RegExp(`${Dc}$`),jc=new RegExp(Dc,"g");function Uc(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(jc,"").match(new RegExp(`^(?:(?:${n.map(t=>t.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")).join("|")}):|[^a-z]|[a-z0-9+.\\-]+(?:[^a-z+.\\-:]|$))`,"i"))}var Kc=C.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?Bc(t.scheme,t.optionalSlashes):Bc(t)})},onDestroy(){il.groups={},Nc.scanner=null,Nc.parser=null,Nc.tokenQueue=[],Nc.pluginQueue=[],Nc.customSchemes=[],Nc.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)=>!!Uc(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=>!!Uc(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol}))&&null}}]},renderHTML({HTMLAttributes:t}){return this.options.isAllowedUri(t.href,{defaultValidate:t=>!!Uc(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=>!!Uc(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=>!!Uc(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[G({find:t=>{const e=[];if(t){const{protocols:n,defaultProtocol:r}=this.options,o=Hc(t).filter(t=>t.isLink&&this.options.isAllowedUri(t.value,{defaultValidate:t=>!!Uc(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=>!!Uc(t,e),protocols:e,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink},new ot({key:new it("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 O(R(e.doc,[...t])).forEach(({newRange:t})=>{const e=N(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(!Wc.test(r))return;o=e[0],i=n.doc.textBetween(o.pos,t.to,void 0," ")}if(o&&i){const t=i.split(Fc).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=zc(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=>{H(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 ot({key:new it("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=B(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 ot({key:new it("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=Hc(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}}),Xc=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Yc=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,_c=C.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[q({find:Xc,type:this.type})]},addPasteRules(){return[G({find:Yc,type:this.type})]}}),qc=T.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")}}}),Gc=(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(...Gc(t,e+1))}),n},Vc=C.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=Gc(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}}}}),Jc=T.create({name:"backgroundColor",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{backgroundColor:{default:null,parseHTML:t=>{var e;const n=null!=(e=j(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()})}),Zc=T.create({name:"color",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{color:{default:null,parseHTML:t=>{var e;const n=null!=(e=j(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()})}),Qc=T.create({name:"fontFamily",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{fontFamily:{default:null,parseHTML:t=>{var e;return null!=(e=j(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()})}),td=T.create({name:"fontSize",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{fontSize:{default:null,parseHTML:t=>{var e;return null!=(e=j(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()})}),ed=T.create({name:"lineHeight",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{lineHeight:{default:null,parseHTML:t=>{var e;return null!=(e=j(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()})}),nd=(T.create({name:"textStyleKit",addExtensions(){const t=[];return!1!==this.options.backgroundColor&&t.push(Jc.configure(this.options.backgroundColor)),!1!==this.options.color&&t.push(Zc.configure(this.options.color)),!1!==this.options.fontFamily&&t.push(Qc.configure(this.options.fontFamily)),!1!==this.options.fontSize&&t.push(td.configure(this.options.fontSize)),!1!==this.options.lineHeight&&t.push(ed.configure(this.options.lineHeight)),!1!==this.options.textStyle&&t.push(Vc.configure(this.options.textStyle)),t}}),C.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()}}})),rd=T.create({name:"selection",addOptions:()=>({className:"selection"}),addProseMirrorPlugins(){const{editor:t,options:e}=this;return t.options.injectCSS&&"undefined"!=typeof document&&$(".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 ot({key:new it("selection"),props:{decorations:n=>n.selection.empty||t.isFocused||!t.isEditable||_(n.selection)||t.view.dragging?null:ct.create(n.doc,[lt.inline(n.selection.from,n.selection.to,{class:e.className})])}})]}});function od(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&&ad(t.charCodeAt(r-1))&&sd(t.charCodeAt(r))&&n--,n}if(o.content.size||i.content.size){let t=od(o.content,i.content,n+1);if(null!=t)return t}n+=o.nodeSize}else n+=o.nodeSize}}function id(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&&ad(t.charCodeAt(o-1))&&sd(t.charCodeAt(o))&&(n++,r++),{a:n,b:r}}if(s.content.size||a.content.size){let t=id(s.content,a.content,n-1,r-1);if(t)return t}n-=l,r-=l}else n-=l,r-=l}}function sd(t){return t>=56320&&t<57344}function ad(t){return t>=55296&&t<56320}var ld=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 od(this,t,e)}findDiffEnd(t,e=this.size,n=t.size){return id(this,t,e,n)}findIndex(t){if(0==t)return dd(0,t);if(t==this.size)return dd(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?dd(e+1,r):dd(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)":""))}};ld.empty=new ld([],0);var cd={index:0,offset:0};function dd(t,e){return cd.index=t,cd.offset=e,cd}function ud(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(!ud(t[n],e[n]))return!1}else{for(let n in t)if(!(n in e)||!ud(t[n],e[n]))return!1;for(let n in e)if(!(n in t))return!1}return!0}var pd=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&&ud(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}};pd.none=[];var hd=class extends Error{},fd=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=md(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(gd(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(ld.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 gd(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(gd(i.content,e-o-1,n-o-1)))}function md(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=md(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))}fd.empty=new fd(ld.empty,0,0);var yd=class t{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new wd(e,n);if(null==r.next)return t.empty;let o=xd(r);r.next&&r.err("Unexpected trailing text");let i=function(t){let e=Object.create(null);return n(Pd(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]);Pd(t,n).forEach(t=>{r||o.push([e,r=[]]),-1==r.indexOf(t)&&r.push(t)})})});let i=e[r.join(",")]=new yd(r.indexOf(t.length-1)>-1);for(let t=0;t<o.length;t++){let r=o[t][1].sort(Id);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 ld.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")}};yd.empty=new yd(!0);var wd=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 xd(t){let e=[];do{e.push(bd(t))}while(t.eat("|"));return 1==e.length?e[0]:{type:"choice",exprs:e}}function bd(t){let e=[];do{e.push(vd(t))}while(t.next&&")"!=t.next&&"|"!=t.next);return 1==e.length?e[0]:{type:"seq",exprs:e}}function vd(t){let e=function(t){if(t.eat("(")){let e=xd(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=Sd(t,e)}return e}function kd(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function Sd(t,e){let n=kd(t),r=n;return t.eat(",")&&(r="}"!=t.next?kd(t):-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function Id(t,e){return e-t}function Pd(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(Id)}var Md=Math.pow(2,16);function Td(t,e){return t+e*Md}function Cd(t){return 65535&t}var Ed=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}},Ad=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=Cd(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))/Md}(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:Td(s/3,t-a),u=t==a?2:t==d?1:4;return(e<0?t!=a:t!=d)&&(u|=8),new Ed(o,u,i)}r+=c-l}return n?t+r:new Ed(t+r,0,null)}touches(t,e){let n=0,r=Cd(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])}};Ad.empty=new Ad([]);var Ld=Object.create(null),Rd=class{getMap(){return Ad.empty}merge(t){return null}static fromJSON(t,e){if(!e||!e.stepType)throw new RangeError("Invalid input for Step.fromJSON");let n=Ld[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 Ld)throw new RangeError("Duplicate use of step JSON ID "+t);return Ld[t]=e,e.prototype.jsonID=t,e}},$d=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(Ve){if(Ve instanceof hd)return t.fail(Ve.message);throw Ve}}};function Nd(t,e,n){let r=[];for(let o=0;o<t.childCount;o++){let i=t.child(o);i.content.size&&(i=i.copy(Nd(i.content,e,i))),i.isInline&&(i=e(i,n,o)),r.push(i)}return ld.fromArray(r)}var Bd=class t extends Rd{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 fd(Nd(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 $d.fromReplace(t,this.from,this.to,o)}invert(){return new Od(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))}};Rd.jsonID("addMark",Bd);var Od=class t extends Rd{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 fd(Nd(e.content,t=>t.mark(this.mark.removeFromSet(t.marks)),t),e.openStart,e.openEnd);return $d.fromReplace(t,this.from,this.to,n)}invert(){return new Bd(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))}};Rd.jsonID("removeMark",Od);var zd=class t extends Rd{constructor(t,e){super(),this.pos=t,this.mark=e}apply(t){let e=t.nodeAt(this.pos);if(!e)return $d.fail("No node at mark step's position");let n=e.type.create(e.attrs,null,this.mark.addToSet(e.marks));return $d.fromReplace(t,this.pos,this.pos+1,new fd(ld.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 Hd(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))}};Rd.jsonID("addNodeMark",zd);var Hd=class t extends Rd{constructor(t,e){super(),this.pos=t,this.mark=e}apply(t){let e=t.nodeAt(this.pos);if(!e)return $d.fail("No node at mark step's position");let n=e.type.create(e.attrs,null,this.mark.removeFromSet(e.marks));return $d.fromReplace(t,this.pos,this.pos+1,new fd(ld.from(n),0,e.isLeaf?0:1))}invert(t){let e=t.nodeAt(this.pos);return e&&this.mark.isInSet(e.marks)?new zd(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))}};Rd.jsonID("removeNodeMark",Hd);var Dd=class t extends Rd{constructor(t,e,n,r=!1){super(),this.from=t,this.to=e,this.slice=n,this.structure=r}apply(t){return this.structure&&Wd(t,this.from,this.to)?$d.fail("Structure replace would overwrite content"):$d.fromReplace(t,this.from,this.to,this.slice)}getMap(){return new Ad([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?fd.empty:new fd(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?fd.empty:new fd(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,fd.fromJSON(e,n.slice),!!n.structure)}};Dd.MAP_BIAS=1,Rd.jsonID("replace",Dd);var Fd=class t extends Rd{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&&(Wd(t,this.from,this.gapFrom)||Wd(t,this.gapTo,this.to)))return $d.fail("Structure gap-replace would overwrite content");let e=t.slice(this.gapFrom,this.gapTo);if(e.openStart||e.openEnd)return $d.fail("Gap is not a flat range");let n=this.slice.insertAt(this.insert,e.content);return n?$d.fromReplace(t,this.from,this.to,n):$d.fail("Content does not fit in gap")}getMap(){return new Ad([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,fd.fromJSON(e,n.slice),n.insert,!!n.structure)}};function Wd(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}Rd.jsonID("replaceAround",Fd);Rd.jsonID("attr",class t extends Rd{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 $d.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 $d.fromReplace(t,this.pos,this.pos+1,new fd(ld.from(r),0,e.isLeaf?0:1))}getMap(){return Ad.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)}});Rd.jsonID("docAttr",class t extends Rd{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 $d.ok(n)}getMap(){return Ad.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 jd=Error;((jd=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n}).prototype=Object.create(Error.prototype)).constructor=jd,jd.prototype.name="TransformError";var Ud=Object.create(null),Kd=class{constructor(t,e,n){this.$anchor=t,this.$head=e,this.ranges=n||[new Xd(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=fd.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?fd.empty:e),0==s&&eu(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),eu(t,n,e.isInline?-1:1))}}static findFrom(t,e,n=!1){let r=t.parent.inlineContent?new qd(t):tu(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?tu(t.node(0),t.node(o),t.before(o+1),t.index(o),e,n):tu(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 Zd(t.node(0))}static atStart(t){return tu(t,t,0,0,1)||new Zd(t)}static atEnd(t){return tu(t,t,t.content.size,t.childCount,-1)||new Zd(t)}static fromJSON(t,e){if(!e||!e.type)throw new RangeError("Invalid input for Selection.fromJSON");let n=Ud[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 Ud)throw new RangeError("Duplicate use of selection JSON ID "+t);return Ud[t]=e,e.prototype.jsonID=t,e}getBookmark(){return qd.between(this.$anchor,this.$head).getBookmark()}};Kd.prototype.visible=!0;var Xd=class{constructor(t,e){this.$from=t,this.$to=e}},Yd=!1;function _d(t){Yd||t.parent.inlineContent||(Yd=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}var qd=class t extends Kd{constructor(t,e=t){_d(t),_d(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 Kd.near(r);let o=e.resolve(n.map(this.anchor));return new t(o.parent.inlineContent?o:r,r)}replace(t,e=fd.empty){if(super.replace(t,e),e==fd.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 Gd(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=Kd.findFrom(n,r,!0)||Kd.findFrom(n,-r,!0);if(!t)return Kd.near(n,r);n=t.$head}return e.parent.inlineContent||(0==o||(e=(Kd.findFrom(e,-r,!0)||Kd.findFrom(e,r,!0)).$anchor).pos<n.pos!=o<0)&&(e=n),new t(e,n)}};Kd.jsonID("text",qd);var Gd=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 qd.between(t.resolve(this.anchor),t.resolve(this.head))}},Vd=class t extends Kd{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?Kd.near(i):new t(i)}content(){return new fd(ld.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 Jd(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}};Vd.prototype.visible=!1,Kd.jsonID("node",Vd);var Jd=class t{constructor(t){this.anchor=t}map(e){let{deleted:n,pos:r}=e.mapResult(this.anchor);return n?new Gd(r,r):new t(r)}resolve(t){let e=t.resolve(this.anchor),n=e.nodeAfter;return n&&Vd.isSelectable(n)?new Vd(e):Kd.near(e)}},Zd=class t extends Kd{constructor(t){super(t.resolve(0),t.resolve(t.content.size))}replace(t,e=fd.empty){if(e==fd.empty){t.delete(0,t.doc.content.size);let e=Kd.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 Qd}};Kd.jsonID("all",Zd);var Qd={map(){return this},resolve:t=>new Zd(t)};function tu(t,e,n,r,o,i=!1){if(e.inlineContent)return qd.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&&Vd.isSelectable(r))return Vd.create(t,n-(o<0?r.nodeSize:0))}else{let e=tu(t,r,n+o,o<0?r.childCount:0,o,i);if(e)return e}n+=r.nodeSize*o}return null}function eu(t,e,n){let r=t.steps.length-1;if(r<e)return;let o,i=t.steps[r];(i instanceof Dd||i instanceof Fd)&&(t.mapping.maps[r].forEach((t,e,n,r)=>{null==o&&(o=r)}),t.setSelection(Kd.near(t.doc.resolve(o),n)))}function nu(t,e){return e&&t?t.bind(e):t}var ru=class{constructor(t,e,n){this.name=t,this.init=nu(e.init,n),this.apply=nu(e.apply,n)}};new ru("doc",{init:t=>t.doc||t.schema.topNodeType.createAndFill(),apply:t=>t.doc}),new ru("selection",{init:(t,e)=>t.selection||Kd.atStart(e.doc),apply:t=>t.selection}),new ru("storedMarks",{init:t=>t.storedMarks||null,apply:(t,e,n,r)=>r.selection.$cursor?t.storedMarks:null}),new ru("scrollToSelection",{init:()=>0,apply:(t,e)=>t.scrolledIntoView?e+1:e});var ou=/^\s*>\s$/,iu=E.create({name:"blockquote",addOptions:()=>({HTMLAttributes:{}}),content:"block+",group:"block",defining:!0,parseHTML:()=>[{tag:"blockquote"}],renderHTML({HTMLAttributes:t}){
|
|
12
|
-
return nt("blockquote",{...V(this.options.HTMLAttributes,t),children:nt("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(qd.create(h.doc,p)),o.dispatch(h.scrollIntoView()),!0})(this.editor,this.type)}},addInputRules(){return[et({find:ou,type:this.type})]}}),su=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},au=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},lu=C.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[q({find:su,type:this.type})]},addPasteRules(){return[G({find:au,type:this.type})]}}),cu=/^```([a-z]+)?[\s\n]$/,du=/^~~~([a-z]+)?[\s\n]$/,uu=E.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(at.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(st.near(r.resolve(s))),!0)):t.commands.exitCode())}}},addInputRules(){return[tt({find:cu,type:this.type,getAttributes:t=>({language:t[1]})}),tt({find:du,type:this.type,getAttributes:t=>({language:t[1]})})]},addProseMirrorPlugins(){return[new ot({key:new it("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(at.near(s.doc.resolve(Math.max(0,s.selection.from-2)))),s.setMeta("paste",!0),t.dispatch(s),!0}}})]}}),pu=E.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,"\n\n"):""}),hu=E.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()}}}),fu=E.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=>tt({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${t}})\\s$`),type:this.type,getAttributes:{level:t}}))}}),gu=E.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(!L(e,e.schema.nodes[this.name]))return!1;const{selection:n}=e,{$to:r}=n,o=t();return _(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(at.create(e.doc,n.pos+1)):n.nodeAfter.isBlock?e.setSelection(rt.create(e.doc,n.pos)):e.setSelection(at.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(at.create(e.doc,r+1)))}e.scrollIntoView()}return!0}).run()}}},addInputRules(){return[J({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),mu=Object.defineProperty,yu="textStyle",wu=/^\s*([-+*])\s$/,xu=E.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(yu)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let t=et({find:wu,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(t=et({find:wu,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(yu),editor:this.editor})),[t]}}),bu=(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,dt.from(c)),d.setSelection(i.map(d.doc,d.mapping)),e&&e(d),!0})(t.state,t.view.dispatch,e,n),vu=(t,e)=>T.create({name:`${t}BranchingDeleteKeymap`,priority:101,addKeyboardShortcuts(){const n=()=>bu(this.editor,t,e);return{Delete:n,"Mod-Delete":n}}}),ku=[[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"]],Su="abcdefghijklmnopqrstuvwxyz",Iu=String.raw`\d+|[ivxlcdmIVXLCDM]+|${"[a-zA-Z]{1,2}"}`;function Pu(t){let e=t,n="";for(const[r,o]of ku)for(;e>=r;)n+=o,e-=r;return n}function Mu(t){return Pu(t).toUpperCase()}function Tu(t){const e=t.toLowerCase();let n=0,r=0;for(;n<e.length;){let t=!1;for(const[o,i]of ku)if(e.startsWith(i,n)){r+=o,n+=i.length,t=!0;break}if(!t)return 0}return r}function Cu(t){if(t<=26)return Su[t-1];const e=Math.floor((t-1)/26)-1,n=(t-1)%26;return e<0?Su[n]:Su[e]+Su[n]}function Eu(t){if(t&&!/^\d+$/.test(t))return function(t){if(!/^[ivxlcdmIVXLCDM]+$/.test(t))return!1;const e=Tu(t);return!(e<=0)&&(t===t.toLowerCase()?Pu(e):Mu(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 Au(t){if(/^\d+$/.test(t))return parseInt(t,10);const e=Eu(t);if("i"===e||"I"===e)return Tu(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 Lu(t,e){if("numeric"===t)return String(e);switch(t){case"a":return Cu(e);case"A":return Cu(e).toUpperCase();case"i":return Pu(e);case"I":return Mu(e);default:return String(e)}}function Ru(t){const{type:e,start:n}=function(t){return{type:Eu(t),start:Au(t)}}(t),r={};return e&&(r.type=e),1!==n&&(r.start=n),r}function $u(t,e){return e.tokenizeInline?e.parseInline(e.tokenizeInline(t)):e.parseInline([{type:"text",raw:t,text:t}])}var Nu=E.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:$u(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)=>Q(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`${Cu(r)}${n}`;case"A":return`${Cu(r).toUpperCase()}${n}`;case"i":return`${Pu(r)}${n}`;case"I":return`${Mu(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[vu(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)mu(t,n,{get:e[n],enumerable:!0})})({},{findListItemPos:()=>Bu,getNextListDepth:()=>Ou,handleBackspace:()=>Hu,handleDelete:()=>Wu,hasListBefore:()=>zu,hasListItemAfter:()=>ju,hasListItemBefore:()=>Uu,listItemHasSubList:()=>Ku,nextListIsDeeper:()=>Du,nextListIsHigher:()=>Fu});var Bu=(t,e)=>{const{$from:n}=e.selection,r=F(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}},Ou=(t,e)=>{const n=Bu(t,e);if(!n)return!1;const[,r]=D(e,t,n.$pos.pos+4);return r},zu=(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))},Hu=(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)&&zu(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)&&(!!K(t.state)&&t.chain().liftListItem(e).run())},Du=(t,e)=>{const n=Ou(t,e),r=Bu(t,e);return!(!r||!n)&&n>r.depth},Fu=(t,e)=>{const n=Ou(t,e),r=Bu(t,e);return!(!r||!n)&&n<r.depth},Wu=(t,e)=>{if(!X(t.state,e))return!1;if(!U(t.state,e))return!1;const{selection:n}=t.state,{$from:r,$to:o}=n;return!(!n.empty&&r.sameParent(o))&&(Du(e,t.state)?t.chain().focus(t.state.selection.from+4).lift(e).joinBackward().run():Fu(e,t.state)?t.chain().joinForward().joinBackward().run():t.commands.joinItemForward())},ju=(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},Uu=(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},Ku=(t,e,n)=>{if(!n)return!1;const r=F(t,e.schema);let o=!1;return n.descendants(t=>{t.type===r&&(o=!0)}),o},Xu=T.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]&&Wu(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]&&Wu(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]&&Hu(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]&&Hu(t,n,r)&&(e=!0)}),e}}}}),Yu=new RegExp(`^(\\s*)(${Iu})([.)])\\s+(.*)$`),_u=new RegExp(`^(\\s*)(${Iu})([.)])\\s+`),qu=/^\s/,Gu={heading:/^#{1,6}(?:\s|$)/,bulletItem:/^[-+*]\s+/,codeFence:/^(?:```|~~~)/,thematicBreak:/^(?:(?:-[ \t]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})$/};function Vu(t){const e=t.trimStart();return Gu.bulletItem.test(e)||function(t){return Yu.test(t.trimStart())}(e)||Gu.heading.test(e)||Gu.thematicBreak.test(e)&&!e.startsWith("-")||/^>\s?/.test(e)||Gu.codeFence.test(e)}function Ju(t){return Object.values(Gu).some(e=>e.test(t))}function Zu(t){const e=[],n=[];let r=!1;return t.forEach(t=>{if(!r)return""===t.trim()||e.length>0&&Vu(t)?(r=!0,void n.push(t)):void e.push(t);n.push(t)}),{paragraphLines:e,blockLines:n}}var Qu=new RegExp(`^(${Iu})([.)])\\s+(.+)$`);function tp(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(Qu);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=Eu(t[0]))?e:"numeric",r=Au(t[0]);if(r<1)return!1;for(let o=0;o<t.length;o++){const e=Lu(n,r+o);if(t[o]!==e)return!1}return!0}(n.map(t=>t.marker))?{type:"orderedList",attrs:Ru(n[0].marker),content:n.map(t=>({type:"listItem",content:[{type:"paragraph",content:[{type:"text",text:t.content}]}]}))}:null}function ep(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}=Zu(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=ep(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 np="textStyle",rp=/^(\d+)\.\s$/;function op(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 ip=E.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=op(n);if(t)return t}const r=t.querySelector("li");if(r){const t=r.getAttribute("style");if(t){const e=op(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(_u),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(Yu);if(!i)break;const[,s,a,l,c]=i,d=s.length,u=parseInt(a,10),p=isNaN(u)?Eu(a):void 0,h=isNaN(u)?Au(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(Yu))break;if(""===e.trim())m.push(e),f.push(""),y=!0,g+=1;else if(e.match(qu)){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||Ju(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=ep(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(np)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addProseMirrorPlugins:()=>[new ot({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=tp(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=et({find:rp,type:this.type,getAttributes:t=>({start:+t[1]}),joinPredicate:t});return(this.options.keepMarks||this.options.keepAttributes)&&(e=et({find:rp,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(np)}),joinPredicate:t,editor:this.editor})),[e]}}),sp=/^\s*(\[([( |x])?\])\s$/,ap=E.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 Q(t,e,`- [${(null==(n=t.attrs)?void 0:n.checked)?"x":" "}] `)},addExtensions(){return this.options.nested?[vu(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=W(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[et({find:sp,type:this.type,getAttributes:t=>({checked:"x"===t[t.length-1]})})]}}),lp=E.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=Z(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=Z(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()}}}),cp=(T.create({name:"listKit",addExtensions(){const t=[];return!1!==this.options.bulletList&&t.push(xu.configure(this.options.bulletList)),!1!==this.options.listItem&&t.push(Nu.configure(this.options.listItem)),!1!==this.options.listKeymap&&t.push(Xu.configure(this.options.listKeymap)),!1!==this.options.orderedList&&t.push(ip.configure(this.options.orderedList)),!1!==this.options.taskItem&&t.push(ap.configure(this.options.taskItem)),!1!==this.options.taskList&&t.push(lp.configure(this.options.taskList)),t}})," "),dp=E.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!==cp&&n[0].text!==cp&&" "!==n[0].raw&&" "!==n[0].text||1!==r.length||"text"!==r[0].type||r[0].text!==cp&&" "!==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?cp:""}return e.renderChildren(i)},addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),up=E.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""}),pp=(T.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 ot({key:new it("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)}})]}}),T.create({name:"dropCursor",addOptions:()=>({color:"currentColor",width:1,class:void 0}),addProseMirrorPlugins(){return[ut(this.options)]}})),hp=(T.create({name:"focus",addOptions:()=>({className:"has-focus",mode:"all"}),addProseMirrorPlugins(){return[new ot({key:new it("focus"),props:{decorations:({doc:t,selection:e})=>{const{isEditable:n,isFocused:r}=this.editor,{anchor:o}=e,i=[];if(!n||!r)return ct.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(lt.node(e,e+t.nodeSize,{class:this.options.className}))))),ct.create(t,i)}}})]}}),T.create({name:"gapCursor",addProseMirrorPlugins:()=>[pt()],extendNodeSchema(t){var e;return{allowGapCursor:null!=(e=A(z(t,"allowGapCursor",{name:t.name,options:t.options,storage:t.storage})))?e:null}}})),fp="placeholder",gp=new it("tiptap__placeholder");function mp(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),lt.node(o,o+i.nodeSize,{class:d.join(" "),[r]:"function"==typeof n?n({editor:e,node:i,pos:o,hasAnchor:a}):n})}function yp(t,e){return"function"==typeof t?t(e):t}function wp({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(mp({editor:t,isEmptyDoc:c,dataAttribute:n,hasAnchor:i,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:yp(e.emptyNodeClass,{editor:t,node:r,pos:o,hasAnchor:i})},node:r,pos:o})),e.includeChildren):e.includeChildren}),l}function xp({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(mp({editor:t,isEmptyDoc:a,dataAttribute:n,hasAnchor:r,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:yp(e.emptyNodeClass,{editor:t,node:l,pos:c,hasAnchor:r})},node:l,pos:c}))}}else s.push(...wp({editor:t,options:e,dataAttribute:n,doc:r,selection:o,from:0,to:r.content.size}));return ct.create(r,s)}function bp(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 vp(t,e){return{from:Math.max(0,e.from-1),to:Math.min(t.content.size,e.to-1)}}function kp(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(vp(t,bp(t,e.from))),e.to>e.from?n.push(vp(t,bp(t,Math.min(e.to,t.content.size+1)-1))):e.from<t.content.size+1&&n.push(vp(t,bp(t,Math.min(e.from+1,t.content.size)))),n}function Sp(t,e,n){const r=[];if(t.docChanged){const e=O(t);for(const t of e)r.push(...kp(n.doc,t.newRange))}return t.selectionSet&&(r.push(vp(n.doc,bp(n.doc,t.mapping.map(e.selection.anchor)))),r.push(vp(n.doc,bp(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 Ip(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 Pp({editor:t,options:e,dataAttribute:n}){return{init(r,o){const i=xp({editor:t,options:e,dataAttribute:n,doc:o.doc,selection:o.selection});return null!=i?i:ct.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}=Ip(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=wp({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:Sp(r,i,s),editor:t,options:e,dataAttribute:n,doc:s.doc,selection:s.selection}):o}}function Mp({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-${fp}`;var r;const o=e.showOnlyCurrent&&!e.includeChildren;return new ot({key:gp,...o?{}:{state:Pp({editor:t,options:e,dataAttribute:n})},props:{decorations:o?({doc:r,selection:o})=>xp({editor:t,options:e,dataAttribute:n,doc:r,selection:o}):n=>{var r;return e.showOnlyWhenEditable&&!t.isEditable?ct.empty:null!=(r=gp.getState(n))?r:ct.empty}}})}T.create({name:"placeholder",addOptions:()=>({emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:fp,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}),addProseMirrorPlugins(){return[Mp({editor:this.editor,options:this.options})]}}),T.create({name:"selection",addOptions:()=>({className:"selection"}),addProseMirrorPlugins(){const{editor:t,options:e}=this;return t.options.injectCSS&&"undefined"!=typeof document&&$(".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 ot({key:new it("selection"),props:{decorations:n=>n.selection.empty||t.isFocused||!t.isEditable||_(n.selection)||t.view.dragging?null:ct.create(n.doc,[lt.inline(n.selection.from,n.selection.to,{class:e.className})])}})]}});function Tp({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||(null==e?void 0:e.type)===t}var Cp=T.create({name:"trailingNode",addOptions:()=>({node:void 0,notAfter:[]}),addProseMirrorPlugins(){var t;const e=new it(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 ot({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)=>!Tp({node:e.tr.doc.lastChild,types:r}),apply:(t,e)=>{if(!t.docChanged)return e;if(t.getMeta("__uniqueIDTransaction"))return e;return!Tp({node:t.doc.lastChild,types:r})}}})]}}),Ep=T.create({name:"undoRedo",addOptions:()=>({depth:100,newGroupDelay:500}),addCommands:()=>({undo:()=>({state:t,dispatch:e})=>gt(t,e),redo:()=>({state:t,dispatch:e})=>ft(t,e)}),addProseMirrorPlugins(){return[ht(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()}}}),Ap=T.create({name:"starterKit",addExtensions(){var t,e,n,r;const o=[];return!1!==this.options.bold&&o.push(Wa.configure(this.options.bold)),!1!==this.options.blockquote&&o.push(iu.configure(this.options.blockquote)),!1!==this.options.bulletList&&o.push(xu.configure(this.options.bulletList)),!1!==this.options.code&&o.push(lu.configure(this.options.code)),!1!==this.options.codeBlock&&o.push(uu.configure(this.options.codeBlock)),!1!==this.options.document&&o.push(pu.configure(this.options.document)),!1!==this.options.dropcursor&&o.push(pp.configure(this.options.dropcursor)),!1!==this.options.gapcursor&&o.push(hp.configure(this.options.gapcursor)),!1!==this.options.hardBreak&&o.push(hu.configure(this.options.hardBreak)),!1!==this.options.heading&&o.push(fu.configure(this.options.heading)),!1!==this.options.undoRedo&&o.push(Ep.configure(this.options.undoRedo)),!1!==this.options.horizontalRule&&o.push(gu.configure(this.options.horizontalRule)),!1!==this.options.italic&&o.push(Ya.configure(this.options.italic)),!1!==this.options.listItem&&o.push(Nu.configure(this.options.listItem)),!1!==this.options.listKeymap&&o.push(Xu.configure(null==(t=this.options)?void 0:t.listKeymap)),!1!==this.options.link&&o.push(Kc.configure(null==(e=this.options)?void 0:e.link)),!1!==this.options.orderedList&&o.push(ip.configure(this.options.orderedList)),!1!==this.options.paragraph&&o.push(dp.configure(this.options.paragraph)),!1!==this.options.strike&&o.push(_c.configure(this.options.strike)),!1!==this.options.text&&o.push(up.configure(this.options.text)),!1!==this.options.underline&&o.push(nd.configure(null==(n=this.options)?void 0:n.underline)),!1!==this.options.trailingNode&&o.push(Cp.configure(null==(r=this.options)?void 0:r.trailingNode)),o}}),Lp=new WeakMap;function Rp(t){return Lp.get(t)?.api??null}function $p(t){const e=Lp.get(t);if(e)return e;const n={api:null,disposeApiSubscription:null,listeners:new Set};return Lp.set(t,n),n}function Np(t){for(const e of t.listeners)e()}function Bp(t){const e=t.content.map(t=>"orderedList"===t.type||"bulletList"===t.type||"taskList"===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 Op(t,e){if(Bp(t)===e)return t;if("taskList"===e){const e=Kp(t.content);return Ss({...t,content:[{type:"taskList",content:e.length>0?e:[{type:"taskItem",attrs:{checked:!1},content:[{type:"paragraph"}]}]}]})}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)};for(const r of Xp(t))n(r);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 Ss({...t,content:r})}var zp={bold:["bold","strong"],italic:["italic","em"],strike:["strike","s"],underline:["underline","u"]};function Hp(t,e){const n=zp[e];let r=!1,o=!1;return Yp(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 Dp(t,e,n){const r=zp[e],o=_p(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?Ss({...t,content:o.nodes}):t}function Fp(t,e){const n=_p(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?Ss({...t,content:n.nodes}):t}function Wp(t,e){const n=_p(t.content,t=>{if("textAlign"===e)return Up(t);if("text"!==t.type||!t.marks)return t;let n=!1;const r=t.marks.flatMap(t=>{if("textStyle"!==t.type||!t.attrs)return[t];const r={...t.attrs};let o=!1;const i="size"===e?["fontSize"]:"font"===e?["fontFamily"]:"lineHeight"===e?["lineHeight"]:["color"];for(const e of i)e in r&&(delete r[e],o=!0);return o?(n=!0,Object.keys(r).length>0?[{...t,attrs:r}]:[]):[t]});return n?{...t,marks:r.length>0?r:void 0}:t});return n.changed?Ss({...t,content:n.nodes}):t}function jp(t){const e=_p(t.content,t=>"text"===t.type&&t.marks&&t.marks.length>0?{...t,marks:void 0}:Up(t));return e.changed?Ss({...t,content:e.nodes}):t}function Up(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}}function Kp(t){const e=[];for(const n of Xp(t))"taskItem"===n.type?e.push(n):"paragraph"===n.type||"codeBlock"===n.type?e.push({type:"taskItem",attrs:{checked:!1},content:[{...n,type:"paragraph"}]}):e.push(...Kp(n.content??[]));return e}function Xp(t){const e=t.at(-1);return t.length>1&&"paragraph"===e?.type&&0===(e.content?.length??0)&&t.slice(0,-1).some(t=>"orderedList"===t.type||"bulletList"===t.type||"taskList"===t.type||"blockquote"===t.type)?t.slice(0,-1):t}function Yp(t,e,n=!1){for(const r of t)e(r,{insideCodeBlock:n}),r.content&&Yp(r.content,e,n||"codeBlock"===r.type)}function _p(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=_p(i,e,n||"codeBlock"===o.type);return s.changed?(r=!0,{...o,content:s.nodes}):(o!==t&&(r=!0),o)}),changed:r}}function qp(t){try{return t.view.dom.isConnected}catch{return!1}}function Gp(t){!t.isDestroyed&&qp(t)&&(t.view.dom.focus(),t.view.focus())}function Vp(t){if(!qp(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")}}function Jp(t,e,n,r){if(0===t.getText().trim().length&&!vs(t.getJSON()))return th(e,r);const o=function(t,e){const n=t.ownerDocument.defaultView?.getComputedStyle(t);return ih(t.ownerDocument).measureElement(t,e,n)}(t.view.dom,{shape:e,fontCatalog:n,...nh(e,r)});return!r&&t.view.dom.scrollHeight>e.props.h+1&&(o.h=Math.max(o.h,t.view.dom.scrollHeight)),eh(e,o,r)}function Zp(t,e,n,r){return Qp(t,e,n,r)}function Qp(t,e,n,r){return 0!==bs(t).trim().length||vs(t)?eh(e,(o=function(t){return t.content.map(t=>As(t)).join("")}(t),i={...nh(e,r),shape:e,fontCatalog:n},ih(document).measureHtml(o,i)),r):th(e,r);var o,i}function th(t,e){const n=e?e.minWidth:t.props.autoSize?16:t.props.w,r=fa(t.props.size,t.props.lineHeight)+2*sa(t.props.padding).y;if(t.props.w!==n||t.props.h!==r)return{w:n,h:r}}function eh(t,e,n){const r=sa(t.props.padding),o=n?Math.min(n.maxWidth,Math.max(n.minWidth,Math.ceil(e.w+2*(n.paddingInline+r.x)))):t.props.autoSize?Math.max(16,Math.ceil(e.w+2*r.x)):t.props.w,i=Math.max(fa(t.props.size,t.props.lineHeight)+2*r.y,Math.ceil(e.h+2*r.y));if(o!==t.props.w||i!==t.props.h)return{w:o,h:i}}function nh(t,e){if(e){const n=Sa(e,e.maxWidth)+sa(t.props.padding).x,r=Math.max(1,e.maxWidth-2*n);return e.minWidth===e.maxWidth?{width:r}:{maxWidth:r}}return t.props.autoSize?{}:{width:Math.max(1,t.props.w-2*sa(t.props.padding).x)}}var rh=class{ownerDocument;container;element;htmlElements=new Map;constructor(t){this.ownerDocument=t;const e=this.container=t.createElement("div");e.setAttribute("aria-hidden","true"),e.style.position="fixed",e.style.left="-10000px",e.style.top="0",e.style.width="0",e.style.height="0",e.style.visibility="hidden",e.style.pointerEvents="none",e.style.contain="strict",this.element=t.createElement("div"),e.appendChild(this.element),t.body.appendChild(e)}measureHtml(t,e){const n=e?.shape?.props,r=JSON.stringify([t,e?.width,e?.maxWidth,n&&e?.fontCatalog?da(n.font,e.fontCatalog):null,n?ua(n.size):null,n?ha(n.size,n.lineHeight):null,n?ga(n.textAlign):null,n?Ft(n.color):null]),o=this.htmlElements.get(r);if(o)return this.htmlElements.delete(r),this.htmlElements.set(r,o),this.measurePreparedElement(o);const i=this.prepareElement(e,this.ownerDocument.createElement("div"));if(i.innerHTML=t,this.prepareParagraphs(i),this.container.appendChild(i),this.htmlElements.set(r,i),this.htmlElements.size>256){const t=this.htmlElements.keys().next().value;this.htmlElements.get(t).remove(),this.htmlElements.delete(t)}return this.measurePreparedElement(i)}measureElement(t,e,n){const r=this.prepareElement(e);return r.replaceChildren(...Array.from(t.childNodes).map(t=>t.cloneNode(!0))),sh(r,"whiteSpace",n?.whiteSpace),sh(r,"overflowWrap",n?.overflowWrap),sh(r,"lineHeight",n?.lineHeight),sh(r,"letterSpacing",n?.letterSpacing),sh(r,"textAlign",n?.textAlign),this.prepareParagraphs(r),this.measurePreparedElement(r)}prepareElement(t,e=this.element){return e.removeAttribute("style"),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=Ft(e.props.color),t.style.fontFamily=da(e.props.font,n),t.style.fontSize=`${ua(e.props.size)}px`,t.style.lineHeight=ha(e.props.size,e.props.lineHeight),t.style.textAlign=ga(e.props.textAlign)}(e,t.shape,t.fontCatalog),e.style.position="absolute",e.style.left="0",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}prepareParagraphs(t){t.querySelectorAll("p").forEach(t=>{t instanceof HTMLElement&&(t.style.margin="0")})}measurePreparedElement(t){return[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})}},oh=new WeakMap;function ih(t){const e=oh.get(t);if(e)return e;const n=new rh(t);return oh.set(t,n),n}function sh(t,e,n){n&&"normal"!==n&&"auto"!==n&&(t.style[e]=n)}function ah(t){if(null===t)return null;if("number"==typeof t){const e=Math.round(1e3*t)/1e3;return Number.isFinite(t)&&t>=.5&&t<=10&&Math.abs(t-e)<=Number.EPSILON*Math.max(1,Math.abs(t))?e:void 0}const e="string"==typeof t?/^((?:\d+(?:\.\d{1,3})?)|(?:\.\d{1,3}))(px|%)?$/iu.exec(t.trim()):null;if(!e)return;const n=Number(e[1]),r=e[2]?.toLowerCase();return"px"===r?n>=1&&n<=1024?`${n}px`:void 0:"%"===r?n>=50&&n<=1e3?`${n}%`:void 0:ah(n)}var lh=new WeakMap;function ch(t,e,n={}){const r=ea(e,t),o=n.ownerDocument??("undefined"==typeof document?void 0:document);if(!o||!dh(r.source))return Promise.resolve(!0);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=lh.get(t);if(e)return e;const n=new Map;return lh.set(t,n),n}(o);let a=s.get(i);a||(a=async function(t,e){const{source:n}=e;if(!dh(n))return;if("stylesheet"===n.kind)return void(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,o)=>{const i=t.createElement("link");i.rel="stylesheet",i.href=n.cssUrl,i.dataset.landTextFont=e.id,i.addEventListener("load",()=>r(),{once:!0}),i.addEventListener("error",()=>{i.remove(),o(new Error(`Failed to load text font: ${e.id}`))},{once:!0}),(t.head??t.documentElement).appendChild(i)})}(t,e,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)}(o,r),s.set(i,a));const l=r.source;return a.then(()=>async function(t,e,n){const{fonts:r}=t;if(!r)return;const o=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),i=(e.sampleText??"Aa")+(n??"");await Promise.all(o.map(t=>r.load(`${t} 16px "${e.family}"`,i)))}(o,l,n.text)).then(()=>!0).catch(()=>(s.delete(i),!1))}function dh(t){return!!t&&"system"!==t.kind}function uh(t,e,n){if(e.isDestroyed()||!e.isConnected())return;const r=e.measure(n);r&&hh(t,n,r,"user")}function ph(t,e,n,r="system"){const o=Zp(e.props.richText,e,n,Aa(t,e));o&&hh(t,e,o,r)}function hh(t,e,n,r){const o=t.shapes.get(e.id);Ks(o)&&o.props.w===n.w&&o.props.h===n.h||t.commands.updateShapes([{id:e.id,props:n}],{source:r})}var fh=/[;{}<>\u0000-\u001f\u007f]/u,gh=/(?:url|expression)\s*\(|!\s*important|@\s*import|javascript\s*:/iu;function mh({editor:t,fontCatalog:e,landEditor:n,shapeId:r}){const o=()=>{const t=n.shapes.get(r);return Ks(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=vh(t),i=r.empty?"shape":"selection",s=Wt(n.props.color),a=jt(n.props.backgroundColor)?null:Wt(n.props.backgroundColor),l=n.props.textAlign;return{shapeId:n.id,target:i,bold:Sh(t,o,"bold"),italic:Sh(t,o,"italic"),strike:Sh(t,o,"strike"),underline:Sh(t,o,"underline"),blockType:Ih(t,o),color:Ph(t,o,"color",s),backgroundColor:Ph(t,o,"backgroundColor",0===t.state.doc.textContent.length?a:null),font:Ah(Ph(t,o,"fontFamily",n.props.font),t=>function(t,e){return e.fontOptions.find(e=>e.cssFamily===t)?.id??t}(t,e)),size:Ah(Ph(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)),lineHeight:Mh(t,o,n.props.lineHeight),textAlign:Th(t,o,l),linkHref:Ch(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=be(`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(kh(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("taskList"===e&&"taskList"===Ih(t,vh(t)))return!1;if(n.empty&&t.state.doc.textContent.length>0){const r=t.getJSON(),o=Op(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():"taskList"===e?r.toggleTaskList():"blockquote"===e?r.toggleBlockquote():r.setParagraph();return r.run()}(t,e),setColor(e){if(null!==e&&!Lh(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=wh(t,"color");null!==r&&bh(e,n,{color:Ot(r)});return o||null!==r}({editor:t,landEditor:n,shape:r,color:e})},setBackgroundColor(e){if(null!==e&&!Lh(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 bh(e,n,{backgroundColor:Ot("transparent")}),i(t.chain().focus()).run();const s=i(i(t.chain().focus().selectAll()).setTextSelection(kh(o))).run();return bh(e,n,{backgroundColor:Ot(r??"transparent")}),s}({editor:t,landEditor:n,shape:r,color:e})},setFont(r){const i=o();if(!i)return!1;if(null===r)return yh({editor:t,font:null,fontFamily:null,landEditor:n,shape:i});const s=e.fontOptions.find(t=>t.id===r);return!!s&&(ch(r,e).then(()=>{if(t.isDestroyed)return;const r=o();r&&ph(n,r,e,"system")}),yh({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=t=>null===i?t.unsetFontSize():t.setFontSize(i);if(!o.empty)return s(t.chain().focus()).run();const a=function(t){const e=t.state.selection;let n=t.chain().focus();t.state.doc.textContent.length>0&&(n=n.selectAll());return xh(n.unsetFontSize().setTextSelection(kh(e)).unsetFontSize()).run()}(t);null!==r&&bh(e,n,{size:r});return a||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";case"justify":return"justify";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(kh(i)).run();return bh(e,n,{textAlign:r}),s||n.props.textAlign!==r}({editor:t,landEditor:n,shape:r,align:e})},setLineHeight(e){const r=ah(e),i=o();if(void 0===r||!i||t.isDestroyed)return!1;const s=t.state.selection;if(!s.empty){const e=t.chain().focus();return(null===r?e.unsetLineHeight():e.setLineHeight(String(r))).run()}let a=t.chain().focus();t.state.doc.textContent.length>0&&(a=a.selectAll());const l=xh(a.unsetLineHeight().setTextSelection(kh(s)).unsetLineHeight()).run();return bh(n,i,{lineHeight:r}),l||i.props.lineHeight!==r},setLink(e){if(t.isDestroyed||void 0===t.schema.marks.link)return!1;const n=null===e?null:ds(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(kh(r)).run()},clearFormatting(){if(t.isDestroyed)return!1;const e=o();e&&bh(n,e,{backgroundColor:Ot("transparent")});const r=t.state.selection;return r.empty?t.chain().focus().selectAll().unsetAllMarks().unsetTextAlign().setTextSelection(kh(r)).command(({tr:t})=>(t.setStoredMarks([]),!0)).run():t.chain().focus().unsetAllMarks().unsetTextAlign().run()},getUnsafeTiptapEditor:()=>t.isDestroyed?null:t};return i}function yh({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=wh(t,"fontFamily");return null!==e&&r&&o&&bh(r,o,{font:e}),i||null!==e}function wh(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(kh(n)),r="color"===e?r.unsetColor():r.unsetFontFamily(),xh(r).run()}function xh(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 bh(t,e,n){t.commands.updateShapes([{id:e.id,props:n}],{source:"user"})}function vh(t){const{selection:e,doc:n}=t.state;return e.empty?{from:0,to:n.content.size}:{from:e.from,to:e.to}}function kh(t){return t.from===t.to?t.from:{from:t.from,to:t.to}}function Sh(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):Eh(r)??!1}function Ih(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||"taskList"===e){i=e;break}if("blockquote"===e){i="blockquote";break}}n.push({blockType:i,isEmptyTrailingParagraph:"paragraph"===i&&0===e.content.size})}),Eh((n.some(({blockType:t})=>"paragraph"!==t)?n.filter(({isEmptyTrailingParagraph:t})=>!t):n).map(({blockType:t})=>t))??"paragraph"}function Ph(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 Eh(o)}function Mh(t,e,n){const r=[],o=t=>ah(t.find(t=>"textStyle"===t.type.name)?.attrs.lineHeight)??n;return t.state.doc.nodesBetween(e.from,e.to,t=>{t.isText&&r.push(o(t.marks))}),r.length>0?Eh(r):o(t.state.storedMarks??t.state.selection.$from.marks())}function Th(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";case"justify":return"justify";default:return e}}(t.attrs.textAlign,n))}),Eh(r)??n}function Ch(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 Eh(t){if(0===t.length)return null;const e=t[0];return t.every(t=>Object.is(t,e))?e:"mixed"}function Ah(t,e){return null===t?null:"mixed"===t?"mixed":e(t)}function Lh(t){const e=t.trim();return e.length>0&&e.length<=128&&!fh.test(e)&&!gh.test(e)}function Rh({shapeId:t,editor:e,fontCatalog:n,landEditor:r}){return{shapeId:t,formatting:mh({editor:e,fontCatalog:n,landEditor:r,shapeId:t}),isDestroyed:()=>e.isDestroyed,isConnected:()=>!e.isDestroyed&&qp(e),isFocused:()=>!e.isDestroyed&&qp(e)&&e.view.dom.contains(document.activeElement),getValue:()=>Ss(e.getJSON()),setValue(t){e.commands.setContent(t)},focus(){Gp(e)},focusEnd(){!e.isDestroyed&&qp(e)&&e.commands.focus("end")},focusSelectAll(){!e.isDestroyed&&qp(e)&&(Gp(e),e.chain().focus().selectAll().run())},focusAtPagePoint(t,n){!function(t,e,n){Gp(e);const r=t.viewport.pageToScreen(new Tt(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||!qp(e)?{type:null,text:null}:Vp(e),collapseSelectionAtClientPoint(t,n){!e.isDestroyed&&qp(e)&&("Range"===Vp(e).type&&function(t,e,n){if(t.isDestroyed||!qp(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&&qp(e))return Jp(e,t,n,Aa(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 $h=Kc.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]}}),Nh=[Ap.configure({bold:!1,italic:!1,link:!1,strike:!1,trailingNode:!1,underline:!1}),lp,ap.configure({nested:!0,HTMLAttributes:{"data-type":"taskItem"}}),Wa.extend({keepOnSplit:!0}),Ya.extend({keepOnSplit:!0}),_c.extend({keepOnSplit:!0}),nd.extend({keepOnSplit:!0}),Vc,Zc,Jc,Qc,td,ed,qc.configure({types:["paragraph"],alignments:["left","center","right","justify"]}),rd.configure({className:"land-rich-text-selection"}),$h.configure({autolink:!0,defaultProtocol:"https",openOnClick:!1,protocols:["mailto","land"],HTMLAttributes:{target:"_blank",rel:"noopener noreferrer",class:"land-rich-text-link"}})];function Bh({landEditor:t,shape:e,fontCatalog:n,initialRichText:r,className:o,editorStyle:i,formattingToolbar:s,onTiptapEditorChange:a,onReady:l,onDispose:c,onRichTextChange:u}){const p=k(null),h=jt(e.props.backgroundColor)?null:Wt(e.props.backgroundColor),f=h&&r.content.length>0?function(t,e){const n=_p(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?Ss({...t,content:n.nodes}):t}(r,h):r,g=m(r=>{const o=p.current;if(o?.editor===r)return o.controller;const i=Rh({shapeId:e.id,editor:r,fontCatalog:n,landEditor:t});return p.current={editor:r,controller:i},i},[n,t,e.id]),y=M({extensions:Nh,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 w(()=>{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?()=>{}:function(t,e){const n=$p(t);return n.disposeApiSubscription?.(),n.api=e,n.disposeApiSubscription=e.subscribe(()=>{Np(n)}),Np(n),()=>{n.api===e&&(n.disposeApiSubscription?.(),n.disposeApiSubscription=null,n.api=null,Np(n))}}(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(P,{editor:y,className:o,style:i})}function Oh({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(()=>{Oh({editor:t,controller:e,shapeId:n,request:r,onApplied:o,attempt:i+1})})}}function zh({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=m(({controller:n,richText:r})=>{if(a.current||!n.isConnected())return;const c=Ss(r);s.current=c,qs(t,e.id,c,n.measure(o.current)??Zp(c,o.current,i,Aa(t,o.current)),"user"),function(t,e,n,r){null!==r.current&&window.clearTimeout(r.current),r.current=window.setTimeout(()=>{r.current=null,uh(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()&&uh(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]),c}function Hh({editor:t,href:e,openExternal:n}){gs({href:e,openExternal:n,openInternal(e){t.viewport.centerOnShape(e,{source:"user",animation:{durationMs:240}})&&t.commands.setSelectedShapeIds([e],{source:"user"})}})}function Dh({shapeId:t,operationKind:e,fontCatalog:n,formattingToolbar:r,openLink:o=()=>{},onTiptapEditorChange:i}){const s=a(),c=l(s.shapes.getSignal(t)),u=l(s.state.shapeEditing).session;return Ks(c)&&u?.shapeId===c.id?d(Fh,{shape:c,session:u,fontCatalog:n,formattingToolbar:r,openLink:o,onTiptapEditorChange:i},`${c.id}:${e}`):null}function Fh({shape:t,session:e,fontCatalog:n,formattingToolbar:r,openLink:o,onTiptapEditorChange:i}){const s=a(),c=k(t.props.richText),u=function(t){const e=k(t);return w(()=>{e.current=t},[t]),e}(t),p=l(s.state.shapeEditingEntryRequest),h=k(null),[f,g]=S(null),[y,x]=S(null),b=m(({editor:t,controller:e})=>{g(t.isDestroyed?null:t),x(e)},[]),I=m(({editor:t,controller:e})=>{g(e=>e===t?null:e),x(t=>t===e?null:t)},[]),P=zh({editor:s,shape:t,tiptapEditor:f,richTextController:y,latestShapeRef:u,fontCatalog:n}),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,jt(t.props.backgroundColor)?null:Wt(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=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(()=>{Oh({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&&Oh({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(()=>{Oh({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:s,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=k(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:s,shapeId:t.id,richTextController:y}),C=function(t,e,n=0){return v(()=>({color:Ft(t.props.color),fontFamily:da(t.props.font,e),fontSize:ua(t.props.size),lineHeight:ha(t.props.size,t.props.lineHeight),textAlign:ga(t.props.textAlign),pointerEvents:"auto",userSelect:"text",cursor:"text",boxSizing:"border-box",position:"absolute",inset:0,width:"100%",height:"100%",paddingBlock:sa(t.props.padding).y,paddingInline:sa(t.props.padding).x+n,...ia(t.props,Ft)}),[t.props.color,t.props.font,t.props.size,t.props.lineHeight,t.props.textAlign,t.props.padding,t.props.backgroundColor,t.props.fill,t.props.stroke,t.props.strokeWidth,t.props.cornerRadius,t.props.shadow,e,n])}(t,n,Sa(Ra(s,t),t.props.w)),E=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(),Hh({editor:s,href:e,openExternal:o}))},[s,o,f]);
|
|
13
|
-
return
|
|
14
|
-
return
|
|
15
|
-
return
|
|
16
|
-
return
|
|
17
|
-
return
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
return d(r,{dataUi:"text-hover-outline",x:n,y:n,width:t.props.w*t.props.scale,height:t.props.h*t.props.scale,strokeWidth:e})}var tf="text.create",ef=class extends we{constructor(t){super(t,"text"),this.initial="idle",this.addChild(new nf(t,this)),this.addChild(new rf(t,this))}},nf=class extends we{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})}},rf=class extends we{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:tf,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(!Ks(e))return this.cancelOperation(),void this.transition("idle");let n;Gt(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:tf,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:{...of(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:of(e)}}(t,this.getDefaultTextProps()))}createTextShapeAt({x:t,y:e,props:n}){const r=_s(this.editor,{x:t,y:e,props:n},"user");return this.editor.commands.setSelectedShapeIds([r.id],{source:"system"}),r}getDefaultTextProps(){return Ys(this.editor)}};function of(t){return Xs(t)}var sf=["start","middle","end","justify"];function af(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function lf(t){return Math.max(.01,t.props.scale)}function cf(t){return t.props.w*lf(t)}function df(t){return t.props.h*lf(t)}function uf(t){return new Ct(0,0,cf(t),df(t))}function pf(t){return"left"===t||"right"===t}function hf(t,e){const n=function(t){return oe({localWidth:cf(t),localHeight:df(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 ff=class extends fe{type="text";getDefaultProps(){return{richText:xs(""),plainText:"",w:16,h:fa(ra),autoSize:!0,scale:1,font:Gs,size:ra,lineHeight:null,color:Bt("text-slate"),backgroundColor:Ot("transparent"),textAlign:"start",padding:0,fill:Ot("transparent"),stroke:Ot("transparent"),strokeWidth:0,cornerRadius:0,shadow:!1}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{richText:Ss(e.richText),plainText:"string"==typeof e.plainText?e.plainText:n.plainText,w:Math.max(1,af(e.w,n.w)),h:Math.max(1,af(e.h,n.h)),autoSize:"boolean"==typeof e.autoSize?e.autoSize:n.autoSize,scale:Math.max(.01,af(e.scale,n.scale)),font:ta(e.font)?e.font:n.font,size:ca(e.size,n.size),lineHeight:ah(e.lineHeight)??n.lineHeight,color:Dt(e.color,n.color),backgroundColor:Dt(e.backgroundColor,n.backgroundColor),textAlign:(r=e.textAlign,"string"==typeof r&&sf.includes(r)?e.textAlign:n.textAlign),padding:aa(e.padding,n.padding),fill:Dt(e.fill,n.fill),stroke:Dt(e.stroke,n.stroke),strokeWidth:Math.max(0,af(e.strokeWidth,n.strokeWidth)),cornerRadius:Math.max(0,af(e.cornerRadius,n.cornerRadius)),shadow:"boolean"==typeof e.shadow?e.shadow:n.shadow};var r}getPositionedBounds(t){return function(t){return new Ct(t.x,t.y,cf(t),df(t))}(t)}getLocalBounds(t){return uf(t)}getRenderBounds(t){return uf(t).expand(oa(t.props))}getExportBounds(t){return this.getRenderBounds(t)}canSnap(t,e){return!e||(n=e.editor,r=t.id,Ca(n,r)?.behavior.canSnap??null??!0);var n,r}canReceiveTerminalBinding(t,e){return!e||(n=e.editor,r=t.id,Ca(n,r)?.behavior.canReceiveTerminalBinding??null??!0);var n,r}canEdit(t){return!0}contributesToSelectionFrame(t,e){return n=e.editor,r=t.id,Ca(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,Ca(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,Ca(n,r)?.behavior.canUseSelectionRotateHandle??null??!0);var n,r}getSelectionTargetId(t,e){return function(t,e){const n=Ca(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=Ca(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=Ca(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=Ca(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&&pf(e.handleId)){const r=ie({width:e.selectionLocalBounds.w,height:e.selectionLocalBounds.h,scaleX:t.scaleX,scaleY:t.scaleY});n.w=Math.max(1,r.width/lf(t)),n.autoSize=!1}else n.scale=Math.max(.01,t.props.scale*hf(t,e));const r=n.scale??lf(t),o=(n.w??t.props.w)*r,i=t.props.h*r,s=oe({localWidth:o,localHeight:i,scaleX:t.scaleX,scaleY:t.scaleY}),a=function(t,e){return 0===e.selectionRotation?t.clone():Tt.RotWith(t,e.selectionRotationCenter,e.selectionRotation)}(se({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&&pf(e.handleId)?Qt:te}onEditEnd(t){if(!(t.props.plainText.trim().length>0||vs(t.props.richText)))return{deleteShapeIds:[t.id]}}},gf=class{fontCatalog;type="text";constructor(t){this.fontCatalog=t}toSvg(t,e){if(0===t.props.plainText.trim().length&&!vs(t.props.richText))return null;const n=Sa(Aa(e.editor,t),t.props.w),r=oa(t.props);return{tag:"foreignObject",attrs:{x:-r,y:-r,width:t.props.w*t.props.scale+2*r,height:t.props.h*t.props.scale+2*r},children:[{tag:"div",attrs:{xmlns:"http://www.w3.org/1999/xhtml",dir:"auto",style:yf(t,e,this.fontCatalog,n)},children:(o=t.props.richText,i=jt(t.props.backgroundColor)?void 0:e.resolveColor(t.props.backgroundColor),o.content.map(t=>mf(t,i)))}]};var o,i}};function mf(t,e){const n="codeBlock"===t.type?void 0:e,r=t.content?.map(t=>function(t,e){if(Is(t)){const n=function(t,e){const n=Ms(t.marks,e);return n?Es(n):void 0}(t,e);return n?{tag:"span",attrs:{style:n},children:[t.text]}:t.text}return"hardBreak"===t.type?{tag:"br"}:mf(t,e)}(t,n))??[];if("taskList"===t.type)return{tag:"ul",attrs:{style:"margin:0;padding:0;list-style:none"},children:r};if("taskItem"===t.type){const e=!0===t.attrs?.checked;return{tag:"li",attrs:{style:"display:flex;align-items:flex-start;gap:0.625em;padding-block:0.18em"},children:[{tag:"span",attrs:{style:`display:inline-flex;align-items:center;justify-content:center;flex:none;box-sizing:border-box;width:1em;height:1em;border:0.085em solid ${e?"#16a34a":"color-mix(in srgb, currentColor 38%, transparent)"};border-radius:0.28em;background:${e?"#16a34a":"color-mix(in srgb, currentColor 3%, transparent)"};color:${e?"white":"inherit"};font-size:1em;margin-block:calc((1lh - 1em)/2)`},children:e?["✓"]:[]},{tag:"div",attrs:{style:"flex:1;min-width:0"},children:r.map((n,r)=>e&&"paragraph"===t.content?.[r]?.type&&"string"!=typeof n?{...n,attrs:{...n.attrs,style:`${n.attrs?.style??""};opacity:0.55;text-decoration:line-through;text-decoration-thickness:0.06em;text-decoration-color:color-mix(in srgb, currentColor 65%, transparent)`}}: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=Ps(t);return{tag:"p",attrs:{style:o?`margin:0;text-align:${o}`:"margin:0"},children:r.length>0?r:[{tag:"br"}]}}function yf(t,e,n,r){const o=ia(t.props,t=>e.resolveColor(t));return[`color:${e.resolveColor(t.props.color)}`,`font-family:${da(t.props.font,n)}`,`font-size:${ua(t.props.size)}px`,`line-height:${ha(t.props.size,t.props.lineHeight)}`,`text-align:${ga(t.props.textAlign)}`,"white-space:pre-wrap","overflow-wrap:break-word","box-sizing:border-box",`padding-block:${sa(t.props.padding).y}px`,`padding-inline:${sa(t.props.padding).x+r}px`,...o.backgroundColor?[`background-color:${o.backgroundColor}`]:[],...o.borderRadius?[`border-radius:${o.borderRadius}`]:[],...o.boxShadow?[`box-shadow:${o.boxShadow}`]:[],`width:${t.props.w}px`,`height:${t.props.h}px`,`transform:translate(${oa(t.props)}px, ${oa(t.props)}px) scale(${t.props.scale})`,"transform-origin:top left"].join(";")}var wf=".label";function xf(t){return t.endpoints.find(({slot:t})=>"owner"===t)??null}function bf(t){return"binding"===t?.typeName&&"path-label"===t.type}function vf(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):e}var kf=class extends Mt{type=ma;getDefaultEndpointProps(){return{labelPosition:.5}}validateEndpointProps(t,e){const n=this.getDefaultEndpointProps();return{labelPosition:vf((e&&"object"==typeof e?e:{}).labelPosition,n.labelPosition)}}canBind(t,e,n){return this.canUseShapeCompanion(e,n,t)}canUseShapeCompanion(t,e,n){return Ks(e.ownerShape)&&1===e.endpoints.length&&(!n||!!e.endpoints[0]&&null!==If(n,e.endpoints[0].targetShape))}getExclusiveBindingKey(t){return xf(t)?.targetId??t.ownerId}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 n.endpointSlots.length>0?[e.ownerId]:[]}getTargetShapeContentCutoutLocalPolygons(t,e,n){if(!Ks(n.ownerShape)||!If(t,n.targetShape))return[];const r=t.shapes.computeLocalToPageTransform(n.targetShape).tryInvert();if(!r)return[];const o=t.shapes.computeLocalBounds(n.ownerShape),i=r.compose(t.shapes.computeLocalToPageTransform(n.ownerShape));return[[new Tt(o.minX,o.minY),new Tt(o.maxX,o.minY),new Tt(o.maxX,o.maxY),new Tt(o.minX,o.maxY)].map(t=>i.applyToPoint(t))]}onAfterShapeChange(t,e,n){return this.syncLabelPosition(t,e)}onBeforeDeleteShape(t,e,n){return n.owner?{deleteBindingIds:[e.id]}:{deleteShapeIds:[e.ownerId],deleteBindingIds:[e.id]}}onBeforeDeleteBinding(t,e){return{deleteBindingIds:[e.id]}}getExportShapeIds(t,e){return[e.ownerId]}getShapeCompanionRootId(t,e){const n=xf(t);return e===t.ownerId?n?.targetId??null:null}getSelectionCompanionFrameGeometries(t,e,n){const r=xf(e);if(r?.targetId!==n.selectedShape.id)return[];if(!0!==function(t,e){return Ca(t,e)?.behavior.showsCompanionFrameWhenOwnerSelected??null}(t,e.ownerId))return[];const o=t.shapes.get(e.ownerId),i=t.shapes.get(r.targetId);if(!(Ks(o)&&r&&i&&If(t,i)))return[];const s=t.shapes.computeGeometry(o),a=t.shapes.computeLocalToPageTransform(o),l=Math.atan2(a.b,a.a);return[{bounds:Ct.FromPoints(s.outlineVertices.map(t=>Tt.RotWith(t,s.center,-l))),rotation:l,rotationCenter:s.center}]}syncLabelPosition(t,e){if(!bf(e))return;const n=xf(e),r=t.shapes.get(e.ownerId),o=n?t.shapes.get(n.targetId):null;if(!(Ks(r)&&n&&o&&If(t,o)))return{deleteBindingIds:[e.id]};const i=function(t,e,n,r){const o=Sf(t,e,n,r),i=n.parentId,s=`${n.index}${wf}`,a=!1,l=Pa(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,r,o,n.props.labelPosition);return i?{shapes:[{...r,...i,props:{...r.props,...i.props}}]}:void 0}};function Sf(t,e,n,r=.5){const o=If(t,n),i=o?Pf(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=Ea(t,e,n,ma),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:Ia(t,n),props:{w:c}}}function If(t,e){return t.shapes.getUtil(e).getLabelPathGeometry(e,{editor:t})}function Pf(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 Mf=".label";function Tf(t){return t.endpoints.find(({slot:t})=>"owner"===t)??null}function Cf(t){return"shape"===t?.typeName&&"geo"===t.type}function Ef(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):e}var Af=class extends Mt{type=ya;getDefaultEndpointProps(){return{...wa(),normalizedAnchor:{x:.5,y:.5},ownerBaseHeight:0}}validateEndpointProps(t,e){const n=this.getDefaultEndpointProps(),r=e&&"object"==typeof e?e:{},o=r.normalizedAnchor&&"object"==typeof r.normalizedAnchor?r.normalizedAnchor:n.normalizedAnchor;return{...wa(r),normalizedAnchor:{x:Ef(o.x,n.normalizedAnchor.x),y:Ef(o.y,n.normalizedAnchor.y)},ownerBaseHeight:Lf(r.ownerBaseHeight,n.ownerBaseHeight)}}canBind(t,e,n){return this.canUseShapeCompanion(e,n)}canUseShapeCompanion(t,e){return Ks(e.ownerShape)&&1===e.endpoints.length&&Cf(e.endpoints[0]?.targetShape)}getExclusiveBindingKey(t){return Tf(t)?.targetId??t.ownerId}onBindingCreate(t,e){return this.syncLabelPosition(t,e)}onBindingUpdate(t,e,n){return this.syncLabelPosition(t,n,Tf(e)?.targetId===Tf(n)?.targetId?void 0:{endpointSlots:["owner"]})}onBindingLoad(t,e){return this.syncLabelPosition(t,e)}getGeometryDependentShapeIds(t,e,n){const r=Tf(e)?.targetId;return n.owner?r?[r]:[]:[e.ownerId]}onAfterShapeChange(t,e,n){return this.syncLabelPosition(t,e,n)}onBeforeDeleteShape(t,e,n){if(n.owner){const n=Tf(e),r=n?t.shapes.get(n.targetId):null,o=r?$f(r,e):null;return{shapes:o?[o]:void 0,deleteBindingIds:[e.id]}}return{deleteShapeIds:[e.ownerId],deleteBindingIds:[e.id]}}onBeforeDeleteBinding(t,e){const n=Tf(e),r=n?t.shapes.get(n.targetId):null,o=r?$f(r,e):null;return{shapes:o?[o]:void 0,deleteBindingIds:[e.id]}}getExportShapeIds(t,e){return[e.ownerId]}getShapeCompanionRootId(t,e){const n=Tf(t);return e===t.ownerId?n?.targetId??null:null}syncLabelPosition(t,e,n){if(r=e,"binding"!==r?.typeName||"geo-label"!==r.type)return;var r;const o=Tf(e),i=t.shapes.get(e.ownerId),s=o?t.shapes.get(o.targetId):null;if(!Ks(i)||!o||!Cf(s))return{deleteBindingIds:[e.id]};const a=function(t,e,n){const r=Tf(t),o=Rf(e,"h")??1;return n?.endpointSlots.includes("owner")?o:r&&r.props.ownerBaseHeight>0?r.props.ownerBaseHeight:o}(e,s,n),l=o.props.ownerBaseHeight===a?null:{...e,endpoints:e.endpoints.map(t=>"owner"===t.slot?{...t,props:{...t.props,ownerBaseHeight:a}}:t)},c=function(t,e,n,r){const o=Rf(t,"h");if(!o)return null;const i=Math.max(n,function(t,e){return Math.max(1,t.props.h*t.props.scale+2*e)}(e,r));return o===i?null:{...t,props:{...t.props,h:i}}}(s,i,a,o.props.padding.y),d=function(t,e,n){const r=Nf(t,e,n),o=n.parentId,i=`${n.index}${Mf}`,s=!1,a=Pa(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,i,c??s),u=[];return c&&u.push(c),d&&u.push({...i,...d,props:{...i.props,...d.props}}),u.length>0||l?{shapes:u.length>0?u:void 0,bindings:l?[l]:void 0}:void 0}};function Lf(t,e){return"number"==typeof t&&Number.isFinite(t)&&t>0?t:e}function Rf(t,e){const n=t.props[e];return"number"==typeof n&&Number.isFinite(n)?n:null}function $f(t,e){const n=Tf(e),r=Rf(t,"h");return!r||!n||n.props.ownerBaseHeight<=0||r===n.props.ownerBaseHeight?null:{...t,props:{...t.props,h:n.props.ownerBaseHeight}}}function Nf(t,e,n){const r=Ea(t,e,n,ya),o=Math.min(r.maxWidth,Math.max(r.minWidth,e.props.w)),i=t.shapes.computeLocalBounds(n),{padding:s,verticalAlign:a}=ba(t,n.id),l=e.props.h*e.props.scale,c="top"===a?i.minY+s.y+l/2:"bottom"===a?i.maxY-s.y-l/2:i.center.y,d=t.shapes.computeLocalToPageTransform(n).applyToPoint(new Tt(i.minX+i.w*(r.normalizedCenterX??.5),c));return{x:d.x-o*e.props.scale/2,y:d.y-l/2,rotation:Ia(t,n),props:{w:o}}}var Bf="text.edit",Of="path-label.create",zf="path-label.drag",Hf="geo-label.edit",Df="geo-label.create",Ff={propagation:"stop"};function Wf(){let t=null,e=null;const n=()=>{t=null,e=null};return{id:"land.text.interactions",editorEvent:{handleEvent(r,o,i){if(r.state.readonly.get())n();else 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||!Ks(a)||!t.editing.canEditShape(a)||va(t,a.id))return;t.editing.start({shapeId:a.id,entryMode:"placeCaret",caretPagePoint:e.pagePoint,operationKind:Bf,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||!Kf(a)||t.layers.isOrAncestorLocked(a.id)||t.state.shapeEditingSession.get()||1!==l.length||l[0]!==a.id||Ma(t,a.id,"geo-label"))return;const c=Yf(t,a);c&&La(t,c,{editOperationKind:Hf,createOperationKind:Df,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||!Ks(e)||!r.editing.canEditShape(e)||va(r,e.id))return;return r.editing.start({shapeId:e.id,entryMode:"selectAll",operationKind:Bf},"user"),Ff}if("double_click"===o.type)return n(),function(t,e){const n=t.shapes.hitTest(e.pagePoint);if(!n)return!1;if(Ks(n))return!(!t.editing.canEditShape(n)||va(t,n.id))&&(t.editing.start({shapeId:n.id,entryMode:"selectAll",operationKind:Bf},"user"),!0);return Kf(n)?function(t,e){return!t.layers.isOrAncestorLocked(e.id)&&(Uf(t,e.id),!0)}(t,n):!!If(t,n)&&function(t,e,n){return!t.layers.isOrAncestorLocked(e.id)&&(jf(t,e.id,n),!0)}(t,n,e.pagePoint)}(r,o)?Ff: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||!Ks(o)||!t.editing.canEditShape(o)||va(t,o.id))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:Bf,preserveInteraction:!0},"user"),Ff):Ff;!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=Ca(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||!Kf(o)||t.layers.isOrAncestorLocked(o.id)||t.state.shapeEditingSession.get()||e.shiftKey||e.altKey||e.accelKey||n>=2||1!==i.length||i[0]!==o.id||Ma(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()||!Ks(e.shape))return null;const n=t.bindings.getOwnedByShape(e.shape.id).find(bf),r=n?xf(n):null;if(!n||!r||r.targetId!==e.selectionTargetId)return null;const o=t.shapes.get(r.targetId),i=t.shapes.getPageBounds(e.shape.id);if(!o||!i||t.layers.isOrAncestorLocked(o.id)||!If(t,o))return null;const s=i.center.sub(e.originPagePoint);return{shapeId:o.id,operationKind:zf,onDragStart({editor:t}){t.commands.setSelectedShapeIds([o.id],{source:"system"})},update({editor:t,pagePoint:e,source:r}){const o=t.bindings.get(n.id),i=bf(o)?xf(o):null,a=t.shapes.get(n.ownerId),l=i?t.shapes.get(i.targetId):null;if(!(bf(o)&&i&&Ks(a)&&l))return"stop";const c=If(t,l);if(!c)return"stop";const d=Xf({editor:t,label:a,pathGeometry:c,pagePoint:e.add(s),hintPosition:i.props.labelPosition,snapToDefault:!0});return Math.abs(d-i.props.labelPosition)>1e-6&&t.commands.setBindingEndpoint({bindingId:o.id,endpoint:{...i,props:{...i.props,labelPosition:d}}},{source:r}),{status:"continue",finalPagePoint:c.getPointAt(d)}}}}(t,e)}}}function jf(t,e,n){const r=t.shapes.get(e);if(!r||t.layers.isOrAncestorLocked(r.id))return!1;const o=If(t,r);if(!o)return!1;const i=Ma(t,r.id,ma),s=i??function(t,e,n){const r=If(t,e);if(!r)return null;const o=_f(e,{...Ys(t),autoSize:!1,textAlign:"middle"}),i=r.getNearestPosition(n,{hintPosition:r.defaultPosition}),s=Sf(t,o,e,i),a=Ta(t,{bindingType:ma,owner:e,operationKind:Of,index:`${e.index}${wf}`,layout:s,bindingProps:{labelPosition:i}});if(!a)return null;const l=t.shapes.get(a.id),c=t.bindings.getOwnedByShape(a.id).find(bf);if(!Ks(l)||!c)return a;const d=Xf({editor:t,label:l,pathGeometry:r,pagePoint:n,hintPosition:i,snapToDefault:!1});if(Math.abs(d-i)>1e-6){const e=xf(c);if(!e)return a;t.commands.setBindingEndpoint({bindingId:c.id,endpoint:{...e,props:{...e.props,labelPosition:d}}},{source:"user"})}return a}(t,r,n??o.getPointAt(o.defaultPosition));return!!s&&(La(t,s,{editOperationKind:"path-label.edit",createOperationKind:Of,isExisting:!!i}),!0)}function Uf(t,e){const n=t.shapes.get(e);if(!n||!Kf(n)||t.layers.isOrAncestorLocked(n.id))return!1;const r=Ma(t,n.id,ya),o=r??Yf(t,n);return!!o&&(La(t,o,{editOperationKind:Hf,createOperationKind:Df,isExisting:!!r,entryMode:r?"selectAll":"focusEnd"}),!0)}function Kf(t){return"geo"===t.type}function Xf({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=Pf(t,e,n);return Math.min(a.end,Math.max(a.start,s))}function Yf(t,e){const n=Nf(t,_f(e,{...Ys(t),autoSize:!1,textAlign:"middle"}),e);return Ta(t,{bindingType:ya,owner:e,operationKind:Df,index:`${e.index}${Mf}`,layout:n,bindingProps:{normalizedAnchor:{x:.5,y:.5}}})}function _f(t,e){return{id:"shape:draft",typeName:"shape",scope:"document",type:"text",subType:null,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 qf({fontCatalog:t=Zs()}={}){return{shapeUtils:[new ff],shapeSvgExporters:[new gf(t)],bindingUtils:[new Af,new kf],interactionHandlers:[Wf()],tools:{text:t=>new ef(t)}}}function Gf({editor:t,fontCatalog:e}){return function({editor:t,fontCatalog:e}){return{createGeoLabel:(n,r)=>function(t,e,n,r){const o=t.shapes.get(n);return!o||"geo"!==o.type||t.state.readonly.get()||t.layers.isOrAncestorLocked(n)||xa(t,n)?null:t.operations.run({kind:"geo-label.create",source:"user"},()=>{const n=_s(t,{x:o.x,y:o.y,parentId:o.parentId,index:`${o.index}${Mf}`,props:{richText:Ss(r.richText),autoSize:!1,...void 0!==r.font?{font:r.font}:{},...void 0!==r.size?{size:r.size}:{},...void 0!==r.lineHeight?{lineHeight:r.lineHeight}:{},...void 0!==r.color?{color:r.color}:{},textAlign:r.textAlign??"middle",padding:0,fill:Ot("transparent"),stroke:Ot("transparent"),backgroundColor:Ot("transparent"),strokeWidth:0,cornerRadius:0,shadow:!1}});t.commands.createBinding({type:ya,ownerId:n.id,endpoints:[{slot:"owner",targetId:o.id,props:{...wa(r)}}]},{source:"user"});const i=t.shapes.get(n.id);return Ks(i)&&ph(t,i,e,"user"),{id:n.id,type:"text"}})}(t,e,n,r),getGeoLabelLayout:e=>xa(t,e)?ba(t,e):null,setGeoLabelLayout:(n,r)=>function(t,e,n,r){const o=xa(t,n);return!(!o||t.state.readonly.get()||t.layers.isOrAncestorLocked(n)||t.layers.isOrAncestorLocked(o.ownerId))&&t.operations.run({kind:"geo-label.layout",source:"user"},()=>{const i=wa({...ba(t,n),...r});t.commands.updateBinding({id:o.id,endpoints:o.endpoints.map(t=>({...t,props:{...t.props,...i}}))},{source:"user"});const s=t.shapes.get(o.ownerId);return Ks(s)&&ph(t,s,e,"user"),!0})}(t,e,n,r),create(e){const n=t.shapes.getDefaultProps("text"),r=e.richText?Ss(e.richText):xs(e.text??""),[o]=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,autoSize:e.autoSize??n.autoSize,font:e.font??n.font,color:e.color??n.color,size:e.size??n.size,lineHeight:void 0===e.lineHeight?n.lineHeight:e.lineHeight,textAlign:e.textAlign??n.textAlign,padding:e.padding??n.padding,fill:e.fill??n.fill,stroke:e.stroke??n.stroke,strokeWidth:e.strokeWidth??n.strokeWidth,cornerRadius:e.cornerRadius??n.cornerRadius,shadow:e.shadow??n.shadow,richText:r,plainText:bs(r)}}],{source:"user"});return"text"===o?.type?{id:o.id,type:o.type}:null},resolveLayoutSize(t){const n={w:t.w,h:t.h};return"undefined"!=typeof document&&document.body?function(t,e){return Qp(t.richText,{props:t},e)}(t,e)??n:n},startEditing(e){const n=e??t.selection.getIds()[0],r=n?t.shapes.get(n):null;return!(!r||"text"!==r.type||va(t,r.id))&&(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&&Uf(t,r)},startEditingPathLabel(e){const n=t.selection.getIds(),r=e??(1===n.length?n[0]:void 0);return!!r&&jf(t,r)},getBoundTextLabel(e){const n=Ma(t,e,"geo-label")??Ma(t,e,"path-label");return n&&n.props.plainText.trim().length>0?{id:n.id,type:n.type}:null},getFormattingSnapshot:()=>function(t){return Rp(t)?.getSnapshot()??null}(t),subscribeFormatting:e=>function(t,e){const n=$p(t);return n.listeners.add(e),()=>{n.listeners.delete(e)}}(t,e),setSelectionStyle(e,n){if(void 0!==e.lineHeight&&void 0===ah(e.lineHeight))return[];const r=n?null:Rp(t);if(r){const n={...void 0!==e.fill?{fill:e.fill}:{},...void 0!==e.stroke?{stroke:e.stroke}:{},...void 0!==e.strokeWidth?{strokeWidth:e.strokeWidth}:{},...void 0!==e.cornerRadius?{cornerRadius:e.cornerRadius}:{},...void 0!==e.shadow?{shadow:e.shadow}:{},...void 0!==e.padding?{padding:e.padding}:{}};return Object.keys(n).length>0&&t.commands.updateShapes([{id:r.shapeId,props:n}],{source:"user"}),void 0!==e.color&&r.setColor(Jf(e.color)),void 0!==e.backgroundColor&&r.setBackgroundColor(Jf(e.backgroundColor)),void 0!==e.font&&r.setFont(e.font),void 0!==e.size&&r.setSize(e.size),void 0!==e.lineHeight&&r.setLineHeight(e.lineHeight),void 0!==e.textAlign&&r.setTextAlign(e.textAlign),[r.shapeId]}const o=Vf(t,n).filter(e=>!va(t,e.id)).map(t=>({id:t.id,props:{...e,...void 0!==e.lineHeight?{richText:Wp(t.props.richText,"lineHeight")}:{}}}));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:Rp(t);if(r)return r.getSnapshot()?.[e]??!1;const o=Vf(t,n).map(t=>Hp(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:Rp(t);if(r)return r.toggle(e);const o=Vf(t,n).filter(e=>!va(t,e.id)),i=!o.every(t=>!0===Hp(t.props.richText,e)),s=o.map(t=>({shape:t,richText:Dp(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:Rp(t);if(n)return n.getSnapshot()?.blockType??null;const r=Vf(t,e).map(t=>Bp(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:Rp(t);if(r)return r.setBlockType(e);const o=Vf(t,n).filter(e=>!va(t,e.id)).map(t=>({shape:t,richText:Op(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,plainText:bs(e)}})),{source:"user"}),!0)},clearFormatting(){const e=Rp(t);if(e)return e.clearFormatting();const n=t.state.selectedShapes.get().filter(Ks).filter(e=>!va(t,e.id)).map(t=>({shape:t,richText:jp(t.props.richText)})).filter(({shape:t,richText:e})=>e!==t.props.richText||!jt(t.props.backgroundColor));return 0!==n.length&&(t.commands.updateShapes(n.map(({shape:t,richText:e})=>({id:t.id,props:{richText:e,backgroundColor:Ot("transparent")}})),{source:"user"}),!0)},getLinkHref(){const e=Rp(t);if(e)return e.getSnapshot()?.linkHref??null;const n=t.state.selectedShapes.get().filter(Ks).map(t=>function(t){const e=[];if(Yp(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=Rp(t);if(n)return n.setLink(e);const r=null===e?null:ds(e);if(null!==e&&null===r)return!1;const o=t.state.selectedShapes.get().filter(Ks).filter(e=>!va(t,e.id)).map(t=>({shape:t,richText:Fp(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)},toolDefaultsState:o(t.signals.computed("Text.toolDefaults",()=>t.shapes.getDefaultProps("text"))),setToolDefaults:e=>(t.shapes.updateDefaultProps("text",e),t.shapes.getDefaultProps("text"))}}({editor:t,fontCatalog:e})}function Vf(t,e){if(e){const n=t.shapes.get(e);return Ks(n)?[n]:[]}return t.state.selectedShapes.get().filter(Ks)}function Jf(t){const e=Wt(t);return"transparent"===e?null:e}function Zf(t={}){const{fontCatalog:e,openLink:n,...r}=t,o={...Js(),...r},i=e??Qs(o);return s({id:"text",editor:qf({fontCatalog:i}),render:Vh({fontCatalog:i,formattingToolbar:o.formattingToolbar,openLink:n,onTiptapEditorChange:o.onTiptapEditorChange}),setup:({editor:t})=>({api:Gf({editor:t,fontCatalog:i})})})}var Qf=Zf();function tg(t){ps(t)&&window.open(t,"_blank","noopener,noreferrer")}function eg(t){return{kind:"svg-inliner",id:"text.svg-inliner",async inline({exportedShapes:e,svg:n}){const r=e.filter(Ks),o=r.map(t=>t.props.plainText).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("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}`));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=ag(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 ig(r,t.id);return og(rg(await ng(await o.text(),o.url||r,t.id)),t.id)}return async function(t,e){const n="string"==typeof t.src?og(rg(await ng(t.src,void 0,e)),e):`url("${await sg(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("&","&").replaceAll("<","<").replaceAll(">",">")}</style>`;var o;return`${n[0]}${r}${t.slice(n[0].length)}`}(n,a.join("\n")):n}}}async function ng(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=ag(i,e).href,r=await sg(await(await ig(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 rg(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 og(t,e){if(!/\burl\(\s*["']?data:/iu.test(t))throw new Error(`Font resource "${e}" has no embeddable source.`);return t}async function ig(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 sg(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 ag(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 lg(t={}){const e=t.fontCatalog??Qs({...Js(),...t});return yt({id:"text.host",setup({editor:t,run:n}){const r=new Set,o=async n=>{for(const r of t.shapes.getAll()){if(!Ks(r))continue;await ch(r.props.font,e,{text:r.props.plainText}),await wt(t,n),n.throwIfAborted();const o=t.shapes.get(r.id);Ks(o)&&o.props.font===r.props.font&&!t.state.readonly.get()&&ph(t,o,e)}},i=t.operations.subscribe(()=>{for(const e of t.shapes.getAll()){if(!Ks(e)||r.has(e.props.font))continue;const t=e.props.font;r.add(t),n(o).catch(()=>r.delete(t))}});return{api:{loadFont:({font:t,text:r})=>n(async n=>{const o=await ch(t,e,{text:r});return n.throwIfAborted(),o})},exports:[eg(e)],assetResolvers:[{id:"text.fonts",resolve:()=>null,async preload({signal:t}){await ch(Gs,e),t.throwIfAborted(),await o(t)}}],dispose:i}}})}var cg=["✍️ 双击此处输入文字..","可以在此输入提示词,比如画面描述、产品卖点、活动主题、场景描述、品牌 slogan 等内容。若暂时没有明确内容,也可先输入关键词或草稿,后续随时修改优化哦!","也可以在底部输入框输入需求,让AI自动完成文字生成。"].join("\n");function dg(t,e){if("text"===e){const n=t.shapes.getDefaultProps("text"),r=360,o=8,i=n.h+2*o;return{kind:e,w:r,h:i,contentProps:{...n,w:r,h:i,autoSize:!1,backgroundColor:Ot("#ffffff"),padding:o,richText:xs(cg),plainText:cg,textAlign:"start"}}}const n=t.shapes.getDefaultProps("image");return{kind:e,w:n.w,h:n.h,contentProps:{...n,altText:""}}}function ug(t,e){if(t.state.readonly.get())return null;const n=t.shapes.get(e);if(!n||fi(n)||"text"!==n.type&&"image"!==n.type||t.layers.isOrAncestorLocked(n.id)||t.shapes.isHidden(n.id))return null;const r=t.operations.begin({kind:"flow.wrap-shape",label:"shape.wrap-flow-node",source:"user",history:"record"});try{t.commands.updateShapes([{id:n.id,subType:ui}],{source:"user"});const e=t.shapes.get(n.id);return fi(e)?(t.commands.setSelectedShapeIds([e.id],{source:"system"}),r.commit(),{nodeId:e.id}):(r.cancel(),null)}catch(o){throw r.isActive&&r.cancel(),o}}function pg(t,e){if(t.state.readonly.get())return null;const n=t.shapes.get(e);if(!fi(n)||t.layers.isOrAncestorLocked(n.id)||t.shapes.isHidden(n.id)||t.bindings.getTargetingShape(n.id).some(t=>mi(t)&&t.endpoints.some(({slot:t,targetId:e})=>"end"===t&&e===n.id)))return null;const r=t.operations.begin({kind:"flow.unwrap-node",label:"shape.unwrap-flow-node",source:"user",history:"record"});try{t.commands.updateShapes([{id:n.id,subType:null}],{source:"user"});const e=t.shapes.get(n.id);return e&&null===e.subType?(t.commands.setSelectedShapeIds([e.id],{source:"system"}),r.commit(),e):(r.cancel(),null)}catch(o){throw r.isActive&&r.cancel(),o}}var hg=96;function fg(t,e,n,r={}){if(t.state.readonly.get())return null;const o=t.shapes.get(e.shape.id);if(!o||t.layers.isOrAncestorLocked(o.id)||t.shapes.isHidden(o.id))return null;const i=ce(t,o,e.port.id);if(!i||!Gi({shape:o,port:i}))return null;const s=function(t,e,n,r,o,i){const s=dg(t,r),a=i?.w??s.w,l=i?.h??s.h,c=e.parentId,d=c.startsWith("shape:")?t.shapes.get(c):null,u=d?t.shapes.computeLocalToPageTransform(d):Kt.Identity(),p=u.tryInvert();let h;if(o){const t=p?.applyToPoint(o)??o;h=new Tt(t.x,t.y-l/2)}else{const t=n.pageOutwardNormal.normalize(),e=new Tt(a/2,l/2),r=u.applyToPoint(e),o=u.applyToPoint(e.add(new Tt(a/2,0))),i=u.applyToPoint(e.add(new Tt(0,l/2))),s=Math.abs(gg(o.sub(r),t))+Math.abs(gg(i.sub(r),t)),c=n.pagePoint.add(t.mul(96+s));h=(p?.applyToPoint(c)??c).sub(new Tt(a/2,l/2))}return{type:r,subType:ui,parentId:c,x:h.x,y:h.y,rotation:0,props:{...s.contentProps,w:a,h:l}}}(t,o,i,n,r.inputPortPagePoint,r.initialSize),a=r.inputPortPagePoint?s:zi(t,{shape:o,port:i},s,function(t,e){const n=[],r=new Set;for(const o of t.state.shapeIds.get()){const i=t.shapes.get(o);if(!hi(i))continue;const s=Qi(t,i.id);if(s.start?.targetId!==e.shape.id||s.start.props.portId!==e.port.id||!s.end||r.has(s.end.targetId))continue;const a=t.shapes.get(s.end.targetId);a&&(r.add(a.id),n.push(a))}return n}(t,{shape:o,port:i})),l=t.operations.begin({kind:`flow.create-${n}-node`,label:"shape.create",source:"user",history:"record"});try{const e=t.commands.createShapes([a],{source:"user",autoReparent:!1})[0];if(!fi(e))return l.cancel(),null;const n=ce(t,e,_i);return n&&ns(t,{start:Pi(o.id,i),end:Pi(e.id,n),selectionAfter:[e.id]})?(l.commit(),{nodeId:e.id}):(l.cancel(),null)}catch(c){throw l.isActive&&l.cancel(),c}}function gg(t,e){return t.x*e.x+t.y*e.y}var mg=class extends Error{code;nodeId;edgeId;constructor(t,e,n){super(e),this.name="FlowConnectionError",this.code=t,this.nodeId=n.nodeId,this.edgeId=n.edgeId}};function yg({editor:t}){const e=new Map;let n=!1;const r=()=>{if(n)throw new Error("Disposed Flow API rejected connection operation.")},o=t.operations.subscribe(({diff:t})=>{for(const n of function(t,e){if(0===e.size)return new Set;const n=new Set,r=t=>{e.has(t)&&n.add(t)},o=t=>{if(mi(t))for(const{targetId:e}of t.endpoints)r(e)};for(const i of t.added)It(i)&&r(i.id),o(i);for(const i of t.removed)It(i)&&r(i.id),o(i);for(const{before:i,after:s}of t.updated)It(i)&&It(s)&&(i.type!==s.type||i.subType!==s.subType)&&r(s.id),o(i),o(s);return n}(t,e))e.get(n)?.refresh()});return{value:{connections:{forNode(n){r();let o=e.get(n);return o||(o=function(t,e){const n=new Set;let r={snapshot:kg(t,e)},o=!1;return{readable:{getSnapshot(){if(r.error)throw r.error;return r.snapshot},subscribe:t=>o?()=>{}:(n.add(t),()=>n.delete(t))},refresh(){if(o)return;const i=function(t,e){try{return{snapshot:kg(t,e)}}catch(n){if(n instanceof mg)return{error:n};throw n}}(t,e);if(a=i,!((s=r).error||a.error?s.error?.code===a.error?.code&&s.error?.nodeId===a.error?.nodeId&&s.error?.edgeId===a.error?.edgeId:s.snapshot.node.id===a.snapshot.node.id&&s.snapshot.node.type===a.snapshot.node.type&&Pg(s.snapshot.inputs,a.snapshot.inputs)&&Pg(s.snapshot.outputs,a.snapshot.outputs))){var s,a;r=i;for(const t of[...n])t()}},dispose(){o||(o=!0,n.clear())}}}(t,n),e.set(n,o)),o.readable},connect:e=>(r(),function(t,e){Sg(t,e.targetNodeId),bg(t,{nodeId:e.targetNodeId,shapeIds:[e.sourceShapeId,e.targetNodeId]});const n=wg(e.sourceShapeId,qi),r=wg(e.targetNodeId,_i);xg(t,n,r,{nodeId:e.targetNodeId});const o=ns(t,{start:n,end:r,selectionAfter:"none"});o||vg("operation_failed","Flow connection creation failed.",{nodeId:e.targetNodeId});return Ig(t,e.targetNodeId,o.id)}(t,e)),reconnect:e=>(r(),function(t,e){t.shapes.get(e.edgeId)||vg("connection_not_found",`Flow connection "${e.edgeId}" was not found.`,{nodeId:e.shapeId,edgeId:e.edgeId});const n=Ig(t,e.shapeId,e.edgeId),r="start"===e.terminal?e.shapeId:n.source.shape.id,o="end"===e.terminal?e.shapeId:n.target.shape.id;Sg(t,o),bg(t,{nodeId:o,edgeId:e.edgeId,shapeIds:[e.edgeId,r,o]});const i=wg(r,qi),s=wg(o,_i);xg(t,i,s,{nodeId:o,edgeId:e.edgeId}),t.operations.run({kind:"flow-edge.reconnect",label:"shape.update",source:"user",history:"record"},()=>os(t,e.edgeId,e.terminal,"start"===e.terminal?i:s))||vg("operation_failed",`Flow connection "${e.edgeId}" terminal update failed.`,{nodeId:o,edgeId:e.edgeId});return Ig(t,o,e.edgeId)}(t,e)),disconnect(e){r(),function(t,e){Sg(t,e.nodeId);const n=t.shapes.get(e.edgeId);if(!n)throw new mg("connection_not_found",`Flow connection "${e.edgeId}" was not found.`,e);if(!hi(n))throw new mg("unsupported_link",`Shape "${e.edgeId}" is not a supported Flow connection.`,e);const r=Ig(t,e.nodeId,e.edgeId);if(r.source.shape.id!==e.nodeId&&r.target.shape.id!==e.nodeId)throw new mg("connection_not_attached",`Flow connection "${e.edgeId}" is not attached to node "${e.nodeId}".`,e);if(t.state.readonly.get())throw new mg("readonly","Readonly canvas rejected Flow connection disconnect.",e);if(t.layers.isOrAncestorLocked(e.edgeId)||t.layers.isOrAncestorLocked(r.source.shape.id)||t.layers.isOrAncestorLocked(r.target.shape.id))throw new mg("locked",`Locked Flow connection "${e.edgeId}" cannot be disconnected.`,e);t.operations.run({kind:"flow-edge.disconnect",label:"shape.delete",source:"user",history:"record"},()=>t.shapes.delete([e.edgeId],"user"))}(t,e)}},createNodeFromPort:e=>(r(),function(t,e){bg(t,{nodeId:e.sourceShapeId,shapeIds:[e.sourceShapeId]});const n=t.shapes.get(e.sourceShapeId),r=n?ce(t,n,qi):null;n&&r||vg("missing_endpoint",`Flow source "${e.sourceShapeId}" output port was not found.`,{nodeId:e.sourceShapeId});const o=fg(t,{shape:n,port:r},e.kind,{inputPortPagePoint:e.inputPortPagePoint?new Tt(e.inputPortPagePoint.x,e.inputPortPagePoint.y):void 0}),i=o?t.shapes.get(o.nodeId):null;fi(i)||vg("operation_failed",`Flow ${e.kind} node creation failed.`,{nodeId:e.sourceShapeId});return{id:i.id,type:i.type}}(t,e)),wrapShape(e){const n=ug(t,e),r=n?t.shapes.get(n.nodeId):null;return!r||"text"!==r.type&&"image"!==r.type?null:{id:r.id,type:r.type}},unwrapNode(e){const n=pg(t,e);return n?{id:n.id,type:n.type}:null}},dispose(){if(!n){n=!0,o();for(const t of e.values())t.dispose();e.clear()}}}}function wg(t,e){return{kind:"bound",shapeId:t,attachment:{kind:"port",portId:e}}}function xg(t,e,n,r){const o=es(t,e,n,r.edgeId);o&&vg("locked_source"===o?"locked":o,`Flow connection rejected: ${o}.`,r)}function bg(t,e){t.state.readonly.get()&&vg("readonly","Readonly canvas rejected Flow connection mutation.",e);const n=e.shapeIds.find(e=>t.layers.isOrAncestorLocked(e));n&&vg("locked",`Locked shape "${n}" rejected Flow connection mutation.`,e)}function vg(t,e,n){throw new mg(t,e,n)}function kg(t,e){const n=Sg(t,e),r=new Set;for(const i of t.bindings.getTargetingShape(e))mi(i)&&r.add(i.ownerId);const o=[...r].flatMap(n=>{const r=Qi(t,n);return r.start&&r.end?[Ig(t,e,n)]:[]}).sort((t,e)=>t.edgeId.localeCompare(e.edgeId));return{node:n,inputs:o.filter(({target:t})=>t.shape.id===e),outputs:o.filter(({source:t})=>t.shape.id===e)}}function Sg(t,e){const n=t.shapes.get(e);if(!n)throw new mg("node_not_found",`Flow node "${e}" was not found.`,{nodeId:e});if(!fi(n))throw new mg("unsupported_node",`Shape "${e}" does not support Flow connections.`,{nodeId:e});return{id:n.id,type:n.type}}function Ig(t,e,n){const r=t.shapes.get(n),o=ts(t,n),i=Qi(t,n),s=i.start?t.shapes.get(i.start.targetId):null,a=i.end?t.shapes.get(i.end.targetId):null;if(!hi(r)||1!==o.length||2!==o[0].endpoints.length||!i.start||!i.end||"right"!==i.start.props.portId||"left"!==i.end.props.portId||!s||"text"!==s.type&&"image"!==s.type||!fi(a))throw new mg("unsupported_link",`Flow connection "${n}" has unsupported endpoints.`,{nodeId:e,edgeId:n});return{edgeId:n,source:{shape:{id:s.id,type:s.type},portId:i.start.props.portId},target:{shape:{id:a.id,type:a.type},portId:i.end.props.portId}}}function Pg(t,e){return t.length===e.length&&t.every((t,n)=>{const r=e[n];return!!r&&t.edgeId===r.edgeId&&t.source.shape.id===r.source.shape.id&&t.source.shape.type===r.source.shape.type&&t.source.portId===r.source.portId&&t.target.shape.id===r.target.shape.id&&t.target.shape.type===r.target.shape.type&&t.target.portId===r.target.portId})}function Mg(t,e){if(e){const n=new Map;if("bound"===e.start.kind){const r=t.shapes.get(e.start.shapeId);r&&n.set(r.id,r)}return e.target&&n.set(e.target.shape.id,e.target.shape),{visibleShapes:[...n.values()],sourceShapeIds:"bound"===e.start.kind?new Set([e.start.shapeId]):new Set}}const n=t.state.selectedShapes.get(),r=1===n.length?n[0]:null;return r&&Eg(r)?{visibleShapes:[r],sourceShapeIds:new Set([r.id])}:{visibleShapes:[],sourceShapeIds:new Set}}function Tg(t,e,n){return n.has(e.id)?fi(t)&&"left"===e.id?"input":"right"!==e.id||"text"!==t.type&&"image"!==t.type?null:"output":null}function Cg(t,e,n={}){const r=$i(t,e,{portFilter:t=>Vi(t)&&(n.portFilter?.(t)??!0)});if(r)return r;const o=t.shapes.hitTestPoint(e,{hitTest:"bindingTarget",filter:fi});for(const i of o){const e=ce(t,i,_i);if(!e)continue;const r={shape:i,port:e};if(!n.portFilter||n.portFilter(r))return r}return null}function Eg(t){return"text"===t.type||"image"===t.type}var Ag={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"}},Lg=(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,...Ag[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},Rg=Lg("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"}]]),$g=Lg("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"}]]),Ng=Lg("outline","plus","Plus",[["path",{d:"M12 5l0 14",key:"svg-0"}],["path",{d:"M5 12l14 0",key:"svg-1"}]]),Bg=Lg("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"}]]),Og=Lg("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"}]]),zg=new WeakMap;var Hg=184,Dg="var(--land-shape-stroke-muted, #94a3b8)",Fg={heading:"flow-node-canvas-heading",dragHandle:"flow-node-drag-handle",name:"flow-node-canvas-name",input:"flow-node-canvas-name-input"},Wg=()=>{},jg={id:"land.flow.dom-events",handle:({event:t,name:e})=>t.target instanceof Element?t.target.closest("[data-flow-node-menu]")?"handled":"key_down"!==e&&"key_up"!==e||!t.target.closest("[data-flow-port-button]")?"continue":"handled":"continue",getCursor:({element:t})=>t?.closest("[data-flow-connector-port]")?"pointer":void 0};function Ug(t={}){const e=new Set(t.visiblePortIds??pi);return{shapeRenderers:[{type:"flow-edge",component:Kg,hoverComponent:Xg}],shapeDecorations:[{id:"land.flow.node-chrome",subType:ui,component:_g}],canvasOverlays:[{id:"land.flow.connector-ports",order:110,component:()=>d(qg,{visiblePortIds:e})}],domEventGuards:[jg]}}function Kg({editor:t,shape:e}){const n=l(t.state.selectedShapeIds);
|
|
21
|
-
return
|
|
22
|
-
return
|
|
23
|
-
return
|
|
24
|
-
return
|
|
25
|
-
|
|
26
|
-
return
|
|
27
|
-
return
|
|
28
|
-
return
|
|
29
|
-
return
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
return
|
|
34
|
-
return
|
|
35
|
-
return u("g",{pointerEvents:"none",children:[d("circle",{"data-flow-port-visual":"true",cx:n.x,cy:n.y,r:i,fill:"var(--land-selection, #2563eb)",style:{filter:"drop-shadow(0 1px 1.5px rgba(15, 23, 42, 0.24))"}}),d(Ng,{"aria-hidden":"true","data-flow-port-plus-icon":"true",x:n.x-s/2,y:n.y-s/2,width:s,height:s,color:"#ffffff",strokeWidth:2.5})]})}function em(t,e,n,r){return t>=r&&t+e<=n-r}function nm(t,e,n,r){return Math.min(Math.max(t,r),Math.max(r,n-e-r))}var rm="\n [data-flow-port-visual] {\n transition: r 120ms ease;\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",om={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:Hg},im={color:"var(--muted-foreground, #64748b)",fontSize:12,fontWeight:600,lineHeight:"18px",padding:"2px 8px 4px"},sm={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%"},am=class extends Mt{type="flow-edge";getDefaultEndpointProps(){return{portId:"right"}}validateEndpointProps(t,e){return function(t,e){const n=t&&"object"==typeof t?t:{};return{portId:"string"==typeof n.portId&&n.portId.length>0?n.portId:e}}(e,"right")}canBind(t,e,n){if(!hi(n.ownerShape)||e.endpoints.some(({slot:t})=>"start"!==t&&"end"!==t))return!1;for(const{endpoint:i,targetShape:s}of n.endpoints){const e=Ei(t,s,i.props);if(!e||!Ji(i.slot,{shape:s,port:e}))return!1}const r=e.endpoints.find(({slot:t})=>"start"===t),o=e.endpoints.find(({slot:t})=>"end"===t);return!(r&&o&&this.changesGraphTopology(t,e)&&Zi(t,r.targetId,o.targetId,e.ownerId))}getExclusiveBindingKey(t){return t.ownerId}onBindingCreate(t,e){return lm(e)||Yi(t).rebindEdgeId===e.ownerId?this.getSyncEffect(t,e.ownerId):{deleteShapeIds:[e.ownerId]}}onBindingUpdate(t,e,n){return lm(n)||Yi(t).rebindEdgeId===n.ownerId?this.getSyncEffect(t,n.ownerId):{deleteShapeIds:[n.ownerId]}}onBindingLoad(t,e){return this.getSyncEffect(t,e.ownerId)}onInvalidBindingLoad(t,e){return{deleteShapeIds:[e.ownerId]}}onAfterShapeChange(t,e){return this.getSyncEffect(t,e.ownerId)}onBeforeDeleteShape(t,e,n){return n.owner?{deleteBindingIds:[e.id]}:{deleteShapeIds:[e.ownerId]}}onBeforeDeleteBinding(t,e){if(Yi(t).rebindEdgeId!==e.ownerId)return{deleteShapeIds:[e.ownerId]};const n=t.shapes.get(e.ownerId);if(!hi(n))return{deleteBindingIds:[e.id]};const r=Ni(t,n);let o=n;for(const i of e.endpoints)o=rs(t,o,i.slot,"start"===i.slot?r.startPoint:r.endPoint)??o;return{shapes:[o],deleteBindingIds:[e.id],suppressBindingIds:[e.id]}}getGeometryDependentShapeIds(t,e,n){return n.endpointSlots.length>0?[e.ownerId]:[]}changesGraphTopology(t,e){const n=t.bindings.get(e.id);return!mi(n)||(n.ownerId!==e.ownerId||["start","end"].some(t=>{const r=n.endpoints.find(e=>e.slot===t),o=e.endpoints.find(e=>e.slot===t);return r?.targetId!==o?.targetId}))}getSyncEffect(t,e){const n=t.shapes.get(e);if(!hi(n))return;const r=function(t,e){return is(t,e)}(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:ts(t,e).map(({id:t})=>t)}:void 0}};function lm(t){return t.endpoints.some(({slot:t})=>"start"===t)&&t.endpoints.some(({slot:t})=>"end"===t)}var cm="flow-edge.rebind",dm={propagation:"stop"},um={propagation:"stop",clickSequence:"break"};function pm(){return{id:"land.flow-edge.interactions",priority:100,editorEvent:{handleEvent(t,e){const n=Yi(t),r=n.pointerSession;if("cancel"===e.type)return r?.cancel(e.reason),r?dm:void 0;if(!r){if("pointer"!==e.type||"pointer_down"!==e.name||0!==e.button)return;const r=function(t,e){if("select"!==t.state.tool.get().activeToolId||t.state.readonly.get()||t.state.shapeEditingSession.get()||t.inputs.isSpacePressed.get())return null;const n=Mg(t,null),r=n.visibleShapes[0];if(!r||!n.sourceShapeIds.has(r.id)||t.layers.isOrAncestorLocked(r.id)||t.shapes.isHidden(r.id)||null===t.shapes.getClippedPageBounds(r.id))return null;if(!Yi(t).isPortVisible("right"))return null;const o=ce(t,r,"right");if(!o)return null;const i=Math.max(t.state.cameraZoom.get(),1e-4),s=12/i;return e.dist(Ri(o,i))<=s?{shape:r,port:o}:null}(t,e.pagePoint);if(!r)return;const o=new hm(t,r,e.screenPoint,e.pointerId);return n.setPointerSession(o),dm}if("tick"===e.type){const n=t.inputs.state.get();if(n.pointerId===r.pointerId&&n.currentScreenPoint){const o=function(t,e,n){if(e.w<=0||e.h<=0||n<=0)return Tt.Zero();const r=Math.min(n,32),o=xe(t.x),i=xe(e.w-t.x),s=xe(t.y),a=1.25*(i-o)*r,l=1.25*(xe(e.h-t.y)-s)*r;return 0===a&&0===l?Tt.Zero():new Tt(a,l)}(n.currentScreenPoint,t.state.viewportScreenSize.get(),e.elapsed);0===o.x&&0===o.y||(t.viewport.pan(o),r.update(n.currentScreenPoint,t.viewport.screenToPage(n.currentScreenPoint),n.accelKey))}return dm}if("pointer"!==e.type||e.pointerId!==r.pointerId)return dm;if("pointer_move"===e.name)r.update(e.screenPoint,e.pagePoint,e.accelKey);else{if("pointer_up"===e.name)return r.complete(e.screenPoint,e.pagePoint,e.accelKey)?um:dm;"pointer_cancel"===e.name&&r.cancel("pointer_cancel")}return dm}},selectionHandle:{createSession:(t,{handle:e,shape:n})=>"binding_terminal"===e.kind&&hi(n)?function(t,e,n){if(!hi(t.shapes.get(e)))return null;const r=n.terminal,o="start"===r?"end":"start";let i=null;return{shapeId:e,operationKind:cm,onDragStart(){Yi(t).setRebindEdgeId(e)},update({pagePoint:n,accelKey:s,source:a}){Yi(t).setRebindEdgeId(e);const l=Qi(t,e)[o],c=s?null:("end"===r?Cg:$i)(t,n,{portFilter:n=>Ji(r,n)&&(!l||!Zi(t,"start"===r?n.shape.id:l.targetId,"start"===r?l.targetId:n.shape.id,e))&&("start"!==r||!t.layers.isOrAncestorLocked(n.shape.id))}),d=c&&!function(t,e,n,r,o){return!!r&&("start"===n?ss(t,o.shape.id,o.port.id,r.targetId,r.props.portId,e):ss(t,r.targetId,r.props.portId,o.shape.id,o.port.id,e))}(t,e,r,l,c)?c:null;i=d;const u=Qi(t,e)[r];if(!d&&u){const n=ts(t,e)[0];n&&t.commands.clearBindingEndpoint({bindingId:n.id,slot:r},{source:a})}const p=t.shapes.get(e);if(!hi(p))return{status:"stop"};const h=d?.port.pagePoint??n,f=rs(t,p,r,h);return f&&function(t,e,n){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:new Set(ts(t,e.id).map(t=>t.id))})}(t,f,a),d&&!os(t,e,r,Pi(d.shape.id,d.port),a)?{status:"stop"}:{status:"continue",finalPagePoint:h}},onCancel(){Yi(t).setRebindEdgeId(null)},onComplete(){Yi(t).setRebindEdgeId(null),!i&&t.shapes.get(e)&&t.shapes.delete([e],"user")}}}(t,n.id,e):null}}}var hm=class{editor;source;originScreenPoint;pointerId;preview;initialSelectedShapeIds;operation;props;didClearSelection=!1;constructor(t,e,n,r){this.editor=t,this.source=e,this.originScreenPoint=n,this.pointerId=r,this.initialSelectedShapeIds=t.selection.getIds(),this.props=t.shapes.getDefaultProps("flow-edge");const o=Mi(t,Pi(e.shape.id,e.port));if(!o?.port)throw new Error("Flow edge creation requires a resolvable output port");this.preview={start:o.draft,end:{kind:"free",pagePoint:o.pagePoint.clone()},startPoint:o.pagePoint,endPoint:o.pagePoint,startNormal:o.port.pageOutwardNormal,endNormal:o.port.pageOutwardNormal.mul(-1),isDragging:!1,invalidReason:null,target:null},this.operation=t.operations.begin({kind:"flow-edge.create",label:"shape.create",source:"user",history:"record"}),Yi(t).preview.set(this.preview)}update(t,e,n){const r=this.originScreenPoint.dist(t)>4;r&&!this.didClearSelection&&(this.initialSelectedShapeIds.length>0&&this.editor.commands.setSelectedShapeIds([],{source:"user"}),this.didClearSelection=!0);const o=r&&!n?Cg(this.editor,e,{portFilter:t=>!Zi(this.editor,this.source.shape.id,t.shape.id)}):null,i=Pi(this.source.shape.id,this.source.port),s=o?Pi(o.shape.id,o.port):{kind:"free",pagePoint:e},a=Mi(this.editor,i),l=Mi(this.editor,s);if(!a?.port||!l)return void this.cancel("command");const c={start:i,end:s,startPoint:a.pagePoint,endPoint:l.pagePoint,startNormal:a.port.pageOutwardNormal,endNormal:l.port?l.port.pageOutwardNormal:a.port.pageOutwardNormal.mul(-1),isDragging:r,invalidReason:es(this.editor,i,s),target:o};Object.assign(this.preview,c),Yi(this.editor).preview.set({...c})}complete(t,e,n){if(this.update(t,e,n),Yi(this.editor).pointerSession!==this)return!1;if(!this.preview.isDragging)return this.clear(),this.operation.cancel(),this.toggleNodeCreationRequest(),!1;if(!this.preview.target&&!this.editor.shapes.hitTest(e)){const t={...this.preview};return this.clear(),this.operation.cancel(),this.restoreSelection(),Yi(this.editor).nodeCreationRequest.set({inputPortPagePoint:e.clone(),preview:t,source:{shapeId:this.source.shape.id,portId:this.source.port.id}}),!0}const r=!this.preview.invalidReason&&!!ns(this.editor,{start:this.preview.start,end:this.preview.end,props:this.props,selectionAfter:"edge"});return this.clear(),r?(Yi(this.editor).nodeCreationRequest.set(null),this.operation.commit()):(this.operation.cancel(),this.restoreSelection()),r}cancel(t){this.clear(),this.operation.isActive&&this.operation.cancel(),this.restoreSelection()}clear(){const t=Yi(this.editor);t.preview.set(null),t.setPointerSession(null)}toggleNodeCreationRequest(){const t=Yi(this.editor),e=t.nodeCreationRequest.get(),n={shapeId:this.source.shape.id,portId:this.source.port.id};t.nodeCreationRequest.set(e?.source.shapeId===n.shapeId&&e.source.portId===n.portId?null:{source:n})}restoreSelection(){this.didClearSelection&&this.editor.commands.setSelectedShapeIds(this.initialSelectedShapeIds,{source:"system"})}};var fm=new Set(["straight","orthogonal","curved"]),gm=new Set(["solid","dashed"]),mm=new Set(["none","arrow"]),ym=class extends fe{type="flow-edge";getDefaultProps(){return{w:1,h:1,start:{x:0,y:.5},end:{x:1,y:.5},routing:"curved",stroke:Bt("stroke-muted"),strokeWidth:2,strokeStyle:"solid",headStart:"none",headEnd:"arrow",cornerRadius:5}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:wm(e.w,n.w,1),h:wm(e.h,n.h,1),start:xm(e.start,n.start),end:xm(e.end,n.end),routing:fm.has(e.routing)?e.routing:n.routing,stroke:zt(e.stroke)?Dt(e.stroke,n.stroke):n.stroke,strokeWidth:wm(e.strokeWidth,n.strokeWidth,.5),strokeStyle:gm.has(e.strokeStyle)?e.strokeStyle:n.strokeStyle,headStart:mm.has(e.headStart)?e.headStart:n.headStart,headEnd:mm.has(e.headEnd)?e.headEnd:n.headEnd,cornerRadius:wm(e.cornerRadius,n.cornerRadius,0)}}getLocalBounds(t){return new Ct(0,0,t.props.w,t.props.h).expand(Math.max(6,4*t.props.strokeWidth))}canSnap(){return!1}canParticipateInSelectionResize(t,e){return!1}canParticipateInSelectionFlip(){return!1}canParticipateInSelectionRotation(){return!1}canParticipateInSelectionTranslation(){return!1}canUseSelectionResizeHandles(){return!1}canUseSelectionRotateHandle(){return!1}canStartTranslateFromSelectionBounds(){return!1}contributesToSelectionFrame(t,e){return!0}getSelectionHandleAnchors(t,e){if(!e.isOnlySelected)return{terminalHandleAnchors:[],middleHandleAnchors:[]};const n=Ni(e.editor,t);return{terminalHandleAnchors:[{kind:"binding_terminal",terminal:"start",point:n.startPoint},{kind:"binding_terminal",terminal:"end",point:n.endPoint}],middleHandleAnchors:[],customHandleAnchors:[]}}getSelectionOverlayInfo(t,e){const n=Ni(e.editor,t),r=Bi(e.editor,t);return{usesSelectionPathOverlay:!0,startPagePoint:n.startPoint,endPagePoint:n.endPoint,middlePagePoint:null,path:n.path,pathStyle:{localPath:r.path,localDecorationPaths:r.markerPath?[r.markerPath]:[],localBounds:r.bounds,localToPage:e.editor.shapes.computeLocalToPageTransform(t),strokeWidth:t.props.strokeWidth,strokeDasharray:"dashed"===t.props.strokeStyle?"8 6":void 0},bindingSegments:[]}}canCopyToClipboard(t,e){const n=Qi(e.editor,t.id);return!!(n.start&&n.end&&e.copiedShapeIds.has(n.start.targetId)&&e.copiedShapeIds.has(n.end.targetId))}isValidAfterBindingLoad(t,e){const n=Qi(e.editor,t.id);return!!(n.start&&n.end&&ts(e.editor,t.id).some(t=>e.editor.bindings.canBind(t)))}isWrappedByBrush(t,e){return Ni(e.editor,t).points.every(t=>e.brushBounds.containsPoint(t))}hitTest(t,e,n){const r=n?.editor?Ni(n.editor,t).points:[new Tt(t.x+t.props.start.x,t.y+t.props.start.y),new Tt(t.x+t.props.end.x,t.y+t.props.end.y)],o=n?.editor?Math.max(8/Math.max(n.editor.state.cameraZoom.get(),1e-4),4):8;return function(t,e){let n=1/0;for(let r=1;r<t.length;r+=1)n=Math.min(n,bm(e,t[r-1],t[r]));return n}(r,n?.pagePoint??e)<=o}hitTestLineSegment(t,e){const n=e.editor?Ni(e.editor,t).points:[new Tt(t.x+t.props.start.x,t.y+t.props.start.y),new Tt(t.x+t.props.end.x,t.y+t.props.end.y)],r=e.editor?e.pageStart:e.positionedStart,o=e.editor?e.pageEnd:e.positionedEnd,i=e.editor?e.pageMargin:e.positionedMargin;for(let s=1;s<n.length;s+=1)if(Math.min(bm(n[s-1],r,o),bm(n[s],r,o),bm(r,n[s-1],n[s]),bm(o,n[s-1],n[s]))<=i)return!0;return!1}};function wm(t,e,n=-1/0){return"number"==typeof t&&Number.isFinite(t)?Math.max(t,n):e}function xm(t,e){const n=t&&"object"==typeof t?t:{};return{x:wm(n.x,e.x),y:wm(n.y,e.y)}}function bm(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)))}var vm=34;function km(t){return new Ct(0,-34,t.props.w,t.props.h+34)}var Sm=class{id="land.flow.node-chrome";subType=ui;getExportBounds(t){return fi(t)?km(t):null}getPointHitTestBounds(t,e){return fi(t)?ye({bodyHeight:t.props.h,bodyWidth:t.props.w,headingHeight:34,shape:t}):new Ct(t.x,t.y,0,0)}hitTest(t,e,n){return fi(t)&&me({bodyHeight:t.props.h,bodyWidth:t.props.w,editor:n.editor,headingHeight:34,shape:t}).containsPoint(e)}toSvg(t,e){return fi(t)?{tag:"g",children:[{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:[gi(t)]}]}:null}},Im=class{type="flow-edge";toSvg(t,e){const n=Bi(e.editor,t),r=e.resolveColor(t.props.stroke),o=[{tag:"path",attrs:{d:n.path,fill:"none",stroke:r,"stroke-width":t.props.strokeWidth,"stroke-dasharray":"dashed"===t.props.strokeStyle?"8 6":void 0,"stroke-linecap":"round","stroke-linejoin":"round"}}];return n.markerPath&&o.push({tag:"path",attrs:{d:n.markerPath,fill:"none",stroke:r,"stroke-width":t.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round"}}),{tag:"g",children:o}}};function Pm(){const t=new Sm;return{shapeUtils:[new ym],shapeSvgExporters:[new Im],shapeSvgDecorations:[t],shapeHitTestDecorations:[t],bindingUtils:[new am],interactionHandlers:[pm()]}}function Mm(t){const e=[...t.visiblePortIds??pi],{image:n,text:r}=t;return s({id:"flow",requires:[n,r],editor:Pm(),render:Ug({visiblePortIds:e}),setup({api:n,editor:o}){const i=n(r),s=function(t){let e=null;const n={resolveTextLayoutSize:t=>e?.(t),setTextLayoutResolver(t){e=t},dispose(){zg.delete(t),e=null}};return zg.set(t,n),n}(o),a=function(t,e){const n=t.signals.atom("flow.edge-preview",null),r=t.signals.atom("flow.node-creation-request",null),o=new Set(e.visiblePortIds);let i=null,s=null;const a={allowCycles:e.allowCycles,nodeCreationRequest:r,preview:n,get pointerSession(){return i},get rebindEdgeId(){return s},isPortVisible:t=>o.has(t),setPointerSession(t){i=t},setRebindEdgeId(t){s=t},dispose(){Xi.delete(t),i?.cancel("dispose"),i=null,s=null,r.set(null),n.set(null)}};return Xi.set(t,a),a}(o,{allowCycles:t.allowCycles??!0,visiblePortIds:e});try{s.setTextLayoutResolver(t=>i.resolveLayoutSize(t));const t=yg({editor:o});return{api:t.value,dispose(){try{t.dispose()}finally{try{a.dispose()}finally{s.dispose()}}}}}catch(l){try{a.dispose()}finally{s.dispose()}throw l}}})}var Tm=["rectangle","ellipse","message-circle","summary","summary-left","burst","rhombus","triangle","pentagon","hexagon","star","trapezoid","arrow-left","arrow-right"],Cm=["solid","dashed","dotted","none"],Em=["none","solid","tint","pattern","linear","radial"];function Am(t){return It(t)&&"geo"===t.type}function Lm(t){return"string"==typeof t&&Tm.includes(t)}function Rm(t){return"string"==typeof t&&Cm.includes(t)}function $m(t){return"string"==typeof t&&Em.includes(t)}var Nm=new WeakMap;function Bm(t){const e=Nm.get(t);if(!e)throw new Error("GeoCreationRuntime is not initialized for this editor.");return e}function Om(t,e){return new Ct(t.x,t.y,e.w,e.h)}var zm=class extends we{kind;constructor(t,e,n){super(t,e),this.kind=n,this.initial="idle",this.addChild(new Hm(t,this)),this.addChild(new Dm(t,this))}getDefaultProps(){return{...this.editor.shapes.getDefaultProps("geo"),kind:this.kind}}onEnter(){this.editor.shapes.updateDefaultProps("geo",{kind:this.kind})}},Hm=class extends we{tool;constructor(t,e){super(t,"idle",e),this.tool=e}onEnter(){this.editor.interaction.clearSelection()}onExit(){Bm(this.editor).clearHover()}onPointerMove(t){const e=Bm(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})}},Dm=class extends we{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(Om(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&&Gt(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 Tt(t.x+r,t.y+o);return new Ct(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}},Fm=class extends zm{constructor(t){super(t,"rectangle","rectangle")}},Wm=class extends zm{constructor(t){super(t,"ellipse","ellipse")}},jm=class extends zm{constructor(t){super(t,"message-circle","message-circle")}},Um=class extends zm{constructor(t){super(t,"summary","summary")}},Km=class extends zm{constructor(t){super(t,"summary-left","summary-left")}},Xm=class extends zm{constructor(t){super(t,"burst","burst")}},Ym=class extends zm{constructor(t){super(t,"rhombus","rhombus")}},_m=class extends zm{constructor(t){super(t,"triangle","triangle")}},qm=class extends zm{constructor(t){super(t,"pentagon","pentagon")}},Gm=class extends zm{constructor(t){super(t,"hexagon","hexagon")}},Vm=class extends zm{constructor(t){super(t,"star","star")}},Jm=class extends zm{constructor(t){super(t,"trapezoid","trapezoid")}},Zm=class extends zm{constructor(t){super(t,"arrow-left","arrow-left")}},Qm=class extends zm{constructor(t){super(t,"arrow-right","arrow-right")}},ty=/[AaCcHhLlMmVvZz]|[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?/g,ey=/^[AaCcHhLlMmVvZz]$/,ny=Math.PI/6,ry=1e-8;function oy(t){const e=t.match(ty)??[],n=t.replace(ty,"").replace(/[\s,]/g,"");if(n.length>0)throw new Error(`Unsupported SVG path content: ${n}`);const r=[];let o=null,i=null,s=new Tt(0,0),a=0;for(;a<e.length;){const t=e[a];if(t&&ey.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=iy(n),c=sy(e,a,l);a+=l;const d=n===n.toLowerCase();switch(n.toLowerCase()){case"m":s=ly(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=ly(s,c[0],c[1],d);cy(o,{type:"line",start:s,end:t}),s=t;break}case"h":{const t=new Tt(d?s.x+c[0]:c[0],s.y);cy(o,{type:"line",start:s,end:t}),s=t;break}case"v":{const t=new Tt(s.x,d?s.y+c[0]:c[0]);cy(o,{type:"line",start:s,end:t}),s=t;break}case"c":{const t=ly(s,c[0],c[1],d),e=ly(s,c[2],c[3],d),n=ly(s,c[4],c[5],d);cy(o,{type:"cubic",start:s,control1:t,control2:e,end:n}),s=n;break}case"a":{const t=ay(c[3]),e=ay(c[4]),n=ly(s,c[5],c[6],d);cy(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 iy(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 sy(t,e,n){const r=[];for(let o=0;o<n;o+=1){const n=t[e+o];if(!n||ey.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 ay(t){if(0!==t&&1!==t)throw new Error(`SVG arc flag must be 0 or 1, received ${t}.`);return 1===t}function ly(t,e,n,r){return r?new Tt(t.x+e,t.y+n):new Tt(e,n)}function cy(t,e){if(!t)throw new Error("SVG path draws before starting a subpath.");t.segments.push(e)}function dy(t){const e=[t.start.clone()];for(const n of t.segments)switch(n.type){case"line":by(e,n.end);break;case"cubic":{const t=[...Array.from({length:8},(t,e)=>(e+1)/8),...py(n)].sort((t,e)=>t-e).filter((t,e,n)=>0===e||Math.abs(t-(n[e-1]??t))>ry);for(const r of t)by(e,uy(n,r));break}case"arc":for(const t of fy(n))by(e,t)}return t.closed&&e.length>1&&vy(e[0],e[e.length-1])&&e.pop(),e}function uy(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 Tt(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 py(t){return[...hy(t.start.x,t.control1.x,t.control2.x,t.end.x),...hy(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))>ry)}function hy(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)<=ry)return Math.abs(i)<=ry?[]:[-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 fy(t){const e=gy(t);if(!e)return[t.end.clone()];const n=Math.max(1,Math.ceil(Math.abs(e.deltaAngle)/ny)),r=[...Array.from({length:n},(t,e)=>(e+1)/n),...my(e).map(t=>function(t,e){return yy(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))>ry),o=[];for(const i of r){const t=e.startAngle+e.deltaAngle*i;o.push(xy(e,t))}return o[o.length-1]=t.end.clone(),o}function gy(t){if(0===t.radiusX||0===t.radiusY||vy(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,w=0===g?0:y*Math.sqrt(m/g),x=w*(l*a/c),b=w*(-c*s/l),v=n*x-r*b+(t.start.x+t.end.x)/2,k=r*x+n*b+(t.start.y+t.end.y)/2,S=(s-x)/l,I=(a-b)/c,P=(-s-x)/l,M=(-a-b)/c,T=Math.atan2(I,S);let C=(E=S,A=I,L=P,R=M,Math.atan2(E*R-A*L,E*L+A*R));var E,A,L,R;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 my(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 yy(t,e)<=Math.abs(t.deltaAngle)+ry}(t,e))}function yy(t,e){return t.deltaAngle>=0?wy(e-t.startAngle):wy(t.startAngle-e)}function wy(t){const e=2*Math.PI;return(t%e+e)%e}function xy(t,e){const n=t.radiusX*Math.cos(e),r=t.radiusY*Math.sin(e);return new Tt(t.centerX+t.cosRotation*n-t.sinRotation*r,t.centerY+t.sinRotation*n+t.cosRotation*r)}function by(t,e){const n=t[t.length-1];n&&vy(n,e)||t.push(e.clone())}function vy(t,e){return Math.abs(t.x-e.x)<=ry&&Math.abs(t.y-e.y)<=ry}var ky=24,Sy=3.222,Iy=12.443999999999999+Math.max(3.191,3.19)+1,Py="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",My=function(t){const e=function(t){return oy(t).map(t=>({closed:t.closed,points:dy(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}(Py),Ty=function(t){const e=[];for(const n of oy(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 py(t))e.push(uy(t,n));break;case"arc":{const n=gy(t);if(!n)break;for(const t of my(n))e.push(xy(n,t));break}}}if(0===e.length)throw new Error("SVG path does not contain any points.");return Ct.FromPoints(e)}(Py),Cy=[[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]],Ey=[[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]],Ay=[[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 Ly(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 Tt(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=[Jy(t,Oy),Jy(t,zy)];let n=zy;for(const r of Hy){for(let o=1;o<=By;o+=1)e.push(Jy(t,Vy(n,r.control1,r.control2,r.end,o/By)));n=r.end}return e}(t);case"summary":case"summary-left":return rw(t);case"burst":return function(t){return My.map(e=>tw(t,(e.x-Ty.minX)/Ty.w,(e.y-Ty.minY)/Ty.h))}(t);case"rhombus":return[new Tt(t.center.x,t.minY),new Tt(t.maxX,t.center.y),new Tt(t.center.x,t.maxY),new Tt(t.minX,t.center.y)];case"triangle":return[new Tt(t.center.x,t.minY),new Tt(t.maxX,t.maxY),new Tt(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 Tt(Math.cos(t),Math.sin(t)))}return ew(n,t)}(t,5);case"hexagon":return[new Tt(t.minX+.25*t.w,t.minY),new Tt(t.maxX-.25*t.w,t.minY),new Tt(t.maxX,t.center.y),new Tt(t.maxX-.25*t.w,t.maxY),new Tt(t.minX+.25*t.w,t.maxY),new Tt(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 Tt(Math.cos(t)*r,Math.sin(t)*r))}return ew(e,t)}(t);case"trapezoid":return function(t){return Cy.map(([e,n])=>tw(t,e/ky,n/ky))}(t);case"arrow-left":return Ky(t,"left").outline;case"arrow-right":return Ky(t,"right").outline;case"rectangle":return function(t,e=$y(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 rw(t);const o=[];return nw(o,{centerX:t.maxX-r,centerY:t.minY+r,radius:r,startAngle:-Math.PI/2,endAngle:0,segments:n}),nw(o,{centerX:t.maxX-r,centerY:t.maxY-r,radius:r,startAngle:0,endAngle:Math.PI/2,segments:n}),nw(o,{centerX:t.minX+r,centerY:t.maxY-r,radius:r,startAngle:Math.PI/2,endAngle:Math.PI,segments:n}),nw(o,{centerX:t.minX+r,centerY:t.minY+r,radius:r,startAngle:Math.PI,endAngle:3*Math.PI/2,segments:n}),o}(t,$y({cornerRadiusPercent:n.cornerRadiusPercent,w:t.w,h:t.h}))}return iw(e)}function Ry(t,e=12){return Math.min(50,Math.max(0,"number"==typeof t&&Number.isFinite(t)?t:e))}function $y({cornerRadiusPercent:t=12,h:e,w:n}){return Math.min(Math.max(0,n),Math.max(0,e))*Ry(t)/100}var Ny=24,By=8,Oy=new Tt(3,20),zy=new Tt(4.3,16.1),Hy=[{control1:new Tt(1.976,12.663),control2:new Tt(2.874,8.228),end:new Tt(6.4,5.726)},{control1:new Tt(9.926,3.225),control2:new Tt(14.99,3.43),end:new Tt(18.245,6.206)},{control1:new Tt(21.5,8.983),control2:new Tt(21.94,13.472),end:new Tt(19.274,16.707)},{control1:new Tt(16.608,19.942),control2:new Tt(11.659,20.922),end:new Tt(7.7,19)}];function Dy(t){const e=Jy(t,Oy),n=Jy(t,zy),r=[`M${Zy(e)}`,`L${Zy(n)}`];for(const o of Hy)r.push(`C${Zy(Jy(t,o.control1))} ${Zy(Jy(t,o.control2))} ${Zy(Jy(t,o.end))}`);return r.push(`L${Zy(e)}`),r.join(" ")}function Fy(t){const e=t.w/ky,n=t.h/ky;return`translate(${Qy(t.x)} ${Qy(t.y)}) scale(${Qy(e)} ${Qy(n)})`}function Wy(t){const e=t.w/Ty.w,n=t.h/Ty.h,r=t.minX-Ty.minX*e,o=t.minY-Ty.minY*n;return`translate(${Qy(r)} ${Qy(o)}) scale(${Qy(e)} ${Qy(n)})`}function jy(t,e){const n=Math.min(t.w/ky,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(${Qy(o)} ${Qy(i)}) scale(${Qy(n)} ${Qy(r)})`}function Uy(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:Dy(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:jy(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:jy(t,"left"),vectorEffect:"non-scaling-stroke"};case"burst":return{tag:"path",d:Py,transform:Wy(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:Fy(t),vectorEffect:"non-scaling-stroke"};case"arrow-left":return{tag:"path",d:Ky(t,"left").path};case"arrow-right":return{tag:"path",d:Ky(t,"right").path};case"rectangle":{const e=$y({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:Ly(t,e,n)}}return iw(e)}function Ky(t,e){const n=Math.min(t.h/ky,t.w/Iy),r=t.center.y-12*n,o="left"===e?t.minX+Sy*n:t.maxX-Sy*n,i="left"===e?o+9.222*n:o-9.222*n;return{outline:("left"===e?Ey:Ay).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-(ky-s)*i:_y(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:_y(s,3.29,11.556,t.minX+3.29*i,r);return new Tt(l,o+a*i)}(t,e,{neckX:i,originY:r,scale:n,x:o,y:s})),path:"left"===e?Xy(t,{neckX:i,originY:r,scale:n}):Yy(t,{neckX:i,originY:r,scale:n})}}function Xy(t,e){if(Gy(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${Zy(new Tt(n,r+6.416*o))}`,`v${Qy(.9*o)}`,`H${Qy(i)}`,`a${qy(o,[.1,.1,0,0,1,.1,.1])}`,`v${Qy(8.455*o)}`,`a${qy(o,[.1,.1,0,0,1,-.1,.1])}`,`H${Qy(n)}`,`v${Qy(4.314*o)}`,`c${qy(o,[0,.034,-.008,.048,-.014,.056])}`,`a${qy(o,[.1,.1,0,0,1,-.047,.036])}`,`a${qy(o,[.1,.1,0,0,1,-.058,.009])}`,`c${qy(o,[-.01,-.002,-.025,-.005,-.05,-.029])}`,`l${qy(o,[-9.053,-8.641])}`,`a${qy(o,[.1,.1,0,0,1,0,-.145])}`,`l${qy(o,[9.053,-8.641])}`,`c${qy(o,[.025,-.024,.04,-.028,.05,-.03])}`,`a${qy(o,[.1,.1,0,0,1,.058,.01])}`,`a${qy(o,[.1,.1,0,0,1,.047,.036])}`,`c${qy(o,[.006,.008,.014,.022,.014,.056])}`,"z"].join(" ")}function Yy(t,e){if(Gy(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${Zy(new Tt(n-.9*o,r+7.316*o))}`,`H${Qy(n)}`,`V${Qy(r+3.002*o)}`,`c${qy(o,[0,-.034,.008,-.048,.014,-.056])}`,`a${qy(o,[.1,.1,0,0,1,.046,-.036])}`,`a${qy(o,[.1,.1,0,0,1,.059,-.01])}`,`c${qy(o,[.01,.002,.025,.006,.05,.03])}`,`l${qy(o,[9.053,8.641])}`,`a${qy(o,[.1,.1,0,0,1,0,.145])}`,`l${qy(o,[-9.053,8.641])}`,`c${qy(o,[-.025,.024,-.04,.027,-.05,.029])}`,`a${qy(o,[.1,.1,0,0,1,-.059,-.01])}`,`a${qy(o,[.1,.1,0,0,1,-.046,-.035])}`,`c${qy(o,[-.006,-.008,-.014,-.022,-.014,-.056])}`,`V${Qy(r+15.97*o)}`,`H${Qy(i)}`,`a${qy(o,[.1,.1,0,0,1,-.1,-.1])}`,`V${Qy(r+7.416*o)}`,`a${qy(o,[.1,.1,0,0,1,.1,-.1])}`,"z"].join(" ")}function _y(t,e,n,r,o){const i=n-e;return 0===i?r:r+(t-e)/i*(o-r)}function qy(t,e){const n=7===e.length;return e.map((e,r)=>Qy(n&&r>=2&&r<=4?e:e*t)).join(" ")}function Gy(t){return 0===t.x&&0===t.y&&t.w===ky&&t.h===ky}function Vy(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 Tt(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 Jy(t,e){return tw(t,e.x/Ny,e.y/Ny)}function Zy(t){return`${Qy(t.x)} ${Qy(t.y)}`}function Qy(t){return Number.isFinite(t)?Number(t.toFixed(4)).toString():"0"}function tw(t,e,n){return new Tt(t.minX+t.w*e,t.minY+t.h*n)}function ew(t,e){const n=Ct.FromPoints([...t]);return 0===n.w||0===n.h?[e.center]:t.map(t=>new Tt(e.minX+(t.x-n.minX)/n.w*e.w,e.minY+(t.y-n.minY)/n.h*e.h))}function nw(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 Tt(e+Math.cos(i)*o,n+Math.sin(i)*o))}}function rw(t){return[new Tt(t.minX,t.minY),new Tt(t.maxX,t.minY),new Tt(t.maxX,t.maxY),new Tt(t.minX,t.maxY)]}function ow(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 iw(t){throw new Error(`Unsupported geo shape kind: ${String(t)}`)}function sw(t){return[{id:"start",offset:0,color:t,midpoint:.5},{id:"end",offset:1,color:Ot("#a855f7"),midpoint:.5}]}function aw(t,e){if(!Array.isArray(t))return e;const n=new Set,r=[];for(const o of t){if(!o||"object"!=typeof o||!zt(o.color)||!Number.isFinite(o.offset))continue;let t="string"==typeof o.id&&o.id?o.id:`stop-${r.length}`;for(;n.has(t);)t+="-copy";n.add(t),r.push({id:t,offset:Math.max(0,Math.min(1,o.offset)),color:o.color,midpoint:Number.isFinite(o.midpoint)?Math.max(.01,Math.min(.99,o.midpoint)):.5})}return r.length>=2?r.sort((t,e)=>t.offset-e.offset):e}function lw(t,e){return t===e||t.length===e.length&&t.every((t,n)=>{const r=e[n];return t.offset===r.offset&&t.midpoint===r.midpoint&&Ut(t.color,r.color)})}function cw(t){if("transparent"===t)return[0,0,0,0];const e=/^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i.exec(t);if(!e)return null;const n=e[1].length<=4?[...e[1]].map(t=>t+t).join(""):e[1];return[0,2,4].map(t=>parseInt(n.slice(t,t+2),16)).concat(8===n.length?parseInt(n.slice(6),16)/255:1)}function dw(t,e,n){if(n<=0)return t;if(n>=1)return e;const r=cw(t),o=cw(e);if(!r||!o)return`color-mix(in srgb, ${t} ${100*(1-n)}%, ${e})`;const i=r[3]*(1-n)+o[3]*n;return`#${[...[0,1,2].map(t=>r[t]*(1-n)+o[t]*n),255*i].map(t=>Math.round(t).toString(16).padStart(2,"0")).join("")}`}function uw(t,e){return t.flatMap((n,r)=>{const o=e(n.color),i=t[r+1],s=[{offset:n.offset,color:o}];return i&&i.offset>n.offset&&.5!==n.midpoint&&s.push({offset:n.offset+(i.offset-n.offset)*n.midpoint,color:dw(o,e(i.color),.5)}),s})}function pw(t,e){const n=uw(t,Wt);let r=n[0];for(const o of n.slice(1)){if(o.offset>e){const t=Math.max(0,(e-r.offset)/(o.offset-r.offset));return Ot(dw(r.color,o.color,t))}r=o}return Ot(r.color)}var hw="drop-shadow(0px 2px 4px rgba(0, 0, 0, 0.04)) drop-shadow(0px 1px 1px rgba(0, 0, 0, 0.02))";function fw(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function gw(t,e){return t.x*e.y-t.y*e.x}function mw(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 yw(t,e,n,r){return ww(t,e,n,r)?0:Math.min(mw(t,n,r),mw(e,n,r),mw(n,t,e),mw(r,t,e))}function ww(t,e,n,r){const o=e.sub(t),i=r.sub(n),s=gw(o,i);if(Math.abs(s)<1e-8)return null;const a=n.sub(t),l=gw(a,i)/s,c=gw(a,o)/s;return l<0||l>1||c<0||c>1?null:{point:t.add(o.mul(l)),t:l}}function xw(t,e,n){const r=new Ct(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=ww(t,e,i,s);!a||a.t<=1e-6||(!r||a.t<r.t)&&(r=a)}return r?.point??null}(e,n,Ly(r,t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent}))}function bw(t){return Ly(new Ct(0,0,t.props.w,t.props.h),t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent})}var vw=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"];function kw(t){const e=new Ct(0,0,t.props.w,t.props.h);return[new Tt(e.minX,e.minY),new Tt(e.center.x,e.minY),new Tt(e.maxX,e.minY),new Tt(e.minX,e.center.y),e.center,new Tt(e.maxX,e.center.y),new Tt(e.minX,e.maxY),new Tt(e.center.x,e.maxY),new Tt(e.maxX,e.maxY)].map((t,e)=>({point:t,kind:vw[e]??"custom"}))}function Sw(t){return"arrow-left"===t.props.kind||"arrow-right"===t.props.kind}function Iw(t){return Ct.FromPoints(Ly(new Ct(0,0,t.w,t.h),t.kind,{cornerRadiusPercent:t.cornerRadiusPercent}))}var Pw=class extends fe{type="geo";getDefaultProps(){return{w:160,h:108,kind:"rectangle",fill:Bt("fill-slate"),fillStyle:"solid",gradientStops:sw(Bt("fill-slate")),gradientAngle:0,stroke:Bt("stroke-slate"),strokeStyle:"solid",strokeWidth:2,cornerRadiusPercent:12,shadow:!1}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Math.max(1,fw(e.w,n.w)),h:Math.max(1,fw(e.h,n.h)),kind:Lm(e.kind)?e.kind:n.kind,fill:Dt(e.fill,n.fill),fillStyle:$m(e.fillStyle)?e.fillStyle:n.fillStyle,gradientStops:aw(e.gradientStops,sw(Dt(e.fill,n.fill))),gradientAngle:(fw(e.gradientAngle,n.gradientAngle)%360+360)%360,stroke:Dt(e.stroke,n.stroke),strokeStyle:Rm(e.strokeStyle)?e.strokeStyle:n.strokeStyle,strokeWidth:Math.max(1,fw(e.strokeWidth,n.strokeWidth)),cornerRadiusPercent:Ry(e.cornerRadiusPercent,n.cornerRadiusPercent),shadow:"boolean"==typeof e.shadow?e.shadow:n.shadow}}getLocalBounds(t){return new Ct(0,0,t.props.w,t.props.h)}getRenderBounds(t){return this.getLocalBounds(t).expand(t.props.shadow?14:0)}getExportBounds(t){return this.getRenderBounds(t)}canReceiveTerminalBinding(t){return!0}getPositionedOutlineVertices(t){return Ly(this.getPositionedBounds(t),t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent})}getSelectionResizeLocalBounds(t){return Sw(t)?Iw(t.props):this.getLocalBounds(t)}resizeSelectionBounds(t,e){if(!Sw(t))return super.resizeSelectionBounds(t,e);const n=Iw(t.props).w*Math.abs(e.scaleX),r=Math.max(1,t.props.h*Math.abs(e.scaleY)),o=function({direction:t,height:e,selectionWidth:n}){const r=Sy+("left"===t?3.191:3.19),o=e/ky,i=n+r*o;return i>=Iy*o?i:n/(1-r/Iy)}({direction:"arrow-left"===t.props.kind?"left":"right",height:r,selectionWidth:n}),i=this.validateProps({...t.props,w:o,h:r}),s=Iw(i),a=oe({localWidth:s.w,localHeight:s.h,scaleX:t.scaleX,scaleY:t.scaleY}),l=ee(se({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 Ct(0,0,i.w,i.h).center,h=s.center.sub(p),f=new Tt(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:kw(t),outline:bw(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(ow(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,Ly(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),w=(-f-y)/(2*h),x=(-f+y)/(2*h);return w>=0&&w<=1||x>=0&&x<=1}(n,e.positionedStart,e.positionedEnd,e.positionedMargin);{const r=Ly(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&&yw(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=xw(t,r.applyToPoint(e.rawPagePoint),r.applyToPoint(e.oppositePagePoint));return o?n.applyToPoint(o):e.rawPagePoint}};function Mw(t,e){switch(t){case"dashed":return`${4*e} ${2*e}`;case"dotted":return"0 "+2*e;default:return}}var Tw=8,Cw="M0 8 8 0",Ew=8,Aw=1.25,Lw="4 4",Rw=-2,$w=.08,Nw=.5;function Bw(t){return"linear"===t||"radial"===t}function Ow({style:t,angle:e,width:n,height:r,x:o=0,y:i=0}){if("radial"===t)return{gradientUnits:"objectBoundingBox",cx:.5,cy:.5,r:.5};const s=e*Math.PI/180,a=Math.cos(s),l=Math.sin(s),c=Math.max(1,n),d=Math.max(1,r),u=(Math.abs(c*a)+Math.abs(d*l))/2;return{gradientUnits:"userSpaceOnUse",x1:o+c/2-a*u,y1:i+d/2-l*u,x2:o+c/2+a*u,y2:i+d/2+l*u}}function zw({stops:t,resolveColor:e,...n}){return{tag:"linear"===n.style?"linearGradient":"radialGradient",attrs:Ow(n),children:uw(t,e).map(({offset:t,color:e})=>({tag:"stop",attrs:{offset:t,"stop-color":e}}))}}function Hw({color:t,style:e,definitionId:n}){return{fill:"none"===e?"none":"pattern"===e||Bw(e)?`url(#${n})`:t,fillOpacity:"tint"===e?.18:1}}function Dw(t,e,n){return{tag:"pattern",attrs:{width:Tw/Math.max(1,e),height:Tw/Math.max(1,n),patternUnits:"objectBoundingBox",viewBox:`0 0 ${Tw} ${Tw}`,preserveAspectRatio:"none"},children:[{tag:"rect",attrs:{width:Tw,height:Tw,fill:t,"fill-opacity":$w}},{tag:"path",attrs:{d:Cw,fill:"none",stroke:t,pathLength:Ew,"stroke-width":Aw,"stroke-dasharray":Lw,"stroke-dashoffset":Rw,"stroke-opacity":Nw}}]}}var Fw=class{type="geo";toSvg(t,e){const{kind:n,fill:r,fillStyle:o,stroke:i,strokeStyle:s,strokeWidth:a,w:l,h:c}=t.props,d=e.resolveColor(r),u="none"===s?0:a,p=u/2,h=Math.max(l-u,0),f=Math.max(c-u,0),g=Hw({color:d,style:o,definitionId:"pattern"===o?e.addDef(Dw(d,h,f)):Bw(o)?e.addDef(zw({stops:t.props.gradientStops,resolveColor:t=>e.resolveColor(t),style:o,angle:t.props.gradientAngle,width:h,height:f,x:p,y:p})):""}),m={fill:g.fill,"fill-opacity":g.fillOpacity,stroke:"none"===s?"none":e.resolveColor(i),"stroke-width":u,"stroke-dasharray":Mw(s,a),"stroke-linejoin":"round","stroke-linecap":"round",style:t.props.shadow?`filter:${hw}`:void 0};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=>`${jw(t.x)},${jw(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}}}}(Uy(new Ct(p,p,h,f),n,{cornerRadiusPercent:t.props.cornerRadiusPercent}),m)}};function Ww(){return{shapeUtils:[new Pw],shapeSvgExporters:[new Fw],tools:{rectangle:t=>new Fm(t),ellipse:t=>new Wm(t),"message-circle":t=>new jm(t),summary:t=>new Um(t),"summary-left":t=>new Km(t),burst:t=>new Xm(t),rhombus:t=>new Ym(t),triangle:t=>new _m(t),pentagon:t=>new qm(t),hexagon:t=>new Gm(t),star:t=>new Vm(t),trapezoid:t=>new Jm(t),"arrow-left":t=>new Zm(t),"arrow-right":t=>new Qm(t)}}}function jw(t){return Number.isFinite(t)?Number(t.toFixed(4)).toString():"0"}function Uw({id:t,stops:e,resolveColor:n=Ft,...r}){
|
|
36
|
-
return
|
|
37
|
-
return
|
|
38
|
-
return
|
|
39
|
-
return
|
|
40
|
-
|
|
41
|
-
return
|
|
42
|
-
return
|
|
43
|
-
return
|
|
44
|
-
return
|
|
45
|
-
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:e,strokeWidth:n,vectorEffect:"non-scaling-stroke"})})}function Sx(t={}){return s({id:"html",editor:xx(),render:vx(t),setup:({editor:t})=>({api:gx({editor:t})})})}var Ix=Sx(),Px=1e-4,Mx=1e-4,Tx="image.crop",Cx=[{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}],Ex={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"},Ax=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"];function Lx(t){return Math.min(1,Math.max(0,t))}function Rx(t,e,n){return Math.min(n,Math.max(e,t))}function $x(t){return!!t&&"object"==typeof t&&"number"==typeof t.x&&Number.isFinite(t.x)&&"number"==typeof t.y&&Number.isFinite(t.y)}function Nx(t,e){const n=Lx(t),r=Lx(e);let o=Math.min(n,r),i=Math.max(n,r);if(i-o<Px){const t=(o+i)/2;o=Math.max(0,Math.min(.9999,t-5e-5)),i=o+Px}return{min:o,max:i}}function Bx(t){if(!t||"object"!=typeof t)return null;const e=t;if(!$x(e.topLeft)||!$x(e.bottomRight))return null;const n=Nx(e.topLeft.x,e.bottomRight.x),r=Nx(e.topLeft.y,e.bottomRight.y);return{topLeft:{x:n.min,y:r.min},bottomRight:{x:n.max,y:r.max}}}function Ox(t){const e=Bx(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 zx(t){return Ox(t)??{left:0,top:0,right:1,bottom:1,width:1,height:1}}function Hx(t,e){return Math.abs(t.left-e.left)<=Mx&&Math.abs(t.top-e.top)<=Mx&&Math.abs(t.right-e.right)<=Mx&&Math.abs(t.bottom-e.bottom)<=Mx}function Dx(t){return function(t){return Math.abs(t.left)<=Mx&&Math.abs(t.top)<=Mx&&Math.abs(1-t.right)<=Mx&&Math.abs(1-t.bottom)<=Mx}(t)?null:Bx({topLeft:{x:t.left,y:t.top},bottomRight:{x:t.right,y:t.bottom}})}function Fx({centerX:t,centerY:e,height:n,width:r}){const o=Rx(r,Px,1),i=Rx(n,Px,1),s=Rx(t-o/2,0,1-o),a=Rx(e-i/2,0,1-i);return{left:s,top:a,right:s+o,bottom:a+i,width:o,height:i}}function Wx(t){return{x:t.left+t.width/2,y:t.top+t.height/2}}function jx({crop:t,shape:e}){const n=zx(t);return{w:e.props.w/n.width,h:e.props.h/n.height}}function Ux(t){const e=t.props.w/t.props.h;for(const n of Cx)if(Math.abs(e-n.ratio)<=.01)return n.value;return null}function Kx(t,e){return e===Xx(t.id)}function Xx(t){return`image.crop:edit:${t}`}function Yx({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 Tt(0,0),top:new Tt(o,0),top_right:new Tt(n,0),right:new Tt(n,i),bottom_right:new Tt(n,r),bottom:new Tt(o,r),bottom_left:new Tt(0,r),left:new Tt(0,i)};return Ax.map(e=>{return{kind:"custom",type:Tx,id:e,point:t.applyToPoint(s[e]),cursor:(n=e,Ex[n])};var n})}function _x({change:t,crop:e,shape:n}){const r=jx({crop:e,shape:n}),o=e.bottomRight.x-e.topLeft.x,i=e.bottomRight.y-e.topLeft.y,s=Rx(e.topLeft.x-t.x/r.w,0,1-o),a=Rx(e.topLeft.y-t.y/r.h,0,1-i),l=Bx({topLeft:{x:s,y:a},bottomRight:{x:s+o,y:a+i}});return l?{id:n.id,props:{crop:l}}:null}function qx({preset:t,shape:e}){const n=Wx(zx(e.props.crop)),r=jx({crop:e.props.crop,shape:e}),o=Cx.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=zx(e.props.crop);if(Hx(n,t))return null;const r=jx({crop:e.props.crop,shape:e}),o=new Tt((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:Dx(t)}}}({nextRect:Fx({centerX:n.x,centerY:n.y,width:s,height:a}),shape:e})}function Gx(t){return Number.isFinite(t)?Number(t.toFixed(4)).toString():"0"}var Vx=new WeakMap;function Jx(t,e){return Vx.get(t)?.get(e)??null}function Zx(t,e){const n=Vx.get(t);n&&(n.delete(e),0===n.size&&Vx.delete(t))}function Qx(t){return Pt(t)&&"image"===t.type}function tb(t){return It(t)&&"image"===t.type}var eb={propagation:"stop"};function nb({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(!tb(s.shapes.get(e)))return"stop";const c=function({handleId:t,pageToLocal:e,shape:n,startCrop:r,startPagePoint:o,currentPagePoint:i}){const s=Bx(r)??{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},a=jx({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=Rx(u+c.x,d.x+8,a.w)-h):(h=Rx(h+c.x,0,u-8),g=u-h),function(t){return"top_left"===t||"top"===t||"top_right"===t}(t)?(f=Rx(f+c.y,0,p-8),m=p-f):function(t){return"bottom_left"===t||"bottom"===t||"bottom_right"===t}(t)&&(m=Rx(p+c.y,d.y+8,a.h)-f);const y=Bx({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 w=new Tt(h-s.topLeft.x*a.w,f-s.topLeft.y*a.h).rot(n.rotation);return{id:n.id,x:n.x+w.x,y:n.y+w.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 rb(){return{createSession(t,{handle:e,shape:n,originPagePoint:r}){return tb(n)&&"custom"===e.kind&&"image.crop"===e.type&&(o=e.id,Ax.some(t=>t===o))?nb({handleId:e.id,shapeId:n.id,startPagePoint:r,startPageToLocal:t.shapes.computeLocalToPageTransform(n).invert(),startShape:n,startCrop:n.props.crop}):null;var o}}}function ob(){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=ib(t);if(!n)return;if("Escape"===e.key&&!e.altKey&&!e.accelKey)return t.editing.cancel("user")&&Zx(t,n.id),eb;if("Enter"===e.key&&!e.altKey&&!e.accelKey)return t.editing.complete("user")&&Zx(t,n.id),eb;const r=function(t){if(t.altKey||t.accelKey)return null;const e=t.shiftKey?10:1;switch(t.key){case"ArrowLeft":return new Tt(e,0);case"ArrowRight":return new Tt(-e,0);case"ArrowUp":return new Tt(0,e);case"ArrowDown":return new Tt(0,-e);default:return null}}(e);if(r){const e=function({pageDelta:t,shape:e,startCrop:n}){const r=Bx(n);return!r||t.equals(Tt.Zero())?null:_x({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"}),eb}}(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=ib(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},eb):n.editing.complete("user")?(Zx(n,o.id),n.handleEvent(r),eb):void 0}if(t&&r.pointerId===t.pointerId)return"pointer_move"===r.name?(sb(n,r,t),eb):"pointer_up"===r.name?(sb(n,r,t),t.operation?.isActive&&t.operation.commit(),e(),eb):void 0}else e()}else e()}},selectionHandle:rb()}}function ib(t){const[e]=t.state.selectedShapes.get();if(!tb(e))return null;const n=t.state.shapeEditingSession.get();return n&&n.shapeId===e.id&&Kx(e,n.operationKind)?e:null}function sb(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(!tb(t.shapes.get(n.shapeId)))return;const r=function({currentPagePoint:t,pageToLocal:e,shape:n,startCrop:r,startPagePoint:o,shiftKey:i}){const s=Bx(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 Tt(0,l.y):new Tt(l.x,0)),0===l.x&&0===l.y?null:_x({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 ab(t,e=0){return Math.max(0,"number"==typeof t&&Number.isFinite(t)?t:e)}function lb({cornerRadius:t,h:e,w:n}){return Math.min(ab(t),Math.max(0,n)/2,Math.max(0,e)/2)}var cb=24,db="#ffff00",ub=1,pb=128,hb=24,fb=db,gb=.45,mb=class{editor;confirmHandler=null;deactivateHistoryScope=null;session=null;snapshot=null;subscribers=new Set;constructor(t){this.editor=t,be("image.smudgeSession.lifecycle",t.state.shapeEditingSession,()=>{this.clearIfEditingSessionInvalid()},{fireImmediately:!1})}start(t,e){if(t.isLocked)return!1;const n=bb(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&&vb(t,r.operationKind))return this.updateSession({...this.session,brush:kb({...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:kb(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===bb(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===bb(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=kb({...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===bb(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=yb(this.session),n={id:`${e.shapeId}:smudge:${e.nextStrokeIndex}`,points:[Nb(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,Nb(t)]}})}endStroke(){this.session?.activeStroke&&this.updateSession(yb(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(yb(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):void 0}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===bb(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 yb(t){return t.activeStroke?{...t,strokes:[...t.strokes,t.activeStroke],activeStroke:null,redoStrokes:[]}:t}var wb=new WeakMap;function xb(t){const e=wb.get(t);if(e)return e;const n=new mb(t);return wb.set(t,n),n}function bb(t){return`image.smudge:edit:${t}`}function vb(t,e){return e===bb(t.id)}function kb(t){const e="number"==typeof t?.size&&Number.isFinite(t.size)?t.size:hb,n="number"==typeof t?.opacity&&Number.isFinite(t.opacity)?t.opacity:gb??.45;return{size:Math.min(128,Math.max(1,e)),color:"string"==typeof t?.color&&t.color.trim().length>0?t.color:fb,opacity:Math.min(1,Math.max(0,n))}}function Sb({brush:t,editor:e,shape:n}){return xb(e).start(n,t)}function Ib(t){xb(t).cancel()}function Pb(t){xb(t).complete()}function Mb(t){return xb(t).cancelIfActive()}function Tb(t,e){return xb(t).updateBrush(e)}function Cb(t){return xb(t).getActiveSession()}function Eb(t){return xb(t).undo()}function Ab(t){return xb(t).redo()}function Lb(t,e){return xb(t).registerConfirmHandler(e)}function Rb(t,e){return xb(t).requestConfirm(e)}function $b(t){return t.map(t=>({id:t.id,brush:{...t.brush},points:t.points.map(Nb)}))}function Nb(t){return{x:t.x,y:t.y,...void 0===t.pressure?{}:{pressure:t.pressure}}}function Bb(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}var Ob=class extends fe{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(),{width:r,height:o}=re({width:Bb(e.w,n.w),height:Bb(e.h,n.h),preserveAspectRatio:!0});return{w:r,h:o,assetId:(i=e.assetId,"string"==typeof i&&i.startsWith("asset:")?e.assetId:null),crop:Bx(e.crop),cornerRadius:ab(e.cornerRadius,n.cornerRadius),altText:"string"==typeof e.altText?e.altText:n.altText};var i}getLocalBounds(t){return new Ct(0,0,t.props.w,t.props.h)}canReceiveTerminalBinding(t){return!0}getAllowedSelectionResizeModes(t,e){return te}canEdit(t){return!0}onEditEnd(t,e){var n,r;n=e.editor,r=t.id,xb(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&&Kx(t,r.operationKind)?{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:Yx({crop:t.props.crop,localToPage:e.editor.shapes.computeLocalToPageTransform(t),shape:t})}:n}},zb=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=Ox(o),c=l?{tag:"svg",attrs:{x:0,y:0,width:s,height:i,viewBox:(d=l,[Gx(d.left),Gx(d.top),Gx(d.width),Gx(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=lb({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]}}},Hb={propagation:"stop"};function Db(){let t=null;const e=e=>{t=null,function(t){xb(t).endStroke()}(e)},n=e=>{t=null,function(t){xb(t).cancelStroke()}(e)};return{id:"land.image.smudge.interactions",editorEvent:{handleEvent(r,o){if("keyboard"===o.type)return(Wb(o)||Fb(o))&&jb(r)&&e(r),function(t,e){if("key_down"!==e.name)return;if(!jb(t))return;if("Escape"===e.key&&!e.altKey&&!e.accelKey)return Ib(t),Hb;if(Fb(e))return Rb(t,{replace:!0}),Hb;if(Wb(e))return e.shiftKey?t.history.redo():t.history.undo(),Hb;return Hb}(r,o);if("cancel"===o.type)return jb(r)?(n(r),"command"!==o.reason&&Ib(r),Hb):void 0;if("pointer"!==o.type)return;const i=jb(r);if(i){if("pointer_down"===o.name){if(e(r),0!==o.button)return 1===o.button?void 0:Hb;const n=Kb(r,i,o.pagePoint),s=Xb(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){xb(t).beginStroke(e)}(r,{x:n.x,y:n.y,pressure:o.pressure}),Hb}return t&&t.pointerId===o.pointerId?"pointer_move"===o.name?("draw"===t.mode&&1&o.buttons?t.acceptsDrawPoints&&(t.acceptsDrawPoints=Ub(r,i,o)):"pan"===t.mode&&t.originCamera&&t.originScreenPoint&&1&o.buttons?Yb(r,o,t):e(r),Hb):"pointer_up"===o.name?("draw"===t.mode&&t.acceptsDrawPoints?Ub(r,i,o):"pan"===t.mode&&Yb(r,o,t),e(r),Hb):"pointer_cancel"===o.name?(n(r),Hb):Hb:Hb}n(r)}}}}function Fb(t){return"key_down"===t.name&&"Enter"===t.key&&!t.altKey&&!t.accelKey}function Wb(t){return"key_down"===t.name&&"z"===t.key.toLowerCase()&&t.accelKey&&!t.altKey}function jb(t){const[e]=t.state.selectedShapes.get();if(!tb(e))return null;const n=t.state.shapeEditingSession.get();return n&&n.shapeId===e.id&&vb(e,n.operationKind)?e:null}function Ub(t,e,n){const r=Kb(t,e,n.pagePoint);return!!Xb(r,e)&&(function(t,e){xb(t).appendPoint(e)}(t,{x:r.x,y:r.y,pressure:n.pressure}),!0)}function Kb(t,e,n){return t.shapes.computeLocalToPageTransform(e).invert().applyToPoint(n)}function Xb(t,e){return t.x>=0&&t.y>=0&&t.x<=e.props.w&&t.y<=e.props.h}function Yb(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 _b(){return{shapeUtils:[new Ob],shapeSvgExporters:[new zb],interactionHandlers:[ob(),Db()]}}var qb=new WeakMap;function Gb(t){return qb.get(t)??null}var Vb={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(!tb(e))return null;const n=t.state.shapeEditingSession.get();return n&&n.shapeId===e.id&&Kx(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 Tt(t.x-i.left,t.y-i.top);return sv(e,o,e.viewport.screenToPage(s))?0!==e.inputs.state.get().buttons?"grabbing":"grab":void 0}},Jb={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(!tb(e))return null;const n=t.state.shapeEditingSession.get();return n&&n.shapeId===e.id&&vb(e,n.operationKind)?e:null}(n);if(!r||!t)return;const o=e.getBoundingClientRect(),i=new Tt(t.x-o.left,t.y-o.top);return sv(n,r,n.viewport.screenToPage(i))?"crosshair":0!==n.inputs.state.get().buttons?"grabbing":"grab"}};function Zb(){return{domEventGuards:[Vb,Jb],selectionCustomHandleRenderers:[{type:Tx,component:rv}],shapeRenderers:[{type:"image",component:Qb,hoverComponent:nv}]}}function Qb({editor:e,shape:n,shapeEditingSession:r}){const{altText:o,assetId:i,crop:s,h:a,w:c}=n.props;l(e.assets.getUrlVersionSignal());const p=i?e.assets.resolveUrl(i):null,h=lb({cornerRadius:n.props.cornerRadius,h:a,w:c}),f=function(t,e){return I(e=>function(t,e){return xb(t).subscribe(e)}(t,e),()=>function(t,e){return xb(t).getSnapshot(e)}(t,e),()=>null)}(e,n.id);if(!p)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:h,boxSizing:"border-box",color:"#cbd5e1",display:"flex",height:a,justifyContent:"center",overflow:"hidden",width:c},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:[
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
return
|
|
51
|
-
return
|
|
52
|
-
return
|
|
53
|
-
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 ov(t,e){return`${t},${e}`}function iv(t){return Number.isFinite(t)?Number(t.toFixed(2)).toString():"0"}function sv(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}function av({editor:t}){return function({editor:t}){return{setMediaPresenter(e){!function(t,e){e?qb.set(t,e):qb.delete(t),t.assets.invalidateUrls()}(t,e)},getSelectionState(){const e=dv(t);if(!e)return null;const n=t.state.shapeEditingSession.get();return{shapeId:e.id,cornerRadius:ab(e.props.cornerRadius),crop:e.props.crop,cropPreset:Ux(e),isCropping:n?.shapeId===e.id&&Kx(e,n.operationKind),smudge:Cb(t)}},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(tb).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...void 0===e.cornerRadius?{}:{cornerRadius:ab(e.cornerRadius)}}}));return n.length>0&&t.commands.updateShapes(n,{source:"user"}),n.map(({id:t})=>t)},startCrop(e){const n=cv(t,e);return!(!n||n.isLocked)&&(!!t.editing.start({shapeId:n.id,operationKind:Xx(n.id),entryMode:"focusEnd"},"user")&&(function(t,e){const n=Vx.get(t)??new Map;Vx.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=dv(t);if(!e||!uv(t,e))return!1;const n=t.editing.complete("user");return n&&Zx(t,e.id),n},cancelCrop(){const e=dv(t);if(!e||!uv(t,e))return!1;const n=t.editing.cancel("user");return n&&Zx(t,e.id),n},zoomCrop:e=>lv(t,t=>function({direction:t,shape:e}){const n=zx(e.props.crop),r=Wx(n),o=Rx("in"===t?.8:1.25,Math.max(Px/n.width,Px/n.height),Math.min(1/n.width,1/n.height)),i=Fx({centerX:r.x,centerY:r.y,width:n.width*o,height:n.height*o});return Hx(n,i)?null:{id:e.id,props:{crop:Dx(i)}}}({direction:e,shape:t})),setCropAspectRatio:e=>lv(t,t=>qx({preset:e,shape:t})),resetCrop:()=>lv(t,e=>function({baselineShape:t,shape:e}){const n=t.x,r=t.y,o=t.props.w,i=t.props.h,s=Bx(t.props.crop);return Math.abs(e.x-n)<=Mx&&Math.abs(e.y-r)<=Mx&&Math.abs(e.props.w-o)<=Mx&&Math.abs(e.props.h-i)<=Mx&&(null===e.props.crop&&null===s||null!==e.props.crop&&null!==s&&Math.abs(e.props.crop.topLeft.x-s.topLeft.x)<=Mx&&Math.abs(e.props.crop.topLeft.y-s.topLeft.y)<=Mx&&Math.abs(e.props.crop.bottomRight.x-s.bottomRight.x)<=Mx&&Math.abs(e.props.crop.bottomRight.y-s.bottomRight.y)<=Mx)?null:{id:e.id,x:n,y:r,props:{w:o,h:i,crop:s}}}({baselineShape:Jx(t,e.id)??e,shape:e})),smudge:{start(e){const n=cv(t,e?.shapeId);return!!n&&!!n.props.assetId&&!n.isLocked&&Sb({brush:e?.brush,editor:t,shape:n})},setBrush:e=>Tb(t,e),cancel(){Ib(t)},undo:()=>Eb(t),redo:()=>Ab(t),getSnapshot:()=>Cb(t)}}}({editor:t})}function lv(t,e){const n=dv(t);if(!n||n.isLocked||!uv(t,n))return!1;const r=e(n);return!!r&&(t.commands.updateShapes([r],{source:"user"}),!0)}function cv(t,e){const n=e?t.shapes.get(e):t.state.selectedShapes.get()[0];return tb(n)?n:null}function dv(t){return 1===t.selection.getIds().length?cv(t):null}function uv(t,e){const n=t.state.shapeEditingSession.get();return n?.shapeId===e.id&&Kx(e,n.operationKind)}var pv=s({id:"image",editor:_b(),render:Zb(),setup({editor:t}){const e=function(t){let e=null;return be("image.cropSession.lifecycle",t.state.shapeEditingSession,()=>{const n=t.state.shapeEditingSession.get(),r=n?.shapeId,o=r&&n?.operationKind===Xx(r)?r:null;e&&e!==o&&Zx(t,e),e=o})}(t);try{return{api:av({editor:t}),dispose:e}}catch(n){throw e(),n}}});async function hv(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 fv="blobs",gv=null;function mv(){return"undefined"==typeof indexedDB?Promise.resolve(null):(gv||(gv=new Promise((t,e)=>{const n=indexedDB.open("land.plugin-image",1);n.addEventListener("upgradeneeded",()=>{n.result.objectStoreNames.contains(fv)||n.result.createObjectStore(fv)}),n.addEventListener("success",()=>{const e=n.result;e.addEventListener("versionchange",()=>{e.close(),gv=null}),t(e)}),n.addEventListener("error",()=>{gv=null,e(n.error)})})),gv)}var yv="image-blob:";function wv(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?`${yv}${crypto.randomUUID()}`:`${yv}${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}async function xv(t){const e=wv();if("undefined"==typeof indexedDB)throw new Error("IndexedDB is not available for image storage.");return await async function(t,e){const n=await mv();n&&await new Promise((r,o)=>{const i=n.transaction(fv,"readwrite");i.addEventListener("complete",()=>r()),i.addEventListener("abort",()=>o(i.error)),i.addEventListener("error",()=>o(i.error)),i.objectStore(fv).put(e,t)})}(e,t),{storageKey:e}}async function bv(t){const e=await async function(t){const e=await mv();return e?new Promise((n,r)=>{const o=e.transaction(fv,"readonly").objectStore(fv).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 vv(t){const e=await bv(t);return e?hv(e):null}async function kv(t){await async function(t){const e=await mv();e&&await new Promise((n,r)=>{const o=e.transaction(fv,"readwrite");o.addEventListener("complete",()=>n()),o.addEventListener("abort",()=>r(o.error)),o.addEventListener("error",()=>r(o.error)),o.objectStore(fv).delete(t)})}(t)}async function Sv(){return(await async function(){const t=await mv();return t?new Promise((e,n)=>{const r=t.transaction(fv,"readonly").objectStore(fv).getAllKeys();r.addEventListener("success",()=>e([...r.result])),r.addEventListener("error",()=>n(r.error))}):null}())?.map(String)??[]}function Iv(t,e){const n=t.assets.get(e);if(!Qx(n)||"local"!==n.props.source.kind)return null;const{storageKey:r}=n.props.source;return r.length>0?r:null}function Pv(t,e){const n=t.assets.get(e);return Qx(n)&&"remote"===n.props.source.kind&&n.props.source.url.length>0?n.props.source.url:null}function Mv(t){const e=new Set;for(const n of t.assets.getAll())Qx(n)&&"local"===n.props.source.kind&&n.props.source.storageKey.length>0&&e.add(n.props.source.storageKey);return e}async function Tv({editor:t,objectUrls:e}){const n=Mv(t),r=await Sv(),o=[];for(const i of r)n.has(i)||(e?.release(i),await kv(i),o.push(i));return o}function Cv(){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){const t=await a;return i.signal?.throwIfAborted(),t}const l=n,c=bv(o).then(e=>{if(!e||r||l!==n)return null;const i=URL.createObjectURL(e);return t.set(o,i),i}).finally(()=>{e.delete(o)});e.set(o,c);const d=await c;return i.signal?.throwIfAborted(),d};return{async preloadForEditor(t,e={}){e.signal?.throwIfAborted(),await Promise.all(Array.from(Mv(t)).map(t=>o(t,e)))},preload:o,resolve:e=>t.get(e)??null,resolveAssetUrl(e,n){const r=Pv(e,n);if(r)return r;const o=Iv(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 Ev(){const t=Cv(),e={objectUrls:t,preloadForEditor:(e,{signal:n})=>t.preloadForEditor(e,{signal:n}),resolveAssetUrl:(e,n)=>t.resolveAssetUrl(e,n)};return{value:e,dispose(){e.objectUrls.releaseAll()}}}function Av(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 Lv(t,{signal:e}={}){e?.throwIfAborted();const n=$v(t)?t:t.blob,r=($v(t),t.name),o=$v(t)?t.type:t.mimeType||t.blob.type,i=URL.createObjectURL(n),s=await Av(i,{signal:e}).finally(()=>{URL.revokeObjectURL(i)});e?.throwIfAborted();const{storageKey:a}=await xv(n);try{e?.throwIfAborted()}catch(l){try{await kv(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,...!$v(t)&&t.originalUrl?{originalUrl:t.originalUrl}:{}},mimeType:o||"image/png",fileSize:n.size,width:s.width,height:s.height}}async function Rv({name:t,signal:e,url:n}){const r=await Av(n,{signal:e});return{name:t||Nv(n)||"Image",source:{kind:"remote",url:n},mimeType:null,width:r.width,height:r.height}}function $v(t){return"undefined"!=typeof File&&t instanceof File}function Nv(t){try{const e=new URL(t).pathname.split("/").filter(Boolean).at(-1);return e?decodeURIComponent(e):null}catch{return null}}function Bv(t){for(const e of t)if(e.type.startsWith("image/"))return e;return null}function Ov({filename:t,url:e}){const n=document.createElement("a");n.href=e,n.download=t,n.click()}async function zv({blob:t,filename:e}){const n=URL.createObjectURL(t);try{Ov({filename:e,url:n})}finally{window.setTimeout(()=>URL.revokeObjectURL(n),0)}}var Hv=1;function Dv(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 Fv({editor:t,imageObjectUrls:e,pagePoint:n,signal:r,size:o,source:i}){return"file"===i.type?_v(i.file)?Wv({editor:t,imageObjectUrls:e,input:await Lv(i.file,{signal:r}),pagePoint:n,size:o,signal:r,altText:i.altText}):null:"blob"===i.type?_v(i.blob)?Wv({editor:t,imageObjectUrls:e,input:await Lv(i,{signal:r}),pagePoint:n,size:o,signal:r,altText:i.altText}):null:async function({editor:t,imageObjectUrls:e,pagePoint:n,signal:r,size:o,source:i}){return Wv({editor:t,imageObjectUrls:e,input:await Rv({...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 Wv({editor:t,imageObjectUrls:e,input:n,pagePoint:r,size:o,signal:i,altText:s}){const a="local"===n.source.kind?n.source.storageKey:null;try{return a&&await e.preload(a,{signal:i}),await wt(t,i),i.throwIfAborted(),t.operations.run({kind:"image.insert",source:"user"},()=>{const e=Dv(t,n),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(),l=r??a?.center??t.viewport.screenToPage(new Tt(360,240)),[c]=t.commands.createShapes([{type:"image",x:Math.round(l.x-i.w/2),y:Math.round(l.y-i.h/2),props:{...i,assetId:e.id,crop:null,altText:s??n.name}}],{source:"user"});return c?(t.commands.setSelectedShapeIds([c.id],{source:"user"}),c.id):null})}catch(l){throw a&&(e.release(a),await kv(a)),l}}async function jv({editor:t,file:e,imageObjectUrls:n,signal:r}){if(!_v(e))return;const[o]=t.state.selectedShapes.get();if(!tb(o)||o.isLocked)return;const i=await Lv(e,{signal:r});await Kv({editor:t,imageObjectUrls:n,input:i,nextProps:{crop:null,altText:i.name},signal:r,shape:o})}async function Uv({editor:t,imageObjectUrls:e,onError:n,signal:r}){r.throwIfAborted();const[o]=t.state.selectedShapes.get();if(!tb(o)||!o.props.assetId)return;const i=t.assets.get(o.props.assetId);if(!Qx(i))return;const s="string"==typeof i.props.name&&i.props.name.length>0?i.props.name:"land-image";if("remote"===i.props.source.kind)return void(await async function({filename:t,onError:e,signal:n,url:r}){try{const e=await fetch(r,{signal:n});if(!e.ok)throw new Error(`Could not download image URL (${e.status}).`);const o=await e.blob();n.throwIfAborted(),await zv({blob:o,filename:t})}catch(o){n.throwIfAborted(),e?.(new Error("Could not download remote image; opening URL instead.",{cause:o})),function(t){const e=document.createElement("a");e.href=t,e.rel="noreferrer",e.target="_blank",e.click()}(r)}}({filename:s,onError:n,signal:r,url:i.props.source.url}));const a=i.props.source.storageKey;if(!a)return;const l=await bv(a);if(r.throwIfAborted(),l)return void(await zv({blob:l,filename:s}));const c=e.resolve(a);c&&Ov({filename:s,url:c})}async function Kv({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}),t||await wt(e,s),s.throwIfAborted()}catch(c){throw await Xv({imageObjectUrls:n,storageKey:l}),c}try{const s=e.shapes.get(i.id);if(!tb(s)||s.isLocked||s.props.assetId!==a||t&&!t())return await Xv({imageObjectUrls:n,storageKey:l}),null;const d=`image.asset.replace:${i.id}:${Hv++}`,u=e.operations.begin({kind:d,label:"image.asset.replace",source:"user",history:"record"});try{const t=Dv(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 Xv({imageObjectUrls:n,storageKey:l}),c}}async function Xv({imageObjectUrls:t,storageKey:e}){e&&(t.release(e),await kv(e))}async function Yv(t){try{const e=await fetch(t);if(!e.ok)return null;const n=await e.blob();return _v(n)?n:null}catch{return null}}function _v(t){return!t.type||t.type.startsWith("image/")}var qv=new WeakSet;async function Gv({editor:t,imageObjectUrls:e,replace:n=!0,signal:r}){r.throwIfAborted();const o=Cb(t);if(!o)return null;const i=$b(o.strokes);if(0===i.length)return Pb(t),null;if(qv.has(o))return null;qv.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(!tb(s)||s.isLocked||!s.props.assetId)return null;const a=t.assets.get(s.props.assetId);if(!Qx(a))return null;const l=s.props.assetId,c=await async function({asset:t,imageObjectUrls:e}){if("remote"===t.props.source.kind)return Yv(t.props.source.url);const n=t.props.source.storageKey,r=await bv(n);if(r)return r;const o=e.resolve(n);return o?Yv(o):null}({asset:a,imageObjectUrls:e});if(o.throwIfAborted(),!c)return null;if(!Vv(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=Jv(r,s);a.context.drawImage(i.source,0,0,r,s),Zv({context:a.context,crop:t,imageHeight:s,imageWidth:r,mask:!1,shape:e,strokes:o});const l=Jv(r,s);Zv({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(),!Vv(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 Lv({blob:t,name:o},{signal:s});return s.throwIfAborted(),Kv({editor:n,imageObjectUrls:r,input:a,nextProps:{},shape:i,canCommit:e,signal:s})}({blob:d,canCommit:()=>!o.aborted&&Vv(t,r,l,s)&&t.assets.get(l)===a,editor:t,imageObjectUrls:e,name:ek(a.props.name),shape:s,signal:o});if(o.throwIfAborted(),!n)return null;if(!Vv(t,r,n.assetId,s)){const o=Cb(t),i=t.shapes.get(r.shapeId);return o?.shapeId===r.shapeId&&tb(i)&&i.props.assetId===n.assetId&&Ib(t),await async function({assetId:t,editor:e,imageObjectUrls:n,storageKey:r}){if(!r||t&&e.assets.get(t))return;n.release(r),await kv(r)}({assetId:n.assetId,editor:t,imageObjectUrls:e,storageKey:n.storageKey}),null}return o.throwIfAborted(),Pb(t),f}return o.throwIfAborted(),Pb(t),f}({editor:t,imageObjectUrls:e,replace:n,session:o,signal:r,strokes:i})}finally{qv.delete(o)}}function Vv(t,e,n,r){if(Cb(t)!==e)return!1;const o=t.shapes.get(e.shapeId);return tb(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 Jv(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 Zv({context:t,crop:e,imageHeight:n,imageWidth:r,mask:o,shape:i,strokes:s}){if(0===s.length)return;const a=zx(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=tk(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=Qv({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=Qv({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 Qv({cropPixelRect:t,point:e,scaleX:n,scaleY:r}){return{x:t.x+e.x*n,y:t.y+e.y*r}}function tk(t){return"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):.45}function ek(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 nk({editor:t,imageAssetService:e,imageApi:n,onError:r,run:o}){let i,s=!1;const a=rk(t=>i.insert({source:{type:"file",file:t}}),r),l=rk(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(async r=>{const o=await Gv({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,signal:s})=>o(async o=>{const a=s?AbortSignal.any([o,s]):o;a.throwIfAborted();const l=await Fv({editor:t,imageObjectUrls:e.objectUrls,source:n,pagePoint:r,size:i,signal:a});return a.throwIfAborted(),l}),replaceSelection:({file:n})=>o(async r=>{if(!n.type.startsWith("image/"))return!1;const[o]=t.state.selectedShapes.get();return!(!tb(o)||o.isLocked)&&(await jv({editor:t,file:n,imageObjectUrls:e.objectUrls,signal:r}),r.throwIfAborted(),!0)}),downloadSelectionOriginal:()=>o(async n=>{await Uv({editor:t,imageObjectUrls:e.objectUrls,onError:r,signal:n}),n.throwIfAborted()}),smudge:c};const d=Lb(t,t=>{c.confirm(t).catch(t=>r?.(t))});return{value:i,dispose(){s||(s=!0,a.dispose(),l.dispose(),d())}}}function rk(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 ok(t){return{kind:"svg-inliner",id:"image.svg-inliner",async prepare({editor:e,requestedShapeIds:n}){const r=ik(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=ik(e,n),s=new Set;for(const a of i.values()){const e=ak(a,t);if(!e)throw new Error(`Could not resolve image asset "${a.id}".`);if(s.has(e))continue;const n=await sk(a,e);if(n.href===n.dataUrl){s.add(e);continue}const r=`href="${lk(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 ik(t,e){const n=new Map;for(const r of e){if(!tb(r)||!r.props.assetId)continue;const e=t.assets.get(r.props.assetId);if(!Qx(e))throw new Error(`Image asset "${r.props.assetId}" is unavailable.`);n.set(e.id,e)}return n}async function sk(t,e){const{source:n}=t.props;if("local"===n.kind){const r=await vv(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 hv(await r.blob());if(!o)throw new Error(`Could not embed remote image asset "${t.id}".`);return{href:e,dataUrl:o}}function ak(t,e){return"local"===t.props.source.kind?e.objectUrls.resolve(t.props.source.storageKey):t.props.source.url}function lk(t){return t.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}function ck(t={}){return yt({id:"image.host",requires:[pv],setup({api:e,canvas:n,editor:r,run:o}){const i=e(pv),s=(t.createAssetService??Ev)();let a=!1;const l=()=>i.setMediaPresenter(mt({run:o,onError:t.onError})),c=n.snapshots.revision.subscribe(()=>{queueMicrotask(()=>{a||l()})});let d=null;const u=()=>{a=!0,c(),i.setMediaPresenter(null);const t=[];try{d?.()}catch(e){t.push(e)}try{s.dispose()}catch(e){t.push(e)}if(t.length)throw new AggregateError(t,"Failed to dispose image host resources.")};try{l();const e=nk({editor:r,imageApi:i,imageAssetService:s.value,onError:t.onError,run:o});return d=e.dispose,{api:e.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!==Bv(t.files)||(t.urls?.some(dk)??!1),async import(t){const n=Bv(t.files),r=t.urls?.find(dk);return(n||r)&&await e.value.insert({source:n?{type:"file",file:n}:{type:"url",url:r},pagePoint:t.pagePoint})?"handled":"ignored"}}],assetResolvers:[{id:"image.host.asset-resolver",resolve:t=>s.value.resolveAssetUrl(r,t),preload:({signal:t})=>s.value.preloadForEditor(r,{signal:t})}],exports:[ok(s.value)],dispose:u}}catch(p){try{u()}catch(h){throw new AggregateError([p,h],"image host setup and cleanup failed.",{cause:p})}throw p}}})}function dk(t){return t.startsWith("data:image/")||/\.(?:avif|bmp|gif|jpe?g|png|svg|webp)(?:[?#].*)?$/i.test(t)}var uk=new WeakMap;function pk(t){const e=uk.get(t);if(!e)throw new Error("LaserRuntime is not initialized for this editor.");return e}function hk(t,e){const n=t.trail[t.trail.length-1];n&&n.dist2(e)<=1e-6||t.trail.push(e.clone())}function fk(t,e){pk(t).set(e.sessionId,e.trail)}var gk=class extends we{constructor(t){super(t,"laser"),this.initial="idle",this.addChild(new mk(t,this)),this.addChild(new yk(t,this)),this.addChild(new wk(t,this))}},mk=class extends we{constructor(t,e){super(t,"idle",e)}onPointerDown(t){0===t.button&&this.transition("pointing",function(t,e){const n={sessionId:pk(t).start(),originScreenPoint:e.screenPoint.clone(),trail:[e.pagePoint.clone()]};return fk(t,n),n}(this.editor,t))}},yk=class extends we{info=null;constructor(t,e){super(t,"pointing",e)}onEnter(t){this.info=t}onPointerMove(t){var e,n;this.info&&(e=this.info.originScreenPoint,n=t.screenPoint,e.dist2(n)>=9&&(hk(this.info,t.pagePoint),fk(this.editor,this.info),this.transition("drawing",this.info)))}onPointerUp(){this.info&&pk(this.editor).finish(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&pk(this.editor).finish(this.info.sessionId),this.transition("idle")}onExit(){this.info&&pk(this.editor).finish(this.info.sessionId),this.info=null}},wk=class extends we{info=null;constructor(t,e){super(t,"drawing",e)}onEnter(t){this.info=t}onPointerMove(t){this.info&&(hk(this.info,t.pagePoint),fk(this.editor,this.info))}onPointerUp(){this.info&&pk(this.editor).finish(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&pk(this.editor).finish(this.info.sessionId),this.transition("idle")}onExit(){this.info&&pk(this.editor).finish(this.info.sessionId),this.info=null}};function xk(){return{canvasOverlays:[{id:"land.laser.trail-overlay",component:bk}]}}var bk=g(function(){return l(pk(a()).activeSignal)?d(vk,{}):null}),vk=g(function(){const t=a(),e=pk(t),n=l(e.trailSignal),r=l(t.state.cameraZoom),o=Math.max(r,1e-4),i=function(){const[t,e]=S(()=>zk());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}(),s=k({sessionId:0,samples:[],sourceLength:0}),c=Math.max(i,zk());let p,h=[];n&&(!function(t,e,n,r){e.sessionId!==t.sessionId&&(t.sessionId=e.sessionId,t.samples=[],t.sourceLength=0);const o=e.points;Dk(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-Lk*s;for(let l=i;l<o.length;l++){const e=o[l],c=(l-i+1)/s;Hk(t,{x:e.x,y:e.y},n,Jk(a,r,c))}t.sourceLength=o.length,Dk(t,r)}(s.current,n,o,c),h=function(t,e){const n=Fk(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(Vk(r[r.length-1],t[o],n));return r}(n.length>Pk?n.slice(-64):n,Ck)}(s.current.samples,c),p=s.current.samples[s.current.samples.length-1]?.time);const f="ending"===n?.phase,g=0===h.length,m=f&&g?n.sessionId:null;if(w(()=>{null!==m&&e.clear(m)},[m,e]),!n||g)return null;const y=f&&void 0!==p?Zk(1-(c-p)/Ok,0,1):1,x=(v=Tk/o,0===(b=h).length||v<=0?null:1===b.length?tS(Uk(b[0],v/2,Ak))??"":tS(function(t){if(0===t.length)return[];if(1===t.length)return Uk(t[0].point,Math.max(t[0].radius,.01),Ak);const e=[],n=[];for(const a of t){const t=Yk(a.direction);Qk(e,qk(a.point,Gk(t,a.radius))),Qk(n,_k(a.point,Gk(t,a.radius)))}const r=[];for(const a of e)Qk(r,a);const o=t[t.length-1],i=Yk(o.direction),s=function({center:t,direction:e,normal:n,radius:r}){if(r<=0)return[];const o=[];for(let i=1;i<Ek;i++){const s=i/Ek;o.push(_k(t,_k(Gk(e,Math.sin(Math.PI*s)*r),Gk(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)Qk(r,a);for(let a=n.length-1;a>=0;a--)Qk(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]+Kk(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=Zk(s/o,0,1);return{point:r,direction:jk(t,i),radius:e/2*a,runningLength:s}})}(b,v))));var b,v;return x?u("g",{"data-ui":"laser-trail-overlay",style:{opacity:y},children:[d("path",{"data-ui":"laser-trail-glow",d:x,fill:Sk,style:{filter:`blur(${Ik/o}px)`}}),d("path",{"data-ui":"laser-trail-beam",d:x,fill:kk})]}):null}),kk="rgb(255, 38, 38)",Sk="rgba(255, 48, 48, 0.55)",Ik=4,Pk=64,Mk=1,Tk=6,Ck=.32,Ek=8,Ak=13,Lk=16,Rk=8,$k=600,Nk=300,Bk=1400,Ok=400;function zk(){return"undefined"==typeof performance?Date.now():performance.now()}function Hk(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=Mk/n,s=Kk(o,e);if(s<i)return void(t.samples[t.samples.length-1]={...o,...e,time:r});const a=s*n/Math.max(Rk,r-o.time);t.samples.push({...e,time:r,velocity:Jk(o.velocity,a,.68)})}function Dk(t,e){t.samples=Fk(t.samples,e)}function Fk(t,e){const n=t[t.length-1];if(!n)return[];const r=e-Zk($k+n.velocity*Nk,$k,Bk);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?[Wk(s,a,Zk((r-s.time)/(a.time-s.time),0,1)),...i]:i}function Wk(t,e,n){return{...Vk(t,e,n),time:Jk(t.time,e.time,n),velocity:Jk(t.velocity,e.velocity,n)}}function jk(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?qk(r,t[e]):e===t.length-1?qk(t[e],n):qk(r,n))}function Uk(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 Kk(t,e){return Math.sqrt(Xk(t,e))}function Xk(t,e){const n=t.x-e.x,r=t.y-e.y;return n*n+r*r}function Yk(t){return{x:-t.y,y:t.x}}function _k(t,e){return{x:t.x+e.x,y:t.y+e.y}}function qk(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Gk(t,e){return{x:t.x*e,y:t.y*e}}function Vk(t,e,n){return{x:Jk(t.x,e.x,n),y:Jk(t.y,e.y,n)}}function Jk(t,e,n){return t+(e-t)*n}function Zk(t,e,n){return Math.max(e,Math.min(n,t))}function Qk(t,e){const n=t[t.length-1];!n||Xk(n,e)>.04?t.push(e):t[t.length-1]=e}function tS(t){if(t.length<2)return null;if(2===t.length)return`M ${nS(t[0])} L ${nS(t[1])} Z`;const e=[`M ${nS(eS(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 ${nS(r)} ${nS(eS(r,o))}`)}return e.push("Z"),e.join(" ")}function eS(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}function nS(t){return`${rS(t.x)},${rS(t.y)}`}function rS(t){return Number.isInteger(t)?`${t}`:t.toFixed(3)}function oS(){return{tools:{laser:t=>new gk(t)}}}var iS=s({id:"laser",editor:oS(),render:xk(),setup({editor:t}){!function(t){const{atom:e,computed:n}=t.signals,r=e("laser.trail",null);let o=1;const i={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)}};uk.set(t,i)}(t)}}),sS="path.node",aS="path.control";function lS(t,e){return["node",t,e].map(encodeURIComponent).join("|")}function cS(t,e,n){return["control",n,t,e].map(encodeURIComponent).join("|")}function dS(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:sS,subpathId:n[1],nodeId:n[2]}:"path.control"!==t||4!==n.length||"control"!==n[0]||"in"!==n[1]&&"out"!==n[1]?null:{type:aS,handle:n[1],subpathId:n[2],nodeId:n[3]}}var uS=new WeakMap;function pS(t,e){e?uS.set(t,hS(e)):uS.delete(t)}function hS(t){return{...t,pagePoint:t.pagePoint.clone()}}var fS=["nonzero","evenodd"],gS=["corner","smooth","symmetric"];function mS(t){return It(t)&&"path"===t.type}function yS(t){return"string"==typeof t&&fS.includes(t)}function wS(t){return"string"==typeof t&&gS.includes(t)}function xS(){const t=a(),e=l(t.state.tool),n=l(t.state.shapeEditingSession),r=l(t.state.selectedShapes),o=l(t.state.camera);if(l(t.inputs.state),"select"!==e.activeToolId||!n)return null;const i=1===r.length?r[0]:null;if(!mS(i)||i.id!==n.shapeId)return null;const s=function(t){const e=uS.get(t);return e?hS(e):null}(t);if(!s||s.shapeId!==i.id)return null;const c=8/o.z,u=c/2,p=1.5/o.z;
|
|
54
|
-
return d("g",{"data-ui":"path-edit-insert-preview",pointerEvents:"none",children:d("rect",{"data-ui":"path-edit-insert-preview-control-point",x:s.pagePoint.x-u,y:s.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/o.z} ${2/o.z}`,strokeWidth:p})})}function bS(t){return Number.isInteger(t)?`${t}`:`${Number(t.toFixed(2))}`}function vS(t){return new Tt(t.x,t.y)}function kS(t,e){const n=vS(e);if(!function(t,e){return!!t.out||!!e.in}(t,e))return`L ${bS(n.x)} ${bS(n.y)}`;const r=function(t){const e=vS(t);return t.out?e.add(new Tt(t.out.dx,t.out.dy)):e}(t),o=function(t){const e=vS(t);return t.in?e.add(new Tt(t.in.dx,t.in.dy)):e}(e);return["C",bS(r.x),bS(r.y),bS(o.x),bS(o.y),bS(n.x),bS(n.y)].join(" ")}function SS(t){const e=t.nodes[0];if(!e)return null;const n=[`M ${bS(e.x)} ${bS(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(kS(e,o))}if(t.closed&&t.nodes.length>1){const r=t.nodes[t.nodes.length-1];r&&n.push(kS(r,e)),n.push("Z")}return n.join(" ")}function IS(t){const e=t.map(SS).filter(t=>null!==t);return e.length>0?e.join(" "):null}var PS=1e-6,MS=1/3,TS=Math.PI/8,CS=new WeakMap;function ES(t){return Number.isFinite(t)}function AS(t){return{dx:t.dx,dy:t.dy}}function LS(t){return{id:t.id,x:t.x,y:t.y,kind:t.kind,...t.in?{in:AS(t.in)}:null,...t.out?{out:AS(t.out)}:null}}function RS(t){return{id:t.id,closed:t.closed,nodes:t.nodes.map(LS)}}function $S(t){return t.map(RS)}function NS(t){return new Tt(t.x,t.y)}function BS(t){const e=NS(t);return t.in?e.add(new Tt(t.in.dx,t.in.dy)):e}function OS(t){const e=NS(t);return t.out?e.add(new Tt(t.out.dx,t.out.dy)):e}function zS(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 Tt(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 HS(t,e,n){return new Tt(t.x+(e.x-t.x)*n,t.y+(e.y-t.y)*n)}function DS(t,e){return[NS(t),OS(t),BS(e),NS(e)]}function FS(t,e){return!!t.out||!!e.in}function WS(t,e,n){return FS(t,e)?zS(...DS(t,e),n):HS(NS(t),NS(e),n)}function jS(t,e,n){const r=NS(e),o=OS(e),i=BS(n),s=NS(n);if(e.out||n.in)for(let a=1;a<=18;a+=1)t.push(zS(r,o,i,s,a/18));else t.push(s)}function US(t){const e=t.nodes[0];if(!e)return{id:t.id,closed:t.closed,points:[]};const n=[NS(e)];for(let r=1;r<t.nodes.length;r+=1){const e=t.nodes[r-1],o=t.nodes[r];e&&o&&jS(n,e,o)}if(t.closed&&t.nodes.length>1){const r=t.nodes[t.nodes.length-1];r&&jS(n,r,e)}return{id:t.id,closed:t.closed,points:n}}function KS(t){const e=t.props,n=CS.get(e);if(n)return n;const r=XS(t.props);return CS.set(e,r),r}function XS(t){const e=t.subpaths.map(US),n=e.flatMap(t=>t.points),r=t.subpaths.flatMap(t=>t.nodes.flatMap(t=>[NS(t),...t.in?[BS(t)]:[],...t.out?[OS(t)]:[]])),o=r.length>0?Ct.FromPoints(r):new Ct(0,0,1,1),i=Math.max(t.strokeWidth/2,1),s=n.length>0?Ct.FromPoints(n).expand(i):o.expand(i),a=new Ct(s.x,s.y,Math.max(s.w,1),Math.max(s.h,1));return{path:IS(t.subpaths),pointBounds:o,localBounds:s,renderBounds:a,outlineVertices:n.map(t=>t.clone()),flattenedSubpaths:e}}function YS(t,e){return t.map(t=>({...t,nodes:t.nodes.map(t=>function(t,e){const n=e(NS(t)),r=t.in?e(BS(t)):null,o=t.out?e(OS(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 _S(t,e){const n=XS({...e,subpaths:$S(t)}).pointBounds,r=Number.isFinite(n.x)?n.x:0,o=Number.isFinite(n.y)?n.y:0,i=function(t,e,n){return YS(t,t=>new Tt(t.x+e,t.y+n))}(t,-r,-o);return{x:r,y:o,subpaths:i,geometry:XS({...e,subpaths:i})}}function qS(t,e){return YS(t.props.subpaths,t=>e.applyToPoint(t))}function GS(t,e){return IS(qS(t,e))}function VS(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 JS(t,e,n){return VS(t,e,n).distanceSquared}function ZS(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=FS(t,s)?32:1;let l=NS(t);for(let n=1;n<=a;n+=1){const c=WS(t,s,n/a),d=VS(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:WS(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 QS(t,e){return t.find(t=>t.id===e)??null}function tI(t,e,n){return QS(t,e)?.nodes.find(t=>t.id===n)??null}function eI(t,e,n,r){return t.map(t=>t.id!==e?RS(t):{...t,nodes:t.nodes.map(t=>t.id===n?r(LS(t)):LS(t))})}function nI(t,e,n){const r=aI(e);return 0===r.size?$S(t):t.map(t=>{const e=r.get(t.id);return e?{...t,nodes:t.nodes.map(t=>e.has(t.id)?n(LS(t)):LS(t))}:RS(t)})}function rI(t,e,n){return t.map(t=>{if(t.id!==e)return RS(t);const r=t.nodes.findIndex(t=>t.id===n),o=t.nodes[r];if(!o)return RS(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=NS(o),l=function(t,e,n){const r=e?NS(e):null,o=n?NS(n):null;if(r&&o){const e=o.sub(r);if(e.len()<=PS)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<=PS||n/r<=.001}(r.sub(t),o.sub(t))?n.rot(TS):n}const i=o?o.sub(t):r?t.sub(r):null;return!i||i.len()<=PS?null:i.normalize().rot(TS)}(a,i,s),c=t.nodes.map(LS);return c[r]={...LS(o),kind:"smooth",in:i&&l?xI(l.mul(-a.dist(NS(i))*MS)):null,out:s&&l?xI(l.mul(a.dist(NS(s))*MS)):null},{...t,nodes:c}})}function oI(t,e,n){return eI(t,e,n,t=>({...t,kind:"corner",in:null,out:null}))}function iI(t,e,n){return null!==sI(t,e,n)}function sI(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=lI(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(NS(e)),Tt.Zero()).div(a.length),p={...LS(c),x:u.x,y:u.y,kind:"corner",in:gI(c.in,NS(c),u),out:gI(d.out,NS(d),u)},h=o.nodes.flatMap((t,e)=>s.has(e)?e===l?[p]:[]:[LS(t)]),f=o.closed&&h.length>=3;o.closed&&!f&&fI(h);return{subpaths:yI(t,r,[{...o,closed:f,nodes:h}]),selectedNodes:[{subpathId:e,nodeId:p.id}]}}(t,n,e);const r=cI(t,e);return r?function(t,e){const[n,r]=e,o=uI(n),i=pI(r),s=o[o.length-1],a=i[0],l=NS(s).add(NS(a)).div(2),c={...LS(s),x:l.x,y:l.y,kind:"corner",in:gI(s.in,NS(s),l),out:gI(a.out,NS(a),l)},{nodes:d}=mI(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:wI(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=lI(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(LS);return s[0]={...s[0],kind:"corner",in:null},s[s.length-1]={...s[s.length-1],kind:"corner",out:null},{subpaths:yI(t,r,[{...o,closed:!0,nodes:s}]),selectedNodes:n.map(t=>({...t}))}}(t,n,e);const r=cI(t,e);return r?function(t,e){const[n,r]=e,o=uI(n),{nodes:i,nodeIdMap:s}=mI(pI(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:wI(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=lI(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(LS),...o.nodes.slice(0,i+1).map(LS)];return fI(n),{subpaths:yI(t,r,[{...o,closed:!1,nodes:n}]),selectedNodes:e.map(t=>({...t}))}}const s=o.nodes.slice(0,i+1).map(LS),a=o.nodes.slice(i+1).map(LS);fI(s),fI(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:yI(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 aI(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 lI(t){const e=t[0];return e&&t.every(t=>t.subpathId===e.subpathId)?e.subpathId:null}function cI(t,e){if(2!==e.length)return null;const n=dI(t,e[0]),r=dI(t,e[1]);return n&&r&&n.subpathIndex!==r.subpathIndex?[n,r]:null}function dI(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 uI(t){return"end"===t.endpoint?t.subpath.nodes.map(LS):hI(t.subpath.nodes)}function pI(t){return"start"===t.endpoint?t.subpath.nodes.map(LS):hI(t.subpath.nodes)}function hI(t){return[...t].reverse().map(t=>({...LS(t),in:t.out?AS(t.out):null,out:t.in?AS(t.in):null}))}function fI(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 gI(t,e,n){return t?xI(e.add(new Tt(t.dx,t.dy)).sub(n)):null}function mI(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),{...LS(t),id:o}}),nodeIdMap:r}}function yI(t,e,n){return t.flatMap((t,r)=>r===e?n.map(RS):[RS(t)])}function wI(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)?[]:[RS(t)])}function xI(t){return t.len2()<=1e-12?null:{dx:t.x,dy:t.y}}function bI(t,e,n){return t.map(t=>{if(t.id!==e.subpathId)return RS(t);const r=t.nodes.findIndex(t=>t.id===e.startNodeId);if(r<0)return RS(t);const o=(r+1)%t.nodes.length,i=t.nodes[r],s=t.nodes[o];if(!i||!s||s.id!==e.endNodeId)return RS(t);const a=function(t,e,n,r){if(!FS(t,e)){const o=HS(NS(t),NS(e),n);return{start:LS(t),node:{id:r,x:o.x,y:o.y,kind:"corner"},end:LS(e)}}const[o,i,s,a]=DS(t,e),l=HS(o,i,n),c=HS(i,s,n),d=HS(s,a,n),u=HS(l,c,n),p=HS(c,d,n),h=HS(u,p,n);return{start:{...LS(t),out:xI(l.sub(o))},node:{id:r,x:h.x,y:h.y,kind:"smooth",in:xI(u.sub(h)),out:xI(p.sub(h))},end:{...LS(e),in:xI(d.sub(a))}}}(i,s,e.t,n),l=t.nodes.map(LS);return l[r]=a.start,l[o]=a.end,l.splice(r+1,0,a.node),{...t,nodes:l}})}var vI=new WeakMap;function kI(t){const e=vI.get(t);return e?function(t){return{shapeId:t.shapeId,nodes:t.nodes.map(t=>({...t})),primary:{...t.primary}}}(e):null}function SI(t){const e=vI.get(t);if(!e)return null;if(t.state.shapeEditingSession.get()?.shapeId!==e.shapeId)return null;const n=t.shapes.get(e.shapeId);if(!mS(n))return null;const r=e.nodes.flatMap(t=>{const e=QS(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})=>AI(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 II(t,{syncCaret:e=!0}={}){const n=vI.get(t);vI.delete(t),e&&t.state.shapeEditingSession.get()?.shapeId===n?.shapeId&&EI(t,null)}function PI(t,e,n,r){const o={subpathId:n,nodeId:r};MI(t,e,[o],o)}function MI(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!==CI(t,e));if(0===r.length)return null;const o=(n&&r.find(t=>AI(t,n)))??r[r.length-1];return{shapeId:t.id,nodes:r,primary:{...o}}}(e,n,r);if(!o)return void II(t);vI.set(t,o);const i=CI(e,o.primary);EI(t,i?t.shapes.computeLocalToPageTransform(e).applyToPoint(NS(i)):null)}function TI(t,e,n){return t.nodes.some(t=>t.subpathId===e&&t.nodeId===n)}function CI(t,e){return QS(t.props.subpaths,e.subpathId)?.nodes.find(t=>t.id===e.nodeId)??null}function EI(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 AI(t,e){return t.subpathId===e.subpathId&&t.nodeId===e.nodeId}var LI="land.path.draftSubpathId",RI="land.path.previewNodeId";function $I(t){const e=t.meta[LI],n=t.meta[RI];return{subpathId:"string"==typeof e?e:null,previewNodeId:"string"==typeof n?n:null}}function NI(t,e){const n=BI(t);return e.subpathId&&(n[LI]=e.subpathId),e.previewNodeId&&(n[RI]=e.previewNodeId),n}function BI(t){const e={...t};return delete e[LI],delete e[RI],e}var OI="var(--land-selection, #2563eb)",zI="rgba(255, 255, 255, 0.98)";function HI(){const t=a(),e=l(t.state.tool),n=l(t.inputs.state),r=l(t.state.selectedShapes),o=l(t.state.camera);if("path"!==e.activeToolId)return null;const i=1===r.length?r[0]:null,s=mS(i)?i:null,c=8/o.z,p=1.5/o.z,h=6/o.z,f=1/o.z,g=n.currentPagePoint;if(!s)return g?d(WI,{point:g,size:c,strokeWidth:p,variant:"candidate"}):null;const m=function(t,e){const n=$I(e);if(!n.subpathId)return null;const r=QS(qS(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?SS({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,s);if(!m)return g?d(WI,{point:g,size:c,strokeWidth:p,variant:"candidate"}):null;const y=m.previewNode?NS(m.previewNode):n.isPointing?null:g,w=y&&!m.committedNodes.some(t=>NS(t).dist2(y)<=.25/(o.z*o.z));
|
|
55
|
-
return
|
|
56
|
-
return
|
|
57
|
-
return
|
|
58
|
-
return
|
|
59
|
-
return
|
|
60
|
-
|
|
61
|
-
return
|
|
62
|
-
return
|
|
63
|
-
return
|
|
64
|
-
return
|
|
65
|
-
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 JI(t,e){const n=a();l(n.state.shapeEditingSession);const r=kI(n),o=dS(t,e);return!!r&&!!o&&TI(r,o.subpathId,o.nodeId)}var ZI=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(!mS(r))return!1;if(this.session?.mode===t&&this.session.shapeId===e)return!0;this.clear();const o=[QI(this.editor,r,t)];this.session={mode:t,shapeId:e,snapshots:o,index:o.length-1,initialShapeSignature:tP(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||!mS(n))return!1;const r=QI(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||!mS(n))return!1;const r=QI(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)&&(!mS(r)||n.initialShapeSignature!==tP(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(!mS(r))return this.clear(),!1;e.index=t;const o=kI(this.editor);this.editor.commands.updateShapes([{id:e.shapeId,..."create"===e.mode&&n.draftMeta?{meta:NI(r.meta,n.draftMeta)}:{},props:{subpaths:$S(n.subpaths)}}],{source:"user"});const i=this.editor.shapes.get(e.shapeId);mS(i)&&e.onApply?.(i);const s=n.selection??o;return s&&mS(i)&&this.editor.state.shapeEditingSession.get()?.shapeId===e.shapeId?MI(this.editor,i,s.nodes,s.primary):II(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 QI(t,e,n){const r=$S(e.props.subpaths),o="create"===n?$I(e):null;return{subpaths:r,draftMeta:o,selection:kI(t),signature:JSON.stringify({subpaths:r,draftMeta:o})}}function tP(t){return JSON.stringify(function(t){return{...t,meta:{...t.meta},props:{...t.props,fill:{...t.props.fill},stroke:{...t.props.stroke},subpaths:$S(t.props.subpaths)}}}(t))}var eP=new WeakMap;function nP(t){const e=eP.get(t);if(e)return e;const n=new ZI(t);return eP.set(t,n),n}function rP(t,e,n,r){return nP(t).start(e,n,r)}function oP(t,e){return nP(t).record(e)}function iP(t,e,n){return nP(t).end(e,n)}var sP=new WeakMap;function aP(t){return sP.get(t)??!1}function lP(t){return function(t,e){const n=t.state.shapeEditingSession.get(),r=n?t.shapes.get(n.shapeId):null;return!(!n||!mS(r))&&(aP(t)===e||(sP.set(t,e),e||t.snaps.clearIndicators(),t.session.update({shapeEditingSession:{...n}},"system")),e)}(t,!aP(t))}function cP(t){sP.delete(t),t.snaps.clearIndicators()}function dP(t){let e=null;const n=be("path.editSnap.lifecycle",t.state.shapeEditingSession,()=>{const n=t.state.shapeEditingSession.get(),r=n?t.shapes.get(n.shapeId):null,o=mS(r)?r.id:null;if(o!==e){if(e){const n=function(t,e,n){return nP(t).hasNetChanges(e,n)}(t,"edit",e);iP(t,"edit",e),n||t.editing.cancelOperation()}e=o,II(t),cP(t),o&&rP(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&&iP(t,"edit",e),II(t,{syncCaret:!1}),cP(t)}}var uP="path.edit",pP=Math.PI/4,hP={propagation:"stop"},fP=1,gP=new WeakMap,mP=new WeakMap;function yP(t){const e=t.state.shapeEditingSession.get();if(!e)return null;const n=t.shapes.get(e.shapeId);return mS(n)?n:null}function wP(t,e,n){return t.shapes.computeLocalToPageTransform(e).invert().applyToPoint(n)}function xP(t){pS(t,null)}function bP(t){xP(t),II(t)}function vP(t){return t.shiftKey}function kP(t){return JSON.stringify([t.subpathId,t.nodeId])}function SP(t,e){const n=gP.get(t);if(!n)return;if(e.pointerId!==n.pointerId)return;const r=t.shapes.get(n.shapeId);if(!mS(r))return void IP(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 Ct(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(NS(e));return n.containsPoint(o)?[{subpathId:t.id,nodeId:e.id}]:[]}))}(t,r,s),l=vP(e)?function(t,e){const n=new Map(t.map(t=>[kP(t),{...t}]));for(const r of e){const t=kP(r);n.has(t)?n.delete(t):n.set(t,{...r})}return Array.from(n.values())}(n.previousEntries,a):a;t.interaction.setBrushBox(s),MI(t,r,l,l.at(-1)??null)}function IP(t){const e=gP.get(t);if(!e)return;const n=t.shapes.get(e.shapeId);mS(n)&&t.state.shapeEditingSession.get()?.shapeId===e.shapeId?MI(t,n,e.previousEntries,e.previousPrimary):II(t),gP.delete(t),t.interaction.setBrushBox(null)}function PP(t,e,n,r){const o=t.shapes.get(e);mS(o)&&MI(t,o,n,r)}function MP(t){return t.filter(t=>t.nodes.length>=2)}function TP(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 CP(t,e,n){const r=MP(function(t,e){const n=aI(e);return 0===n.size?$S(t):t.map(t=>{const e=n.get(t.id);if(!e)return RS(t);const r=t.nodes.filter(t=>!e.has(t.id)).map(LS),o=t.closed&&r.length>=3;return t.closed&&!o&&fI(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"}),II(t),oP(t,e.id)):TP(t,e)}function EP(t,e){const n=SI(t);if(!n||n.shape.isLocked)return!1;const{shape:r,selection:o}=n,i=sI(r.props.subpaths,o.nodes,e,o.primary);if(!i)return!1;const s=MP(i.subpaths);return 0===s.length?(TP(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"}),PP(t,r.id,i.selectedNodes,i.primaryNode)}),oP(t,r.id),!0)}function AP(t,e){const n=SI(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 Tt(0,0));return r.applyToPoint(n).sub(o)}(t,r,e),s=nI(r.props.subpaths,o.nodes,t=>NP(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"}),PP(t,r.id,o.nodes,o.primary)}),oP(t,r.id),!0}function LP(t,e,n){const r=yP(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||!mS(n)||!t.editing.canEditShape(n)||(bP(t),cP(t),!t.editing.start({shapeId:n.id,operationKind:uP,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 lP(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 EP(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 Tt(-e,0);case"ArrowRight":return new Tt(e,0);case"ArrowUp":return new Tt(0,-e);case"ArrowDown":return new Tt(0,e);default:return null}}(e);if(o)return AP(t,o);if(e.altKey||e.ctrlKey||e.metaKey||e.accelKey)return!1;const i=SI(t);if(!i||i.shape.isLocked)return!1;const s=e.key.toLowerCase();return"backspace"===s||"delete"===s?(CP(t,i.shape,i.selection.nodes),!0):"c"===s?function(t,e,n){const r=n.filter(t=>{const n=tI(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)=>rI(t,e.subpathId,e.nodeId),e.props.subpaths);return t.commands.updateShapes([{id:e.id,props:{subpaths:o}}],{source:"user"}),PP(t,e.id,n,n.at(-1)??null),oP(t,e.id),!0}(t,i.shape,i.selection.nodes):"x"===s?(function(t,e,n){const r=n.reduce((t,e)=>oI(t,e.subpathId,e.nodeId),e.props.subpaths);t.commands.updateShapes([{id:e.id,props:{subpaths:r}}],{source:"user"}),PP(t,e.id,n,n.at(-1)??null),oP(t,e.id)}(t,i.shape,i.selection.nodes),!0):"j"===s?EP(t,"join"):"k"===s&&EP(t,"separate")}function RP(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 $P(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)/pP)*pP;return t.add(new Tt(Math.cos(o)*r,Math.sin(o)*r))}function NP(t,e){return{...t,x:t.x+e.x,y:t.y+e.y}}function BP(){return{createSession(t,{handle:e,shape:n,originPagePoint:r}){if(!mS(n)||"custom"!==e.kind)return null;const o=dS(e.type,e.id);if(!o)return null;if(t.state.shapeEditingSession.get()?.shapeId!==n.id)return null;const i=mP.get(t),s="path.node"===o.type&&i?.shapeId===n.id&&i.nodeId===o.nodeId;s&&mP.delete(t);const a=n,l=tI(a.props.subpaths,o.subpathId,o.nodeId),c=wP(t,a,r),d=SI(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&&TI(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?MI(t,n,y,h):t.inputs.state.get().shiftKey||f||PI(t,n,o.subpathId,o.nodeId);const w="path.node"===o.type&&(y||g)?y??d.selection.nodes:[h],x=t.shapes.computeLocalToPageTransform(a),b=l?x.applyToPoint(NS(l)):r,v=e.point.sub(r),k="path.node"===o.type?w.flatMap(t=>{const e=tI(a.props.subpaths,t.subpathId,t.nodeId);return e?[x.applyToPoint(NS(e))]:[]}):[e.point],S=(k.length>0?k:[e.point]).map(t=>t.sub(r)),I=function(t,e,n){const r=new Set(n.map(kP)),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(kP(i))?[]:[{id:`${e.id}:${t.id}:${n.id}`,nodeId:e.id,point:o.applyToPoint(NS(n)),kind:"custom"}]})),outlines:[]}}(t,a,"path.node"===o.type?w:[]);return{shapeId:n.id,operationKind:"path.handle",onClick:m&&g?({editor:t})=>{const e=t.shapes.get(n.id);mS(e)&&function(t,e,n,r){const o=kI(t);if(!o||o.shapeId!==e.id)return void PI(t,e,n,r);const i={subpathId:n,nodeId:r},s=TI(o,n,r),a=s?o.nodes.filter(t=>!AI(t,i)):[...o.nodes,i];MI(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);mS(r)&&t.state.shapeEditingSession.get()?.shapeId===n.id&&(0!==u.length?MI(t,r,u,p):II(t))},onComplete({editor:t}){s?function(t,e){nP(t).replaceCurrent(e)}(t,n.id):oP(t,n.id)},update({editor:t,pagePoint:e,accelKey:i,source:s}){if(!mS(t.shapes.get(n.id)))return"stop";const d=t.inputs.state.get(),u=d.shiftKey?"path.node"===o.type?$P(r,e):$P(b,e.add(v)).sub(v):e,p=aP(t)&&!i&&!d.shiftKey&&I.points.length>0,h=p?t.snaps.snapHandle({mode:"align",pagePoint:u,sourcePointOffsets:S,snapshot:I,threshold:10/t.state.camera.get().z}):null;p||t.snaps.clearIndicators();const f=h?.snappedPagePoint??u,g=wP(t,a,"path.node"===o.type?f:f.add(v)),m="path.node"===o.type?l?nI(a.props.subpaths,w,t=>NP(t,g.sub(c))):$S(a.props.subpaths):eI(a.props.subpaths,o.subpathId,o.nodeId,t=>function(t,e,n,r){const o=NS(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=RP(s,t.out?OS(t).sub(o):null,"symmetric"===t.kind))):(i.out={dx:s.x,dy:s.y},r.altKey||"corner"===t.kind||(i.in=RP(s,t.in?BS(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);mS(e)&&MI(t,e,w,{subpathId:o.subpathId,nodeId:o.nodeId})}return"continue"}}}}}function OP(){return{id:"land.path.interactions",editorEvent:{handleEvent(t,e,n){if("pointer"===e.type&&"pointer_move"===e.name&&gP.get(t)?.pointerId===e.pointerId)return xP(t),SP(t,e),hP;if("pointer"===e.type&&"pointer_up"===e.name&&(mP.delete(t),xP(t),gP.get(t)?.pointerId===e.pointerId))return function(t,e){const n=gP.get(t);n&&(n.isActive?SP(t,e):vP(e)||II(t),gP.delete(t),t.interaction.setBrushBox(null))}(t,e),hP;if("pointer"===e.type&&"pointer_cancel"===e.name&&(mP.delete(t),xP(t),gP.get(t)?.pointerId===e.pointerId))return IP(t),hP;if("double_click"===e.type&&!e.shiftKey&&!e.altKey&&!e.accelKey){bP(t);const n=t.shapes.hitTest(e.pagePoint);if(mS(n))return cP(t),t.editing.start({shapeId:n.id,operationKind:uP,entryMode:"focusEnd"},"user"),hP}if("cancel"===e.type)return mP.delete(t),gP.has(t)?(IP(t),hP):"command"===e.reason?void xP(t):"escape"===e.reason&&t.tools.isInInitialState()&&yP(t)&&t.editing.complete("user")?hP:void bP(t);if("keyboard"===e.type&&"key_down"===e.name)return LP(t,e,n)?hP:void 0;if("pointer"!==e.type||"pointer_move"!==e.name){if("pointer"===e.type&&"pointer_down"===e.name&&0===e.button&&e.altKey){xP(t);const n=yP(t);if(!n)return;const r=t.selection.hitTestHandle(e.pagePoint);if("custom"===r?.kind&&"path.node"===r.type){const e=dS(r.type,r.id);if("path.node"===e?.type){const r=SI(t);return CP(t,n,r?.selection.shapeId===n.id&&TI(r.selection,e.subpathId,e.nodeId)?r.selection.nodes:[{subpathId:e.subpathId,nodeId:e.nodeId}]),hP}}}if("pointer"===e.type&&"pointer_down"===e.name&&0===e.button&&!e.altKey){xP(t);const n=yP(t);if(!n)return;const r=t.selection.hitTestHandle(e.pagePoint);if("custom"===r?.kind)return void(dS(r.type,r.id)||II(t));const o=wP(t,n,e.pagePoint),i=ZS(n.props.subpaths,o,7/t.state.camera.get().z);if(!i)return function(t,e,n){const r=SI(t);gP.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),hP;const s=`insert-node:${fP+=1}`;return t.operations.run({kind:"path.insert-node",label:"shape.edit",source:"user",history:"record"},()=>{const e=bI(n.props.subpaths,i,s);t.commands.updateShapes([{id:n.id,props:{subpaths:e}}],{source:"user"});const r=t.shapes.get(n.id);mS(r)&&PI(t,r,i.subpathId,s)}),oP(t,n.id),void mP.set(t,{shapeId:n.id,nodeId:s})}}else"mouse"!==e.pointerType||0!==e.buttons||e.altKey?xP(t):function(t,e){const n=yP(t);if(!n||"select"!==t.state.tool.get().activeToolId||!t.tools.isInInitialState())return void xP(t);if("custom"===t.selection.hitTestHandle(e.pagePoint)?.kind)return void xP(t);const r=wP(t,n,e.pagePoint),o=ZS(n.props.subpaths,r,7/t.state.camera.get().z);if(!o)return void xP(t);const i=t.shapes.computeLocalToPageTransform(n);pS(t,{shapeId:n.id,subpathId:o.subpathId,startNodeId:o.startNodeId,endNodeId:o.endNodeId,t:o.t,pagePoint:i.applyToPoint(o.point)})}(t,e)}},selectionHandle:BP()}}function zP(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function HP(t){if(!t||"object"!=typeof t)return null;const e=t,n=zP(e.dx,NaN),r=zP(e.dy,NaN);return Number.isFinite(n)&&Number.isFinite(r)?e.dx===n&&e.dy===r?t:{dx:n,dy:r}:null}function DP(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=zP(r.x,NaN),i=zP(r.y,NaN);return Number.isFinite(o)&&Number.isFinite(i)?{id:WP("string"==typeof r.id&&r.id.length>0?r.id:`node:${e}`,n),x:o,y:i,kind:wS(r.kind)?r.kind:"corner",in:HP(r.in),out:HP(r.out)}:null}(t,e,o)).filter(t=>null!==t):[];return 0===i.length?null:{id:WP("string"==typeof r.id&&r.id.length>0?r.id:`subpath:${e}`,n),closed:"boolean"==typeof r.closed&&r.closed,nodes:i}}function FP(t,e){if(!Array.isArray(t))return e;const n=new Set,r=t.map((t,e)=>DP(t,e,n)).filter(t=>null!==t);return r.length>0?r:e}function WP(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 jP(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 UP=class extends fe{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:Ot("transparent"),stroke:Bt("stroke-slate"),strokeWidth:3,fillRule:"nonzero"}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{subpaths:(r=FP(e.subpaths,n.subpaths),r.map(t=>({...t,nodes:t.nodes.filter(t=>ES(t.x)&&ES(t.y))})).filter(t=>t.nodes.length>0).map(RS)),fill:Dt(e.fill,n.fill),stroke:Dt(e.stroke,n.stroke),strokeWidth:Math.max(1,zP(e.strokeWidth,n.strokeWidth)),fillRule:yS(e.fillRule)?e.fillRule:n.fillRule};var r}getPositionedBounds(t){const e=KS(t).localBounds;return new Ct(t.x+e.x,t.y+e.y,e.w,e.h)}getLocalBounds(t){return KS(t).localBounds}getRenderBounds(t){return KS(t).renderBounds}getExportBounds(t){return this.getRenderBounds(t)}getSelectionResizeLocalBounds(t){return KS(t).pointBounds}resizeSelectionBounds(t,e){const n=qS(t,this.getLocalTransform(t)).map(t=>({...t,nodes:t.nodes.map(t=>XP(t,t=>function(t,e){return 0===e.selectionRotation?t:Tt.RotWith(t,e.selectionRotationCenter,-e.selectionRotation)}(t,e)))})),r=_S(function(t,e){const n=KS(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 YS(t.props.subpaths,t=>new Tt(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=>XP(t,t=>function(t,e){return 0===e.selectionRotation?t:Tt.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 KS(t).outlineVertices.map(e=>new Tt(t.x+e.x,t.y+e.y))}getTerminalBindingOutlines(t){return KS(t).flattenedSubpaths.filter(t=>t.points.length>0).map(e=>({points:e.points.map(e=>new Tt(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=KP(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:NS(t),kind:"custom"},...t.in?[{point:BS(t),kind:"custom"}]:[],...t.out?[{point:OS(t),kind:"custom"}]:[]])),outline:KS(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:sS,id:lS(t.id,e.id),point:o.applyToPoint(NS(e)),cursor:"grab"}];return e.in&&n.push({kind:"custom",type:aS,id:cS(t.id,e.id,"in"),point:o.applyToPoint(BS(e)),cursor:"grab"}),e.out&&n.push({kind:"custom",type:aS,id:cS(t.id,e.id,"out"),point:o.applyToPoint(OS(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:GS(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 Tt(e.x-t.x,e.y-t.y),o=KS(t);return!jt(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&&JS(e,n,i)<=r)return!0}return!1}(o.flattenedSubpaths,r,t.props.strokeWidth/2+6)}hitTestLineSegment(t,e){const n=new Tt(e.positionedStart.x-t.x,e.positionedStart.y-t.y),r=new Tt(e.positionedEnd.x-t.x,e.positionedEnd.y-t.y),o=e.positionedMargin+t.props.strokeWidth/2;return KS(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&&(jP(r,t,e)<=o||jP(s,t,e)<=o||jP(t,r,s)<=o||jP(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 KP(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 XP(t,e){const n=e(NS(t)),r=t.in?e(BS(t)):null,o=t.out?e(OS(t)):null;return{...LS(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 YP=Math.PI/4,_P=1,qP=1;function GP(){return`node:${_P+=1}`}function VP(t,e,n){return t.shapes.computeLocalToPageTransform(e).invert().applyToPoint(n)}function JP(t,e,n,r){const o=(QS(e.props.subpaths,n)?.nodes.filter(t=>t.id!==r))?.at(-1);return o?t.shapes.computeLocalToPageTransform(e).applyToPoint(new Tt(o.x,o.y)):null}function ZP(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)/YP)*YP;return t.add(new Tt(Math.cos(o)*r,Math.sin(o)*r))}function QP(t,e,n,r,o){const i=function(t,e,n){const r=QS(e.props.subpaths,n)?.nodes[0];return r?t.shapes.computeLocalToPageTransform(e).applyToPoint(new Tt(r.x,r.y)):null}(t,e,n),s=QS(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 tM(t,e){return e.previewNodeId?t.map(t=>t.id===e.subpathId?{...t,nodes:t.nodes.filter(t=>t.id!==e.previewNodeId)}:t):$S(t)}function eM(t,e){return QS(t.props.subpaths,e.subpathId)?.nodes.filter(t=>t.id!==e.previewNodeId).length??0}var nM=class extends we{draft=null;operation=null;constructor(t){super(t,"path"),this.initial="idle",this.addChild(new rM(t,this)),this.addChild(new oM(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:${qP+=1}`,o=GP(),i={id:o,x:0,y:0,kind:"corner"},[s]=this.editor.commands.createShapes([{type:"path",x:t.x,y:t.y,meta:NI({},{subpathId:r,previewNodeId:null}),props:{...n,subpaths:[{id:r,closed:!1,nodes:[i]}]}}],{source:"user",autoReparent:!1});if(!mS(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},rP(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=QS(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:LS(i),finishOnPointerUp:!1}}const r=this.editor.shapes.get(this.draft.shapeId);if(!mS(r))return this.cancelDraft(),null;const o=n.shiftKey?JP(this.editor,r,this.draft.subpathId,this.draft.previewNodeId)??t:t,i=n.shiftKey?ZP(o,t):t;if(QP(this.editor,r,this.draft.subpathId,this.draft.previewNodeId,t)){const n=this.draft,o=QS(r.props.subpaths,n.subpathId)?.nodes.find(t=>t.id!==n.previewNodeId);return o?(this.editor.commands.updateShapes([{id:r.id,meta:NI(r.meta,{subpathId:n.subpathId,previewNodeId:null}),props:{subpaths:tM(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:LS(o),finishOnPointerUp:!0}):null}const s=VP(this.editor,r,i),a=this.draft.previewNodeId??GP(),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:NI(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(!mS(o))return;const i=r.shiftKey?ZP(t.originPagePoint,e):e,s=VP(this.editor,o,t.originPagePoint),a=VP(this.editor,o,i),l=t.originScreenPoint.dist(n)>=3,c=eI(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):LS(t.startNode));this.editor.commands.updateShapes([{id:o.id,meta:NI(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(!mS(n)||eM(n,this.draft)<1)return;const r=e.shiftKey?JP(this.editor,n,this.draft.subpathId,this.draft.previewNodeId):null,o=r?ZP(r,t):t,i=VP(this.editor,n,o),s=this.draft.previewNodeId??GP(),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:NI(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!!mS(t)&&eM(t,this.draft)>=2}finishDraft(t={}){if(!this.draft)return;const e=t.switchToSelect??!0,n=this.editor.shapes.get(this.draft.shapeId);if(mS(n)){const t=tM(n.props.subpaths,this.draft),e=_S(qS({...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:BI(n.meta),props:{subpaths:e.subpaths}}],{source:"user"}),this.draft.createdShape&&Gt(this.editor,n.id,{source:"user"})}iP(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}),mS(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&&(iP(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()}},rM=class extends we{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()}},oM=class extends we{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}),oP(this.editor,e.shapeId)),this.transition("idle"),e?.finishOnPointerUp&&this.tool.finishDraft()}onCancel(){this.tool.cancelDraft(),this.transition("idle")}onExit(){this.info=null}},iM=class{type="path";toSvg(t,e){const n=KS(t);return n.path?{tag:"path",attrs:{d:n.path,fill:jt(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 sM(){return{shapeUtils:[new UP],shapeSvgExporters:[new iM],interactionHandlers:[OP()],tools:{path:t=>new nM(t)}}}var{difference:aM,intersection:lM,union:cM,xor:dM}=xt,uM=1,pM=1;function hM(t,e){return Math.abs(t[0]-e[0])<1e-6&&Math.abs(t[1]-e[1])<1e-6}function fM(t){return qS(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&&hM(r,t)||e.push(t)}return e.length>1&&hM(e[0],e[e.length-1])&&e.pop(),e.length>=3?e:null}(US(t).points)).filter(t=>null!==t).map(t=>[t])}function gM(t){const e=t.length>1&&hM(t[0],t[t.length-1])?t.slice(0,-1):t;return e.length<3?null:{id:`boolean-subpath:${uM+=1}`,closed:!0,nodes:e.map(([t,e])=>({id:`boolean-node:${pM+=1}`,x:t,y:e,kind:"corner"}))}}function mM(t,e){const n=e.map(fM).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 cM(n,...r);case"subtract":return aM(n,...r);case"intersect":return lM(n,...r);case"xor":return dM(n,...r)}}(t,n).flatMap(t=>t).map(gM).filter(t=>null!==t)}function yM({editor:t}){return function({editor:t}){return{getSelectionStyle:()=>function(t){const e=t.state.selectedShapes.get().filter(mS);return 0===e.length?null:{fill:IM(e.map(t=>t.props.fill)),stroke:IM(e.map(t=>t.props.stroke)),strokeWidth:SM(e.map(t=>t.props.strokeWidth))}}(t),setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(mS).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)},toolDefaultsState:o(t.signals.computed("Path.toolDefaults",()=>t.shapes.getDefaultProps("path"))),setToolDefaults:e=>(t.shapes.updateDefaultProps("path",e),t.shapes.getDefaultProps("path")),canBeginEdit:()=>null!==wM(t),beginEdit(){const e=wM(t);return!!e&&(II(t),cP(t),t.editing.start({shapeId:e.id,operationKind:"path.edit",entryMode:"focusEnd"},"user"),!0)},isEditing:()=>null!==xM(t),completeEdit:()=>!!xM(t)&&(t.editing.complete("user"),!0),isNodeSnapEnabled:()=>aP(t),canToggleNodeSnap:()=>{const e=xM(t);return!!e&&!e.isLocked},toggleNodeSnap(){const e=xM(t);return!(!e||e.isLocked)&&(lP(t),!0)},canDeleteSelectedNodes:()=>bM(t,()=>!0),deleteSelectedNodes(){const e=SI(t);return!(!e||e.shape.isLocked)&&(CP(t,e.shape,e.selection.nodes),!0)},canMakeSelectedNodesCurve:()=>bM(t,t=>t.entries.some(({node:t})=>!t.in&&!t.out)),makeSelectedNodesCurve:()=>vM(t,"make-curve"),canRemoveSelectedNodeHandles:()=>bM(t,t=>t.entries.some(({node:t})=>!!t.in||!!t.out)),removeSelectedNodeHandles:()=>vM(t,"remove-handles"),canRunSelectedNodeOperation:e=>bM(t,t=>iI(t.shape.props.subpaths,t.selection.nodes,e)),runSelectedNodeOperation(e){const n=SI(t);return!(!n||n.shape.isLocked||!iI(n.shape.props.subpaths,n.selection.nodes,e))&&(EP(t,e),!0)},canRunBooleanOperation:()=>kM(t).length>=2,runBooleanOperation:e=>function(t,e){const n=kM(t),r=n[0];if(!r||n.length<2)return null;const o=function(t,e,n){const r=mM(t,e);return 0===r.length?null:_S(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 wM(t){const e=t.state.selectedShapes.get(),n=1===e.length?e[0]:null;return mS(n)&&!n.isLocked?n:null}function xM(t){const e=t.state.shapeEditingSession.get(),n=e?t.shapes.get(e.shapeId):null;return mS(n)?n:null}function bM(t,e){const n=SI(t);return!!n&&!n.shape.isLocked&&e(n)}function vM(t,e){const n=SI(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})=>rI(t,e.subpathId,e.nodeId),n.shape.props.subpaths):n.selection.nodes.reduce((t,e)=>oI(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 mS(o)&&MI(t,o,n.selection.nodes,n.selection.primary),oP(t,n.shape.id),!0}function kM(t){return t.state.selectedShapes.get().filter(mS).filter(t=>!t.isLocked&&!t.isHidden)}function SM(t){const[e,...n]=t;return void 0!==e&&n.every(t=>t===e)?e:null}function IM(t){const[e,...n]=t;return void 0!==e&&n.every(t=>Ut(e,t))?e:null}var PM=s({id:"path",editor:sM(),render:YI(),setup({editor:t}){const e=dP(t);try{return{api:yM({editor:t}),dispose:e}}catch(n){throw e(),n}}});function MM(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 TM({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),CM({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=RM(a[1]??""),n=NM(a[2]??"");for(const r of $M(t)){const t=n.get(r)?.trim();if(!t)continue;const o="srcset"===r?BM(t):[t];for(const n of o)OM(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&&!OM(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 CM({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 CM({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 EM={audio:["src"],embed:["src"],iframe:["src"],img:["src","srcset"],input:["src"],object:["data"],script:["src"],source:["src","srcset"],track:["src"],video:["poster","src"]},AM=["href","xlink:href"],LM=new Set(["a","area"]);function RM(t){return(t.split(":").pop()??t).toLowerCase()}function $M(t){const e=EM[t]??[];return LM.has(t)?e:[...AM,...e]}function NM(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 BM(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 OM(t){return t.startsWith("#")||/^data:/iu.test(t)}var zM=16384,HM=67108864;async function DM({background:t,pixelRatio:e=2,...n}){const r=await TM(n);if(!r.svg||null===r.width||null===r.height)return{status:"error"===r.status.tone?WM(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>zM||t>zM||o*t>HM)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 MM(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 FM(c),width:i,height:s}}({background:t,height:r.height,pixelRatio:e,svg:r.svg,width:r.width});return{status:WM(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 FM(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 WM(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 jM(t,e){return(await t.export("svg",{..._M(e),options:e})).result}async function UM(t,e){return(await t.export("png",{..._M(e),options:e})).result}function KM(){return{kind:"provider",id:"canvas-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 TM({assetInliners:[YM(n,r.inlineSvg)],editor:t,padding:o.padding,resolveThemeColor:o.appearance?.resolveThemeColor,shapeIds:n});return{data:i.svg,result:i,status:i.status}}}}function XM(){return{kind:"provider",id:"canvas-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 DM({assetInliners:[YM(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 YM(t,e){return{inline:n=>e({...n,requestedShapeIds:t})}}function _M(t){return t.scope?{scope:t.scope}:{shapeIds:t.shapeIds}}function qM(){return yt({id:"canvas-export",setup:()=>({exports:[KM(),XM()]})})}var GM=new WeakMap;function VM(t){return GM.get(t)??null}function JM(t,e=0){return Math.max(0,"number"==typeof t&&Number.isFinite(t)?t:e)}function ZM({cornerRadius:t,h:e,w:n}){return Math.min(JM(t),Math.max(0,n)/2,Math.max(0,e)/2)}function QM(t){return Pt(t)&&"video"===t.type}function tT(t){return It(t)&&"video"===t.type}function eT({editor:t}){return{setMediaPresenter(e){!function(t,e){e?GM.set(t,e):GM.delete(t),t.assets.invalidateUrls()}(t,e)},getSelectionState(){if(1!==t.selection.getIds().length)return null;const[e]=t.state.selectedShapes.get();return tT(e)?{shapeId:e.id,cornerRadius:JM(e.props.cornerRadius),loop:e.props.loop}:null},setSelectionStyle(e){const n=t.state.selectedShapes.get().filter(tT).filter(t=>!t.isLocked).map(t=>({id:t.id,props:{...void 0===e.cornerRadius?{}:{cornerRadius:JM(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 nT(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}var rT=class extends fe{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(),{width:r,height:o}=re({width:nT(e.w,n.w),height:nT(e.h,n.h),preserveAspectRatio:!0});return{w:r,h:o,assetId:(i=e.assetId,"string"==typeof i&&i.startsWith("asset:")?e.assetId:null),name:"string"==typeof e.name?e.name:"",loop:!0===e.loop,cornerRadius:JM(e.cornerRadius)};var i}getLocalBounds(t){return new Ct(0,0,t.props.w,t.props.h)}getRenderBounds(t){return aT(t)}getExportBounds(t){return this.getLocalBounds(t)}getPointHitTestBounds(t,e){return ye({bodyHeight:t.props.h,bodyWidth:t.props.w,headingHeight:34,shape:t})}canEdit(t){return!0}hitTest(t,e,n){return this.getPositionedBounds(t).containsPoint(e)||(n?me({bodyHeight:t.props.h,bodyWidth:t.props.w,editor:n.editor,headingHeight:34,shape:t}).containsPoint(e):new Ct(t.x,t.y-34,t.props.w,t.props.h+34).containsPoint(e))}hitTestBindingTarget(t,e){return this.getPositionedBounds(t).containsPoint(e)}canReceiveTerminalBinding(t){return!0}getAllowedSelectionResizeModes(t,e){return te}},oT="Video",iT=34;function sT(t){return/^\s*$/.test(t)?oT:t}function aT(t){return new Ct(0,-34,t.props.w,t.props.h+34)}function lT(){return{shapeUtils:[new rT]}}var cT='[data-ui="video-shape-player"]',dT=new Set(["key_down","key_up","pointer_cancel","pointer_down","pointer_move","pointer_up"]),uT=["Inter","ui-sans-serif","system-ui","-apple-system","BlinkMacSystemFont","'Segoe UI'","sans-serif"].join(", "),pT={id:"land.video.player.dom-events",handle({event:t,name:e}){if(!dT.has(e))return"continue";const n=t.target;return n instanceof Element&&n.closest(cT)?"handled":"continue"},getCursor:({element:t})=>t?.closest(cT)?"default":void 0},hT=i({id:"land.video.name.dom-events",selector:'[data-ui="video-canvas-name"]'});function fT(){return{domEventGuards:[pT,hT],shapeRenderers:[{type:"video",component:gT,hoverComponent:mT}]}}function gT({editor:e,isSelected:n,shape:r,shapeEditingSession:o}){const{assetId:i,h:s,loop:a,name:c,w:p}=r.props;l(e.assets.getUrlVersionSignal());const h=i?e.assets.resolveUrl(i):null,f=o?.shapeId===r.id;
|
|
66
|
-
return
|
|
67
|
-
return
|
|
68
|
-
return d(n,{editor:t,shape:e,isEditing:r,value:e.props.name,fallback:sT(""),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 wT=s({id:"video",editor:lT(),render:fT(),setup:({editor:t})=>({api:eT({editor:t})})}),xT="blobs",bT=null;function vT(){return"undefined"==typeof indexedDB?Promise.resolve(null):(bT||(bT=new Promise((t,e)=>{const n=indexedDB.open("land.plugin-video",1);n.addEventListener("upgradeneeded",()=>{n.result.objectStoreNames.contains(xT)||n.result.createObjectStore(xT)}),n.addEventListener("success",()=>{const e=n.result;e.addEventListener("versionchange",()=>{e.close(),bT=null}),t(e)}),n.addEventListener("error",()=>{bT=null,e(n.error)})})),bT)}var kT="video-blob:";function ST(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?`${kT}${crypto.randomUUID()}`:`${kT}${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}async function IT(t){if("undefined"==typeof indexedDB)throw new Error("IndexedDB is not available for video storage.");const e=ST();return await async function(t,e){const n=await vT();n&&await new Promise((r,o)=>{const i=n.transaction(xT,"readwrite");i.addEventListener("complete",()=>r()),i.addEventListener("abort",()=>o(i.error)),i.addEventListener("error",()=>o(i.error)),i.objectStore(xT).put(e,t)})}(e,t),{storageKey:e}}async function PT(t){const e=await async function(t){const e=await vT();return e?new Promise((n,r)=>{const o=e.transaction(xT,"readonly").objectStore(xT).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 MT(t){await async function(t){const e=await vT();e&&await new Promise((n,r)=>{const o=e.transaction(xT,"readwrite");o.addEventListener("complete",()=>n()),o.addEventListener("abort",()=>r(o.error)),o.addEventListener("error",()=>r(o.error)),o.objectStore(xT).delete(t)})}(t)}async function TT(){return(await async function(){const t=await vT();return t?new Promise((e,n)=>{const r=t.transaction(xT,"readonly").objectStore(xT).getAllKeys();r.addEventListener("success",()=>e([...r.result])),r.addEventListener("error",()=>n(r.error))}):null}())?.map(String)??[]}function CT(t,e){const n=t.assets.get(e);return QM(n)&&"local"===n.props.source.kind&&n.props.source.storageKey||null}function ET(t,e){const n=t.assets.get(e);return QM(n)&&"remote"===n.props.source.kind&&n.props.source.url||null}function AT(t){const e=new Set;for(const n of t.assets.getAll())QM(n)&&"local"===n.props.source.kind&&n.props.source.storageKey&&e.add(n.props.source.storageKey);return e}async function LT({editor:t,objectUrls:e}){const n=AT(t),r=await TT(),o=[];for(const i of r)n.has(i)||(e?.release(i),await MT(i),o.push(i));return o}function RT(){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=PT(o).then(e=>{if(!e||r||l!==n)return null;const i=URL.createObjectURL(e);return t.set(o,i),i}).finally(()=>{e.delete(o)});e.set(o,c);const d=await c;return i.signal?.throwIfAborted(),d};return{async preloadForEditor(t,e={}){e.signal?.throwIfAborted(),await Promise.all(Array.from(AT(t)).map(t=>o(t,e)))},preload:o,resolve:e=>t.get(e)??null,resolveAssetUrl(e,n){const r=ET(e,n);if(r)return r;const o=CT(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 $T(t,{signal:e}){if("url"===t.type)return{...await NT(t.url,{signal:e}),name:t.name||FT(t.url)||"Video",source:{kind:"remote",url:t.url},mimeType:null};const n="file"===t.type?t.file:t.blob;if(!zT(n))throw new Error("The selected file is not a video.");const r=URL.createObjectURL(n),o=await NT(r,{signal:e}).finally(()=>URL.revokeObjectURL(r));e.throwIfAborted();const{storageKey:i}=await IT(n);try{e.throwIfAborted()}catch(s){throw await MT(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 NT(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 BT({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 OT(t){for(const e of t)if(e.type.startsWith("video/"))return e;return null}function zT(t){return!t.type||t.type.startsWith("video/")}function HT({filename:t,url:e}){const n=document.createElement("a");n.href=e,n.download=t,n.click()}async function DT({blob:t,filename:e}){const n=URL.createObjectURL(t);try{HT({filename:e,url:n})}finally{window.setTimeout(()=>URL.revokeObjectURL(n),0)}}function FT(t){try{const e=new URL(t).pathname.split("/").filter(Boolean).at(-1);return e?decodeURIComponent(e):null}catch{return null}}var WT=1;function jT(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 UT({editor:t,objectUrls:e,pagePoint:n,signal:r,size:o,source:i}){return KT({editor:t,input:await $T(i,{signal:r}),objectUrls:e,pagePoint:n,signal:r,size:o})}async function KT({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}),await wt(t,o),o.throwIfAborted()}catch(a){throw await _T({objectUrls:n,storageKey:s}),a}try{const o=t.operations.run({kind:"video.insert",source:"user"},()=>{const n=jT(t,e),o=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)??BT({width:n.props.w,height:n.props.h}),s=t.state.viewportPageBounds.get(),a=r??s?.center??t.viewport.screenToPage(new Tt(360,240)),[l]=t.commands.createShapes([{type:"video",x:Math.round(a.x-o.w/2),y:Math.round(a.y-o.h/2),props:{...o,assetId:n.id,name:e.name}}],{source:"user"});return l?(t.commands.setSelectedShapeIds([l.id],{source:"user"}),l.id):(t.commands.deleteAsset(n.id,{source:"system"}),null)});return o||await _T({objectUrls:n,storageKey:s}),o}catch(a){throw await _T({objectUrls:n,storageKey:s}),a}}async function XT({editor:t,file:e,objectUrls:n,signal:r}){if(!zT(e))return!1;const[o]=t.state.selectedShapes.get();return!(1!==t.selection.getIds().length||!tT(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}),await wt(t,o),o.throwIfAborted()}catch(a){throw await _T({objectUrls:n,storageKey:s}),a}try{const o=t.shapes.get(r.id);if(!tT(o)||o.isLocked||o.props.assetId!==i)return await _T({objectUrls:n,storageKey:s}),!1;const l=t.operations.begin({kind:`video.asset.replace:${r.id}:${WT++}`,label:"video.asset.replace",source:"user",history:"record"});try{const n=jT(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 _T({objectUrls:n,storageKey:s}),a}}({editor:t,input:await $T({type:"file",file:e},{signal:r}),objectUrls:n,shape:o,signal:r})}async function YT({editor:t,objectUrls:e,onError:n,signal:r}){if(r.throwIfAborted(),1!==t.selection.getIds().length)return;const[o]=t.state.selectedShapes.get();if(!tT(o)||!o.props.assetId)return;const i=t.assets.get(o.props.assetId);if(!QM(i))return;const s=i.props.name||"land-video";if("remote"===i.props.source.kind)return void(await async function({filename:t,onError:e,signal:n,url:r}){n.throwIfAborted();try{const e=await fetch(r,{signal:n});if(!e.ok)throw new Error(`Could not download video URL (${e.status}).`);const o=await e.blob();n.throwIfAborted(),await DT({blob:o,filename:t})}catch(o){n.throwIfAborted(),e?.(new Error("Could not download remote video; opening URL instead.",{cause:o})),function(t){const e=document.createElement("a");e.href=t,e.rel="noreferrer",e.target="_blank",e.click()}(r)}}({filename:s,onError:n,signal:r,url:i.props.source.url}));const a=i.props.source.storageKey,l=await PT(a);if(r.throwIfAborted(),l)return void(await DT({blob:l,filename:s}));const c=e.resolve(a);c&&HT({filename:s,url:c})}async function _T({objectUrls:t,storageKey:e}){e&&(t.release(e),await MT(e))}function qT({editor:t,onError:e,run:n,videoAssetService:r}){let o;const i=GT(t=>o.insert({source:{type:"file",file:t}}),e),s=GT(t=>o.replaceSelection({file:t}),e);return o={openInsertFilePicker(){i.open()},openReplaceFilePicker(){s.open()},insert:({pagePoint:e,size:o,source:i})=>n(async n=>{n.throwIfAborted();const s=await UT({editor:t,objectUrls:r.objectUrls,pagePoint:e,signal:n,size:o,source:i});return n.throwIfAborted(),s}),replaceSelection:({file:e})=>n(async n=>{if(!e.type.startsWith("video/"))return!1;const[o]=t.state.selectedShapes.get();if(!tT(o)||o.isLocked)return!1;const i=await XT({editor:t,file:e,objectUrls:r.objectUrls,signal:n});return n.throwIfAborted(),i}),downloadSelectionOriginal:()=>n(async n=>{await YT({editor:t,objectUrls:r.objectUrls,onError:e,signal:n}),n.throwIfAborted()})},{value:o,dispose(){i.dispose(),s.dispose()}}}function GT(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 VT(){const t=RT();return{value:{objectUrls:t,preloadForEditor:(e,{signal:n})=>t.preloadForEditor(e,{signal:n}),resolveAssetUrl:(e,n)=>t.resolveAssetUrl(e,n)},dispose(){t.releaseAll()}}}function JT(t={}){return yt({id:"video.host",requires:[wT],setup({api:e,canvas:n,editor:r,run:o}){const i=e(wT),s=(t.createAssetService??VT)();let a=!1;const l=()=>i.setMediaPresenter(mt({run:o,onError:t.onError})),c=n.snapshots.revision.subscribe(()=>{queueMicrotask(()=>{a||l()})});let d=null;const u=()=>{a=!0,c(),i.setMediaPresenter(null);const t=[];try{d?.()}catch(e){t.push(e)}try{s.dispose()}catch(e){t.push(e)}if(t.length)throw new AggregateError(t,"Failed to dispose video host resources.")};try{l();const e=qT({editor:r,onError:t.onError,run:o,videoAssetService:s.value});return d=e.dispose,{api:e.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!==OT(t.files)||(t.urls?.some(ZT)??!1),async import(t){const n=OT(t.files),r=t.urls?.find(ZT);return(n||r)&&await e.value.insert({source:n?{type:"file",file:n}:{type:"url",url:r},pagePoint:t.pagePoint})?"handled":"ignored"}}],assetResolvers:[{id:"video.host.asset-resolver",resolve:t=>s.value.resolveAssetUrl(r,t),preload:({signal:t})=>s.value.preloadForEditor(r,{signal:t})}],dispose:u}}catch(p){try{u()}catch(h){throw new AggregateError([p,h],"video host setup and cleanup failed.",{cause:p})}throw p}}})}function ZT(t){return t.startsWith("data:video/")||/\.(?:m4v|mov|mp4|ogv|webm)(?:[?#].*)?$/i.test(t)}function QT({toolIds:t,shortcutOverrides:e}){return kt([...t.map(eC),{id:"standard.history.undo",repeat:!0,shortcut:{key:"z",accelKey:!0},isEnabled:t=>rC(t)&&t.history.canUndoState.getSnapshot(),run:t=>{t.history.undo()}},{id:"standard.history.redo",repeat:!0,shortcut:{key:"z",accelKey:!0,shiftKey:!0},isEnabled:t=>rC(t)&&t.history.canRedoState.getSnapshot(),run:t=>{t.history.redo()}},{id:"standard.selection.select-all",shortcut:{key:"a",accelKey:!0},isEnabled:t=>t.shapes.getAll().length>0,run:t=>t.selection.selectAll()},{id:"standard.selection.duplicate",shortcut:{key:"d",accelKey:!0},isEnabled:t=>rC(t)&&oC(t),run:t=>{t.selection.duplicate()}},{id:"standard.selection.delete",shortcut:["Backspace","Delete"],isEnabled:t=>rC(t)&&oC(t),run:t=>t.selection.delete()},{id:"standard.layer.move-selection-backward",shortcut:{key:"ArrowDown",altKey:!0},isEnabled:t=>rC(t)&&iC(t).canMoveBackward,run:t=>{t.layers.move(t.selection.idsState.getSnapshot(),"backward")}},{id:"standard.layer.move-selection-forward",shortcut:{key:"ArrowUp",altKey:!0},isEnabled:t=>rC(t)&&iC(t).canMoveForward,run:t=>{t.layers.move(t.selection.idsState.getSnapshot(),"forward")}},{id:"standard.view.zoom-in",repeat:!0,shortcut:{key:"="},isEnabled:()=>!0,run:t=>t.viewport.zoomIn()},{id:"standard.view.zoom-out",repeat:!0,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 tC(t){return kt([{id:"standard.clipboard.copy",shortcut:{key:"c",accelKey:!0},isEnabled:oC,run:async t=>{await(vt(t).api(bt)?.copy())}},{id:"standard.clipboard.cut",shortcut:{key:"x",accelKey:!0},isEnabled:t=>rC(t)&&oC(t),run:async t=>{await(vt(t).api(bt)?.cut())}},{id:"standard.clipboard.paste",shortcut:{key:"v",accelKey:!0},isEnabled:t=>rC(t)&&(vt(t).api(bt)?.hasContent()??!1),run:async t=>{await(vt(t).api(bt)?.paste())}}],t)}function eC(t){return{id:`standard.tool.${t}`,shortcut:sC(t),isEnabled:e=>rC(e)||nC.has(t),run:e=>e.tools.setCurrent(t)}}var nC=new Set(["select","hand","laser"]);function rC(t){return!t.document.readonlyState.getSnapshot()}function oC(t){return t.selection.idsState.getSnapshot().length>0}function iC(t){return t.layers.getActionState(t.selection.idsState.getSnapshot())}function sC(t){const e=aC[t];return e?{key:e}:void 0}var aC={select:"v",hand:"h",rectangle:"r",ellipse:"o",rhombus:"d",triangle:"3",pentagon:"5",hexagon:"6",star:"8",draw:"p",eraser:"e",laser:"l",path:"b",text:"t",frame:"f"};function lC(t={}){const e=!1!==t.flow&&!1!==t.image&&!1!==t.text,n=Zf("object"==typeof t.text?t.text:{}),r=ck({onError:t.onError}),o=JT({onError:t.onError}),i=lg("object"==typeof t.text?t.text:{}),s=Qw({text:!1===t.text?void 0:n}),a=Mm({..."object"==typeof t.flow?t.flow:{},image:pv,text:n}),l=["select","hand",...!1===t.geo?[]:Tm,...!1===t.draw?[]:["draw"],...!1===t.eraser?[]:["eraser"],...!1===t.laser?[]:["laser"],...!1===t.path?[]:["path"],...!1===t.text?[]:["text"],...!1===t.frame?[]:["frame"]];return{text:n,geo:s,flow:a,imageHost:r,videoHost:o,textHost:i,plugins:[...!1===t.geo?[]:[s],...!1===t.draw?[]:[Lr],...!1===t.eraser?[]:[Do],...!1===t.laser?[]:[iS],...!1===t.path?[]:[PM],...!1===t.html?[]:[Ix],...!1===t.image?[]:[pv],...!1===t.video?[]:[wT],...!1===t.text?[]:[n],...e?[a]:[],...!1===t.frame?[]:[di],...!1===t.group?[]:[cx]],hostModules:[...!1===t.image?[]:[r],...!1===t.video?[]:[o],...!1===t.text?[]:[i],bt,qM()],hostActions:tC(cC(t.shortcutOverrides,"standard.clipboard.")),actions:QT({toolIds:l,shortcutOverrides:cC(t.shortcutOverrides,"standard.clipboard.",!1)})}}function cC(t,e,n=!0){return t&&Object.fromEntries(Object.entries(t).filter(([t])=>t.startsWith(e)===n))}export{Zm as ArrowLeftTool,Qm as ArrowRightTool,Xm as BurstTool,bx as DEFAULT_HTML_IFRAME_SANDBOX,db as DEFAULT_IMAGE_SMUDGE_BRUSH_COLOR,cb as DEFAULT_IMAGE_SMUDGE_BRUSH_SIZE,Gs as DEFAULT_TEXT_FONT,Lr as Draw,Sr as DrawShapeSvg,vr as DrawShapeSvgExporter,br as DrawShapeUtil,nr as DrawTool,Wm as EllipseTool,Do as Eraser,Vr as EraserTool,_i as FLOW_INPUT_PORT_ID,hg as FLOW_NODE_GAP_PAGE,ui as FLOW_NODE_SUB_TYPE,vm as FLOW_NODE_TITLE_RENDER_HEIGHT,qi as FLOW_OUTPUT_PORT_ID,mg as FlowConnectionError,Xg as FlowEdgeShapeHoverRenderer,Sm as FlowNodeSvgDecoration,di as Frame,Jo as FrameShapeSvgExporter,Uo as FrameShapeUtil,qo as FrameTool,Em as GEO_FILL_STYLES,Tm as GEO_SHAPE_KINDS,Cm as GEO_STROKE_STYLES,tx as Geo,Uw as GeoFillGradient,Kw as GeoFillPattern,Fw as GeoShapeSvgExporter,Pw as GeoShapeUtil,cx as Group,rx as GroupShapeSvgExporter,nx as GroupShapeUtil,Vs as HOST_TEXT_FONT,ux as HTML_INTERACTION_OPERATION_KIND,Gm as HexagonTool,Ix as Html,yx as HtmlShapeUtil,Cx as IMAGE_CROP_ASPECT_RATIO_PRESETS,pb as IMAGE_SMUDGE_BRUSH_SIZE_MAX,ub as IMAGE_SMUDGE_BRUSH_SIZE_MIN,pv as Image,zb as ImageShapeSvgExporter,Ob as ImageShapeUtil,iS as Laser,gk as LaserTool,jm as MessageCircleTool,aS as PATH_CONTROL_HANDLE_TYPE,fS as PATH_FILL_RULES,sS as PATH_NODE_HANDLE_TYPE,gS as PATH_NODE_KINDS,PM as Path,iM as PathShapeSvgExporter,UP as PathShapeUtil,nM as PathTool,qm as PentagonTool,Fm as RectangleTool,Ym as RhombusTool,Vm as StarTool,Km as SummaryLeftTool,Um as SummaryTool,na as TEXT_SIZE_PRESETS,Qf as Text,Uh as TextLinkPopoverPresenterProvider,Yh as TextSearchHighlightProvider,Jm as TrapezoidTool,_m as TriangleTool,oT as VIDEO_NAME_FALLBACK,iT as VIDEO_NAME_RENDER_HEIGHT,wT as Video,rT as VideoShapeUtil,Ib as cancelImageSmudgeSession,Mb as cancelImageSmudgeSessionIfActive,Tv as cleanupUnreferencedImageBlobs,LT as cleanupUnreferencedVideoBlobs,$b as cloneImageSmudgeStrokes,ns as commitFlowEdgeCreation,Pb as completeImageSmudgeSession,Gv as confirmImageSmudgeSession,qM as createCanvasExportHostModule,hs as createCanvasShapeLinkHref,Zs as createDefaultTextFontCatalog,Js as createDefaultTextPluginOptions,Pr as createDrawCanvasRenderContributions,kr as createDrawEditorContributions,eo as createEraserCanvasRenderContributions,Ho as createEraserEditorContributions,Ug as createFlowCanvasRenderContributions,Pi as createFlowEdgeBoundEndpoint,Pm as createFlowEditorContributions,fg as createFlowNodeFromPort,Mm as createFlowPlugin,oi as createFrameCanvasRenderContributions,Zo as createFrameEditorContributions,Xw as createGeoCanvasRenderContributions,Ww as createGeoEditorContributions,sw as createGeoGradientStops,Qw as createGeoPlugin,ix as createGroupCanvasRenderContributions,ox as createGroupEditorContributions,vx as createHtmlCanvasRenderContributions,xx as createHtmlEditorContributions,fx as createHtmlInteractionHandler,Sx as createHtmlPlugin,gx as createHtmlPluginApi,Zb as createImageCanvasRenderContributions,ob as createImageCropInteractionHandler,rb as createImageCropSelectionHandleInteractionHandler,_b as createImageEditorContributions,nk as createImageHostApi,ck as createImageHostModule,Cv as createImageObjectUrlStore,Db as createImageSmudgeInteractionHandler,wv as createImageStorageKey,ok as createImageSvgAssetInliner,xk as createLaserCanvasRenderContributions,oS as createLaserEditorContributions,Ev as createLocalImageAssetService,VT as createLocalVideoAssetService,YI as createPathCanvasRenderContributions,cS as createPathControlHandleId,sM as createPathEditorContributions,lS as createPathNodeHandleId,XM as createPngExportFormatProvider,xs as createRichTextFromPlainText,QT as createStandardCanvasActions,tC as createStandardCanvasHostActions,lC as createStandardCanvasKitProfile,KM as createSvgExportFormatProvider,Vh as createTextCanvasRenderContributions,qf as createTextEditorContributions,Qs as createTextFontCatalog,lg as createTextHostModule,Zf as createTextPlugin,fT as createVideoCanvasRenderContributions,lT as createVideoEditorContributions,qT as createVideoHostApi,JT as createVideoHostModule,RT as createVideoObjectUrlStore,ST as createVideoStorageKey,NT as decodeVideoMetadata,kv as deleteImageBlob,MT as deleteVideoBlob,Uv as downloadSelectedImageOriginal,YT as downloadSelectedVideoOriginal,UM as exportCanvasPng,jM as exportCanvasSvg,DM as exportEditorPng,TM as exportEditorSvg,_h as findRichTextSearchMatches,BT as fitVideoSize,Qn as flipDrawShapeInSelectionBounds,Cb as getActiveImageSmudgeSession,Sv as getAllImageBlobStorageKeys,TT as getAllVideoBlobStorageKeys,er as getDrawShapeDiagnostics,Vn as getDrawShapeParentPoints,Jn as getDrawShapeParentSegments,Dr as getEraserRuntime,Bv as getFirstImageFile,OT as getFirstVideoFile,es as getFlowEdgeCreationInvalidReason,Qi as getFlowEdgeTerminalBindings,Ri as getFlowEdgeVisualPortPoint,gi as getFlowNodeDisplayTitle,km as getFlowNodeRenderBounds,wx as getHtmlDisplayTitle,Xx as getImageCropModeOperationKind,zx as getImageCropRectOrDefault,bb as getImageSmudgeModeOperationKind,pk as getLaserRuntime,Iv as getLocalImageAssetStorageKey,CT as getLocalVideoAssetStorageKey,bs as getPlainTextFromRichText,Mv as getReferencedImageStorageKeys,AT as getReferencedVideoStorageKeys,Pv as getRemoteImageAssetUrl,ET as getRemoteVideoAssetUrl,sT as getVideoDisplayName,aT as getVideoRenderBounds,Fv as insertImageIntoEditor,KT as insertPreparedVideoIntoEditor,UT as insertVideoIntoEditor,Or as interpolateDrawShapeRecords,us as isAllowedRichTextLinkHref,Cr as isDrawShapeRecord,ps as isExternalRichTextLinkHref,mi as isFlowEdgeBindingRecord,hi as isFlowEdgeShapeRecord,fi as isFlowNodeShape,$m as isGeoFillStyle,Bw as isGeoGradientStyle,Lm as isGeoShapeKind,Am as isGeoShapeRecord,Rm as isGeoStrokeStyle,dx as isHtmlShapeRecord,Qx as isImageAssetRecord,tb as isImageShapeRecord,vb as isImageSmudgeModeForShape,yS as isPathFillRule,wS as isPathNodeKind,mS as isPathShapeRecord,Ks as isTextShapeRecord,QM as isVideoAssetRecord,zT as isVideoBlob,tT as isVideoShapeRecord,ds as normalizeRichTextLinkHref,tg as openBrowserRichTextLink,gs as openRichTextLink,fs as parseCanvasShapeLinkHref,dS as parsePathHandle,$T as prepareVideoAssetInput,MM as readBlobAsDataUrl,bv as readImageBlob,vv as readImageBlobAsDataUrl,PT as readVideoBlob,Ab as redoImageSmudgeStroke,Lb as registerImageSmudgeConfirmHandler,jv as replaceSelectedImageFromFile,XT as replaceSelectedVideoFromFile,Rb as requestImageSmudgeConfirm,Hw as resolveGeoFillPaint,pw as sampleGeoGradientColor,Sb as startImageSmudgeSession,hx as startInteractingWithHtmlShape,Eb as undoImageSmudgeStroke,pg as unwrapFlowNode,Tb as updateImageSmudgeBrush,qs as updateTextShapeRichText,Ss as validateRichTextDocument,ug as wrapShapeAsFlowNode,xv as writeImageBlob,IT as writeVideoBlob};
|
|
2
|
+
import{BindingUtil as t,Box as e,CanvasMedia as n,DEFAULT_DOCUMENT_ID as r,MIN_SHAPE_SIZE as o,Mat as s,SELECTION_RESIZE_ASPECT_RATIO_LOCKED_ONLY_MODES as i,SELECTION_RESIZE_CORNER_HANDLE_IDS as a,SELECTION_RESIZE_FREE_ONLY_MODES as l,SHAPE_HOVER_STROKE as d,ShapeHeadingControl as c,ShapeHoverRect as u,ShapeUtil as p,StateNode as h,Vec as f,areShapeColorsEqual as g,clampShapeSize as m,compareStrings as y,createCanvasReadable as w,createCustomShapeColor as x,createShapeHeadingDomEventGuard as b,createThemeShapeColor as k,defineCanvasPlugin as v,distanceBetweenSegments as S,getAnchoredSelectionResizeLocalBounds as I,getEdgeScrollDelta as P,getLocalDimensionsFromSelectionResize as M,getResolvedShapeTerminalBindingPort as T,getResolvedShapeTerminalBindingPorts as C,getSelectionResizeDimensionsFromLocal as E,getShapeHeadingMaxPointHitTestBounds as A,getShapeHeadingPositionedHitBounds as L,getShapeLocalToParentTransform as $,getShapeTransformFieldsFromMatrix as R,isAssetRecord as N,isBindingRecord as O,isShapeColor as B,isShapeRecord as z,isTransparentShapeColor as H,mirrorSelectionLocalPoint as D,normalizeShapeColor as _,observeValue as j,reparentShapeToContainingParent as F,resolveShapeColor as W,segmentsIntersect as U,selectionLocalPointToPagePoint as K,selectionPagePointToLocalPoint as X,shapeColorToCssColor as Y,useEditor as q,useValue as G}from"@yuzhouu/canvas-kit/plugin";import{Fragment as V,jsx as J,jsxs as Z}from"react/jsx-runtime";import{createContext as Q,createElement as tt,forwardRef as et,memo as nt,useCallback as rt,useContext as ot,useEffect as st,useId as it,useLayoutEffect as at,useMemo as lt,useRef as dt,useState as ct,useSyncExternalStore as ut}from"react";import{EditorContent as pt,useEditor as ht}from"@tiptap/react";import{Extension as ft,Mark as gt,Node as mt,callOrReturn as yt,canInsertNode as wt,combineTransactionSteps as xt,createStyleTag as bt,findChildrenInRange as kt,getAttributes as vt,getChangedRanges as St,getExtensionField as It,getMarksBetween as Pt,getNodeAtPosition as Mt,getNodeType as Tt,getRenderedAttributes as Ct,getStyleProperty as Et,isAtEndOfNode as At,isAtStartOfNode as Lt,isNodeActive as $t,isNodeEmpty as Rt,isNodeSelection as Nt,markInputRule as Ot,markPasteRule as Bt,mergeAttributes as zt,nodeInputRule as Ht,parseIndentedBlocks as Dt,renderNestedMarkdownContent as _t,textblockTypeInputRule as jt,wrappingInputRule as Ft}from"@tiptap/core";import{jsx as Wt}from"@tiptap/core/jsx-runtime";import{NodeSelection as Ut,Plugin as Kt,PluginKey as Xt,Selection as Yt,TextSelection as qt}from"@tiptap/pm/state";import{Decoration as Gt,DecorationSet as Vt}from"@tiptap/pm/view";import{Fragment as Jt}from"@tiptap/pm/model";import{dropCursor as Zt}from"@tiptap/pm/dropcursor";import{gapCursor as Qt}from"@tiptap/pm/gapcursor";import{history as te,redo as ee,undo as ne}from"@tiptap/pm/history";import{createCanvasMediaPresenter as re,defineCanvasHostModule as oe,waitForEditorIdle as se}from"@yuzhouu/canvas-host/module";import ie from"polygon-clipping";import{DefaultClipboardHostModule as ae}from"@yuzhouu/canvas-host/clipboard";import{getCanvasHost as le}from"@yuzhouu/canvas-host";import{applyCanvasActionShortcutOverrides as de}from"@yuzhouu/canvas-kit";export*from"@yuzhouu/canvas-host/clipboard";function ce(t){return Number.isInteger(t)?`${t}`:`${Number(t.toFixed(2))}`}function ue(t,e,n){return Math.max(e,Math.min(n,t))}function pe(t){return t?640:480}function he(t,e){return t.x===e.x&&t.y===e.y&&t.pressure===e.pressure&&t.segment===e.segment}function fe(t){return new f(t.x,t.y)}function ge(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 me(t){const e=[];for(const n of t)e.push(...n.points.map(ge));return e}function ye(t){return[{points:t.map(ge)}]}function we(t){if(void 0!==t&&Number.isFinite(t))return ue(t,0,1)}function xe(t,e,n,r,o={}){const s=ge(e),i=t[t.length-1];if(!i)return t.push(s),{anchorPoint:ge(s),hasProvisionalPoint:!1};if(he(i,s))return o.force&&r.hasProvisionalPoint?{anchorPoint:ge(s),hasProvisionalPoint:!1}:r;if(he(r.anchorPoint,s))return r.hasProvisionalPoint&&t.pop(),{anchorPoint:ge(r.anchorPoint),hasProvisionalPoint:!1};const a=function(t,e){if(t<=e.softMaxPointCount)return e.minPointDistance;const n=ue((t-e.softMaxPointCount)/Math.max(e.hardMaxPointCount-e.softMaxPointCount,1),0,1);return e.minPointDistance*(1+n*e.maxDistanceMultiplier)}(t.length,n),l=s.x-r.anchorPoint.x,d=s.y-r.anchorPoint.y,c=Math.abs((s.pressure??0)-(r.anchorPoint.pressure??0)),u=!0===o.force||l*l+d*d>=a*a||c>=n.pressureDeltaThreshold;return r.hasProvisionalPoint?t[t.length-1]=s:t.push(s),u?{anchorPoint:ge(s),hasProvisionalPoint:!1}:{anchorPoint:ge(r.anchorPoint),hasProvisionalPoint:!0}}function be(t,e){const n=Math.max(2,Math.floor(e));if(t.length<=n)return t.map(ge);const r=function(t,e){let n=ke(t,!0);n.length<e&&(n=ke(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(ge)}function ke(t,e){const n=[];for(let r=1;r<t.length-1;r+=1){if(e&&ve(t,r))continue;const o=t[r],s=t[r-1],i=t[r+1];o&&s&&i&&n.push({index:r,score:Se(o,s,i)})}return n.sort((t,e)=>t.score-e.score||t.index-e.index),n}function ve(t,e){return"straight"===t[e]?.segment||"straight"===t[e+1]?.segment}function Se(t,e,n){const r=function(t,e,n){const r=n.x-e.x,o=n.y-e.y,s=r*r+o*o;if(0===s){const n=t.x-e.x,r=t.y-e.y;return n*n+r*r}const i=ue(((t.x-e.x)*r+(t.y-e.y)*o)/s,0,1),a=e.x+r*i,l=e.y+o*i,d=t.x-a,c=t.y-l;return d*d+c*c}(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 Ie(t){if(0===t.length)return null;if(1===t.length){const e=t[0];return`M ${ce(e.x)} ${ce(e.y)}`}if(2===t.length){const e=t[0],n=t[1];return[`M ${ce(e.x)} ${ce(e.y)}`,`L ${ce(n.x)} ${ce(n.y)}`].join(" ")}const e=[],n=t[0];e.push(`M ${ce(n.x)} ${ce(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 ${ce(n.x)} ${ce(n.y)}`);continue}const o=t[r+1];if(!o||"straight"===o.segment){if(Pe(t,r)){const o=t[r-1];e.push(`Q ${ce(o.x)} ${ce(o.y)} ${ce(n.x)} ${ce(n.y)}`)}else e.push(`L ${ce(n.x)} ${ce(n.y)}`);continue}const s=f.Med(fe(n),fe(o));e.push(`Q ${ce(n.x)} ${ce(n.y)} ${ce(s.x)} ${ce(s.y)}`)}return e.join(" ")}function Pe(t,e){return e>=2&&"straight"!==t[e-1]?.segment&&"straight"!==t[e-2]?.segment}function Me(t){if(t.length<3)return function(t){if(0===t.length)return null;const[e,...n]=t;return e?[`M ${ce(e.x)} ${ce(e.y)}`,...n.map(t=>`L ${ce(t.x)} ${ce(t.y)}`),"Z"].join(" "):null}(t);const e=t[0],n=t[t.length-1];if(!e||!n)return null;const r=f.Med(n,e),o=[`M ${ce(r.x)} ${ce(r.y)}`];for(let s=0;s<t.length;s+=1){const e=t[s],n=t[(s+1)%t.length];if(!e||!n)continue;const r=f.Med(e,n);o.push(`Q ${ce(e.x)} ${ce(e.y)} ${ce(r.x)} ${ce(r.y)}`)}return o.push("Z"),o.join(" ")}function Te(t){return t.map(ge)}function Ce(t){return t.map(Ee)}function Ee(t){return function(t){return{points:t.points.map(ge)}}(t)}function Ae(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 Le(t,e,n){return t.map(t=>({points:Ae(t.points,e,n)}))}function $e(t,e){return t.map((t,n)=>({points:t.points.map((t,r)=>{const o=e(fe(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 Re(t,e,n){const r=0===e.w?1:e.w,o=0===e.h?1:e.h,s=0===n.w?1:n.w,i=0===n.h?1:n.h;return t.map(t=>({x:n.minX+(t.x-e.minX)/r*s,y:n.minY+(t.y-e.minY)/o*i,...void 0===t.pressure?null:{pressure:t.pressure},...void 0===t.segment?null:{segment:t.segment}}))}function Ne(t,e,n){return t.map(t=>({points:Re(t.points,e,n)}))}function Oe(t){return{rotation:t.selectionRotation,rotationCenter:t.selectionRotationCenter}}function Be(t,e){const n=Oe(e);return $e(t,t=>X(t,n))}function ze(t,e){const n=Oe(e);return $e(t,t=>K(t,n))}function He(t,e){return $e(t,t=>D({axis:e.axis,bounds:e.selectionMirrorBounds,point:t}))}var{PI:De}=Math,_e=De+1e-4,je=[1,1];function Fe(t,e,n,r=t=>t){return t*r(.5-e*(.5-n))}var{min:We}=Math;function Ue(t,e,n){let r=We(1,e/n);return We(1,t+(We(1,1-r)-t)*(.275*r))}function Ke(t,e){return[t[0]+e[0],t[1]+e[1]]}function Xe(t,e,n){return t[0]=e[0]+n[0],t[1]=e[1]+n[1],t}function Ye(t,e){return[t[0]-e[0],t[1]-e[1]]}function qe(t,e,n){return t[0]=e[0]-n[0],t[1]=e[1]-n[1],t}function Ge(t,e){return[t[0]*e,t[1]*e]}function Ve(t,e,n){return t[0]=e[0]*n,t[1]=e[1]*n,t}function Je(t){return[t[1],-t[0]]}function Ze(t,e){let n=e[0];return t[0]=e[1],t[1]=-n,t}function Qe(t,e){return t[0]*e[0]+t[1]*e[1]}function tn(t,e){return t[0]===e[0]&&t[1]===e[1]}function en(t,e){let n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function nn(t){return function(t,e){return[t[0]/e,t[1]/e]}(t,function(t){return Math.hypot(t[0],t[1])}(t))}function rn(t,e){return Math.hypot(t[1]-e[1],t[0]-e[0])}function on(t,e,n){let r=Math.sin(n),o=Math.cos(n),s=t[0]-e[0],i=t[1]-e[1],a=s*r+i*o;return[s*o-i*r+e[0],a+e[1]]}function sn(t,e,n,r){let o=Math.sin(r),s=Math.cos(r),i=e[0]-n[0],a=e[1]-n[1],l=i*s-a*o,d=i*o+a*s;return t[0]=l+n[0],t[1]=d+n[1],t}function an(t,e,n){return Ke(t,Ge(Ye(e,t),n))}function ln(t,e,n,r){let o=n[0]-e[0],s=n[1]-e[1];return t[0]=e[0]+o*r,t[1]=e[1]+s*r,t}function dn(t,e,n){return Ke(t,Ge(e,n))}var cn=[0,0],un=[0,0],pn=[0,0];function hn(t,e){let n=dn(t,nn(Je(Ye(t,Ke(t,[1,1])))),-e),r=[],o=1/13;for(let s=o;s<=1;s+=o)r.push(on(n,t,2*_e*s));return r}function fn(t,e,n){let r=[],o=1/n;for(let s=o;s<=1;s+=o)r.push(on(e,t,_e*s));return r}function gn(t,e,n){let r=Ye(e,n),o=Ge(r,.5),s=Ge(r,.51);return[Ye(t,o),Ye(t,s),Ke(t,s),Ke(t,o)]}function mn(t,e,n,r){let o=[],s=dn(t,e,n),i=1/r;for(let a=i;a<1;a+=i)o.push(on(s,t,3*_e*a));return o}function yn(t,e,n){return[Ke(t,Ge(e,n)),Ke(t,Ge(e,.99*n)),Ye(t,Ge(e,.99*n)),Ye(t,Ge(e,n))]}function wn(t,e,n){return!1===t||void 0===t?0:!0===t?Math.max(e,n):t}function xn(t,e={}){let{size:n=16,smoothing:r=.5,thinning:o=.5,simulatePressure:s=!0,easing:i=t=>t,start:a={},end:l={},last:d=!1}=e,{cap:c=!0,easing:u=t=>t*(2-t)}=a,{cap:p=!0,easing:h=t=>--t*t*t+1}=l;if(0===t.length||n<=0)return[];let f,g=t[t.length-1].runningLength,m=wn(a.taper,n,g),y=wn(l.taper,n,g),w=(n*r)**2,x=[],b=[],k=function(t,e,n){return t.slice(0,10).reduce((t,r)=>{let o=r.pressure;return e&&(o=Ue(t,r.distance,n)),(t+o)/2},t[0].pressure)}(t,s,n),v=Fe(n,o,t[t.length-1].pressure,i),S=t[0].vector,I=t[0].point,P=I,M=I,T=P,C=!1;for(let R=0;R<t.length;R++){let{pressure:e}=t[R],{point:r,vector:a,distance:l,runningLength:d}=t[R],c=R===t.length-1;if(!c&&g-d<3)continue;o?(s&&(e=Ue(k,l,n)),v=Fe(n,o,e,i)):v=n/2,void 0===f&&(f=v);let p=d<m?u(d/m):1,E=g-d<y?h((g-d)/y):1;v=Math.max(.01,v*Math.min(p,E));let A=(c?t[R]:t[R+1]).vector,L=c?1:Qe(a,A),$=null!==L&&L<0;if(Qe(a,S)<0&&!C||$){Ze(cn,S),Ve(cn,cn,v);for(let t=0;t<=1;t+=.07692307692307693)qe(un,r,cn),sn(un,un,r,_e*t),M=[un[0],un[1]],x.push(M),Xe(pn,r,cn),sn(pn,pn,r,_e*-t),T=[pn[0],pn[1]],b.push(T);I=M,P=T,$&&(C=!0)}else C=!1,c?(Ze(cn,a),Ve(cn,cn,v),x.push(Ye(r,cn)),b.push(Ke(r,cn))):(ln(cn,A,a,L),Ze(cn,cn),Ve(cn,cn,v),qe(un,r,cn),M=[un[0],un[1]],(R<=1||en(I,M)>w)&&(x.push(M),I=M),Xe(pn,r,cn),T=[pn[0],pn[1]],(R<=1||en(P,T)>w)&&(b.push(T),P=T),k=e,S=a)}let E=[t[0].point[0],t[0].point[1]],A=t.length>1?[t[t.length-1].point[0],t[t.length-1].point[1]]:Ke(t[0].point,[1,1]),L=[],$=[];if(1===t.length){if(!m&&!y||d)return hn(E,f||v)}else{m||y&&1===t.length||(c?L.push(...fn(E,b[0],13)):L.push(...gn(E,x[0],b[0])));let e=Je(function(t){return[-t[0],-t[1]]}(t[t.length-1].vector));y||m&&1===t.length?$.push(A):p?$.push(...mn(A,e,v,29)):$.push(...yn(A,e,v))}return x.concat($,b.reverse(),L)}var bn=[0,0];function kn(t){return null!=t&&t>=0}function vn(t,e={}){return xn(function(t,e={}){let{streamline:n=.5,size:r=16,last:o=!1}=e;if(0===t.length)return[];let s=.15+.85*(1-n),i=Array.isArray(t[0])?t:t.map(({x:t,y:e,pressure:n=.5})=>[t,e,n]);if(2===i.length){let t=i[1];i=i.slice(0,-1);for(let e=1;e<5;e++)i.push(an(i[0],t,e/4))}1===i.length&&(i=[...i,[...Ke(i[0],je),...i[0].slice(2)]]);let a=[{point:[i[0][0],i[0][1]],pressure:kn(i[0][2])?i[0][2]:.25,vector:[...je],distance:0,runningLength:0}],l=!1,d=0,c=a[0],u=i.length-1;for(let p=1;p<i.length;p++){let t=o&&p===u?[i[p][0],i[p][1]]:an(c.point,i[p],s);if(tn(c.point,t))continue;let e=rn(t,c.point);if(d+=e,p<u&&!l){if(d<r)continue;l=!0}qe(bn,c.point,t),c={point:t,pressure:kn(i[p][2])?i[p][2]:.5,vector:nn(bn),distance:e,runningLength:d},a.push(c)}return a[0].vector=a[1]?.vector||[0,0],a}(t,e),e)}var Sn=new WeakMap;function In(t){return{...t}}function Pn(t,e,n){return t.map(t=>new f(t.x+e,t.y+n))}function Mn(t,e,n){return t.map(t=>Pn(t,e,n))}function Tn({segments:t,outlineVertices:n,outlinePolygons:r,strokeWidth:o,sampling:s,isClosed:i}){const a=me(t),l=a.map(fe),d=l.length>0?e.FromPoints(l):new e(0,0,1,1),c=i||0===n.length?d.expand(Math.max(o/2,1)):e.FromPoints([...n]),u=i&&a.length>=3?function(t){if(t.length<3)return null;const e=Ie(t);return e?`${e} Z`:null}(a):null,p=void 0!==r?function(t){const e=t.map(t=>Me(t)).filter(t=>null!==t);return e.length>0?e.join(" "):null}(r):Me(n);return{normalizedSegments:Ce(t),normalizedPoints:Te(a),pointBounds:d,path:p,selectionPath:u??Ie(a),fillPath:u,localBounds:c,renderBounds:c.clone(),outlineVertices:n.map(t=>t.clone()),outlinePolygons:r?r.map(t=>t.map(t=>t.clone())):[n.map(t=>t.clone())],sampling:In(s)}}function Cn(t,e,n,r){const o=function({strokeWidth:t,isPen:e}){return[t,e?"pen":"pointer"].join(":")}({strokeWidth:n,isPen:r}),s=Sn.get(t),i=s?.get(o);if(i)return{normalizedSegment:Ee(i.normalizedSegment),sampling:In(i.sampling)};const a=function(t,e){if(t.length<=1)return{points:t.map(ge),rawPointCount:t.length,sampledPointCount:t.length,maxPointCount:e.maxPointCount,reduced:!1,capped:!1};const n=[ge(t[0])];for(let s=1;s<t.length;s+=1){const e=t[s];if(!e)continue;const r=we(e.pressure),o={x:e.x,y:e.y,...void 0===r?null:{pressure:r},...void 0===e.segment?null:{segment:e.segment}},i=n[n.length-1];i&&he(i,o)||n.push(o)}const r=n.length>e.maxPointCount,o=be(n,e.maxPointCount);return{points:o,rawPointCount:t.length,sampledPointCount:o.length,maxPointCount:e.maxPointCount,reduced:o.length<t.length,capped:r}}(t.points,e),l={normalizedSegment:{points:Te(a.points)},sampling:{rawPointCount:a.rawPointCount,sampledPointCount:a.sampledPointCount,sampledPointLimit:a.maxPointCount,reduced:a.reduced,capped:a.capped}},d=s??new Map;return d.set(o,{normalizedSegment:Ee(l.normalizedSegment),sampling:In(l.sampling)}),s||Sn.set(t,d),l}function En(t,e,n=!1,r=!1,{brush:o="pencil"}={}){const s=function(t){return{maxPointCount:pe(t)}}(n),i=[],a=[],l=t.filter(t=>t.points.length>0);for(let h=0;h<l.length;h+=1){const t=Cn(l[h],s,e,n);i.push(Ee(t.normalizedSegment)),a.push(In(t.sampling))}const d=function({points:t,strokeWidth:e,isPen:n,isClosed:r,constantWidth:o}){const s=r&&t.length>2?[...t,t[0]]:t,i=s.filter((t,e)=>{const n=s[e-1];return!n||t.x!==n.x||t.y!==n.y||t.pressure!==n.pressure||t.segment!==n.segment}),a=[],l=(t,{straight:s=!1}={})=>{const i=vn(t.map(({x:t,y:e,pressure:n})=>[t,e,n??.5]),{size:e,thinning:n&&!o?.4:0,simulatePressure:!1,streamline:s||r?0:.5,last:!0}).map(([t,e])=>new f(t,e));i.length>0&&a.push(i)};let d=[];for(const c of i){const t=d[d.length-1];"straight"===c.segment&&t?(d.length>1&&l(d),l([t,c],{straight:!0}),d=[c]):d.push(c)}return(d.length>1||0===a.length)&&l(d),a}({points:me(i),strokeWidth:e,isPen:n,isClosed:r,constantWidth:"highlighter"===o||r}),c=(u=a,p=s.maxPointCount,{rawPointCount:u.reduce((t,e)=>t+e.rawPointCount,0),sampledPointCount:u.reduce((t,e)=>t+e.sampledPointCount,0),sampledPointLimit:p,reduced:u.some(t=>t.reduced),capped:u.some(t=>t.capped)});var u,p;return Tn({segments:i,outlineVertices:d.flat(),outlinePolygons:d,strokeWidth:e,sampling:c,isClosed:r})}var An=new WeakMap,Ln=new WeakMap;function $n(t){return t.segments}function Rn(t,n,r){return function(t,n){const r=Math.max(0,t.w-n.left-n.right),o=Math.max(0,t.h-n.top-n.bottom);return new e(t.x+n.left,t.y+n.top,r,o)}(r,{left:t.minX-n.minX,right:n.maxX-t.maxX,top:t.minY-n.minY,bottom:n.maxY-t.maxY})}function Nn(t){const e=t,n=An.get(e);if(n)return n;const r=En($n(t.props),t.props.strokeWidth,t.props.isPen??!1,t.props.isClosed,{brush:t.props.brush});return An.set(e,r),r}function On(t,e,n=!1,r=!1,o={}){const s=En(t,e,n,r,o),i=s.pointBounds,a=En($e(s.normalizedSegments,t=>new f(t.x-i.x,t.y-i.y)),e,n,r,o);return{x:i.x,y:i.y,segments:a.normalizedSegments,pointBounds:a.pointBounds,localBounds:a.localBounds,renderBounds:a.renderBounds,path:a.path,selectionPath:a.selectionPath,fillPath:a.fillPath,outlineVertices:a.outlineVertices,outlinePolygons:a.outlinePolygons,sampling:a.sampling}}function Bn(t,e,n=!1,r=!1,o={}){return function(t,e,n=!1,r=!1,o={}){return On(ye(t),e,n,r,o)}(t,e,n,r,o)}function zn(t,e,n=!1,r=!1,o={}){return On(t,e,n,r,o)}function Hn(t){const e=t,n=Ln.get(e);if(n)return n;const r=function(t,e,n,r,o){return Tn({segments:Le(t.normalizedSegments,n,r),outlineVertices:Pn(t.outlineVertices,n,r),outlinePolygons:Mn(t.outlinePolygons,n,r),strokeWidth:e,sampling:t.sampling,isClosed:o})}(Nn(t),t.props.strokeWidth,t.x,t.y,t.props.isClosed);return Ln.set(e,r),r}function Dn(t){return me(_n(t))}function _n(t){const e=function(t,e){return new f(t.x+e.localBounds.center.x,t.y+e.localBounds.center.y)}(t,Nn(t));return $e(function(t){return Le($n(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 f(r.x*t.scaleX,r.y*t.scaleY);return n.add(o.rot(t.rotation))}(t,n,e))}function jn(t,e){let n=function({segments:t,strokeWidth:e,isPen:n,isClosed:r,brush:o,targetSelectionStrokeBounds:s}){let i=Ce(t);for(let a=0;a<2;a+=1){const t=En(i,e,n,r,{brush:o}),a=Rn(t.pointBounds,t.localBounds,s);i=Ne(i,t.pointBounds,a)}return i}({segments:Be(_n(t),e),strokeWidth:t.props.strokeWidth,isPen:t.props.isPen??!1,isClosed:t.props.isClosed,brush:t.props.brush,targetSelectionStrokeBounds:e.targetSelectionStrokeBounds});return e.scaleX<0&&(n=He(n,{axis:"horizontal",selectionMirrorBounds:e.targetSelectionStrokeBounds,selectionRotation:e.selectionRotation,selectionRotationCenter:e.selectionRotationCenter})),e.scaleY<0&&(n=He(n,{axis:"vertical",selectionMirrorBounds:e.targetSelectionStrokeBounds,selectionRotation:e.selectionRotation,selectionRotationCenter:e.selectionRotationCenter})),zn(ze(n,e),t.props.strokeWidth,t.props.isPen??!1,t.props.isClosed,{brush:t.props.brush})}function Fn(t,e){return zn(ze(He(Be(_n(t),e),e),e),t.props.strokeWidth,t.props.isPen??!1,t.props.isClosed,{brush:t.props.brush})}function Wn(t){return Ce(t)}function Un(t){const e=Nn(t);return{...e.sampling,hasPath:null!==e.path,hasSelectionPath:null!==e.selectionPath,outlineVertexCount:e.outlineVertices.length}}var Kn=class extends h{constructor(t){super(t,"draw"),this.initial="idle",this.addChild(new Xn(t,this)),this.addChild(new Yn(t,this))}getDefaultProps(){return this.editor.shapes.getDefaultProps("draw")}},Xn=class extends h{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=r;let o=null,s=1/0,i=-1;const a=t.state.$_shapeIds.get();for(let r=0;r<a.length;r+=1){const n=t.store.get(a[r]);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.geometry.isPagePointInClip(n.id,e))continue;const d=l.getChildClipLocalBounds(n)??l.getLocalBounds(n),c=t.shapes.geometry.computeLocalToPageTransform(n).invert().applyToPoint(e);if(!d.containsPoint(c))continue;const u=t.shapes.geometry.computePageBounds(n),p=u.w*u.h;(!o||p<s||p===s&&r>i)&&(o=n,s=p,i=r)}return o?.id??n}(this.editor,t.pagePoint),o=n.startsWith("shape:")?this.editor.store.get(n):null,i=o?this.editor.shapes.geometry.computeLocalToPageTransform(o).invert():s.Identity(),a=i.applyToPoint(t.pagePoint),l=qn(a,a,t.pressure,"pen"===t.pointerType);var d,c;this.transition("drawing",{originPagePoint:t.pagePoint.clone(),originScreenPoint:t.screenPoint.clone(),originParentPoint:a,pageToParent:i,parentId:n,shapeId:null,brush:e.brush,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,isClosed:e.isClosed,isPen:"pen"===t.pointerType,pointGuard:(d=e.strokeWidth,c="pen"===t.pointerType,c?{minPointDistance:Math.max(.12,Math.min(.35,.04*d)),pressureDeltaThreshold:.035,softMaxPointCount:1600,hardMaxPointCount:3200,maxDistanceMultiplier:2.5}:{minPointDistance:Math.max(.2,Math.min(.5,.06*d)),pressureDeltaThreshold:.08,softMaxPointCount:900,hardMaxPointCount:2200,maxDistanceMultiplier:6}),pointGuardState:{anchorPoint:Gn(l),hasProvisionalPoint:!1},lastPressure:t.pressure,straightSegmentAnchorPoint:null,preserveStraightEndpointOnNextFreePoint:!1,segments:[{points:[l]}]})}},Yn=class extends h{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.selection.set([],{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:")||F(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;e||(this.info.lastPressure=t.pressure);const n=qn(this.info.pageToParent.applyToPoint(t.pagePoint),this.info.originParentPoint,this.info.lastPressure,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.shapes.update([{id:this.info.shapeId,props:Zn(this.info.segments)}],{source:"user"})}createShape(){const t=this.tool.getDefaultProps(),e=function(t,e){return e&&t.layers.canReceiveChildren(e)?e:r}(this.editor,this.info?.parentId);this.info&&(this.info.parentId=e);const[n]=this.editor.shapes.create([{type:"draw",x:this.info?.originParentPoint.x??0,y:this.info?.originParentPoint.y??0,...e.startsWith("shape:")?{parentId:e}:{},props:{...t,brush:this.info?.brush??t.brush,stroke:this.info?.stroke??t.stroke,strokeWidth:this.info?.strokeWidth??t.strokeWidth,fill:this.info?.fill??t.fill,isClosed:this.info?.isClosed??t.isClosed,...Zn(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=Vn(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=Gn(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=Vn(this.info),n=e[e.length-1];return(!n||!function(t,e){return t.x===e.x&&t.y===e.y&&t.pressure===e.pressure&&t.segment===e.segment}(n,t))&&(this.replaceCurrentSegmentPoints([...e,Gn(t)]),this.resetPointGuard(t),!0)}appendGuardedCurrentPoint(t,e={}){if(!this.info)return;const n=Vn(this.info).map(Gn);this.info.pointGuardState=xe(n,t,this.info.pointGuard,this.info.pointGuardState,e),this.replaceCurrentSegmentPoints(n)}resetPointGuard(t){this.info&&(this.info.pointGuardState={anchorPoint:Gn(t),hasProvisionalPoint:!1})}replaceCurrentSegmentPoints(t){if(!this.info)return;const e=Jn(this.info.segments);this.info.segments=[...e.slice(0,-1),{points:t.map(Gn)}]}splitCurrentSegmentAtLimit(){if(!this.info)return;const t=pe(this.info.isPen);let e=Jn(this.info.segments),n=e[e.length-1];for(;n.points.length>t;){const r=n.points.slice(0,t).map(Gn),o=r[r.length-1],s=n.points.slice(t).map(Gn);if(!o||0===s.length)break;const i={points:[Gn(o),...s]};e=[...e.slice(0,-1),{points:r},i],n=i}this.info.segments=e}};function qn(t,e,n,r){return{x:t.x-e.x,y:t.y-e.y,...r?{pressure:n}:null}}function Gn(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 Vn(t){const e=Jn(t.segments),n=e[e.length-1];return n?n.points.map(Gn):[]}function Jn(t){return t.length>0?[...t]:[{points:[]}]}function Zn(t){return{segments:Wn(Jn(t))}}function Qn(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist(e);const s=Math.max(0,Math.min(1,((t.x-e.x)*r.x+(t.y-e.y)*r.y)/o)),i=new f(e.x+r.x*s,e.y+r.y*s);return t.dist(i)}function tr(t,e,n,r){return function(t,e,n,r){const o=e.sub(t),s=r.sub(n),i=o.x*s.y-o.y*s.x;if(Math.abs(i)<1e-8)return!1;const a=n.sub(t),l=(a.x*s.y-a.y*s.x)/i,d=(a.x*o.y-a.y*o.x)/i;return l>=0&&l<=1&&d>=0&&d<=1}(t,e,n,r)?0:Math.min(Qn(t,n,r),Qn(e,n,r),Qn(n,t,e),Qn(r,t,e))}function er(t,e){let n=0;for(let r=0,o=e.length-1;r<e.length;o=r,r+=1){const s=e[r],i=e[o];if(!s||!i)continue;const a=(s.x-i.x)*(t.y-i.y)-(t.x-i.x)*(s.y-i.y);i.y<=t.y?s.y>t.y&&a>0&&(n+=1):s.y<=t.y&&a<0&&(n-=1)}return 0!==n}function nr(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],s=e[(r+1)%e.length];o&&s&&(n=Math.min(n,Qn(t,o,s)))}return n}function rr(t,e,n,r){if(0===n.length)return!1;if(er(t,n)||er(e,n))return!0;for(let o=0;o<n.length;o+=1){const s=n[o],i=n[(o+1)%n.length];if(s&&i&&tr(t,e,s,i)<=r)return!0}return!1}function or(t,e,n,r={}){if(r.isClosed&&void 0!==r.fill&&!H(r.fill)&&t.normalizedPoints.length>=3&&er(n,t.normalizedPoints.map(fe)))return!0;if(r.isClosed&&function(t,e,n){if(0===e.length)return Number.POSITIVE_INFINITY;if(1===e.length)return t.dist(fe(e[0]));let r=Number.POSITIVE_INFINITY;for(let o=1;o<e.length;o+=1){const n=e[o-1],s=e[o];n&&s&&(r=Math.min(r,Qn(t,fe(n),fe(s))))}return n&&e.length>=3&&(r=Math.min(r,Qn(t,fe(e[e.length-1]),fe(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(er(n,o))return!0;if(nr(n,o)<=Math.max(4,.5*e))return!0}return!1}function sr(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function ir(t){if(!t||"object"!=typeof t)return null;const e=t,n=sr(e.x,NaN),r=sr(e.y,NaN);if(!Number.isFinite(n)||!Number.isFinite(r))return null;const o=sr(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 ar(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=ir(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 lr(t,e){if(!Array.isArray(t))return e;let n=!1;const r=[];for(const o of t){const t=ar(o);t?(n=n||t!==o,r.push(t)):n=!0}return 0===r.length?e:n?r:t}var dr=class extends p{type="draw";getDefaultProps(){return{brush:"pencil",segments:ye([{x:0,y:0},{x:24,y:12}]),stroke:k("stroke-slate"),strokeWidth:4,fill:x("transparent"),isClosed:!1,isPen:!1}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{segments:lr(e.segments,n.segments),brush:"highlighter"===e.brush?"highlighter":"pencil",stroke:_(e.stroke,n.stroke),strokeWidth:Math.max(4,sr(e.strokeWidth,n.strokeWidth)),fill:_(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 n=Nn(t);return new e(t.x+n.localBounds.x,t.y+n.localBounds.y,n.localBounds.w,n.localBounds.h)}getLocalBounds(t){return Nn(t).localBounds}getRenderBounds(t){return Nn(t).renderBounds}getExportBounds(t){return this.getRenderBounds(t)}canReceiveTerminalBinding(t){return!0}canUseTerminalBindingPortHandles(t){return!1}getSelectionResizeLocalBounds(t){return this.getLocalBounds(t)}resizeSelectionBounds(t,e){const n=jn(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:Wn(n.segments)}}}flipSelectionBounds(t,e){const n=Fn(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:Wn(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 f(t.minX,t.minY),n=new f(t.maxX,t.minY),r=new f(t.maxX,t.maxY),o=new f(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],s=n[(r+1)%n.length];if(o&&s&&U(t,e,o,s))return!0}return!1})}getPositionedOutlineVertices(t){return Hn(t).outlineVertices}hitTest(t,e){return or(Hn(t),t.props.strokeWidth,e,{fill:t.props.fill,isClosed:t.props.isClosed})}hitTestLineSegment(t,e){return function(t,e,n,r,o={}){const s=Math.max(4,.5*e,o.margin??0);return!!(o.isClosed&&void 0!==o.fill&&!H(o.fill)&&t.normalizedPoints.length>=3&&rr(n,r,t.normalizedPoints.map(fe),s))||0!==t.outlineVertices.length&&t.outlinePolygons.some(t=>rr(n,r,t,s))}(Hn(t),t.props.strokeWidth,e.positionedStart,e.positionedEnd,{fill:t.props.fill,isClosed:t.props.isClosed,margin:e.positionedMargin})}},cr=class{type="draw";toSvg(t,e){const n=Nn(t);if(!n.path&&!n.selectionPath)return null;const r=[];return n.fillPath&&!H(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",attrs:"highlighter"===t.props.brush?{opacity:.35}:void 0,children:r}}};function ur(){return{shapeUtils:[new dr],shapeSvgExporters:[new cr],tools:{draw:t=>new Kn(t)}}}function pr({shape:t,stroke:e=t.props.stroke,strokeWidth:n=t.props.strokeWidth}){const{fillPath:r,renderBounds:o,path:s,selectionPath:i}=Nn({props:{...t.props,strokeWidth:n}});if(!s&&!i)return null;const a=Y(e);
|
|
3
|
+
return J("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:Z("g",{opacity:"highlighter"===t.props.brush?.35:void 0,children:[r&&!H(t.props.fill)?J("path",{d:r,fill:Y(t.props.fill),stroke:"none"}):null,t.props.isClosed&&i?J("path",{d:i,fill:"none",stroke:a,strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round"}):s?J("path",{d:s,fill:a,stroke:"none"}):null]})})}function hr({shape:t,strokeWidth:e}){const{path:n,renderBounds:r,selectionPath:o}=Nn(t),s=o??n;return s?J("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:J("path",{d:s,fill:"none",stroke:d,strokeWidth:e,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:"non-scaling-stroke"})}):null}function fr(){return{shapeRenderers:[{type:"draw",component:gr,hoverComponent:mr}]}}function gr({shape:t}){
|
|
4
|
+
return J(pr,{shape:t})}function mr({shape:t,strokeWidth:e}){
|
|
5
|
+
return J(hr,{shape:t,strokeWidth:e})}function yr(t){return z(t)&&"draw"===t.type}function wr({editor:t}){return function({editor:t}){const e=()=>t.shapes.getDefaultProps("draw"),{brush:n,stroke:r,strokeWidth:o,fill:s,isClosed:i}=e(),a={pencil:{brush:n,stroke:r,strokeWidth:o,fill:s,isClosed:i},highlighter:{brush:"highlighter",stroke:x("#f8de0d"),strokeWidth:24,fill:x("transparent"),isClosed:!1}};return{getSelectionStyle(){const e=t.state.$_selectedShapes.get().filter(yr);return 0===e.length?null:{brush:xr(e.map(t=>t.props.brush)),fill:xr(e.map(t=>t.props.fill)),stroke:xr(e.map(t=>t.props.stroke)),strokeWidth:xr(e.map(t=>t.props.strokeWidth)),isClosed:xr(e.map(t=>t.props.isClosed))}},setSelectionStyle(e){const n=t.state.$_selectedShapes.get().filter(yr).filter(e=>!t.layers.isLocked(e.id)).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.shapes.update(n,{source:"user"}),n.map(({id:t})=>t)},toolDefaultsState:w(t.signalGraph.computed("Draw.toolDefaults",e)),getBrushDefaults(t){const n=e();return n.brush===t?n:a[t]},setToolDefaults(n){const r=e();if(n.brush&&n.brush!==r.brush){const{brush:e,stroke:o,strokeWidth:s,fill:i,isClosed:l}=r;a[e]={brush:e,stroke:o,strokeWidth:s,fill:i,isClosed:l},t.shapes.updateDefaultProps("draw",{...a[n.brush],...n})}else t.shapes.updateDefaultProps("draw",n);return e()}}}({editor:t})}function xr(t){const[e,...n]=t;return void 0!==e&&n.every(t=>t===e)?e:void 0}var br=v({id:"draw",editor:ur(),render:fr(),setup:({editor:t})=>({api:wr({editor:t})})});function kr(t,e,n){return Math.max(e,Math.min(n,t))}function vr(t,e,n){return t+(e-t)*n}function Sr(t,e,n){if(void 0!==t||void 0!==e)return vr(t??e??0,e??t??0,n)}function Ir(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:ge(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:fe(e).dist(fe(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:fe(e).dist(fe(r)),segmentWeight:1})}return n}(t,n),s=o.reduce((t,e)=>t+e.length,0);return 0===o.length||s<=1e-6?Array.from({length:r},()=>({point:ge(t[0]),segmentWeight:0})):Array.from({length:r},(t,e)=>{let i=n?e/r*s:e/Math.max(r-1,1)*s,a=o[o.length-1];for(const n of o){if(i<=n.length||n===a){a=n;break}i-=n.length}const l=a.length<=1e-6?0:kr(i/a.length,0,1),d=fe(a.start),c=fe(a.end),u=f.Lrp(d,c,l),p=Sr(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 Pr(t,e,n,r={}){if(t.parentId!==e.parentId)throw new Error("Cannot interpolate draw shapes with different parents");const o=kr(n,0,1),s=t.props.isClosed&&e.props.isClosed,i=Dn(t),a=Dn(e),l=(d=i.length,c=a.length,"number"==typeof(u=r.pointCount)&&Number.isFinite(u)?Math.max(2,Math.round(u)):Math.max(2,d,c,12));var d,c,u;const p=Ir(i,l,s),h=Ir(a,l,s),g=p.map((t,e)=>{const n=h[e]??h[h.length-1]??t,r=f.Lrp(fe(t.point),fe(n.point),o),s=Sr(t.point.pressure,n.point.pressure,o),i=vr(t.segmentWeight,n.segmentWeight,o);return{x:r.x,y:r.y,...void 0===s?null:{pressure:s},...e>0&&i>=.5?{segment:"straight"}:null}}),m=o<.5?t.props.isClosed:e.props.isClosed,y=o<.5?t.props.isPen??!1:e.props.isPen??!1,w=Math.max(1,vr(t.props.strokeWidth,e.props.strokeWidth,o)),x=Bn(g,w,y,m,{brush:(o<.5?t:e).props.brush}),b=o<.5?t:e;return{...b,id:t.id,x:x.x,y:x.y,rotation:0,scaleX:1,scaleY:1,opacity:vr(t.opacity,e.opacity,o),props:{...b.props,segments:Ce(x.segments),strokeWidth:w,isClosed:m,isPen:y}}}var Mr=new WeakMap;function Tr(t,e){if(t.length!==e.length)return!1;const n=new Set(e);return t.every(t=>n.has(t))}function Cr(t){const e=Mr.get(t);if(!e)throw new Error("EraserRuntime is not initialized for this editor.");return e}function Er(t){return 4/t.state.$_camera.get().z}function Ar(t,e,n,r){const o=[new f(e.minX,e.minY),new f(e.maxX,e.minY),new f(e.maxX,e.maxY),new f(e.minX,e.maxY)].map(t=>n.applyToPoint(t));let s=0,i=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 d=Math.sign(l);if(0===s)s=d;else if(d!==s)return!1;const c=n.len2(),u=0===c?0:Math.max(0,Math.min(1,(r.x*n.x+r.y*n.y)/c));i=Math.min(i,t.dist(e.add(n.mul(u))))}return i>r}function Lr(t,e){const n=new Set,r=Er(t);for(const o of t.shapes.hitTesting.allAtPoint(e,{hitTest:"bindingTarget"})){const s=t.shapes.getUtil(o);if(!s.canReceiveChildren(o))continue;const i=s.getChildClipLocalBounds(o);i&&(Ar(e,i,t.shapes.geometry.computeLocalToPageTransform(o),r)&&n.add(o.id))}return n}function $r(t,e,n){return n.protectedContainerIds.has(e.id)||t.layers.isLocked(e.id)||t.shapes.getUtil(e).canReceiveChildren(e)&&t.layers.hasLockedDescendant(e.id)?null:e.id}function Rr(t,e,n,r){const o=r.topMostOnly?n.slice(0,1):n;for(const s of o){const n=$r(t,s,e);n&&e.erasingShapeIds.add(n)}}function Nr(t,e,n){Rr(t,e,t.shapes.hitTesting.allAtPoint(n.pagePoint),{topMostOnly:n.accelKey})}function Or(t,e,n){Rr(t,e,t.shapes.hitTesting.lineSegment(e.previousPagePoint,n.pagePoint,{margin:Er(t)}),{topMostOnly:n.accelKey})}function Br(t,e){const n=t.trail[t.trail.length-1];n&&n.dist2(e)<=1e-6||t.trail.push(e.clone())}function zr(t,e){Cr(t).setPreview(Array.from(e.erasingShapeIds),e.trail)}function Hr(t){Cr(t).clear()}var Dr=class extends h{constructor(t){super(t,"eraser"),this.initial="idle",this.addChild(new _r(t,this)),this.addChild(new jr(t,this)),this.addChild(new Fr(t,this))}onExit(){Hr(this.editor)}},_r=class extends h{constructor(t,e){super(t,"idle",e)}onEnter(){Hr(this.editor)}onPointerDown(t){0===t.button&&this.transition("pointing",function(t,e){const n={originScreenPoint:e.screenPoint.clone(),previousPagePoint:e.pagePoint.clone(),protectedContainerIds:Lr(t,e.pagePoint),erasingShapeIds:new Set,trail:[e.pagePoint.clone()]};return Nr(t,n,e),zr(t,n),n}(this.editor,t))}},jr=class extends h{info=null;constructor(t,e){super(t,"pointing",e)}onEnter(t){this.info=t}onPointerMove(t){var e,n;this.info&&(e=this.info.originScreenPoint,n=t.screenPoint,e.dist2(n)>=9&&(Or(this.editor,this.info,t),Br(this.info,t.pagePoint),this.info.previousPagePoint=t.pagePoint.clone(),zr(this.editor,this.info),this.transition("erasing",this.info)))}onPointerUp(t){this.info&&(Nr(this.editor,this.info,t),zr(this.editor,this.info),Wr(this.editor,this.info)),this.transition("idle")}onCancel(){Hr(this.editor),this.transition("idle")}onExit(){this.info=null}},Fr=class extends h{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&&Wr(this.editor,this.info),this.transition("idle")}onCancel(){Hr(this.editor),this.transition("idle")}onExit(){this.info=null}update(t){this.info&&(Or(this.editor,this.info,t),Br(this.info,t.pagePoint),this.info.previousPagePoint=t.pagePoint.clone(),zr(this.editor,this.info))}};function Wr(t,e){const n=Array.from(e.erasingShapeIds);Hr(t),0!==n.length&&t.shapes.delete(n,{source:"user",preserveInteraction:!0})}function Ur(){return{canvasOverlays:[{id:"land.eraser.trail-overlay",component:Kr}],shapeOpacityModifiers:[{id:"land.eraser.preview-opacity",getOpacityValue(t,e){const n=Cr(t).$_erasingShapeIdSet;return{signalGraph:t.signalGraph,get:()=>t.layers.isOrAncestorInSet(e,n.get())?.32:1}}}]}}var Kr=nt(function(){return G(Cr(q()).$_trailActive)?J(Xr,{}):null}),Xr=nt(function(){const t=q(),e=G(Cr(t).$_trail),n=G(t.state.$_cameraZoom),r=Math.max(n,1e-4),o=function(){const[t,e]=ct(()=>so());return st(()=>{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}(),s=dt({samples:[],sourceLength:0}),i=Math.max(o,so());!function(t,e,n,r){ao(t,r),e.length<t.sourceLength&&(t.samples=[],t.sourceLength=0);if(e.length===t.sourceLength)return;const o=t.sourceLength,s=e.length-o,i=t.samples[t.samples.length-1]?.time??r-to*s;for(let a=o;a<e.length;a++){const l=e[a],d=(a-o+1)/s;io(t,{x:l.x,y:l.y},n,bo(i,r,d))}t.sourceLength=e.length,ao(t,r)}(s.current,e,r,i);const a=function(t,e){const n=lo(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(xo(r[r.length-1],t[o],n));return r}(n.length>qr?n.slice(-48):n,Jr)}(s.current.samples,i);if(0===a.length)return null;const l=(c=Vr/r,0===(d=a).length||c<=0?null:1===d.length?So(po(d[0],c/2,Qr))??"":So(function(t){if(0===t.length)return[];if(1===t.length)return po(t[0].point,Math.max(t[0].radius,.01),Qr);const e=[],n=[];for(const a of t){const t=go(a.direction);vo(e,yo(a.point,wo(t,a.radius))),vo(n,mo(a.point,wo(t,a.radius)))}const r=[];for(const a of e)vo(r,a);const o=t[t.length-1],s=go(o.direction),i=function({center:t,direction:e,normal:n,radius:r}){if(r<=0)return[];const o=[];for(let s=1;s<Zr;s++){const i=s/Zr;o.push(mo(t,mo(wo(e,Math.sin(Math.PI*i)*r),wo(n,-Math.cos(Math.PI*i)*r))))}return o}({center:o.point,direction:o.direction,normal:s,radius:o.radius});for(const a of i)vo(r,a);for(let a=n.length-1;a>=0;a--)vo(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]+ho(t[n-1],t[n]));return e}(t),r=n[n.length-1]??0,o=Math.max(e,r);return t.map((r,s)=>{const i=n[s]??0,a=ko(i/o,0,1);return{point:r,direction:uo(t,s),radius:e/2*a,runningLength:i}})}(d,c))));var d,c;return l?J("g",{"data-ui":"eraser-trail-overlay",children:J("path",{"data-ui":"eraser-trail-scribble",d:l,fill:Yr})}):null}),Yr="rgba(142, 142, 142, 0.16)",qr=48,Gr=1,Vr=12,Jr=.32,Zr=8,Qr=13,to=16,eo=8,no=180,ro=180,oo=680;function so(){return"undefined"==typeof performance?Date.now():performance.now()}function io(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 s=Gr/n,i=ho(o,e);if(i<s)return void(t.samples[t.samples.length-1]={...o,...e,time:r});const a=i*n/Math.max(eo,r-o.time);t.samples.push({...e,time:r,velocity:bo(o.velocity,a,.68)})}function ao(t,e){t.samples=lo(t.samples,e)}function lo(t,e){const n=t[t.length-1];if(!n)return[];const r=e-ko(no+n.velocity*ro,no,oo);if(n.time<r)return[];const o=t.findIndex(t=>t.time>=r);if(-1===o)return[];const s=t.slice(o),i=t[o-1],a=s[0];return i&&a.time>r?[co(i,a,ko((r-i.time)/(a.time-i.time),0,1)),...s]:s}function co(t,e,n){return{...xo(t,e,n),time:bo(t.time,e.time,n),velocity:bo(t.velocity,e.velocity,n)}}function uo(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?yo(r,t[e]):e===t.length-1?yo(t[e],n):yo(r,n))}function po(t,e,n){const r=[];for(let o=0;o<n;o++){const s=2*Math.PI*o/n;r.push({x:t.x+Math.cos(s)*e,y:t.y+Math.sin(s)*e})}return r}function ho(t,e){return Math.sqrt(fo(t,e))}function fo(t,e){const n=t.x-e.x,r=t.y-e.y;return n*n+r*r}function go(t){return{x:-t.y,y:t.x}}function mo(t,e){return{x:t.x+e.x,y:t.y+e.y}}function yo(t,e){return{x:t.x-e.x,y:t.y-e.y}}function wo(t,e){return{x:t.x*e,y:t.y*e}}function xo(t,e,n){return{x:bo(t.x,e.x,n),y:bo(t.y,e.y,n)}}function bo(t,e,n){return t+(e-t)*n}function ko(t,e,n){return Math.max(e,Math.min(n,t))}function vo(t,e){const n=t[t.length-1];!n||fo(n,e)>.04?t.push(e):t[t.length-1]=e}function So(t){if(t.length<2)return null;if(2===t.length)return`M ${Po(t[0])} L ${Po(t[1])} Z`;const e=[`M ${Po(Io(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 ${Po(r)} ${Po(Io(r,o))}`)}return e.push("Z"),e.join(" ")}function Io(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}function Po(t){return`${Mo(t.x)},${Mo(t.y)}`}function Mo(t){return Number.isInteger(t)?`${t}`:t.toFixed(3)}function To(){return{tools:{eraser:t=>new Dr(t)}}}var Co=v({id:"eraser",editor:To(),render:Ur(),setup({editor:t}){!function(t){const{atom:e,computed:n}=t.signalGraph,r=e("eraser.shapeIds",[],{isEqual:Tr}),o=n("eraser.shapeIdSet",()=>new Set(r.get())),s=e("eraser.trail",[]),i={$_erasingShapeIds:r,$_erasingShapeIdSet:o,$_trail:s,$_trailActive:n("eraser.trailActive",()=>s.get().length>1),setPreview(t,e){r.set(Array.from(new Set(t))),s.set(e.map(t=>t.clone()))},clear(){r.set([]),s.get().length>0&&s.set([])}};Mr.set(t,i)}(t)}});function Eo(t){return/^\s*$/.test(t)?"Frame":t}function Ao(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function Lo(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 $o=class extends p{type="frame";getDefaultProps(){return{w:640,h:360,name:"",fill:x("transparent"),stroke:k("stroke-muted"),strokeWidth:1}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Math.max(o,Ao(e.w,n.w)),h:Math.max(o,Ao(e.h,n.h)),name:"string"==typeof e.name?e.name:n.name,fill:_(e.fill,n.fill),stroke:_(e.stroke,n.stroke),strokeWidth:Math.max(0,Ao(e.strokeWidth,n.strokeWidth))}}getLocalBounds(t){return new e(0,0,t.props.w,t.props.h)}getExportBounds(t){return function(t){return new e(0,-34,t.props.w,t.props.h+34)}(t)}getPointHitTestBounds(t,n){const r=this.getPositionedBounds(t).expand(3),o=A({bodyHeight:t.props.h,bodyWidth:t.props.w,headingHeight:34,shape:t});return e.FromPoints([new f(r.minX,r.minY),new f(r.maxX,r.maxY),new f(o.minX,o.minY),new f(o.maxX,o.maxY)])}canEdit(t){return!0}canReceiveChildren(t){return!0}canSnapChildrenToSelf(t){return!0}canReceiveTerminalBinding(t){return!0}getSelectionResizeHandleIds(t,e){return a}shouldRotateDescendants(t){return!0}getChildClipLocalBounds(t){return this.getLocalBounds(t)}canSelectByBrush(t,e){return super.isWrappedByBrush(t,e)}hitTest(t,n,r){return function(t,n){return n?L({bodyHeight:t.props.h,bodyWidth:t.props.w,editor:n.editor,headingHeight:34,shape:t}):new e(t.x,t.y-34,t.props.w,34)}(t,r).containsPoint(n)||Lo(this.getPositionedBounds(t),n,6)}hitTestBindingTarget(t,e){return this.getPositionedBounds(t).containsPoint(e)}hitTestLineSegment(t,e){return function(t,e,n,r){const o=r/2;if(Lo(t,e,r)||Lo(t,n,r))return!0;const s=[new f(t.minX,t.minY),new f(t.maxX,t.minY),new f(t.maxX,t.maxY),new f(t.minX,t.maxY)];for(let i=0;i<s.length;i+=1){const t=s[i],r=s[(i+1)%s.length];if(t&&r&&S(e,n,t,r)<=o)return!0}return!1}(this.getPositionedBounds(t),e.positionedStart,e.positionedEnd,Math.max(6,e.positionedMargin))}},Ro=new WeakMap;function No(t){const e=t.shapes.getDefaultProps("frame"),n=t.signalGraph.atom("frame.creation-config",{w:e.w,h:e.h,aspectRatio:null}),r=t.signalGraph.atom("frame.creation-hover",null),o={$_preview:t.signalGraph.computed("frame.creation-preview",()=>{const e=n.get(),o=r.get(),s=t.inputs.$_state.get();return null===e.aspectRatio||!o||t.state.$_readonly.get()||t.inputs.$_isSpacePressed.get()||s.isPointing||s.currentTimestamp!==o.timestamp||!s.currentPagePoint?.equals(o.pagePoint)||"frame"!==t.state.$_tool.get().activeToolId?null:{bounds:Bo(o.pagePoint,e),props:{...t.shapes.getDefaultProps("frame"),w:e.w,h:e.h}}}),getConfig:()=>({...n.get()}),setConfig:t=>(n.set(function(t){if(!Number.isFinite(t.w)||t.w<=0)throw new RangeError("Frame creation width must be a positive number.");if(!Number.isFinite(t.h)||t.h<=0)throw new RangeError("Frame creation height must be a positive number.");if(null!==t.aspectRatio&&(!Number.isFinite(t.aspectRatio)||t.aspectRatio<=0))throw new RangeError("Frame creation aspect ratio must be null or a positive number.");return{...t}}(t)),{...n.get()}),setHover(t){r.set({pagePoint:t.pagePoint.clone(),timestamp:t.timestamp})},clearHover(){r.set(null)}};return Ro.set(t,o),o}function Oo(t){const e=Ro.get(t);if(!e)throw new Error("FrameCreationRuntime is not initialized for this editor.");return e}function Bo(t,n){return new e(t.x,t.y,n.w,n.h)}var zo=class extends h{constructor(t){super(t,"frame"),this.initial="idle",this.addChild(new Ho(t,this)),this.addChild(new Do(t,this))}getDefaultProps(){return this.editor.shapes.getDefaultProps("frame")}getCreationConfig(){return Oo(this.editor).getConfig()}},Ho=class extends h{tool;constructor(t,e){super(t,"idle",e),this.tool=e}onEnter(){this.editor.interaction.clearSelection()}onExit(){Oo(this.editor).clearHover()}onPointerMove(t){const e=Oo(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,isDragCreating:!1,creationConfig:this.tool.getCreationConfig()})}},Do=class extends h{tool;info=null;operation=null;constructor(t,e){super(t,"creating",e),this.tool=e}onEnter(t){if(this.info=t,this.operation=this.editor.operations.begin({kind:"frame.create",label:"shape.create",source:"user",history:"record"}),null!==this.info.creationConfig.aspectRatio)try{const t=this.createShape(Bo(this.info.originPagePoint,this.info.creationConfig));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,!0),this.commitOperation(),this.editor.state.$_tool.get().isToolLocked?this.transition("idle"):this.editor.tools.select("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,n,r,o=!1){if(!this.info)return;const s=this.info.originScreenPoint.dist(n);if(!this.info.isDragCreating){if(s<4){if(!this.info.shapeId&&o){const e=this.createShape(Bo(t,this.info.creationConfig));this.info.shapeId=e.id}return}this.info.isDragCreating=!0}const i=function(t,n,r,o){let s=n.x-t.x,i=n.y-t.y;const a=o.aspectRatio??(r?o.w/o.h:null);if(null!==a){const t=Math.abs(s),e=Math.abs(i);0===e||t/Math.max(e,1)>=a?i=t/a*(i<0?-1:1):s=e*a*(s<0?-1:1)}const l=new f(t.x+s,t.y+i);return new e(Math.min(t.x,l.x),Math.min(t.y,l.y),Math.max(Math.abs(l.x-t.x),1),Math.max(Math.abs(l.y-t.y),1))}(this.info.originPagePoint,t,r,this.info.creationConfig);if(!this.info.shapeId){const t=this.createShape(i);return void(this.info.shapeId=t.id)}this.editor.shapes.update([{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.shapes.create([{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.selection.set([e.id],{source:"system"}),e}};var _o=class{type="frame";toSvg(t,e){const{fill:n,stroke:r,strokeWidth:o,w:s,h:i,name:a}=t.props,l=e.resolveColor(r),d=o/2;return{tag:"g",children:[{tag:"rect",attrs:{x:d,y:d,width:Math.max(s-o,0),height:Math.max(i-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:[Eo(a)]}]}}};function jo(){return{shapeUtils:[new $o],shapeSvgExporters:[new _o],tools:{frame:t=>new zo(t)}}}var Fo="frame.edit";function Wo({editor:t}){return function({editor:t}){return{create(e){const n=t.shapes.getDefaultProps("frame"),[r]=t.shapes.create([{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},startEditingTitle(e){const n=t.selection.getIds(),r=e??(1===n.length?n[0]:void 0),o=r?t.store.get(r):null;return!(!o||"frame"!==o.type||!t.editing.canEditShape(o))&&(t.editing.start({shapeId:o.id,entryMode:"selectAll",operationKind:Fo},"user"),!0)},moveShapesToFrame(e,n){const r=t.store.get(n);if(!r||"frame"!==r.type)return[];const o=e.filter(e=>{const n=t.store.get(e);return!!n&&!t.layers.isLocked(n.id)});return o.length>0&&t.shapes.reparent({ids:[...o],parentId:n},{source:"user"}),o},getSelectionStyle(){const e=t.state.$_selectedShapes.get().filter(Uo);return 0===e.length?null:{name:Ko(e.map(t=>t.props.name)),fill:Xo(e.map(t=>t.props.fill)),stroke:Xo(e.map(t=>t.props.stroke)),strokeWidth:Ko(e.map(t=>t.props.strokeWidth))}},setSelectionStyle(e){const n=t.state.$_selectedShapes.get().filter(Uo).filter(e=>!t.layers.isLocked(e.id)).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.shapes.update(n,{source:"user"}),n.map(({id:t})=>t)},toolDefaultsState:w(t.signalGraph.computed("Frame.toolDefaults",()=>t.shapes.getDefaultProps("frame"))),setToolDefaults:e=>(t.shapes.updateDefaultProps("frame",e),t.shapes.getDefaultProps("frame")),getToolCreationConfig:()=>Oo(t).getConfig(),setToolCreationConfig:e=>Oo(t).setConfig(e),getSelectedChildOrderState(){const e=t.state.$_selectedShapeIds.get();if(1!==e.length)return null;const n=t.layers.getOrderState(e);if(!n||!n.parentId.startsWith("shape:"))return null;const r=t.store.get(n.parentId);return r&&"frame"===r.type?{index:t.layers.tree.getChildIds(r.id).indexOf(e[0]),count:n.count,canMoveBackward:n.canMoveBackward,canMoveForward:n.canMoveForward}:null},moveSelectedChild:e=>t.layers.move(t.selection.getIds(),e,"user")}}({editor:t})}function Uo(t){return"frame"===t.type}function Ko(t){const e=t[0];return void 0!==e&&t.every(t=>t===e)?e:null}function Xo(t){const e=t[0];return e&&t.every(t=>g(t,e))?e:null}function Yo(){return{canvasOverlays:[{id:"land.frame.creation-preview",component:Vo,order:10}],shapeRenderers:[{type:"frame",component:qo,hoverComponent:Jo}]}}function qo({editor:t,shape:e,shapeEditingSession:n}){
|
|
6
|
+
return Z("div",{style:{height:"100%",overflow:"visible",position:"relative",width:"100%"},children:[J(Go,{props:e.props}),J(Zo,{editor:t,shape:e,isEditing:n?.shapeId===e.id})]})}function Go({props:t,width:e="100%",height:n="100%"}){const{fill:r,h:o,stroke:s,strokeWidth:i,w:a}=t,l=i/2;
|
|
7
|
+
return J("svg",{width:e,height:n,viewBox:`0 0 ${a} ${o}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:J("rect",{x:l,y:l,width:Math.max(a-i,0),height:Math.max(o-i,0),fill:Y(r),stroke:Y(s),strokeWidth:i,strokeLinejoin:"round",strokeLinecap:"round"})})}var Vo=nt(function(){const t=G(Oo(q()).$_preview);return t?J("g",{"data-ui":"frame-creation-preview",transform:`translate(${t.bounds.x} ${t.bounds.y})`,opacity:.48,pointerEvents:"none",children:J(Go,{props:t.props,width:t.bounds.w,height:t.bounds.h})}):null});function Jo({shape:t,strokeWidth:e}){const{h:n,w:r}=t.props;
|
|
8
|
+
return J("svg",{"data-ui":"frame-hover-outline",width:"100%",height:"100%",viewBox:`0 0 ${r} ${n}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:J("rect",{x:0,y:0,width:r,height:n,fill:"none",stroke:d,strokeWidth:e,strokeLinejoin:"round",strokeLinecap:"round",vectorEffect:"non-scaling-stroke"})})}function Zo({editor:t,shape:e,isEditing:n}){
|
|
9
|
+
return J(c,{editor:t,shape:e,isEditing:n,value:e.props.name,fallback:Eo(""),bodyWidth:e.props.w,bodyHeight:e.props.h,renderHeight:0,operationKind:Fo,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"},offsetX:0,showDragHandle:!1,onValueChange:n=>{t.shapes.update([{id:e.id,props:{name:n}}],{source:"user"})}})}var Qo=v({id:"frame",editor:jo(),render:Yo(),setup:({editor:t})=>(No(t),{api:Wo({editor:t})})}),ts="flow-node",es=["left","right"];function ns(t){return z(t)&&"flow-edge"===t.type}function rs(t){return("text"===t?.type||"image"===t?.type)&&"flow-node"===t.subType}function os(t){return"text"===t.type?"文字生成":"图片生成"}function ss(t){return O(t)&&"flow-edge"===t.type}var is={left:new f(-1,0),right:new f(1,0),top:new f(0,-1),bottom:new f(0,1)};function as(t){const e=ds(t.sourceOutwardNormal),n=ds(t.targetOutwardNormal),r=us(e,t.source,t.target,.25),o=us(n,t.target,t.source,.25);return{path:`M${t.source.x},${t.source.y} C${r.x},${r.y} ${o.x},${o.y} ${t.target.x},${t.target.y}`,points:Array.from({length:25},(e,n)=>function(t,e,n,r,o){const s=1-o;return new f(s**3*t.x+3*s**2*o*e.x+3*s*o**2*n.x+o**3*r.x,s**3*t.y+3*s**2*o*e.y+3*s*o**2*n.y+o**3*r.y)}(t.source,r,o,t.target,n/24))}}function ls(t){const e=function(t){const e=is[t.sourcePosition],n=is[t.targetPosition],r=t.source.add(e.mul(t.offset)),o=t.target.add(n.mul(t.offset)),s=function(t){return"left"===t.sourcePosition||"right"===t.sourcePosition?t.source.x<t.target.x?new f(1,0):new f(-1,0):t.source.y<t.target.y?new f(0,1):new f(0,-1)}({source:r,sourcePosition:t.sourcePosition,target:o}),i=0!==s.x?"x":"y",a=s[i];let l;const d=new f(0,0),c=new f(0,0);if(e[i]*n[i]===-1){const n="x"===i?r.x+(o.x-r.x)*t.stepPosition:(r.x+o.x)/2,s="y"===i?r.y+(o.y-r.y)*t.stepPosition:(r.y+o.y)/2,d=[new f(n,r.y),new f(n,o.y)],c=[new f(r.x,s),new f(o.x,s)];l=e[i]===a?"x"===i?d:c:"x"===i?c:d}else{const s=[new f(r.x,o.y)],u=[new f(o.x,r.y)];if(l="x"===i?e.x===a?u:s:e.y===a?s:u,t.sourcePosition===t.targetPosition){const n=Math.abs(t.source[i]-t.target[i]);if(n<=t.offset){const s=Math.min(t.offset-1,t.offset-n);e[i]===a?d[i]=(r[i]>t.source[i]?-1:1)*s:c[i]=(o[i]>t.target[i]?-1:1)*s}}if(t.sourcePosition!==t.targetPosition){const t="x"===i?"y":"x",a=e[i]===n[t],d=r[t]>o[t],c=r[t]<o[t];(1===e[i]&&(!a&&d||a&&c)||1!==e[i]&&(!a&&c||a&&d))&&(l="x"===i?s:u)}}const u=r.add(d),p=o.add(c);return[t.source,...u.x!==l[0].x||u.y!==l[0].y?[u]:[],...l,...p.x!==l.at(-1).x||p.y!==l.at(-1).y?[p]:[],t.target]}({source:t.source,sourcePosition:ds(t.sourceOutwardNormal),target:t.target,targetPosition:ds(t.targetOutwardNormal),offset:20,stepPosition:.5});let n=`M${e[0].x} ${e[0].y}`;for(let r=1;r<e.length-1;r+=1)n+=ps(e[r-1],e[r],e[r+1],t.borderRadius);return n+=`L${e.at(-1).x} ${e.at(-1).y}`,{path:n,points:e}}function ds(t){return Math.abs(t.x)>=Math.abs(t.y)?t.x<0?"left":"right":t.y<0?"top":"bottom"}function cs(t,e){return t>=0?.5*t:25*e*Math.sqrt(-t)}function us(t,e,n,r){switch(t){case"left":return new f(e.x-cs(e.x-n.x,r),e.y);case"right":return new f(e.x+cs(n.x-e.x,r),e.y);case"top":return new f(e.x,e.y-cs(e.y-n.y,r));case"bottom":return new f(e.x,e.y+cs(n.y-e.y,r))}}function ps(t,e,n,r){const o=Math.min(t.dist(e)/2,e.dist(n)/2,r),{x:s,y:i}=e;if(t.x===s&&s===n.x||t.y===i&&i===n.y)return`L${s} ${i}`;if(t.y===i){return`L ${s+o*(t.x<n.x?-1:1)},${i}Q ${s},${i} ${s},${i+o*(t.y<n.y?1:-1)}`}const a=t.x<n.x?1:-1;return`L ${s},${i+o*(t.y<n.y?-1:1)}Q ${s},${i} ${s+o*a},${i}`}var hs="shape:flow-edge-preview";function fs(t,e){return{kind:"bound",shapeId:t,attachment:{kind:"port",portId:e.id}}}function gs(t,e){if("free"===e.kind)return{draft:e,pagePoint:e.pagePoint.clone(),shape:null,port:null};const n=t.store.get(e.shapeId);if(!n||ns(n)||t.shapes.isHidden(n.id)||null===t.shapes.geometry.getClippedPageBounds(n.id)||!t.shapes.getUtil(n).canReceiveTerminalBinding(n,{editor:t}))return null;const r=T(t,n,e.attachment.portId);return r?{draft:e,pagePoint:r.pagePoint.clone(),shape:n,port:r}:null}function ms(t,e,n,r){if(e.shape&&e.port)return{point:e.pagePoint,outwardNormal:e.port.pageOutwardNormal};const o=n.pagePoint.sub(e.pagePoint).normalize();return{point:e.pagePoint,outwardNormal:o.len2()>0?o:new f("start"===r?1:-1,0)}}function ys(t){return{portId:t.id}}function ws(t,e,n){return T(t,e,n.portId)}function xs(t,e,n){const o=new Set(Ts(t,n));for(const r of Ts(t,e))if(o.has(r)&&t.layers.canReceiveChildren(r))return r;return r}function bs(t){const{editor:n,parentId:r,start:o,end:i,props:a}=t,l=r.startsWith("shape:")?n.store.get(r):null,d=(l?n.shapes.geometry.computeLocalToPageTransform(l):s.Identity()).tryInvert();if(!d)throw new Error("Flow edge parent transform is not invertible");const c=d.applyToPoint(o.point),u=d.applyToPoint(i.point),p=Ps({start:o,end:i,props:a}),h=e.FromPoints(p.points.map(t=>d.applyToPoint(t))),f=t=>({x:t.x-h.x,y:t.y-h.y});return{type:"flow-edge",parentId:r,x:h.x,y:h.y,rotation:0,props:{...a,w:Math.max(1,h.w),h:Math.max(1,h.h),start:f(c),end:f(u)}}}function ks(t,e){return t.pagePoint.add(t.pageOutwardNormal.mul(20/Math.max(e,1e-4)))}function vs(t,n,r={}){const o=Math.max(t.state.$_cameraZoom.get(),1e-4),s=12/o,i=s+20/o;let a=null;for(const l of t.shapes.hitTesting.getInBounds(new e(n.x-i,n.y-i,2*i,2*i)))if(!ns(l)&&!t.shapes.isHidden(l.id)&&null!==t.shapes.geometry.getClippedPageBounds(l.id))for(const e of C(t,l)){const t={shape:l,port:e};if(r.portFilter&&!r.portFilter(t))continue;const i=Math.min(n.dist(e.pagePoint),n.dist(ks(e,o)));i<=s&&(!a||i<a.distance||i===a.distance&&`${l.index}:${l.id}:${e.id}`<`${a.shape.index}:${a.shape.id}:${a.port.id}`)&&(a={...t,distance:i})}return a?{shape:a.shape,port:a.port}:null}function Ss(t,n){const r=t.shapes.geometry.computeLocalToPageTransform(n),o=r.tryInvert(),s=Is(t,n);return o?function(t,n){const r=t.points.map(n),o=n(t.startPoint),s=n(t.endPoint);return{...t,path:Cs(r),points:r,startPoint:o,endPoint:s,markerPath:t.markerPath?Ls(s,r.at(-2),2):null,bounds:e.FromPoints(r)}}(s,t=>r.applyToPoint(t)):s}function Is(t,e){const n=t.shapes.geometry.computeLocalToPageTransform(e).tryInvert(),r=new f(e.props.start.x,e.props.start.y),o=new f(e.props.end.x,e.props.end.y);if(!n)return Ps({start:{point:r,outwardNormal:new f(1,0)},end:{point:o,outwardNormal:new f(-1,0)},props:e.props});const s=t.bindings.relations.getOwnedByShape(e.id).find(ss),i=(e,r,o)=>{const i=s?.endpoints.find(({slot:t})=>t===e),a=i?t.store.get(i.targetId):null,l=i&&a?ws(t,a,i.props):null;if(!l||!a)return{point:r,outwardNormal:o};const d=l.pagePoint,c=d.add(l.pageOutwardNormal),u=n.applyToPoint(d);return{point:u,outwardNormal:n.applyToPoint(c).sub(u).normalize()}};return Ps({start:i("start",r,new f(1,0)),end:i("end",o,new f(-1,0)),props:e.props})}function Ps(t){const{start:n,end:r,props:o}=t,{path:s,points:i}="curved"===o.routing?as({source:n.point,sourceOutwardNormal:n.outwardNormal,target:r.point,targetOutwardNormal:r.outwardNormal}):"orthogonal"===o.routing?ls({source:n.point,sourceOutwardNormal:n.outwardNormal,target:r.point,targetOutwardNormal:r.outwardNormal,borderRadius:o.cornerRadius}):(a=n.point,l=r.point,{path:`M ${a.x},${a.y}L ${l.x},${l.y}`,points:[a,l]});var a,l;const d="arrow"===o.headEnd?Ls(i.at(-1),i.at(-2),o.strokeWidth):null,c=d?As(i.at(-1),i.at(-2),o.strokeWidth):[];return{path:s,points:[...i],startPoint:n.point,endPoint:r.point,markerPath:d,bounds:e.FromPoints([...i,...c]).expand(Math.max(o.strokeWidth/2,1))}}function Ms(t,e,n,o){if(0===o.length)return n;const i=function(t,e){const n={id:hs,typeName:"shape",scope:"document",type:e.type,subType:e.subType??null,parentId:e.parentId??r,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,lockMode:e.lockMode??"none",props:{...t.shapes.getDefaultProps(e.type),...e.props},meta:e.meta??{}};return{...n,props:t.shapes.getUtil(n).validateProps(n.props)}}(t,n),a=t.shapes.geometry.computePageCenter(i),l=new f(-e.port.pageOutwardNormal.y,e.port.pageOutwardNormal.x).normalize();if(0===l.len2())return n;const d=Rs(e.port.pagePoint,l),c=$s(t,i,l,d),u=(c.max-c.min)/2,p=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 i of n){const t=r.at(-1);!t||i.min>t.max+1e-6?r.push({...i}):t.max=Math.max(t.max,i.max)}const o=r.find(({min:t,max:e})=>t<0&&e>0);if(!o)return 0;const s=t.reduce((t,e)=>t+(e.min+e.max)/2,0);return[o.min,o.max].sort((t,e)=>Math.abs(s+t)-Math.abs(s+e)||Math.abs(t)-Math.abs(e)||e-t)[0]}(o.map(e=>$s(t,e,l,d)),u)-(Rs(a,l)-d);if(Math.abs(p)<=1e-6)return n;const h=n.parentId??e.shape.parentId,g=h.startsWith("shape:")?t.store.get(h):null,m=(g?t.shapes.geometry.computeLocalToPageTransform(g):s.Identity()).tryInvert();if(!m)return n;const y=a.add(l.mul(p)),w=m.applyToPoint(y).sub(m.applyToPoint(a));return{...n,x:n.x+w.x,y:n.y+w.y}}function Ts(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 s=t.store.get(e);if(!s)break;o=s.parentId}return n.push(o),n}function Cs(t){return t.map((t,e)=>`${0===e?"M":"L"} ${Es(t)}`).join(" ")}function Es(t){return`${t.x.toFixed(3)} ${t.y.toFixed(3)}`}function As(t,e,n){const r=t.sub(e).normalize(),o=Math.max(8,4*n),s=t.sub(r.mul(o)),i=new f(-r.y,r.x).mul(.55*o);return[s.add(i),t,s.sub(i)]}function Ls(t,e,n){const[r,o,s]=As(t,e,n);return`M ${Es(r)} L ${Es(o)} L ${Es(s)}`}function $s(t,e,n,r){const o=t.shapes.geometry.computePageCorners(e).map(t=>Rs(t,n)-r);return{min:Math.min(...o),max:Math.max(...o)}}function Rs(t,e){return t.x*e.x+t.y*e.y}var Ns=new WeakMap;function Os(t){const e=Ns.get(t);if(!e)throw new Error("FlowEdgeRuntime is not initialized for this editor.");return e}var Bs="left",zs="right";function Hs(t){return"right"===t.port.id&&("text"===t.shape.type||"image"===t.shape.type)}function Ds(t){return rs(t.shape)&&"left"===t.port.id}function _s(t,e){return"start"===t?Hs(e):Ds(e)}function js(t,e,n,r){return!Os(t).allowCycles&&function(t,e,n,r){const o=new Map;for(const a of t.state.$_shapeIds.get()){if(a===r)continue;const e=t.store.get(a);if(!ns(e))continue;const n=Fs(t,e.id);if(!n.start||!n.end)continue;const s=o.get(n.start.targetId)??[];s.push(n.end.targetId),o.set(n.start.targetId,s)}const s=[n],i=new Set;for(;s.length>0;){const t=s.pop();if(t===e)return!0;if(!i.has(t)){i.add(t);for(const e of o.get(t)??[])i.has(e)||s.push(e)}}return!1}(t,e,n,r)}function Fs(t,e){let n=null,r=null;for(const o of t.bindings.relations.getOwnedByShape(e))if(ss(o)){n=o.endpoints.find(({slot:t})=>"start"===t)??null,r=o.endpoints.find(({slot:t})=>"end"===t)??null;break}return{start:n,end:r}}function Ws(t,e){return t.bindings.relations.getOwnedByShape(e).filter(ss)}function Us(t,e,n,r){const o=gs(t,e),s=gs(t,n);return o?.shape&&o.port&&s?.shape&&s.port?Hs({shape:o.shape,port:o.port})?Ds({shape:s.shape,port:s.port})?(i=o.shape,a=s.shape,i.id!==a.id||Os(t).allowCycles?t.layers.isLocked(o.shape.id)?"locked_source":Gs(t,o.shape.id,o.port.id,s.shape.id,s.port.id,r)?"duplicate":js(t,o.shape.id,s.shape.id,r)?"cycle":xs(t,o.shape,s.shape)?null:"invalid_parent":"self_loop"):"invalid_input":"invalid_output":"missing_endpoint";var i,a}function Ks(t,e,n="user"){if(Us(t,e.start,e.end))return null;const r=gs(t,e.start),o=gs(t,e.end);if(!(r?.shape&&r.port&&o?.shape&&o.port))return null;const s=xs(t,r.shape,o.shape);if(!s)return null;const i={...t.shapes.getDefaultProps("flow-edge"),...e.props},a=bs({editor:t,parentId:s,start:ms(0,r,o,"start"),end:ms(0,o,r,"end"),props:i}),l=t.operations.begin({kind:"flow-edge.commit",label:"shape.create",source:n,history:"user"===n?"record":"ignore"});try{const s=t.shapes.create([a],{source:n,autoReparent:!1})[0];if(!ns(s))return l.cancel(),null;t.bindings.create({type:"flow-edge",ownerId:s.id,endpoints:[{slot:"start",targetId:r.shape.id,props:ys(r.port)},{slot:"end",targetId:o.shape.id,props:ys(o.port)}]},{source:n}),"none"!==e.selectionAfter&&t.selection.set(Array.isArray(e.selectionAfter)?[...e.selectionAfter]:[s.id],{source:n});const i=t.store.get(s.id);return ns(i)?(l.commit(),i):(l.cancel(),null)}catch(d){throw l.isActive&&l.cancel(),d}}function Xs(t,e,n,r){return qs(t,e,{[n]:r})}function Ys(t,e,n,r,o="user"){const s=gs(t,r),i=Ws(t,e)[0];if(!s?.shape||!s.port||!i)return null;t.bindings.setEndpoint({bindingId:i.id,endpoint:{slot:n,targetId:s.shape.id,props:ys(s.port)}},{source:o});const a=t.store.get(e);return ns(a)?a:null}function qs(t,e,n={}){const r=Fs(t,e.id),o=t.shapes.geometry.computeLocalToPageTransform(e),s=o.applyToPoint(new f(e.props.start.x,e.props.start.y)),i=o.applyToPoint(new f(e.props.end.x,e.props.end.y)),a=Vs(t,r.start),l=Vs(t,r.end),d=n.start?gs(t,{kind:"free",pagePoint:n.start}):a??gs(t,{kind:"free",pagePoint:s}),c=n.end?gs(t,{kind:"free",pagePoint:n.end}):l??gs(t,{kind:"free",pagePoint:i});if(!d||!c)return null;const u=a&&l?xs(t,a.shape,l.shape):e.parentId;if(!u||!t.layers.canReceiveChildren(u))return null;const p=bs({editor:t,parentId:u,start:ms(0,d,c,"start"),end:ms(0,c,d,"end"),props:e.props});return{...e,parentId:u,x:p.x??e.x,y:p.y??e.y,rotation:0,scaleX:1,scaleY:1,props:{...e.props,...p.props}}}function Gs(t,e,n,r,o,s){for(const i of t.state.$_shapeIds.get()){if(i===s)continue;const a=t.store.get(i);if(!ns(a))continue;const l=Fs(t,a.id);if(l.start?.targetId===e&&l.start.props.portId===n&&l.end?.targetId===r&&l.end.props.portId===o)return!0}return!1}function Vs(t,e){if(!e)return null;const n=t.store.get(e.targetId);if(!n)return null;const r=ws(t,n,e.props);return r&&_s(e.slot,{shape:n,port:r})?gs(t,fs(n.id,r)):null}var Js="land:",Zs="shape";function Qs(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 ti(n)?n:null}function ti(t){return null!==ri(t)||ei(t)}function ei(t){try{const e=new URL(t);return"http:"===e.protocol||"https:"===e.protocol||"mailto:"===e.protocol}catch{return!1}}function ni(t){return`${Js}//${Zs}/${encodeURIComponent(t)}`}function ri(t){try{const e=new URL(t);if(e.protocol!==Js||e.hostname!==Zs||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 oi({href:t,openExternal:e,openInternal:n}){const r=ri(t);r?n?.(r):ei(t)&&e(t)}var si=/[;{}<>\u0000-\u001f\u007f]/u,ii=/(?:url|expression)\s*\(|!\s*important|@\s*import|javascript\s*:/iu,ai=/^((?:\d+(?:\.\d{1,3})?)|(?:\.\d{1,3}))(px|em|rem|%)?$/iu;function li(t){return{type:"doc",content:t.split("\n").map(t=>({type:"paragraph",content:t.length>0?[{type:"text",text:t}]:[]}))}}function di(t){return t.content.map(t=>yi(t)).join("\n")}function ci(t){return"taskItem"===t.type||(t.content?.some(ci)??!1)}function ui(t){return"taskList"===t.type||"taskItem"===t.type?"\n":""}function pi(t){if(!t||"object"!=typeof t)return li("");const e=t,n=Array.isArray(e.content)?e.content.map(t=>Si(t,0)).filter(t=>null!==t):[];return{type:"doc",attrs:Li(e.attrs),content:n}}function hi(t){return"text"===t.type&&"string"==typeof t.text}function fi(t){if("paragraph"===t.type)return Ai(t.attrs?.textAlign)}function gi(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 s of t??[])switch(s.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=Mi(s.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 mi(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 yi(t){return hi(t)?t.text:t.content?.map(t=>yi(t)).join(ui(t))??""}function wi(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 xi(t){const e=t.content?.map(t=>function(t){if(hi(t)){const e=gi(t.marks),n=mi(t.marks),r=bi(t.text),o=e?`<span style="${ki(wi(e))}">${r}</span>`:r;return n&&ei(n)?`<a href="${ki(n)}" target="_blank" rel="noopener noreferrer">${o}</a>`:e?o:r}return"hardBreak"===t.type?"<br>":xi(t)}(t)).join("")??"";if("taskList"===t.type)return`<ul data-type="taskList" style="margin:0;padding:0;list-style:none">${e}</ul>`;if("taskItem"===t.type){const n=!0===t.attrs?.checked;return`<li data-type="taskItem" data-checked="${n}" style="display:flex;align-items:flex-start;gap:0.625em;padding-block:0.18em"><label contenteditable="false" style="display:flex;align-items:center;flex:none;height:1lh;user-select:none"><input type="checkbox"${n?" checked":""} style="width:1em;height:1em;margin:0;font:inherit"></label><div style="flex:1;min-width:0">${e}</div></li>`}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=fi(t);return`<p style="${n?`margin:0;text-align:${n}`:"margin:0"}">${e.length>0?e:"<br>"}</p>`}function bi(t){return t.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function ki(t){return bi(t).replaceAll('"',""")}function vi(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(Ii).filter(t=>null!==t):void 0}}(n);return t.text.length>0?t:null}return Si(n,e)}function Si(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=>vi(t,e+1)).filter(t=>null!==t):[];return{type:r,attrs:Pi(r,n.attrs),content:o}}function Ii(t){if(!t||"object"!=typeof t)return null;const e=t;if("string"!=typeof e.type)return null;if("link"===e.type){const t=Li(e.attrs),n=t?.href;return"string"==typeof n&&ti(n)?{type:"link",attrs:{...t,href:n}}:null}if("textStyle"===e.type){const t=Mi(e.attrs);return t?{type:"textStyle",attrs:t}:null}return{type:e.type,attrs:Li(e.attrs)}}function Pi(t,e){const n=Li(e);if("taskItem"===t)return{...n,checked:!0===n?.checked};if("paragraph"!==t)return n;const r={...n};delete r.textAlign;const o=e&&"object"==typeof e&&!Array.isArray(e)?Ai(e.textAlign):void 0;return void 0!==o&&(r.textAlign=o),Object.keys(r).length>0?r:void 0}function Mi(t){if(!t||"object"!=typeof t||Array.isArray(t))return;const e=t,n={color:Ti(e.color,128),backgroundColor:Ti(e.backgroundColor,128),fontFamily:Ti(e.fontFamily,256),fontSize:Ci(e.fontSize),lineHeight:Ei(e.lineHeight)},r=Object.entries(n).filter(t=>void 0!==t[1]);return r.length>0?Object.fromEntries(r):void 0}function Ti(t,e){if("string"!=typeof t)return;const n=t.trim();return 0===n.length||n.length>e||si.test(n)||ii.test(n)?void 0:n}function Ci(t){const e="string"==typeof t?ai.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 Ei(t){const e="string"==typeof t?ai.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 Ai(t){return"left"===t||"center"===t||"right"===t||"justify"===t?t:void 0}function Li(t){if(!t||"object"!=typeof t)return;const e=Object.entries(t).map(([t,e])=>[t,$i(e)]).filter(t=>void 0!==t[1]);return e.length>0?Object.fromEntries(e):void 0}function $i(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=>$i(t,e+1)).filter(t=>void 0!==t);if(t&&"object"==typeof t){const n=Object.entries(t).map(([t,n])=>[t,$i(n,e+1)]).filter(t=>void 0!==t[1]);return Object.fromEntries(n)}}}function Ri(t){return z(t)&&"text"===t.type}function Ni(t){return{richText:t.richText,plainText:t.plainText,w:t.w,h:t.h,autoSize:t.autoSize,scale:t.scale,font:t.font,size:t.size,lineHeight:t.lineHeight,color:t.color,backgroundColor:t.backgroundColor,textAlign:t.textAlign,padding:t.padding,fill:t.fill,stroke:t.stroke,strokeWidth:t.strokeWidth,cornerRadius:t.cornerRadius,shadow:t.shadow}}function Oi(t){return Ni(t.shapes.getDefaultProps("text"))}function Bi(t,e,n="user"){const r=Oi(t),o=e.props?.richText??li(""),s={...r,...e.props,richText:o,plainText:di(o)},[i]=t.shapes.create([{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:s.richText,plainText:s.plainText,w:s.w,h:s.h,autoSize:s.autoSize,scale:s.scale,font:s.font,size:s.size,lineHeight:s.lineHeight,color:s.color,backgroundColor:s.backgroundColor,textAlign:s.textAlign,padding:s.padding,fill:s.fill,stroke:s.stroke,strokeWidth:s.strokeWidth,cornerRadius:s.cornerRadius,shadow:s.shadow}}],{source:n});if(!Ri(i))throw new Error("Failed to create text shape");return i}function zi(t,e,n,r,o="user"){const s=t.store.get(e);Ri(s)&&t.shapes.update([{id:s.id,props:{richText:n,plainText:di(n),..."number"==typeof r?.w?{w:r.w}:null,..."number"==typeof r?.h?{h:r.h}:null}}],{source:o})}var Hi="default",Di={id:"host-default",label:"Host default",cssFamily:"inherit",source:{kind:"system"}};function _i(){return{defaultFont:Di,defaultFontLabel:"Default",fonts:[]}}function ji(){return Fi(_i())}function Fi(t){const e=new Map;for(const r of t.fonts)Wi(r.id)&&"default"!==r.id&&e.set(r.id,r);const n={id:Hi,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 Wi(t){return"string"==typeof t&&t.trim().length>0}function Ui(t,e){return"default"===e?t.defaultFont:t.fontsById.get(e)??t.defaultFont}var Ki={s:14,m:16,l:20,xl:28},Xi=Ki.m;function Yi(t){return t.shadow?14*t.scale:0}function qi(t,e){const n=[...t.strokeWidth>0&&!H(t.stroke)?[`inset 0 0 0 ${t.strokeWidth}px ${e(t.stroke)}`]:[],...t.shadow?["0 2px 8px rgba(0, 0, 0, 0.04)","0 1px 2px rgba(0, 0, 0, 0.02)"]:[]];return{backgroundColor:H(t.fill)?(Gi(t.padding).x>0||Gi(t.padding).y>0)&&!H(t.backgroundColor)?e(t.backgroundColor):void 0:e(t.fill),borderRadius:t.cornerRadius>0?`${t.cornerRadius}px`:void 0,boxShadow:n.length>0?n.join(", "):void 0}}function Gi(t){return"number"==typeof t?{x:t,y:t}:t}function Vi(t,e=0){const n=(t,e)=>"number"==typeof t&&Number.isFinite(t)?Math.max(0,t):e;if(t&&"object"==typeof t){const r=t,o=Gi(e);return{x:n(r.x,o.x),y:n(r.y,o.y)}}return"number"==typeof t&&Number.isFinite(t)?Math.max(0,t):e}var Ji={[Ki.s]:20,[Ki.m]:24,[Ki.l]:28,[Ki.xl]:36};function Zi(t,e=Xi){return"number"==typeof t&&Number.isFinite(t)?Math.max(1,t):e}function Qi(t,e){return Ui(e,t).cssFamily}function ta(t){return Zi(t)}function ea(t,e=null){const n=Zi(t);return"number"==typeof e?n*e:"string"==typeof e?e.endsWith("%")?n*Number.parseFloat(e)/100:Number.parseFloat(e):Ji[n]??Math.ceil(1.4*n)}function na(t,e=null){return String(e??ea(t)/Zi(t))}function ra(t,e=null){return Math.max(1,Math.ceil(ea(t,e)))}function oa(t){switch(t){case"middle":return"center";case"end":return"right";case"justify":return"justify";default:return"left"}}var sa="path-label",ia="geo-label";function aa(t={}){return{padding:Gi(Vi(t.padding,16)),verticalAlign:"top"===t.verticalAlign||"bottom"===t.verticalAlign?t.verticalAlign:"middle"}}function la(t,e){return t.bindings.relations.getTargetingShape(e).find(t=>"geo-label"===t.type&&t.endpoints.some(t=>"owner"===t.slot&&t.targetId===e))??null}function da(t,e){const n=la(t,e)?.endpoints.find(({slot:t})=>"owner"===t);return aa(n?.props)}function ca(t,e){const n=ya(t,e);return t.layers.isLocked(e)||null!==n&&t.layers.isLocked(n.ownerId)}var ua={[sa]:{selectionTarget:"owner",hoverTarget:"owner",hoverDecorationTarget:"owner",translateTarget:"owner",canSnap:!1,canReceiveTerminalBinding:!1,contributesToSelectionFrame:!0,canUseSelectionResizeHandles:!1,canUseSelectionRotateHandle:!1,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!0},[ia]:{selectionTarget:"owner",hoverTarget:"owner",hoverDecorationTarget:"label",translateTarget:"owner",canSnap:!1,canReceiveTerminalBinding:!1,contributesToSelectionFrame:!1,canUseSelectionResizeHandles:!0,canUseSelectionRotateHandle:!0,canPlaceCaretWhenOwnerSelected:!0,showsCompanionFrameWhenOwnerSelected:!1}};function pa(t,e){return t?Math.min(t.paddingInline,Math.max(0,(e-1)/2)):0}function ha(t,e){return R(t.shapes.geometry.computeLocalToPageTransform(e),t.shapes.geometry.computeLocalBounds(e),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY})?.rotation??e.rotation}function fa(t,e,n,r){const o=t.shapes.getUtil(e),i=R(t.shapes.geometry.computeLocalToPageTransform(e),t.shapes.geometry.computeLocalBounds(e),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY});if(!i)return null;const a={...e,...i,x:r.x,y:r.y,rotation:r.rotation,props:o.validateProps({...e.props,...r.props})},l=n.startsWith("shape:")?t.store.get(n):null;if(n.startsWith("shape:")&&!l)return null;const d=(l?t.shapes.geometry.computeLocalToPageTransform(l):s.Identity()).tryInvert();return d?R(d.compose($(a,o.getLocalBounds(a))),o.getLocalBounds(a),{preferredRotation:e.rotation,preferredScaleXSign:e.scaleX,preferredScaleYSign:e.scaleY}):null}function ga(t,e,n){const r=t.bindings.relations.getTargetingShape(e).find(t=>t.type===n&&t.endpoints.some(({slot:t,targetId:n})=>"owner"===t&&n===e));if(!r)return null;const o=t.store.get(r.ownerId);return Ri(o)?o:null}function ma(t,e){const n={...Oi(t),...e.layout.props,autoSize:!1,textAlign:"middle"},r=fa(t,{id:"shape:draft-label",typeName:"shape",scope:"document",type:"text",subType:null,parentId:e.owner.parentId,index:e.index,x:0,y:0,rotation:0,scaleX:1,scaleY:1,opacity:1,isHidden:!1,lockMode:"none",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=Bi(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.bindings.create({type:e.bindingType,ownerId:o.id,endpoints:[{slot:"owner",targetId:e.owner.id,props:e.bindingProps}]},{source:"user"}),o}catch(s){throw o.cancel(),s}}function ya(t,e){const n=t.store.get(e);if(!Ri(n))return null;const r=t.bindings.relations.getOwnedByShape(e).find(t=>t.type in ua);if(!r)return null;const o=r.type,s=r.endpoints.find(({slot:t})=>"owner"===t);return s?{label:n,ownerId:s.targetId,bindingType:o,behavior:ua[o]}:null}function wa(t,e,n,r){if("path-label"===r)return{minWidth:24,maxWidth:120,paddingInline:4.25};const o=Math.max(.01,e.props.scale),s=t.shapes.geometry.computeLocalBounds(n),i="geo"===n.type?n.props.kind:null,a="summary"===i||"summary-left"===i?.75:1,l=Math.max(16,s.w*a/o);return{minWidth:l,maxWidth:l,paddingInline:da(t,n.id).padding.x,normalizedCenterX:"summary-left"===i?1-a/2:a/2}}function xa(t,e){const n=ya(t,e.id);if(!n)return null;const r=t.store.get(n.ownerId);return r?wa(t,e,r,n.bindingType):null}function ba(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 ka(t,e){return G(lt(()=>t.signalGraph.computed(`textLabelLayout(${e.id})`,()=>xa(t,e)),[t,e]))}function va(t,e={}){const n={offset:0};return t.content.map((t,r)=>(r>0&&(n.offset+=1),Sa(t,`block:${r}`,n,e,[r])))}function Sa(t,e,n,r,o){const s="codeBlock"===t.type?void 0:r.defaultBackgroundColor,i=function(t,e,n,r,o){return t.content?.map((s,i)=>(i>0&&(n.offset+=ui(t).length),function(t,e,n,r,o){if(hi(t)){const o=n.offset;n.offset+=t.text.length;const s=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 s=[];let i=0;for(const a of o){const o=Math.max(a.from,e)-e,l=Math.min(a.to,r)-e;o>i&&s.push(t.slice(i,o)),s.push(J("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}`)),i=l}i<t.length&&s.push(t.slice(i));return s}(t.text,o,r),i=gi(t.marks,r.defaultBackgroundColor),a=mi(t.marks);return a&&ti(a)?J("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:{...i,cursor:r.linkHandlers?"pointer":void 0,pointerEvents:r.linkHandlers?"auto":"none",textDecorationLine:Pa(i?.textDecorationLine)},children:s},e):J("span",{style:i,children:s},e)}return"hardBreak"===t.type?J("br",{},e):Sa(t,e,n,{...r,defaultBackgroundColor:"codeBlock"===t.type?void 0:r.defaultBackgroundColor},o)}(s,`${e}:${i}`,n,r,[...o,i])))??[]}(t,e,n,{...r,defaultBackgroundColor:s},o);if("taskList"===t.type)return J("ul",{"data-type":"taskList",style:{listStyle:"none",margin:0,padding:0},children:i},e);if("taskItem"===t.type){const n=!0===t.attrs?.checked;
|
|
10
|
+
return Z("li",{"data-type":"taskItem","data-checked":n,style:{display:"flex",alignItems:"flex-start",gap:"0.625em",paddingBlock:"0.18em"},children:[J("label",{style:{display:"flex",alignItems:"center",flex:"none",height:"1lh",userSelect:"none"},children:J("input",{type:"checkbox","data-rich-text-task-checkbox":"true","aria-label":Ia(t),checked:n,disabled:!r.onTaskChecked,style:{width:"1em",height:"1em",margin:0,font:"inherit",pointerEvents:r.onTaskChecked?"auto":"none",cursor:"pointer"},onMouseDown:t=>t.preventDefault(),onDoubleClick:t=>t.stopPropagation(),onClick:t=>t.stopPropagation(),onChange:t=>r.onTaskChecked?.({path:o,checked:t.currentTarget.checked})})}),J("div",{style:{flex:1,minWidth:0},children:i})]},e)}return"bulletList"===t.type?J("ul",{style:{listStyleType:"disc",margin:0,paddingInlineStart:"1.5em"},children:i},e):"orderedList"===t.type?J("ol",{style:{listStyleType:"decimal",margin:0,paddingInlineStart:"1.5em"},children:i},e):"listItem"===t.type?J("li",{children:i},e):"blockquote"===t.type?J("blockquote",{style:{borderInlineStart:"2px solid currentColor",margin:0,paddingInlineStart:"0.75em"},children:i},e):J("p",{style:{margin:0,textAlign:fi(t)},children:i.length>0?i:J("br",{})},e)}function Ia(t){const e=t=>t.text??t.content?.map(e).join("")??"";return e(t.content?.[0]??{}).trim()||"To-do item"}function Pa(t){const e=new Set(t?.split(/\s+/u)??[]);return e.add("underline"),["line-through","underline"].filter(t=>e.has(t)).join(" ")}var Ma=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,Ta=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,Ca=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,Ea=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,Aa=gt.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}){
|
|
11
|
+
return Wt("strong",{...zt(this.options.HTMLAttributes,t),children:Wt("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[Ot({find:Ma,type:this.type}),Ot({find:Ca,type:this.type})]},addPasteRules(){return[Bt({find:Ta,type:this.type}),Bt({find:Ea,type:this.type})]}}),La=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,$a=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Ra=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Na=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,Oa=gt.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",zt(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[Ot({find:La,type:this.type}),Ot({find:Ra,type:this.type})]},addPasteRules(){return[Bt({find:$a,type:this.type}),Bt({find:Na,type:this.type})]}}),Ba="numeric",za="ascii",Ha="alpha",Da="asciinumeric",_a="alphanumeric",ja="domain",Fa="emoji",Wa="scheme",Ua="slashscheme",Ka="whitespace";function Xa(t,e){return t in e||(e[t]=[]),e[t]}function Ya(t,e,n){e[Ba]&&(e[Da]=!0,e[_a]=!0),e[za]&&(e[Da]=!0,e[Ha]=!0),e[Da]&&(e[_a]=!0),e[Ha]&&(e[_a]=!0),e[_a]&&(e[ja]=!0),e[Fa]&&(e[ja]=!0);for(const r in e){const e=Xa(r,n);e.indexOf(t)<0&&e.push(t)}}function qa(t=null){this.j={},this.jr=[],this.jd=null,this.t=t}qa.groups={},qa.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||qa.groups,e&&e.j?o=e:(o=new qa(e),n&&r&&Ya(e,n,r)),this.jr.push([t,o]),o},ts(t,e,n,r){let o=this;const s=t.length;if(!s)return o;for(let i=0;i<s-1;i++)o=o.tt(t[i]);return o.tt(t[s-1],e,n,r)},tt(t,e,n,r){r=r||qa.groups;const o=this;if(e&&e.j)return o.j[t]=e,e;const s=e;let i,a=o.go(t);return a?(i=new qa,Object.assign(i.j,a.j),i.jr.push.apply(i.jr,a.jr),i.jd=a.jd,i.t=a.t):i=new qa,s&&(r&&(i.t&&"string"==typeof i.t?Ya(s,Object.assign(function(t,e){const n={};for(const r in e)e[r].indexOf(t)>=0&&(n[r]=!0);return n}(i.t,r),n),r):n&&Ya(s,n,r)),i.t=s),o.j[t]=i,i}};var Ga=(t,e,n,r,o)=>t.ta(e,n,r,o),Va=(t,e,n,r,o)=>t.tr(e,n,r,o),Ja=(t,e,n,r,o)=>t.ts(e,n,r,o),Za=(t,e,n,r,o)=>t.tt(e,n,r,o),Qa="WORD",tl="UWORD",el="ASCIINUMERICAL",nl="ALPHANUMERICAL",rl="LOCALHOST",ol="TLD",sl="UTLD",il="SCHEME",al="SLASH_SCHEME",ll="NUM",dl="WS",cl="NL",ul="OPENBRACE",pl="CLOSEBRACE",hl="OPENBRACKET",fl="CLOSEBRACKET",gl="OPENPAREN",ml="CLOSEPAREN",yl="OPENANGLEBRACKET",wl="CLOSEANGLEBRACKET",xl="FULLWIDTHLEFTPAREN",bl="FULLWIDTHRIGHTPAREN",kl="LEFTCORNERBRACKET",vl="RIGHTCORNERBRACKET",Sl="LEFTWHITECORNERBRACKET",Il="RIGHTWHITECORNERBRACKET",Pl="FULLWIDTHLESSTHAN",Ml="FULLWIDTHGREATERTHAN",Tl="AMPERSAND",Cl="APOSTROPHE",El="ASTERISK",Al="AT",Ll="BACKSLASH",$l="BACKTICK",Rl="CARET",Nl="COLON",Ol="COMMA",Bl="DOLLAR",zl="DOT",Hl="EQUALS",Dl="EXCLAMATION",_l="HYPHEN",jl="PERCENT",Fl="PIPE",Wl="PLUS",Ul="POUND",Kl="QUERY",Xl="QUOTE",Yl="FULLWIDTHMIDDLEDOT",ql="SEMI",Gl="SLASH",Vl="TILDE",Jl="UNDERSCORE",Zl="EMOJI",Ql="SYM",td=Object.freeze({__proto__:null,ALPHANUMERICAL:nl,AMPERSAND:Tl,APOSTROPHE:Cl,ASCIINUMERICAL:el,ASTERISK:El,AT:Al,BACKSLASH:Ll,BACKTICK:$l,CARET:Rl,CLOSEANGLEBRACKET:wl,CLOSEBRACE:pl,CLOSEBRACKET:fl,CLOSEPAREN:ml,COLON:Nl,COMMA:Ol,DOLLAR:Bl,DOT:zl,EMOJI:Zl,EQUALS:Hl,EXCLAMATION:Dl,FULLWIDTHGREATERTHAN:Ml,FULLWIDTHLEFTPAREN:xl,FULLWIDTHLESSTHAN:Pl,FULLWIDTHMIDDLEDOT:Yl,FULLWIDTHRIGHTPAREN:bl,HYPHEN:_l,LEFTCORNERBRACKET:kl,LEFTWHITECORNERBRACKET:Sl,LOCALHOST:rl,NL:cl,NUM:ll,OPENANGLEBRACKET:yl,OPENBRACE:ul,OPENBRACKET:hl,OPENPAREN:gl,PERCENT:jl,PIPE:Fl,PLUS:Wl,POUND:Ul,QUERY:Kl,QUOTE:Xl,RIGHTCORNERBRACKET:vl,RIGHTWHITECORNERBRACKET:Il,SCHEME:il,SEMI:ql,SLASH:Gl,SLASH_SCHEME:al,SYM:Ql,TILDE:Vl,TLD:ol,UNDERSCORE:Jl,UTLD:sl,UWORD:tl,WORD:Qa,WS:dl}),ed=/[a-z]/,nd=/\p{L}/u,rd=/\p{Emoji}/u,od=/\d/,sd=/\s/,id=null,ad=null;function ld(t,e){const n=function(t){const e=[],n=t.length;let r=0;for(;r<n;){let o,s=t.charCodeAt(r),i=s<55296||s>56319||r+1===n||(o=t.charCodeAt(r+1))<56320||o>57343?t[r]:t.slice(r,r+2);e.push(i),r+=i.length}return e}(e.replace(/[A-Z]/g,t=>t.toLowerCase())),r=n.length,o=[];let s=0,i=0;for(;i<r;){let a=t,l=null,d=0,c=null,u=-1,p=-1;for(;i<r&&(l=a.go(n[i]));)a=l,a.accepts()?(u=0,p=0,c=a):u>=0&&(u+=n[i].length,p++),d+=n[i].length,s+=n[i].length,i++;s-=u,i-=p,d-=u,o.push({t:c.t,v:e.slice(s-d,s),s:s-d,e:s})}return o}function dd(t,e,n,r,o){let s;const i=e.length;for(let a=0;a<i-1;a++){const n=e[a];t.j[n]?s=t.j[n]:(s=new qa(r),s.jr=o.slice(),t.j[n]=s),t=s}return s=new qa(n),s.jr=o.slice(),t.j[e[i-1]]=s,s}function cd(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 ud={defaultProtocol:"http",events:null,format:hd,formatHref:hd,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function pd(t,e=null){let n=Object.assign({},ud);t&&(n=Object.assign(n,t instanceof pd?t.o:t));const r=n.ignoreTags,o=[];for(let s=0;s<r.length;s++)o.push(r[s].toUpperCase());this.o=n,e&&(this.defaultRender=e),this.ignoreTags=o}function hd(t){return t}function fd(t,e){this.t="token",this.v=t,this.tk=e}function gd(t,e){class n extends fd{constructor(e,n){super(e,n),this.t=t}}for(const r in e)n.prototype[r]=e[r];return n.t=t,n}pd.prototype={o:ud,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]:ud[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)}},fd.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=ud.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),s=this.toFormattedString(t),i={},a=t.get("className",n,e),l=t.get("target",n,e),d=t.get("rel",n,e),c=t.getObj("attributes",n,e),u=t.getObj("events",n,e);return i.href=r,a&&(i.class=a),l&&(i.target=l),d&&(i.rel=d),c&&Object.assign(i,c),{tagName:o,attributes:i,content:s,eventListeners:u}}};var md=gd("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),yd=gd("text"),wd=gd("nl"),xd=gd("url",{isLink:!0,toHref(t=ud.defaultProtocol){return this.hasProtocol()?this.v:`${t}://${this.v}`},hasProtocol(){const t=this.tk;return t.length>=2&&t[0].t!==rl&&t[1].t===Nl}}),bd=t=>new qa(t);function kd(t,e,n){const r=n[0].s,o=n[n.length-1].e;return new t(e.slice(r,o),n)}var vd="undefined"!=typeof console&&console&&console.warn||(()=>{}),Sd={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function Id(t,e=!1){if(Sd.initialized&&vd(`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');Sd.customSchemes.push([t,e])}function Pd(){Sd.scanner=function(t=[]){const e={};qa.groups=e;const n=new qa;null==id&&(id=cd("aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2")),null==ad&&(ad=cd("ελ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")),Za(n,"'",Cl),Za(n,"{",ul),Za(n,"}",pl),Za(n,"[",hl),Za(n,"]",fl),Za(n,"(",gl),Za(n,")",ml),Za(n,"<",yl),Za(n,">",wl),Za(n,"(",xl),Za(n,")",bl),Za(n,"「",kl),Za(n,"」",vl),Za(n,"『",Sl),Za(n,"』",Il),Za(n,"<",Pl),Za(n,">",Ml),Za(n,"&",Tl),Za(n,"*",El),Za(n,"@",Al),Za(n,"`",$l),Za(n,"^",Rl),Za(n,":",Nl),Za(n,",",Ol),Za(n,"$",Bl),Za(n,".",zl),Za(n,"=",Hl),Za(n,"!",Dl),Za(n,"-",_l),Za(n,"%",jl),Za(n,"|",Fl),Za(n,"+",Wl),Za(n,"#",Ul),Za(n,"?",Kl),Za(n,'"',Xl),Za(n,"/",Gl),Za(n,";",ql),Za(n,"~",Vl),Za(n,"_",Jl),Za(n,"\\",Ll),Za(n,"・",Yl);const r=Va(n,od,ll,{[Ba]:!0});Va(r,od,r);const o=Va(r,ed,el,{[Da]:!0}),s=Va(r,nd,nl,{[_a]:!0}),i=Va(n,ed,Qa,{[za]:!0});Va(i,od,o),Va(i,ed,i),Va(o,od,o),Va(o,ed,o);const a=Va(n,nd,tl,{[Ha]:!0});Va(a,ed),Va(a,od,s),Va(a,nd,a),Va(s,od,s),Va(s,ed),Va(s,nd,s);const l=Za(n,"\n",cl,{[Ka]:!0}),d=Za(n,"\r",dl,{[Ka]:!0}),c=Va(n,sd,dl,{[Ka]:!0});Za(n,"",c),Za(d,"\n",l),Za(d,"",c),Va(d,sd,c),Za(c,"\r"),Za(c,"\n"),Va(c,sd,c),Za(c,"",c);const u=Va(n,rd,Zl,{[Fa]:!0});Za(u,"#"),Va(u,rd,u),Za(u,"️",u);const p=Za(u,"");Za(p,"#"),Va(p,rd,u);const h=[[ed,i],[od,o]],f=[[ed,null],[nd,a],[od,s]];for(let g=0;g<id.length;g++)dd(n,id[g],ol,Qa,h);for(let g=0;g<ad.length;g++)dd(n,ad[g],sl,tl,f);Ya(ol,{tld:!0,ascii:!0},e),Ya(sl,{utld:!0,alpha:!0},e),dd(n,"file",il,Qa,h),dd(n,"mailto",il,Qa,h),dd(n,"http",al,Qa,h),dd(n,"https",al,Qa,h),dd(n,"ftp",al,Qa,h),dd(n,"ftps",al,Qa,h),Ya(il,{scheme:!0,ascii:!0},e),Ya(al,{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]?{[Wa]:!0}:{[Ua]:!0};e.indexOf("-")>=0?r[ja]=!0:ed.test(e)?od.test(e)?r[Da]=!0:r[za]=!0:r[Ba]=!0,Ja(n,e,e,r)}return Ja(n,"localhost",rl,{ascii:!0}),n.jd=new qa(Ql),{start:n,tokens:Object.assign({groups:e},td)}}(Sd.customSchemes);for(let t=0;t<Sd.tokenQueue.length;t++)Sd.tokenQueue[t][1]({scanner:Sd.scanner});Sd.parser=function({groups:t}){const e=t.domain.concat([Tl,El,Al,Ll,$l,Rl,Bl,Hl,_l,ll,jl,Fl,Wl,Ul,Gl,Ql,Vl,Jl]),n=[Cl,Nl,Ol,zl,Dl,jl,Kl,Xl,ql,yl,wl,ul,pl,fl,hl,gl,ml,xl,bl,kl,vl,Sl,Il,Pl,Ml],r=[Tl,Cl,El,Ll,$l,Rl,Bl,Hl,_l,ul,pl,jl,Fl,Wl,Ul,Kl,Gl,Ql,Vl,Jl],o=bd(),s=Za(o,Vl);Ga(s,r,s),Ga(s,t.domain,s);const i=bd(),a=bd(),l=bd();Ga(o,t.domain,i),Ga(o,t.scheme,a),Ga(o,t.slashscheme,l),Ga(i,r,s),Ga(i,t.domain,i);const d=Za(i,Al);Za(s,Al,d),Za(a,Al,d),Za(l,Al,d);const c=Za(s,zl);Ga(c,r,s),Ga(c,t.domain,s);const u=bd();Ga(d,t.domain,u),Ga(u,t.domain,u);const p=Za(u,zl);Ga(p,t.domain,u);const h=bd(md);Ga(p,t.tld,h),Ga(p,t.utld,h),Za(d,rl,h);const f=Za(u,_l);Za(f,_l,f),Ga(f,t.domain,u),Ga(h,t.domain,u),Za(h,zl,p),Za(h,_l,f);const g=Za(i,_l),m=Za(i,zl);Za(g,_l,g),Ga(g,t.domain,i),Ga(m,r,s),Ga(m,t.domain,i);const y=bd(xd);Ga(m,t.tld,y),Ga(m,t.utld,y),Ga(y,t.domain,i),Ga(y,r,s),Za(y,zl,m),Za(y,_l,g),Za(y,Al,d);const w=Za(y,Nl),x=bd(xd);Ga(w,t.numeric,x);const b=bd(xd),k=bd();Ga(b,e,b),Ga(b,n,k),Ga(k,e,b),Ga(k,n,k),Za(y,Gl,b),Za(x,Gl,b);const v=Za(a,Nl),S=Za(Za(Za(l,Nl),Gl),Gl);Ga(a,t.domain,i),Za(a,zl,m),Za(a,_l,g),Ga(l,t.domain,i),Za(l,zl,m),Za(l,_l,g),Ga(v,t.domain,b),Za(v,Gl,b),Za(v,Kl,b),Ga(S,t.domain,b),Ga(S,e,b),Za(S,Gl,b);const I=[[ul,pl],[hl,fl],[gl,ml],[yl,wl],[xl,bl],[kl,vl],[Sl,Il],[Pl,Ml]];for(let P=0;P<I.length;P++){const[t,r]=I[P],o=Za(b,t);Za(k,t,o);const s=bd(xd);Ga(o,e,s);const i=bd();Ga(o,n,i),Za(o,r,b),Ga(s,e,s),Ga(s,n,i),Ga(i,e,s),Ga(i,n,i),Za(s,r,b),Za(i,r,b)}return Za(o,rl,y),Za(o,cl,wd),{start:o,tokens:td}}(Sd.scanner.tokens);for(let t=0;t<Sd.pluginQueue.length;t++)Sd.pluginQueue[t][1]({scanner:Sd.scanner,parser:Sd.parser});return Sd.initialized=!0,Sd}function Md(t){return Sd.initialized||Pd(),function(t,e,n){let r=n.length,o=0,s=[],i=[];for(;o<r;){let a=t,l=null,d=null,c=0,u=null,p=-1;for(;o<r&&!(l=a.go(n[o].t));)i.push(n[o++]);for(;o<r&&(d=l||a.go(n[o].t));)l=null,a=d,a.accepts()?(p=0,u=a):p>=0&&p++,o++,c++;if(p<0)o-=c,o<r&&(i.push(n[o]),o++);else{i.length>0&&(s.push(kd(yd,e,i)),i=[]),o-=p,c-=p;const t=u.t,r=n.slice(o-c,o);s.push(kd(t,e,r))}}return i.length>0&&s.push(kd(yd,e,i)),s}(Sd.parser.start,t,ld(Sd.scanner.start,t))}function Td(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 pd(n),o=Md(t),s=[];for(let i=0;i<o.length;i++){const t=o[i];!t.isLink||e&&t.t!==e||!r.check(t)||s.push(t.toFormattedObject(r))}return s}Md.scan=ld;var Cd="[\0- -\u2029 ]",Ed=new RegExp(Cd),Ad=new RegExp(`${Cd}$`),Ld=new RegExp(Cd,"g");function $d(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(Ld,"").match(new RegExp(`^(?:(?:${n.map(t=>t.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")).join("|")}):|[^a-z]|[a-z0-9+.\\-]+(?:[^a-z+.\\-:]|$))`,"i"))}var Rd=gt.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?Id(t.scheme,t.optionalSlashes):Id(t)})},onDestroy(){qa.groups={},Sd.scanner=null,Sd.parser=null,Sd.tokenQueue=[],Sd.pluginQueue=[],Sd.customSchemes=[],Sd.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)=>!!$d(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=>!!$d(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol}))&&null}}]},renderHTML({HTMLAttributes:t}){return this.options.isAllowedUri(t.href,{defaultValidate:t=>!!$d(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",zt(this.options.HTMLAttributes,t),0]:["a",zt(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,s;const i=null!=(r=null==(n=t.attrs)?void 0:n.href)?r:"",a=null!=(s=null==(o=t.attrs)?void 0:o.title)?s:"",l=e.renderChildren(t);return a?`[${l}](${i} "${a}")`:`[${l}](${i})`},addCommands(){return{setLink:t=>({chain:e})=>{const{href:n}=t;return!!this.options.isAllowedUri(n,{defaultValidate:t=>!!$d(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=>!!$d(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[Bt({find:t=>{const e=[];if(t){const{protocols:n,defaultProtocol:r}=this.options,o=Td(t).filter(t=>t.isLink&&this.options.isAllowedUri(t.value,{defaultValidate:t=>!!$d(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=>!!$d(t,e),protocols:e,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink},new Kt({key:new Xt("autolink"),appendTransaction:(t,e,n)=>{const o=t.some(t=>t.docChanged)&&!e.doc.eq(n.doc),s=t.some(t=>t.getMeta("preventAutolink"));if(!o||s)return;const{tr:i}=n;return St(xt(e.doc,[...t])).forEach(({newRange:t})=>{const e=kt(n.doc,t,t=>t.isTextblock);let o,s;if(e.length>1)o=e[0],s=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(!Ad.test(r))return;o=e[0],s=n.doc.textBetween(o.pos,t.to,void 0," ")}if(o&&s){const t=s.split(Ed).filter(Boolean);if(t.length<=0)return!1;const e=t[t.length-1],l=o.pos+s.lastIndexOf(e);if(!e)return!1;const d=Md(e).map(t=>t.toObject(r.defaultProtocol));if(!(1===(a=d).length?a[0].isLink:3===a.length&&a[1].isLink&&["()","[]"].includes(a[0].value+a[2].value)))return!1;d.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=>{Pt(t.from,t.to,n.doc).some(t=>t.mark.type===r.type)||i.addMark(t.from,t.to,r.type.create({href:t.href}))})}var a}),i.steps.length?i:void 0}}))),t.push(function(t){return new Kt({key:new Xt("handleClickLink"),props:{handleClick:(e,n,r)=>{var o,s;if(0!==r.button)return!1;if(!e.editable)return!1;let i=null;if(r.target instanceof HTMLAnchorElement)i=r.target;else{const e=r.target;if(!e)return!1;const n=t.editor.view.dom;i=e.closest("a"),i&&!n.contains(i)&&(i=null)}if(!i)return!1;let a=!1;if(t.enableClickSelection&&(a=t.editor.commands.extendMarkRange(t.type.name)),t.openOnClick){const n=vt(e.state,t.type.name),r=null!=(o=i.href)?o:n.href,l=null!=(s=i.target)?s: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 Kt({key:new Xt("handlePasteLink"),props:{handlePaste:(e,n,r)=>{const{shouldAutoLink:o}=t,{state:s}=e,{selection:i}=s,{empty:a}=i;if(a)return!1;let l="";r.content.forEach(t=>{l+=t.textContent});const d=Td(l,{defaultProtocol:t.defaultProtocol}).find(t=>t.isLink&&t.value===l);return!(!l||!d||void 0!==o&&!o(d.value))&&t.editor.commands.setMark(t.type,{href:d.href})}}})}({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),t}}),Nd=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Od=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,Bd=gt.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",zt(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[Ot({find:Nd,type:this.type})]},addPasteRules(){return[Bt({find:Od,type:this.type})]}}),zd=ft.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")}}}),Hd=(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(...Hd(t,e+1))}),n},Dd=gt.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=Hd(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",zt(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}}}}),_d=ft.create({name:"backgroundColor",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{backgroundColor:{default:null,parseHTML:t=>{var e;const n=null!=(e=Et(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()})}),jd=ft.create({name:"color",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{color:{default:null,parseHTML:t=>{var e;const n=null!=(e=Et(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()})}),Fd=ft.create({name:"fontFamily",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{fontFamily:{default:null,parseHTML:t=>{var e;return null!=(e=Et(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()})}),Wd=ft.create({name:"fontSize",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{fontSize:{default:null,parseHTML:t=>{var e;return null!=(e=Et(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()})}),Ud=ft.create({name:"lineHeight",addOptions:()=>({types:["textStyle"]}),addGlobalAttributes(){return[{types:this.options.types,attributes:{lineHeight:{default:null,parseHTML:t=>{var e;return null!=(e=Et(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()})}),Kd=(ft.create({name:"textStyleKit",addExtensions(){const t=[];return!1!==this.options.backgroundColor&&t.push(_d.configure(this.options.backgroundColor)),!1!==this.options.color&&t.push(jd.configure(this.options.color)),!1!==this.options.fontFamily&&t.push(Fd.configure(this.options.fontFamily)),!1!==this.options.fontSize&&t.push(Wd.configure(this.options.fontSize)),!1!==this.options.lineHeight&&t.push(Ud.configure(this.options.lineHeight)),!1!==this.options.textStyle&&t.push(Dd.configure(this.options.textStyle)),t}}),gt.create({name:"underline",addOptions:()=>({HTMLAttributes:{}}),parseHTML:()=>[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:t=>!!t.includes("underline")&&{}}],renderHTML({HTMLAttributes:t}){return["u",zt(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()}}})),Xd=ft.create({name:"selection",addOptions:()=>({className:"selection"}),addProseMirrorPlugins(){const{editor:t,options:e}=this;return t.options.injectCSS&&"undefined"!=typeof document&&bt(".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 Kt({key:new Xt("selection"),props:{decorations:n=>n.selection.empty||t.isFocused||!t.isEditable||Nt(n.selection)||t.view.dragging?null:Vt.create(n.doc,[Gt.inline(n.selection.from,n.selection.to,{class:e.className})])}})]}});function Yd(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),s=e.child(r);if(o!=s){if(!o.sameMarkup(s))return n;if(o.isText&&o.text!=s.text){let t=o.text,e=s.text,r=0;for(;t[r]==e[r];r++)n++;return r&&r<t.length&&r<e.length&&Vd(t.charCodeAt(r-1))&&Gd(t.charCodeAt(r))&&n--,n}if(o.content.size||s.content.size){let t=Yd(o.content,s.content,n+1);if(null!=t)return t}n+=o.nodeSize}else n+=o.nodeSize}}function qd(t,e,n,r){for(let o=t.childCount,s=e.childCount;;){if(0==o||0==s)return o==s?null:{a:n,b:r};let i=t.child(--o),a=e.child(--s),l=i.nodeSize;if(i!=a){if(!i.sameMarkup(a))return{a:n,b:r};if(i.isText&&i.text!=a.text){let t=i.text,e=a.text,o=t.length,s=e.length;for(;o>0&&s>0&&t[o-1]==e[s-1];)o--,s--,n--,r--;return o&&s&&o<t.length&&Vd(t.charCodeAt(o-1))&&Gd(t.charCodeAt(o))&&(n++,r++),{a:n,b:r}}if(i.content.size||a.content.size){let t=qd(i.content,a.content,n-1,r-1);if(t)return t}n-=l,r-=l}else n-=l,r-=l}}function Gd(t){return t>=56320&&t<57344}function Vd(t){return t>=55296&&t<56320}var Jd=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 s=0,i=0;i<e;s++){let a=this.content[s],l=i+a.nodeSize;if(l>t&&!1!==n(a,r+i,o||null,s)&&a.content.size){let o=i+1;a.nodesBetween(Math.max(0,t-o),Math.min(a.content.size,e-o),n,r+o)}i=l}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,e,n,r){let o="",s=!0;return this.nodesBetween(t,e,(i,a)=>{let l=i.isText?i.text.slice(Math.max(t,a)-a,e-a):i.isLeaf?r?"function"==typeof r?r(i):r:i.type.spec.leafText?i.type.spec.leafText(i):"":"";i.isBlock&&(i.isLeaf&&l||i.isTextblock)&&n&&(s?s=!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(),s=0;for(n.isText&&n.sameMarkup(r)&&(o[o.length-1]=n.withText(n.text+r.text),s=1);s<e.content.length;s++)o.push(e.content[s]);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,s=0;s<n;t++){let i=this.content[t],a=s+i.nodeSize;a>e&&((s<e||a>n)&&(i=i.isText?i.cut(Math.max(0,e-s),Math.min(i.text.length,n-s)):i.cut(Math.max(0,e-s-1),Math.min(i.content.size,n-s-1))),r.push(i),o+=i.nodeSize),s=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(),s=this.size+n.nodeSize-r.nodeSize;return o[e]=n,new t(o,s)}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 Yd(this,t,e)}findDiffEnd(t,e=this.size,n=t.size){return qd(this,t,e,n)}findIndex(t){if(0==t)return Qd(0,t);if(t==this.size)return Qd(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?Qd(e+1,r):Qd(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)":""))}};Jd.empty=new Jd([],0);var Zd={index:0,offset:0};function Qd(t,e){return Zd.index=t,Zd.offset=e,Zd}function tc(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(!tc(t[n],e[n]))return!1}else{for(let n in t)if(!(n in e)||!tc(t[n],e[n]))return!1;for(let n in e)if(!(n in t))return!1}return!0}var ec=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&&tc(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}};ec.none=[];var nc=class extends Error{},rc=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=sc(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(oc(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(Jd.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 oc(t,e,n){let{index:r,offset:o}=t.findIndex(e),s=t.maybeChild(r),{index:i,offset:a}=t.findIndex(n);if(o==e||s.isText){if(a!=n&&!t.child(i).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=i)throw new RangeError("Removing non-flat range");return t.replaceChild(r,s.copy(oc(s.content,e-o-1,n-o-1)))}function sc(t,e,n,r,o,s){let{index:i,offset:a}=t.findIndex(e),l=t.maybeChild(i);if(a==e||l.isText)return s&&r<=0&&o<=0&&!s.canReplace(i,i,n)?null:t.cut(0,e).append(n).append(t.cut(e));let d=sc(l.content,e-a-1,n,0==i?r-1:0,i==t.childCount-1?o-1:0,l);return d&&t.replaceChild(i,l.copy(d))}rc.empty=new rc(Jd.empty,0,0);var ic=class t{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new ac(e,n);if(null==r.next)return t.empty;let o=lc(r);r.next&&r.err("Unexpected trailing text");let s=function(t){let e=Object.create(null);return n(fc(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]);fc(t,n).forEach(t=>{r||o.push([e,r=[]]),-1==r.indexOf(t)&&r.push(t)})})});let s=e[r.join(",")]=new ic(r.indexOf(t.length-1)>-1);for(let t=0;t<o.length;t++){let r=o[t][1].sort(hc);s.next.push({type:o[t][0],next:e[r.join(",")]||n(r)})}return s}}(function(t){let e=[[]];return o(s(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 s(t,e){if("choice"==t.type)return t.exprs.reduce((t,n)=>t.concat(s(n,e)),[]);if("seq"!=t.type){if("star"==t.type){let i=n();return r(e,i),o(s(t.expr,i),i),[r(i)]}if("plus"==t.type){let i=n();return o(s(t.expr,e),i),o(s(t.expr,i),i),[r(i)]}if("opt"==t.type)return[r(e)].concat(s(t.expr,e));if("range"==t.type){let i=e;for(let e=0;e<t.min;e++){let e=n();o(s(t.expr,i),e),i=e}if(-1==t.max)o(s(t.expr,i),i);else for(let e=t.min;e<t.max;e++){let e=n();r(i,e),o(s(t.expr,i),e),i=e}return[r(i)]}if("name"==t.type)return[r(e,void 0,t.value)];throw new Error("Unknown expr type")}for(let r=0;;r++){let i=s(t.exprs[r],e);if(r==t.exprs.length-1)return i;o(i,e=n())}}}(o));return function(t,e){for(let n=0,r=[t];n<r.length;n++){let t=r[n],o=!t.validEnd,s=[];for(let e=0;e<t.next.length;e++){let{type:n,next:i}=t.next[e];s.push(n.name),!o||n.isText||n.hasRequiredAttrs()||(o=!1),-1==r.indexOf(i)&&r.push(i)}o&&e.err("Only non-generatable nodes ("+s.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}(s,r),s}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(s,i){let a=s.matchFragment(t,n);if(a&&(!e||a.validEnd))return Jd.from(i.map(t=>t.createAndFill()));for(let t=0;t<s.next.length;t++){let{type:e,next:n}=s.next[t];if(!e.isText&&!e.hasRequiredAttrs()&&-1==r.indexOf(n)){r.push(n);let t=o(n,i.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:s,next:i}=o.next[t];s.isLeaf||s.hasRequiredAttrs()||s.name in e||r.type&&!i.validEnd||(n.push({match:s.contentMatch,type:s,via:r}),e[s.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")}};ic.empty=new ic(!0);var ac=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 lc(t){let e=[];do{e.push(dc(t))}while(t.eat("|"));return 1==e.length?e[0]:{type:"choice",exprs:e}}function dc(t){let e=[];do{e.push(cc(t))}while(t.next&&")"!=t.next&&"|"!=t.next);return 1==e.length?e[0]:{type:"seq",exprs:e}}function cc(t){let e=function(t){if(t.eat("(")){let e=lc(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 s in n){let t=n[s];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=pc(t,e)}return e}function uc(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function pc(t,e){let n=uc(t),r=n;return t.eat(",")&&(r="}"!=t.next?uc(t):-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function hc(t,e){return e-t}function fc(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:s}=o[t];r||-1!=n.indexOf(s)||e(s)}}(e),n.sort(hc)}var gc=Math.pow(2,16);function mc(t,e){return t+e*gc}function yc(t){return 65535&t}var wc=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}},xc=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=yc(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))/gc}(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,s=this.inverted?1:2;for(let i=0;i<this.ranges.length;i+=3){let a=this.ranges[i]-(this.inverted?r:0);if(a>t)break;let l=this.ranges[i+o],d=this.ranges[i+s],c=a+l;if(t<=c){let o=a+r+((l?t==a?-1:t==c?1:e:e)<0?0:d);if(n)return o;let s=t==(e<0?a:c)?null:mc(i/3,t-a),u=t==a?2:t==c?1:4;return(e<0?t!=a:t!=c)&&(u|=8),new wc(o,u,s)}r+=d-l}return n?t+r:new wc(t+r,0,null)}touches(t,e){let n=0,r=yc(e),o=this.inverted?2:1,s=this.inverted?1:2;for(let i=0;i<this.ranges.length;i+=3){let e=this.ranges[i]-(this.inverted?n:0);if(e>t)break;let a=this.ranges[i+o];if(t<=e+a&&i==3*r)return!0;n+=this.ranges[i+s]-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 s=this.ranges[r],i=s-(this.inverted?o:0),a=s+(this.inverted?0:o),l=this.ranges[r+e],d=this.ranges[r+n];t(i,i+l,a,a+d),o+=d-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])}};xc.empty=new xc([]);var bc=Object.create(null),kc=class{getMap(){return xc.empty}merge(t){return null}static fromJSON(t,e){if(!e||!e.stepType)throw new RangeError("Invalid input for Step.fromJSON");let n=bc[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 bc)throw new RangeError("Duplicate use of step JSON ID "+t);return bc[t]=e,e.prototype.jsonID=t,e}},vc=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(De){if(De instanceof nc)return t.fail(De.message);throw De}}};function Sc(t,e,n){let r=[];for(let o=0;o<t.childCount;o++){let s=t.child(o);s.content.size&&(s=s.copy(Sc(s.content,e,s))),s.isInline&&(s=e(s,n,o)),r.push(s)}return Jd.fromArray(r)}var Ic=class t extends kc{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 rc(Sc(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 vc.fromReplace(t,this.from,this.to,o)}invert(){return new Pc(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))}};kc.jsonID("addMark",Ic);var Pc=class t extends kc{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 rc(Sc(e.content,t=>t.mark(this.mark.removeFromSet(t.marks)),t),e.openStart,e.openEnd);return vc.fromReplace(t,this.from,this.to,n)}invert(){return new Ic(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))}};kc.jsonID("removeMark",Pc);var Mc=class t extends kc{constructor(t,e){super(),this.pos=t,this.mark=e}apply(t){let e=t.nodeAt(this.pos);if(!e)return vc.fail("No node at mark step's position");let n=e.type.create(e.attrs,null,this.mark.addToSet(e.marks));return vc.fromReplace(t,this.pos,this.pos+1,new rc(Jd.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 Tc(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))}};kc.jsonID("addNodeMark",Mc);var Tc=class t extends kc{constructor(t,e){super(),this.pos=t,this.mark=e}apply(t){let e=t.nodeAt(this.pos);if(!e)return vc.fail("No node at mark step's position");let n=e.type.create(e.attrs,null,this.mark.removeFromSet(e.marks));return vc.fromReplace(t,this.pos,this.pos+1,new rc(Jd.from(n),0,e.isLeaf?0:1))}invert(t){let e=t.nodeAt(this.pos);return e&&this.mark.isInSet(e.marks)?new Mc(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))}};kc.jsonID("removeNodeMark",Tc);var Cc=class t extends kc{constructor(t,e,n,r=!1){super(),this.from=t,this.to=e,this.slice=n,this.structure=r}apply(t){return this.structure&&Ac(t,this.from,this.to)?vc.fail("Structure replace would overwrite content"):vc.fromReplace(t,this.from,this.to,this.slice)}getMap(){return new xc([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?rc.empty:new rc(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?rc.empty:new rc(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,rc.fromJSON(e,n.slice),!!n.structure)}};Cc.MAP_BIAS=1,kc.jsonID("replace",Cc);var Ec=class t extends kc{constructor(t,e,n,r,o,s,i=!1){super(),this.from=t,this.to=e,this.gapFrom=n,this.gapTo=r,this.slice=o,this.insert=s,this.structure=i}apply(t){if(this.structure&&(Ac(t,this.from,this.gapFrom)||Ac(t,this.gapTo,this.to)))return vc.fail("Structure gap-replace would overwrite content");let e=t.slice(this.gapFrom,this.gapTo);if(e.openStart||e.openEnd)return vc.fail("Gap is not a flat range");let n=this.slice.insertAt(this.insert,e.content);return n?vc.fromReplace(t,this.from,this.to,n):vc.fail("Content does not fit in gap")}getMap(){return new xc([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),s=this.to==this.gapTo?r.pos:e.map(this.gapTo,1);return n.deletedAcross&&r.deletedAcross||o<n.pos||s>r.pos?null:new t(n.pos,r.pos,o,s,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,rc.fromJSON(e,n.slice),n.insert,!!n.structure)}};function Ac(t,e,n){let r=t.resolve(e),o=n-e,s=r.depth;for(;o>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,o--;if(o>0){let t=r.node(s).maybeChild(r.indexAfter(s));for(;o>0;){if(!t||t.isLeaf)return!0;t=t.firstChild,o--}}return!1}kc.jsonID("replaceAround",Ec);kc.jsonID("attr",class t extends kc{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 vc.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 vc.fromReplace(t,this.pos,this.pos+1,new rc(Jd.from(r),0,e.isLeaf?0:1))}getMap(){return xc.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)}});kc.jsonID("docAttr",class t extends kc{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 vc.ok(n)}getMap(){return xc.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 Lc=Error;((Lc=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n}).prototype=Object.create(Error.prototype)).constructor=Lc,Lc.prototype.name="TransformError";var $c=Object.create(null),Rc=class{constructor(t,e,n){this.$anchor=t,this.$head=e,this.ranges=n||[new Nc(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=rc.empty){let n=e.content.lastChild,r=null;for(let i=0;i<e.openEnd;i++)r=n,n=n.lastChild;let o=t.steps.length,s=this.ranges;for(let i=0;i<s.length;i++){let{$from:a,$to:l}=s[i],d=t.mapping.slice(o);t.replaceRange(d.map(a.pos),d.map(l.pos),i?rc.empty:e),0==i&&Uc(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:s,$to:i}=r[o],a=t.mapping.slice(n),l=a.map(s.pos),d=a.map(i.pos);o?t.deleteRange(l,d):(t.replaceRangeWith(l,d,e),Uc(t,n,e.isInline?-1:1))}}static findFrom(t,e,n=!1){let r=t.parent.inlineContent?new zc(t):Wc(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?Wc(t.node(0),t.node(o),t.before(o+1),t.index(o),e,n):Wc(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 jc(t.node(0))}static atStart(t){return Wc(t,t,0,0,1)||new jc(t)}static atEnd(t){return Wc(t,t,t.content.size,t.childCount,-1)||new jc(t)}static fromJSON(t,e){if(!e||!e.type)throw new RangeError("Invalid input for Selection.fromJSON");let n=$c[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 $c)throw new RangeError("Duplicate use of selection JSON ID "+t);return $c[t]=e,e.prototype.jsonID=t,e}getBookmark(){return zc.between(this.$anchor,this.$head).getBookmark()}};Rc.prototype.visible=!0;var Nc=class{constructor(t,e){this.$from=t,this.$to=e}},Oc=!1;function Bc(t){Oc||t.parent.inlineContent||(Oc=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}var zc=class t extends Rc{constructor(t,e=t){Bc(t),Bc(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 Rc.near(r);let o=e.resolve(n.map(this.anchor));return new t(o.parent.inlineContent?o:r,r)}replace(t,e=rc.empty){if(super.replace(t,e),e==rc.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 Hc(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=Rc.findFrom(n,r,!0)||Rc.findFrom(n,-r,!0);if(!t)return Rc.near(n,r);n=t.$head}return e.parent.inlineContent||(0==o||(e=(Rc.findFrom(e,-r,!0)||Rc.findFrom(e,r,!0)).$anchor).pos<n.pos!=o<0)&&(e=n),new t(e,n)}};Rc.jsonID("text",zc);var Hc=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 zc.between(t.resolve(this.anchor),t.resolve(this.head))}},Dc=class t extends Rc{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),s=e.resolve(o);return r?Rc.near(s):new t(s)}content(){return new rc(Jd.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 _c(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}};Dc.prototype.visible=!1,Rc.jsonID("node",Dc);var _c=class t{constructor(t){this.anchor=t}map(e){let{deleted:n,pos:r}=e.mapResult(this.anchor);return n?new Hc(r,r):new t(r)}resolve(t){let e=t.resolve(this.anchor),n=e.nodeAfter;return n&&Dc.isSelectable(n)?new Dc(e):Rc.near(e)}},jc=class t extends Rc{constructor(t){super(t.resolve(0),t.resolve(t.content.size))}replace(t,e=rc.empty){if(e==rc.empty){t.delete(0,t.doc.content.size);let e=Rc.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 Fc}};Rc.jsonID("all",jc);var Fc={map(){return this},resolve:t=>new jc(t)};function Wc(t,e,n,r,o,s=!1){if(e.inlineContent)return zc.create(t,n);for(let i=r-(o>0?0:1);o>0?i<e.childCount:i>=0;i+=o){let r=e.child(i);if(r.isAtom){if(!s&&Dc.isSelectable(r))return Dc.create(t,n-(o<0?r.nodeSize:0))}else{let e=Wc(t,r,n+o,o<0?r.childCount:0,o,s);if(e)return e}n+=r.nodeSize*o}return null}function Uc(t,e,n){let r=t.steps.length-1;if(r<e)return;let o,s=t.steps[r];(s instanceof Cc||s instanceof Ec)&&(t.mapping.maps[r].forEach((t,e,n,r)=>{null==o&&(o=r)}),t.setSelection(Rc.near(t.doc.resolve(o),n)))}function Kc(t,e){return e&&t?t.bind(e):t}var Xc=class{constructor(t,e,n){this.name=t,this.init=Kc(e.init,n),this.apply=Kc(e.apply,n)}};new Xc("doc",{init:t=>t.doc||t.schema.topNodeType.createAndFill(),apply:t=>t.doc}),new Xc("selection",{init:(t,e)=>t.selection||Rc.atStart(e.doc),apply:t=>t.selection}),new Xc("storedMarks",{init:t=>t.storedMarks||null,apply:(t,e,n,r)=>r.selection.$cursor?t.storedMarks:null}),new Xc("scrollToSelection",{init:()=>0,apply:(t,e)=>t.scrolledIntoView?e+1:e});var Yc=/^\s*>\s$/,qc=mt.create({name:"blockquote",addOptions:()=>({HTMLAttributes:{}}),content:"block+",group:"block",defining:!0,parseHTML:()=>[{tag:"blockquote"}],renderHTML({HTMLAttributes:t}){
|
|
12
|
+
return Wt("blockquote",{...zt(this.options.HTMLAttributes,t),children:Wt("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,s;const i=(null!=(s=null==(o=e.renderChild)?void 0:o.call(e,t,r))?s:e.renderChildren([t])).split("\n").map(t=>""===t.trim()?">":`> ${t}`);n.push(i.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:s}=r;if(!s.empty)return!1;const{$from:i}=s;if(0!==i.parentOffset)return!1;const a=i.depth-1,l=i.node(a),d=i.index(a);if(0===d)return!1;if(l.type===e)return t.commands.lift(e.name);const c=l.child(d-1);if(c.type!==e||!(null==(n=c.lastChild)?void 0:n.isTextblock))return!1;const u=i.before(),p=u-1-1,{tr:h}=r;return h.delete(u,i.after()).insert(p,i.parent.content),h.setSelection(zc.create(h.doc,p)),o.dispatch(h.scrollIntoView()),!0})(this.editor,this.type)}},addInputRules(){return[Ft({find:Yc,type:this.type})]}}),Gc=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},Vc=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},Jc=gt.create({name:"code",addOptions:()=>({HTMLAttributes:{}}),excludes:"_",code:!0,exitable:!0,parseHTML:()=>[{tag:"code"}],renderHTML({HTMLAttributes:t}){return["code",zt(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[Ot({find:Gc,type:this.type})]},addPasteRules(){return[Bt({find:Vc,type:this.type})]}}),Zc=/^```([a-z]+)?[\s\n]$/,Qc=/^~~~([a-z]+)?[\s\n]$/,tu=mt.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",zt(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:s,empty:i}=o;if(s.parent.type!==this.type)return!1;const a=" ".repeat(n);return i?t.commands.insertContent(a):t.commands.command(({tr:t})=>{const{from:e,to:n}=o,s=r.doc.textBetween(e,n,"\n","\n").split("\n").map(t=>a+t).join("\n");return t.replaceWith(e,n,r.schema.text(s)),!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:s,empty:i}=o;return s.parent.type===this.type&&(i?t.commands.command(({tr:t})=>{var e;const{pos:o}=s,i=s.start(),a=s.end(),l=r.doc.textBetween(i,a,"\n","\n").split("\n");let d=0,c=0;const u=o-i;for(let n=0;n<l.length;n+=1){if(c+l[n].length>=u){d=n;break}c+=l[n].length+1}const p=(null==(e=l[d].match(/^ */))?void 0:e[0])||"",h=Math.min(p.length,n);if(0===h)return!0;let f=i;for(let n=0;n<d;n+=1)f+=l[n].length+1;return t.delete(f,f+h),o-f<=h&&t.setSelection(qt.create(t.doc,f)),!0}):t.commands.command(({tr:t})=>{const{from:e,to:s}=o,i=r.doc.textBetween(e,s,"\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,s,r.schema.text(i)),!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 s=r.parentOffset===r.parent.nodeSize-2,i=r.parent.textContent.endsWith("\n\n");return!(!s||!i)&&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:s}=n;if(!s||o.parent.type!==this.type)return!1;if(o.parentOffset!==o.parent.nodeSize-2)return!1;const i=o.after();return void 0!==i&&(r.nodeAt(i)?t.commands.command(({tr:t})=>(t.setSelection(Yt.near(r.resolve(i))),!0)):t.commands.exitCode())}}},addInputRules(){return[jt({find:Zc,type:this.type,getAttributes:t=>({language:t[1]})}),jt({find:Qc,type:this.type,getAttributes:t=>({language:t[1]})})]},addProseMirrorPlugins(){return[new Kt({key:new Xt("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,s=null==o?void 0:o.mode;if(!n||!s)return!1;const{tr:i,schema:a}=t.state,l=a.text(n.replace(/\r\n?/g,"\n"));return i.replaceSelectionWith(this.type.create({language:s},l)),i.selection.$from.parent.type!==this.type&&i.setSelection(qt.near(i.doc.resolve(Math.max(0,i.selection.from-2)))),i.setMeta("paste",!0),t.dispatch(i),!0}}})]}}),eu=mt.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(t,e)=>t.content?e.renderChildren(t.content,"\n\n"):""}),nu=mt.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",zt(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:s}=this.options,{splittableMarks:i}=r.extensionManager,a=o||t.$to.parentOffset&&t.$from.marks();return e().insertContent({type:this.name}).command(({tr:t,dispatch:e})=>{if(e&&a&&s){const e=a.filter(t=>i.includes(t.type.name));t.ensureMarks(e)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),ru=mt.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]}`,zt(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=>jt({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${t}})\\s$`),type:this.type,getAttributes:{level:t}}))}}),ou=mt.create({name:"horizontalRule",addOptions:()=>({HTMLAttributes:{},nextNodeType:"paragraph"}),group:"block",parseHTML:()=>[{tag:"hr"}],renderHTML({HTMLAttributes:t}){return["hr",zt(this.options.HTMLAttributes,t)]},markdownTokenName:"hr",parseMarkdown:(t,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:t,state:e})=>{if(!wt(e,e.schema.nodes[this.name]))return!1;const{selection:n}=e,{$to:r}=n,o=t();return Nt(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(qt.create(e.doc,n.pos+1)):n.nodeAfter.isBlock?e.setSelection(Ut.create(e.doc,n.pos)):e.setSelection(qt.create(e.doc,n.pos));else{const o=t.schema.nodes[this.options.nextNodeType]||n.parent.type.contentMatch.defaultType,s=null==o?void 0:o.create();s&&(e.insert(r,s),e.setSelection(qt.create(e.doc,r+1)))}e.scrollIntoView()}return!0}).run()}}},addInputRules(){return[Ht({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),su=Object.defineProperty,iu="textStyle",au=/^\s*([-+*])\s$/,lu=mt.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",zt(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(iu)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let t=Ft({find:au,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(t=Ft({find:au,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(iu),editor:this.editor})),[t]}}),du=(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 s=-1;for(let h=o.depth;h>0;h-=1)if(o.node(h).type.name===e){s=h;break}if(s<0)return null;const i=o.node(s),a=o.index(s);if(a+1>=i.childCount)return null;const l=i.child(a+1);if(!n.includes(l.type.name))return null;const d=t.schema.nodes[e];let c=!1;if(l.forEach(t=>{t.type===d&&t.childCount>1&&(c=!0)}),!c)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:s,nestedList:u,nestedListPos:o.after(),insertPos:o.after(s),items:p}})(t,n,r);if(!o)return!1;const{selection:s}=t,{nestedList:i,nestedListPos:a,insertPos:l,items:d}=o,c=t.tr;c.delete(a,a+i.nodeSize);const u=c.mapping.map(l);return c.insert(u,Jt.from(d)),c.setSelection(s.map(c.doc,c.mapping)),e&&e(c),!0})(t.state,t.view.dispatch,e,n),cu=(t,e)=>ft.create({name:`${t}BranchingDeleteKeymap`,priority:101,addKeyboardShortcuts(){const n=()=>du(this.editor,t,e);return{Delete:n,"Mod-Delete":n}}}),uu=[[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"]],pu="abcdefghijklmnopqrstuvwxyz",hu=String.raw`\d+|[ivxlcdmIVXLCDM]+|${"[a-zA-Z]{1,2}"}`;function fu(t){let e=t,n="";for(const[r,o]of uu)for(;e>=r;)n+=o,e-=r;return n}function gu(t){return fu(t).toUpperCase()}function mu(t){const e=t.toLowerCase();let n=0,r=0;for(;n<e.length;){let t=!1;for(const[o,s]of uu)if(e.startsWith(s,n)){r+=o,n+=s.length,t=!0;break}if(!t)return 0}return r}function yu(t){if(t<=26)return pu[t-1];const e=Math.floor((t-1)/26)-1,n=(t-1)%26;return e<0?pu[n]:pu[e]+pu[n]}function wu(t){if(t&&!/^\d+$/.test(t))return function(t){if(!/^[ivxlcdmIVXLCDM]+$/.test(t))return!1;const e=mu(t);return!(e<=0)&&(t===t.toLowerCase()?fu(e):gu(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 xu(t){if(/^\d+$/.test(t))return parseInt(t,10);const e=wu(t);if("i"===e||"I"===e)return mu(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 bu(t,e){if("numeric"===t)return String(e);switch(t){case"a":return yu(e);case"A":return yu(e).toUpperCase();case"i":return fu(e);case"I":return gu(e);default:return String(e)}}function ku(t){const{type:e,start:n}=function(t){return{type:wu(t),start:xu(t)}}(t),r={};return e&&(r.type=e),1!==n&&(r.start=n),r}function vu(t,e){return e.tokenizeInline?e.parseInline(e.tokenizeInline(t)):e.parseInline([{type:"text",raw:t,text:t}])}var Su=mt.create({name:"listItem",addOptions:()=>({HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}),content:"paragraph block*",defining:!0,parseHTML:()=>[{tag:"li"}],renderHTML({HTMLAttributes:t}){return["li",zt(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:vu(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)=>_t(t,e,t=>{var e,n,r,o;if("bulletList"===t.parentType)return"- ";if("orderedList"===t.parentType){const s=(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`${yu(r)}${n}`;case"A":return`${yu(r).toUpperCase()}${n}`;case"i":return`${fu(r)}${n}`;case"I":return`${gu(r)}${n}`;default:return`${r}${n}`}}(null==(o=null==(r=t.meta)?void 0:r.parentAttrs)?void 0:o.type,s-1+(t.index||0),". ")}return"- "},n),addExtensions(){return[cu(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)su(t,n,{get:e[n],enumerable:!0})})({},{findListItemPos:()=>Iu,getNextListDepth:()=>Pu,handleBackspace:()=>Tu,handleDelete:()=>Au,hasListBefore:()=>Mu,hasListItemAfter:()=>Lu,hasListItemBefore:()=>$u,listItemHasSubList:()=>Ru,nextListIsDeeper:()=>Cu,nextListIsHigher:()=>Eu});var Iu=(t,e)=>{const{$from:n}=e.selection,r=Tt(t,e.schema);let o=null,s=n.depth,i=n.pos,a=null;for(;s>0&&null===a;)o=n.node(s),o.type===r?a=s:(s-=1,i-=1);return null===a?null:{$pos:e.doc.resolve(i),depth:a}},Pu=(t,e)=>{const n=Iu(t,e);if(!n)return!1;const[,r]=Mt(e,t,n.$pos.pos+4);return r},Mu=(t,e,n)=>{const{$anchor:r}=t.selection,o=Math.max(0,r.pos-2),s=t.doc.resolve(o).node();return!(!s||!n.includes(s.type.name))},Tu=(t,e,n)=>{if(t.commands.undoInputRule())return!0;if(t.state.selection.from!==t.state.selection.to)return!1;if(!$t(t.state,e)&&Mu(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 s=o.at(-1);if(!s)return!1;const i=t.state.doc.resolve(r.start()+s.pos+1);return t.chain().cut({from:n.start()-1,to:n.end()+1},i.end()).joinForward().run()}return!!$t(t.state,e)&&(!!Lt(t.state)&&t.chain().liftListItem(e).run())},Cu=(t,e)=>{const n=Pu(t,e),r=Iu(t,e);return!(!r||!n)&&n>r.depth},Eu=(t,e)=>{const n=Pu(t,e),r=Iu(t,e);return!(!r||!n)&&n<r.depth},Au=(t,e)=>{if(!$t(t.state,e))return!1;if(!At(t.state,e))return!1;const{selection:n}=t.state,{$from:r,$to:o}=n;return!(!n.empty&&r.sameParent(o))&&(Cu(e,t.state)?t.chain().focus(t.state.selection.from+4).lift(e).joinBackward().run():Eu(e,t.state)?t.chain().joinForward().joinBackward().run():t.commands.joinItemForward())},Lu=(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},$u=(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},Ru=(t,e,n)=>{if(!n)return!1;const r=Tt(t,e.schema);let o=!1;return n.descendants(t=>{t.type===r&&(o=!0)}),o},Nu=ft.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]&&Au(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]&&Au(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]&&Tu(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]&&Tu(t,n,r)&&(e=!0)}),e}}}}),Ou=new RegExp(`^(\\s*)(${hu})([.)])\\s+(.*)$`),Bu=new RegExp(`^(\\s*)(${hu})([.)])\\s+`),zu=/^\s/,Hu={heading:/^#{1,6}(?:\s|$)/,bulletItem:/^[-+*]\s+/,codeFence:/^(?:```|~~~)/,thematicBreak:/^(?:(?:-[ \t]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})$/};function Du(t){const e=t.trimStart();return Hu.bulletItem.test(e)||function(t){return Ou.test(t.trimStart())}(e)||Hu.heading.test(e)||Hu.thematicBreak.test(e)&&!e.startsWith("-")||/^>\s?/.test(e)||Hu.codeFence.test(e)}function _u(t){return Object.values(Hu).some(e=>e.test(t))}function ju(t){const e=[],n=[];let r=!1;return t.forEach(t=>{if(!r)return""===t.trim()||e.length>0&&Du(t)?(r=!0,void n.push(t)):void e.push(t);n.push(t)}),{paragraphLines:e,blockLines:n}}var Fu=new RegExp(`^(${hu})([.)])\\s+(.+)$`);function Wu(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(Fu);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=wu(t[0]))?e:"numeric",r=xu(t[0]);if(r<1)return!1;for(let o=0;o<t.length;o++){const e=bu(n,r+o);if(t[o]!==e)return!1}return!0}(n.map(t=>t.marker))?{type:"orderedList",attrs:ku(n[0].marker),content:n.map(t=>({type:"listItem",content:[{type:"paragraph",content:[{type:"text",text:t.content}]}]}))}:null}function Uu(t,e,n){const r=[];let o=0;for(;o<t.length;){const s=t[o];if(s.indent===e){const{paragraphLines:i,blockLines:a}=ju(s.contentLines),l=i.join("\n").trim(),d=[];l&&d.push({type:"paragraph",raw:l,tokens:n.inlineTokens(l)});const c=a.join("\n").trim();if(c){const t=n.blockTokens(c);d.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=Uu(p,Math.min(...p.map(t=>t.indent)),n);d.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:s.raw,tokens:d}),o=u}else o+=1}return r}var Ku="textStyle",Xu=/^(\d+)\.\s$/;function Yu(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 qu=mt.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=Yu(n);if(t)return t}const r=t.querySelector("li");if(r){const t=r.getAttribute("style");if(t){const e=Yu(t);if(e)return e}}return null}}}),parseHTML:()=>[{tag:"ol"}],renderHTML({HTMLAttributes:t}){const{start:e,type:n,...r}=t,o=zt(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):[],s={};return 1!==n&&(s.start=n),r&&(s.type=r),Object.keys(s).length>0?{type:"orderedList",attrs:s,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(Bu),n=null==e?void 0:e.index;return void 0!==n?n:-1},tokenize:(t,e,n)=>{var r,o;const s=t.split("\n"),[i,a]=function(t){const e=[];let n=0,r=0;for(;n<t.length;){const o=t[n],s=o.match(Ou);if(!s)break;const[,i,a,l,d]=s,c=i.length,u=parseInt(a,10),p=isNaN(u)?wu(a):void 0,h=isNaN(u)?xu(a):u,f=[d];let g=n+1;const m=[o];let y=!1;for(;g<t.length;){const e=t[g];if(e.match(Ou))break;if(""===e.trim())m.push(e),f.push(""),y=!0,g+=1;else if(e.match(zu)){const t=e.length-e.trimStart().length,n=c+a.length+1;m.push(e),f.push(e.slice(Math.min(t,n))),g+=1}else{if(y||_u(e))break;m.push(e),f.push(e),g+=1}}e.push({indent:c,number:h,type:p,content:f.join("\n").trim(),contentLines:f,raw:m.join("\n")}),r=g,n=g}return[e,r]}(s);if(0===i.length)return;const l=Uu(i,i[0].indent,n);return 0!==l.length?{type:"list",ordered:!0,start:(null==(r=i[0])?void 0:r.number)||1,typeMarker:null==(o=i[0])?void 0:o.type,items:l,raw:s.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(Ku)).run():t.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addProseMirrorPlugins:()=>[new Kt({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 s=null==(r=e.clipboardData)?void 0:r.getData("text/plain");if(!s)return!1;const i=Wu(s);if(!i)return!1;try{const e=t.state.schema.nodeFromJSON(i),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=Ft({find:Xu,type:this.type,getAttributes:t=>({start:+t[1]}),joinPredicate:t});return(this.options.keepMarks||this.options.keepAttributes)&&(e=Ft({find:Xu,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(Ku)}),joinPredicate:t,editor:this.editor})),[e]}}),Gu=/^\s*(\[([( |x])?\])\s$/,Vu=mt.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",zt(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 _t(t,e,`- [${(null==(n=t.attrs)?void 0:n.checked)?"x":" "}] `)},addExtensions(){return this.options.nested?[cu(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"),s=document.createElement("label"),i=document.createElement("span"),a=document.createElement("input"),l=document.createElement("div"),d=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"}`};d(t),s.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,s.append(a,i),o.append(s,l),Object.entries(e).forEach(([t,e])=>{o.setAttribute(t,e)});let c=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,d(t);const e=r.extensionManager.attributes,n=Ct(t,e),s=new Set(Object.keys(n)),i=this.options.HTMLAttributes;return c.forEach(t=>{s.has(t)||(t in i?o.setAttribute(t,i[t]):o.removeAttribute(t))}),Object.entries(n).forEach(([t,e])=>{null==e?t in i?o.setAttribute(t,i[t]):o.removeAttribute(t):o.setAttribute(t,e)}),c=s,!0}}}},addInputRules(){return[Ft({find:Gu,type:this.type,getAttributes:t=>({checked:"x"===t[t.length-1]})})]}}),Ju=mt.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",zt(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=Dt(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=Dt(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()}}}),Zu=(ft.create({name:"listKit",addExtensions(){const t=[];return!1!==this.options.bulletList&&t.push(lu.configure(this.options.bulletList)),!1!==this.options.listItem&&t.push(Su.configure(this.options.listItem)),!1!==this.options.listKeymap&&t.push(Nu.configure(this.options.listKeymap)),!1!==this.options.orderedList&&t.push(qu.configure(this.options.orderedList)),!1!==this.options.taskItem&&t.push(Vu.configure(this.options.taskItem)),!1!==this.options.taskList&&t.push(Ju.configure(this.options.taskList)),t}})," "),Qu=mt.create({name:"paragraph",priority:1e3,addOptions:()=>({HTMLAttributes:{}}),group:"block",content:"inline*",parseHTML:()=>[{tag:"p"}],renderHTML({HTMLAttributes:t}){return["p",zt(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!==Zu&&n[0].text!==Zu&&" "!==n[0].raw&&" "!==n[0].text||1!==r.length||"text"!==r[0].type||r[0].text!==Zu&&" "!==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 s=Array.isArray(t.content)?t.content:[];if(0===s.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?Zu:""}return e.renderChildren(s)},addCommands(){return{setParagraph:()=>({commands:t})=>t.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),tp=mt.create({name:"text",group:"inline",parseMarkdown:t=>({type:"text",text:t.text||""}),renderMarkdown:t=>t.text||""}),ep=(ft.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 Kt({key:new Xt("characterCount"),appendTransaction:(e,n,r)=>{if(t)return;const o=this.options.limit,s=this.options.autoTrim;if(null==o||0===o||!1===s)return void(t=!0);const i=this.storage.characters({node:r.doc});if(i>o){const e=0,n=i-o;console.warn(`[CharacterCount] Initial content exceeded limit of ${o} characters. Content was automatically trimmed.`);const s=r.tr.deleteRange(e,n);return t=!0,s}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 s=t.selection.$head.pos,i=s-(o-n),a=s;return t.deleteRange(i,a),!(this.storage.characters({node:t.doc})>n)}})]}}),ft.create({name:"dropCursor",addOptions:()=>({color:"currentColor",width:1,class:void 0}),addProseMirrorPlugins(){return[Zt(this.options)]}})),np=(ft.create({name:"focus",addOptions:()=>({className:"has-focus",mode:"all"}),addProseMirrorPlugins(){return[new Kt({key:new Xt("focus"),props:{decorations:({doc:t,selection:e})=>{const{isEditable:n,isFocused:r}=this.editor,{anchor:o}=e,s=[];if(!n||!r)return Vt.create(t,[]);let i=0;"deepest"===this.options.mode&&t.descendants((t,e)=>{if(!t.isText)return o>=e&&o<=e+t.nodeSize-1&&void(i+=1)});let a=0;return t.descendants((t,e)=>!t.isText&&(o>=e&&o<=e+t.nodeSize-1&&(a+=1,"deepest"===this.options.mode&&i-a>0||"shallowest"===this.options.mode&&a>1?"deepest"===this.options.mode:void s.push(Gt.node(e,e+t.nodeSize,{class:this.options.className}))))),Vt.create(t,s)}}})]}}),ft.create({name:"gapCursor",addProseMirrorPlugins:()=>[Qt()],extendNodeSchema(t){var e;return{allowGapCursor:null!=(e=yt(It(t,"allowGapCursor",{name:t.name,options:t.options,storage:t.storage})))?e:null}}})),rp="placeholder",op=new Xt("tiptap__placeholder");function sp(t){const{editor:e,placeholder:n,dataAttribute:r,pos:o,node:s,isEmptyDoc:i,hasAnchor:a,classes:{emptyNode:l,emptyEditor:d}}=t,c=[l];return i&&c.push(d),Gt.node(o,o+s.nodeSize,{class:c.join(" "),[r]:"function"==typeof n?n({editor:e,node:s,pos:o,hasAnchor:a}):n})}function ip(t,e){return"function"==typeof t?t(e):t}function ap({editor:t,options:e,dataAttribute:n,doc:r,selection:o,from:s,to:i}){const{anchor:a}=o,l=[],d=t.isEmpty;return r.nodesBetween(s,i,(r,o)=>{const s=a>=o&&a<=o+r.nodeSize,i=!r.isLeaf&&Rt(r);return r.type.isTextblock?(!s&&e.showOnlyCurrent||!i||l.push(sp({editor:t,isEmptyDoc:d,dataAttribute:n,hasAnchor:s,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:ip(e.emptyNodeClass,{editor:t,node:r,pos:o,hasAnchor:s})},node:r,pos:o})),e.includeChildren):e.includeChildren}),l}function lp({editor:t,options:e,dataAttribute:n,doc:r,selection:o}){if(!t.isEditable&&e.showOnlyWhenEditable)return null;const{anchor:s}=o,i=[],a=t.isEmpty;if(e.showOnlyCurrent&&!e.includeChildren){const o=r.resolve(s),l=o.depth>0?o.node(1):o.nodeAfter,d=o.depth>0?o.before(1):s;if(l&&l.type.isTextblock&&Rt(l)){const r=s>=d&&s<=d+l.nodeSize;i.push(sp({editor:t,isEmptyDoc:a,dataAttribute:n,hasAnchor:r,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:ip(e.emptyNodeClass,{editor:t,node:l,pos:d,hasAnchor:r})},node:l,pos:d}))}}else i.push(...ap({editor:t,options:e,dataAttribute:n,doc:r,selection:o,from:0,to:r.content.size}));return Vt.create(r,i)}function dp(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 cp(t,e){return{from:Math.max(0,e.from-1),to:Math.min(t.content.size,e.to-1)}}function up(t,e){const n=function(t,e,n){const r=[];return t.forEach((t,o)=>{const s=o,i=s+t.nodeSize;s+1<n&&i+1>e&&r.push({from:s,to:i})}),r}(t,e.from,e.to);return n.push(cp(t,dp(t,e.from))),e.to>e.from?n.push(cp(t,dp(t,Math.min(e.to,t.content.size+1)-1))):e.from<t.content.size+1&&n.push(cp(t,dp(t,Math.min(e.from+1,t.content.size)))),n}function pp(t,e,n){const r=[];if(t.docChanged){const e=St(t);for(const t of e)r.push(...up(n.doc,t.newRange))}return t.selectionSet&&(r.push(cp(n.doc,dp(n.doc,t.mapping.map(e.selection.anchor)))),r.push(cp(n.doc,dp(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 hp(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 fp({editor:t,options:e,dataAttribute:n}){return{init(r,o){const s=lp({editor:t,options:e,dataAttribute:n,doc:o.doc,selection:o.selection});return null!=s?s:Vt.empty},apply:(r,o,s,i)=>r.docChanged||r.selectionSet?function({decorations:t,ranges:e,editor:n,options:r,dataAttribute:o,doc:s,selection:i}){let a=t;for(const l of e){const{from:t,to:e}=hp(l.from,l.to,s),d=a.find(t,e).filter(n=>n.from>=t&&n.to<=e);d.length&&(a=a.remove(d));const c=ap({editor:n,options:r,dataAttribute:o,doc:s,selection:i,from:t,to:e});c.length&&(a=a.add(s,c))}return a}({decorations:o.map(r.mapping,r.doc),ranges:pp(r,s,i),editor:t,options:e,dataAttribute:n,doc:i.doc,selection:i.selection}):o}}function gp({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-${rp}`;var r;const o=e.showOnlyCurrent&&!e.includeChildren;return new Kt({key:op,...o?{}:{state:fp({editor:t,options:e,dataAttribute:n})},props:{decorations:o?({doc:r,selection:o})=>lp({editor:t,options:e,dataAttribute:n,doc:r,selection:o}):n=>{var r;return e.showOnlyWhenEditable&&!t.isEditable?Vt.empty:null!=(r=op.getState(n))?r:Vt.empty}}})}ft.create({name:"placeholder",addOptions:()=>({emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:rp,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}),addProseMirrorPlugins(){return[gp({editor:this.editor,options:this.options})]}}),ft.create({name:"selection",addOptions:()=>({className:"selection"}),addProseMirrorPlugins(){const{editor:t,options:e}=this;return t.options.injectCSS&&"undefined"!=typeof document&&bt(".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 Kt({key:new Xt("selection"),props:{decorations:n=>n.selection.empty||t.isFocused||!t.isEditable||Nt(n.selection)||t.view.dragging?null:Vt.create(n.doc,[Gt.inline(n.selection.from,n.selection.to,{class:e.className})])}})]}});function mp({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||(null==e?void 0:e.type)===t}var yp=ft.create({name:"trailingNode",addOptions:()=>({node:void 0,notAfter:[]}),addProseMirrorPlugins(){var t;const e=new Xt(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 Kt({key:e,appendTransaction:(t,r,o)=>{const{doc:s,tr:i,schema:a}=o,l=e.getState(o),d=s.content.size,c=a.nodes[n];if(!t.some(t=>t.getMeta("skipTrailingNode"))&&l)return i.insert(d,c.create())},state:{init:(t,e)=>!mp({node:e.tr.doc.lastChild,types:r}),apply:(t,e)=>{if(!t.docChanged)return e;if(t.getMeta("__uniqueIDTransaction"))return e;return!mp({node:t.doc.lastChild,types:r})}}})]}}),wp=ft.create({name:"undoRedo",addOptions:()=>({depth:100,newGroupDelay:500}),addCommands:()=>({undo:()=>({state:t,dispatch:e})=>ne(t,e),redo:()=>({state:t,dispatch:e})=>ee(t,e)}),addProseMirrorPlugins(){return[te(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()}}}),xp=ft.create({name:"starterKit",addExtensions(){var t,e,n,r;const o=[];return!1!==this.options.bold&&o.push(Aa.configure(this.options.bold)),!1!==this.options.blockquote&&o.push(qc.configure(this.options.blockquote)),!1!==this.options.bulletList&&o.push(lu.configure(this.options.bulletList)),!1!==this.options.code&&o.push(Jc.configure(this.options.code)),!1!==this.options.codeBlock&&o.push(tu.configure(this.options.codeBlock)),!1!==this.options.document&&o.push(eu.configure(this.options.document)),!1!==this.options.dropcursor&&o.push(ep.configure(this.options.dropcursor)),!1!==this.options.gapcursor&&o.push(np.configure(this.options.gapcursor)),!1!==this.options.hardBreak&&o.push(nu.configure(this.options.hardBreak)),!1!==this.options.heading&&o.push(ru.configure(this.options.heading)),!1!==this.options.undoRedo&&o.push(wp.configure(this.options.undoRedo)),!1!==this.options.horizontalRule&&o.push(ou.configure(this.options.horizontalRule)),!1!==this.options.italic&&o.push(Oa.configure(this.options.italic)),!1!==this.options.listItem&&o.push(Su.configure(this.options.listItem)),!1!==this.options.listKeymap&&o.push(Nu.configure(null==(t=this.options)?void 0:t.listKeymap)),!1!==this.options.link&&o.push(Rd.configure(null==(e=this.options)?void 0:e.link)),!1!==this.options.orderedList&&o.push(qu.configure(this.options.orderedList)),!1!==this.options.paragraph&&o.push(Qu.configure(this.options.paragraph)),!1!==this.options.strike&&o.push(Bd.configure(this.options.strike)),!1!==this.options.text&&o.push(tp.configure(this.options.text)),!1!==this.options.underline&&o.push(Kd.configure(null==(n=this.options)?void 0:n.underline)),!1!==this.options.trailingNode&&o.push(yp.configure(null==(r=this.options)?void 0:r.trailingNode)),o}}),bp=new WeakMap;function kp(t){return bp.get(t)?.api??null}function vp(t){const e=bp.get(t);if(e)return e;const n={api:null,disposeApiSubscription:null,listeners:new Set};return bp.set(t,n),n}function Sp(t){for(const e of t.listeners)e()}function Ip(t){const e=t.content.map(t=>"orderedList"===t.type||"bulletList"===t.type||"taskList"===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 Pp(t,e){if(Ip(t)===e)return t;if("taskList"===e){const e=Rp(t.content);return pi({...t,content:[{type:"taskList",content:e.length>0?e:[{type:"taskItem",attrs:{checked:!1},content:[{type:"paragraph"}]}]}]})}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)};for(const r of Np(t))n(r);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 pi({...t,content:r})}var Mp={bold:["bold","strong"],italic:["italic","em"],strike:["strike","s"],underline:["underline","u"]};function Tp(t,e){const n=Mp[e];let r=!1,o=!1;return Op(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 Cp(t,e,n){const r=Mp[e],o=Bp(t.content,(t,o)=>{if("text"!==t.type||!t.text)return t;const s=t.marks??[],i=s.filter(t=>r.includes(t.type));if(n&&(o.insideCodeBlock||s.some(t=>"code"===t.type)))return t;if(n&&1===i.length&&i[0]?.type===e)return t;const a=s.filter(t=>!r.includes(t.type)),l=n?[...a,{type:e}]:a;return s.length===l.length&&s.every((t,e)=>t===l[e])?t:{...t,marks:l.length>0?l:void 0}});return o.changed?pi({...t,content:o.nodes}):t}function Ep(t,e){const n=Bp(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 s=o[0];return{...t,marks:[...r.filter(t=>"link"!==t.type),{type:"link",attrs:{...s?.attrs,href:e}}]}});return n.changed?pi({...t,content:n.nodes}):t}function Ap(t,e){const n=Bp(t.content,t=>{if("textAlign"===e)return $p(t);if("text"!==t.type||!t.marks)return t;let n=!1;const r=t.marks.flatMap(t=>{if("textStyle"!==t.type||!t.attrs)return[t];const r={...t.attrs};let o=!1;const s="size"===e?["fontSize"]:"font"===e?["fontFamily"]:"lineHeight"===e?["lineHeight"]:["color"];for(const e of s)e in r&&(delete r[e],o=!0);return o?(n=!0,Object.keys(r).length>0?[{...t,attrs:r}]:[]):[t]});return n?{...t,marks:r.length>0?r:void 0}:t});return n.changed?pi({...t,content:n.nodes}):t}function Lp(t){const e=Bp(t.content,t=>"text"===t.type&&t.marks&&t.marks.length>0?{...t,marks:void 0}:$p(t));return e.changed?pi({...t,content:e.nodes}):t}function $p(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}}function Rp(t){const e=[];for(const n of Np(t))"taskItem"===n.type?e.push(n):"paragraph"===n.type||"codeBlock"===n.type?e.push({type:"taskItem",attrs:{checked:!1},content:[{...n,type:"paragraph"}]}):e.push(...Rp(n.content??[]));return e}function Np(t){const e=t.at(-1);return t.length>1&&"paragraph"===e?.type&&0===(e.content?.length??0)&&t.slice(0,-1).some(t=>"orderedList"===t.type||"bulletList"===t.type||"taskList"===t.type||"blockquote"===t.type)?t.slice(0,-1):t}function Op(t,e,n=!1){for(const r of t)e(r,{insideCodeBlock:n}),r.content&&Op(r.content,e,n||"codeBlock"===r.type)}function Bp(t,e,n=!1){let r=!1;return{nodes:t.map(t=>{const o=e(t,{insideCodeBlock:n}),s=o.content;if(!s)return o!==t&&(r=!0),o;const i=Bp(s,e,n||"codeBlock"===o.type);return i.changed?(r=!0,{...o,content:i.nodes}):(o!==t&&(r=!0),o)}),changed:r}}function zp(t){try{return t.view.dom.isConnected}catch{return!1}}function Hp(t){!t.isDestroyed&&zp(t)&&(t.view.dom.focus(),t.view.focus())}function Dp(t){if(!zp(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,s=!!n&&!!r&&null!==o&&o.contains(n)&&o.contains(r);return{type:s?e.type:null,text:s?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")}}function _p(t,e,n,r){if(0===t.getText().trim().length&&!ci(t.getJSON()))return Wp(e,r);const o=function(t,e){const n=t.ownerDocument.defaultView?.getComputedStyle(t);return qp(t.ownerDocument).measureElement(t,e,n)}(t.view.dom,{shape:e,fontCatalog:n,...Kp(e,r)});return!r&&t.view.dom.scrollHeight>e.props.h+1&&(o.h=Math.max(o.h,t.view.dom.scrollHeight)),Up(e,o,r)}function jp(t,e,n,r){return Fp(t,e,n,r)}function Fp(t,e,n,r){return 0!==di(t).trim().length||ci(t)?Up(e,(o=function(t){return t.content.map(t=>xi(t)).join("")}(t),s={...Kp(e,r),shape:e,fontCatalog:n},qp(document).measureHtml(o,s)),r):Wp(e,r);var o,s}function Wp(t,e){const n=e?e.minWidth:t.props.autoSize?16:t.props.w,r=ra(t.props.size,t.props.lineHeight)+2*Gi(t.props.padding).y;if(t.props.w!==n||t.props.h!==r)return{w:n,h:r}}function Up(t,e,n){const r=Gi(t.props.padding),o=n?Math.min(n.maxWidth,Math.max(n.minWidth,Math.ceil(e.w+2*(n.paddingInline+r.x)))):t.props.autoSize?Math.max(16,Math.ceil(e.w+2*r.x)):t.props.w,s=Math.max(ra(t.props.size,t.props.lineHeight)+2*r.y,Math.ceil(e.h+2*r.y));if(o!==t.props.w||s!==t.props.h)return{w:o,h:s}}function Kp(t,e){if(e){const n=pa(e,e.maxWidth)+Gi(t.props.padding).x,r=Math.max(1,e.maxWidth-2*n);return e.minWidth===e.maxWidth?{width:r}:{maxWidth:r}}return t.props.autoSize?{}:{width:Math.max(1,t.props.w-2*Gi(t.props.padding).x)}}var Xp=class{ownerDocument;container;element;htmlElements=new Map;constructor(t){this.ownerDocument=t;const e=this.container=t.createElement("div");e.setAttribute("aria-hidden","true"),e.style.position="fixed",e.style.left="-10000px",e.style.top="0",e.style.width="0",e.style.height="0",e.style.visibility="hidden",e.style.pointerEvents="none",e.style.contain="strict",this.element=t.createElement("div"),e.appendChild(this.element),t.body.appendChild(e)}measureHtml(t,e){const n=e?.shape?.props,r=JSON.stringify([t,e?.width,e?.maxWidth,n&&e?.fontCatalog?Qi(n.font,e.fontCatalog):null,n?ta(n.size):null,n?na(n.size,n.lineHeight):null,n?oa(n.textAlign):null,n?Y(n.color):null]),o=this.htmlElements.get(r);if(o)return this.htmlElements.delete(r),this.htmlElements.set(r,o),this.measurePreparedElement(o);const s=this.prepareElement(e,this.ownerDocument.createElement("div"));if(s.innerHTML=t,this.prepareParagraphs(s),this.container.appendChild(s),this.htmlElements.set(r,s),this.htmlElements.size>256){const t=this.htmlElements.keys().next().value;this.htmlElements.get(t).remove(),this.htmlElements.delete(t)}return this.measurePreparedElement(s)}measureElement(t,e,n){const r=this.prepareElement(e);return r.replaceChildren(...Array.from(t.childNodes).map(t=>t.cloneNode(!0))),Gp(r,"whiteSpace",n?.whiteSpace),Gp(r,"overflowWrap",n?.overflowWrap),Gp(r,"lineHeight",n?.lineHeight),Gp(r,"letterSpacing",n?.letterSpacing),Gp(r,"textAlign",n?.textAlign),this.prepareParagraphs(r),this.measurePreparedElement(r)}prepareElement(t,e=this.element){return e.removeAttribute("style"),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=Y(e.props.color),t.style.fontFamily=Qi(e.props.font,n),t.style.fontSize=`${ta(e.props.size)}px`,t.style.lineHeight=na(e.props.size,e.props.lineHeight),t.style.textAlign=oa(e.props.textAlign)}(e,t.shape,t.fontCatalog),e.style.position="absolute",e.style.left="0",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}prepareParagraphs(t){t.querySelectorAll("p").forEach(t=>{t instanceof HTMLElement&&(t.style.margin="0")})}measurePreparedElement(t){return[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})}},Yp=new WeakMap;function qp(t){const e=Yp.get(t);if(e)return e;const n=new Xp(t);return Yp.set(t,n),n}function Gp(t,e,n){n&&"normal"!==n&&"auto"!==n&&(t.style[e]=n)}function Vp(t){if(null===t)return null;if("number"==typeof t){const e=Math.round(1e3*t)/1e3;return Number.isFinite(t)&&t>=.5&&t<=10&&Math.abs(t-e)<=Number.EPSILON*Math.max(1,Math.abs(t))?e:void 0}const e="string"==typeof t?/^((?:\d+(?:\.\d{1,3})?)|(?:\.\d{1,3}))(px|%)?$/iu.exec(t.trim()):null;if(!e)return;const n=Number(e[1]),r=e[2]?.toLowerCase();return"px"===r?n>=1&&n<=1024?`${n}px`:void 0:"%"===r?n>=50&&n<=1e3?`${n}%`:void 0:Vp(n)}var Jp=new WeakMap;function Zp(t,e,n={}){const r=Ui(e,t),o=n.ownerDocument??("undefined"==typeof document?void 0:document);if(!o||!Qp(r.source))return Promise.resolve(!0);const s=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),i=function(t){const e=Jp.get(t);if(e)return e;const n=new Map;return Jp.set(t,n),n}(o);let a=i.get(s);a||(a=async function(t,e){const{source:n}=e;if(!Qp(n))return;if("stylesheet"===n.kind)return void(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,o)=>{const s=t.createElement("link");s.rel="stylesheet",s.href=n.cssUrl,s.dataset.landTextFont=e.id,s.addEventListener("load",()=>r(),{once:!0}),s.addEventListener("error",()=>{s.remove(),o(new Error(`Failed to load text font: ${e.id}`))},{once:!0}),(t.head??t.documentElement).appendChild(s)})}(t,e,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)}(o,r),i.set(s,a));const l=r.source;return a.then(()=>async function(t,e,n){const{fonts:r}=t;if(!r)return;const o=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),s=(e.sampleText??"Aa")+(n??"");await Promise.all(o.map(t=>r.load(`${t} 16px "${e.family}"`,s)))}(o,l,n.text)).then(()=>!0).catch(()=>(i.delete(s),!1))}function Qp(t){return!!t&&"system"!==t.kind}function th(t,e,n){if(e.isDestroyed()||!e.isConnected())return;const r=e.measure(n);r&&nh(t,n,r,"user")}function eh(t,e,n,r="system"){const o=jp(e.props.richText,e,n,xa(t,e));o&&nh(t,e,o,r)}function nh(t,e,n,r){const o=t.store.get(e.id);Ri(o)&&o.props.w===n.w&&o.props.h===n.h||t.shapes.update([{id:e.id,props:n}],{source:r})}var rh=/[;{}<>\u0000-\u001f\u007f]/u,oh=/(?:url|expression)\s*\(|!\s*important|@\s*import|javascript\s*:/iu;function sh({editor:t,fontCatalog:e,landEditor:n,shapeId:r}){const o=()=>{const t=n.store.get(r);return Ri(t)?t:null},s={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=ch(t),s=r.empty?"shape":"selection",i=W(n.props.color),a=H(n.props.backgroundColor)?null:W(n.props.backgroundColor),l=n.props.textAlign;return{shapeId:n.id,target:s,bold:ph(t,o,"bold"),italic:ph(t,o,"italic"),strike:ph(t,o,"strike"),underline:ph(t,o,"underline"),blockType:hh(t,o),color:fh(t,o,"color",i),backgroundColor:fh(t,o,"backgroundColor",0===t.state.doc.textContent.length?a:null),font:xh(fh(t,o,"fontFamily",n.props.font),t=>function(t,e){return e.fontOptions.find(e=>e.cssFamily===t)?.id??t}(t,e)),size:xh(fh(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)),lineHeight:gh(t,o,n.props.lineHeight),textAlign:mh(t,o,l),linkHref:yh(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 s=j(`TextFormattingApi(${r})`,n.store.getRecordSignal(r),o,{fireImmediately:!1});return()=>{s(),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 s=t.chain().focus().selectAll();return s=o?s.setMark(e):s.unsetMark(e),s=s.setTextSelection(uh(r)),s=o?s.setMark(e):s.unsetMark(e),s.run()}(t,e,s.getSnapshot()),setBlockType:e=>function(t,e){if(t.isDestroyed)return!1;const n=t.state.selection;if("taskList"===e&&"taskList"===hh(t,ch(t)))return!1;if(n.empty&&t.state.doc.textContent.length>0){const r=t.getJSON(),o=Pp(r,e);if(o===r)return!1;const s=function(t,e,n){const r=t.schema.nodeFromJSON(e);let o=Math.max(0,n),s=1,i=!1;return r.descendants((t,e)=>!i&&t.isText&&t.text?o<=t.text.length?(s=e+o,i=!0,!1):(o-=t.text.length,s=e+t.text.length,!1):!i),s}(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(s).run()}let r=t.chain().focus();r=r.clearNodes(),r="orderedList"===e?r.toggleOrderedList():"bulletList"===e?r.toggleBulletList():"taskList"===e?r.toggleTaskList():"blockquote"===e?r.toggleBlockquote():r.setParagraph();return r.run()}(t,e),setColor(e){if(null!==e&&!bh(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=ah(t,"color");null!==r&&dh(e,n,{color:x(r)});return o||null!==r}({editor:t,landEditor:n,shape:r,color:e})},setBackgroundColor(e){if(null!==e&&!bh(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,s=t=>null===r?t.unsetBackgroundColor():t.setBackgroundColor(r);if(!o.empty)return dh(e,n,{backgroundColor:x("transparent")}),s(t.chain().focus()).run();const i=s(s(t.chain().focus().selectAll()).setTextSelection(uh(o))).run();return dh(e,n,{backgroundColor:x(r??"transparent")}),i}({editor:t,landEditor:n,shape:r,color:e})},setFont(r){const s=o();if(!s)return!1;if(null===r)return ih({editor:t,font:null,fontFamily:null,landEditor:n,shape:s});const i=e.fontOptions.find(t=>t.id===r);return!!i&&(Zp(r,e).then(()=>{if(t.isDestroyed)return;const r=o();r&&eh(n,r,e,"system")}),ih({editor:t,fontFamily:i.cssFamily,font:r,landEditor:n,shape:s}))},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 s=o();return!!s&&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,s=null===r?null:`${r}px`,i=t=>null===s?t.unsetFontSize():t.setFontSize(s);if(!o.empty)return i(t.chain().focus()).run();const a=function(t){const e=t.state.selection;let n=t.chain().focus();t.state.doc.textContent.length>0&&(n=n.selectAll());return lh(n.unsetFontSize().setTextSelection(uh(e)).unsetFontSize()).run()}(t);null!==r&&dh(e,n,{size:r});return a||null!==r}({editor:t,landEditor:n,shape:s,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";case"justify":return"justify";default:return"left"}}(r),s=t.state.selection;if(!s.empty)return t.chain().focus().setTextAlign(o).run();const i=t.chain().focus().selectAll().unsetTextAlign().setTextSelection(uh(s)).run();return dh(e,n,{textAlign:r}),i||n.props.textAlign!==r}({editor:t,landEditor:n,shape:r,align:e})},setLineHeight(e){const r=Vp(e),s=o();if(void 0===r||!s||t.isDestroyed)return!1;const i=t.state.selection;if(!i.empty){const e=t.chain().focus();return(null===r?e.unsetLineHeight():e.setLineHeight(String(r))).run()}let a=t.chain().focus();t.state.doc.textContent.length>0&&(a=a.selectAll());const l=lh(a.unsetLineHeight().setTextSelection(uh(i)).unsetLineHeight()).run();return dh(n,s,{lineHeight:r}),l||s.props.lineHeight!==r},setLink(e){if(t.isDestroyed||void 0===t.schema.marks.link)return!1;const n=null===e?null:Qs(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(uh(r)).run()},clearFormatting(){if(t.isDestroyed)return!1;const e=o();e&&dh(n,e,{backgroundColor:x("transparent")});const r=t.state.selection;return r.empty?t.chain().focus().selectAll().unsetAllMarks().unsetTextAlign().setTextSelection(uh(r)).command(({tr:t})=>(t.setStoredMarks([]),!0)).run():t.chain().focus().unsetAllMarks().unsetTextAlign().run()},getUnsafeTiptapEditor:()=>t.isDestroyed?null:t};return s}function ih({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 s=ah(t,"fontFamily");return null!==e&&r&&o&&dh(r,o,{font:e}),s||null!==e}function ah(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(uh(n)),r="color"===e?r.unsetColor():r.unsetFontFamily(),lh(r).run()}function lh(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 dh(t,e,n){t.shapes.update([{id:e.id,props:n}],{source:"user"})}function ch(t){const{selection:e,doc:n}=t.state;return e.empty?{from:0,to:n.content.size}:{from:e.from,to:e.to}}function uh(t){return t.from===t.to?t.from:{from:t.from,to:t.to}}function ph(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 s=o?.type.schema.marks[n];t.isText&&s&&o?.type.allowsMarkType(s)&&!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):wh(r)??!1}function hh(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 s="paragraph";for(let t=o.depth;t>=0;t-=1){const e=o.node(t).type.name;if("orderedList"===e||"bulletList"===e||"taskList"===e){s=e;break}if("blockquote"===e){s="blockquote";break}}n.push({blockType:s,isEmptyTrailingParagraph:"paragraph"===s&&0===e.content.size})}),wh((n.some(({blockType:t})=>"paragraph"!==t)?n.filter(({isEmptyTrailingParagraph:t})=>!t):n).map(({blockType:t})=>t))??"paragraph"}function fh(t,e,n,r){const o=[];if(t.state.doc.nodesBetween(e.from,e.to,(t,e,s)=>{if(!t.isText)return;if("backgroundColor"===n&&(t.marks.some(t=>"code"===t.type.name)||"codeBlock"===s?.type.name))return;const i=t.marks.find(t=>"textStyle"===t.type.name)?.attrs[n];o.push("string"==typeof i&&i.length>0?i: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 wh(o)}function gh(t,e,n){const r=[],o=t=>Vp(t.find(t=>"textStyle"===t.type.name)?.attrs.lineHeight)??n;return t.state.doc.nodesBetween(e.from,e.to,t=>{t.isText&&r.push(o(t.marks))}),r.length>0?wh(r):o(t.state.storedMarks??t.state.selection.$from.marks())}function mh(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";case"justify":return"justify";default:return e}}(t.attrs.textAlign,n))}),wh(r)??n}function yh(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 wh(t){if(0===t.length)return null;const e=t[0];return t.every(t=>Object.is(t,e))?e:"mixed"}function xh(t,e){return null===t?null:"mixed"===t?"mixed":e(t)}function bh(t){const e=t.trim();return e.length>0&&e.length<=128&&!rh.test(e)&&!oh.test(e)}function kh({shapeId:t,editor:e,fontCatalog:n,landEditor:r}){return{shapeId:t,formatting:sh({editor:e,fontCatalog:n,landEditor:r,shapeId:t}),isDestroyed:()=>e.isDestroyed,isConnected:()=>!e.isDestroyed&&zp(e),isFocused:()=>!e.isDestroyed&&zp(e)&&e.view.dom.contains(document.activeElement),getValue:()=>pi(e.getJSON()),setValue(t){e.commands.setContent(t)},focus(){Hp(e)},focusEnd(){!e.isDestroyed&&zp(e)&&e.commands.focus("end")},focusSelectAll(){!e.isDestroyed&&zp(e)&&(Hp(e),e.chain().focus().selectAll().run())},focusAtPagePoint(t,n){!function(t,e,n){Hp(e);const r=t.viewport.pageToScreen(new f(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||!zp(e)?{type:null,text:null}:Dp(e),collapseSelectionAtClientPoint(t,n){!e.isDestroyed&&zp(e)&&("Range"===Dp(e).type&&function(t,e,n){if(t.isDestroyed||!zp(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&&zp(e))return _p(e,t,n,xa(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 vh=Rd.extend({inclusive:!1,renderHTML({HTMLAttributes:t}){const{href:e,target:n,rel:r,...o}=t;return["span",zt(o,{"data-rich-text-link-href":e,style:"text-decoration-line: underline;"}),0]}}),Sh=[xp.configure({bold:!1,italic:!1,link:!1,strike:!1,trailingNode:!1,underline:!1}),Ju,Vu.configure({nested:!0,HTMLAttributes:{"data-type":"taskItem"}}),Aa.extend({keepOnSplit:!0}),Oa.extend({keepOnSplit:!0}),Bd.extend({keepOnSplit:!0}),Kd.extend({keepOnSplit:!0}),Dd,jd,_d,Fd,Wd,Ud,zd.configure({types:["paragraph"],alignments:["left","center","right","justify"]}),Xd.configure({className:"land-rich-text-selection"}),vh.configure({autolink:!0,defaultProtocol:"https",openOnClick:!1,protocols:["mailto","land"],HTMLAttributes:{target:"_blank",rel:"noopener noreferrer",class:"land-rich-text-link"}})];function Ih({landEditor:t,shape:e,fontCatalog:n,initialRichText:r,className:o,editorStyle:s,formattingToolbar:i,onTiptapEditorChange:a,onReady:l,onDispose:d,onRichTextChange:c}){const u=dt(null),p=H(e.props.backgroundColor)?null:W(e.props.backgroundColor),h=p&&r.content.length>0?function(t,e){const n=Bp(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 s=r[o]?.attrs?.backgroundColor;return"string"==typeof s&&s.length>0?t:{...t,marks:r.map((t,n)=>n===o?{...t,attrs:{...t.attrs,backgroundColor:e}}:t)}});return n.changed?pi({...t,content:n.nodes}):t}(r,p):r,f=rt(r=>{const o=u.current;if(o?.editor===r)return o.controller;const s=kh({shapeId:e.id,editor:r,fontCatalog:n,landEditor:t});return u.current={editor:r,controller:s},s},[n,t,e.id]),g=ht({extensions:Sh,content:h,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=f(t);c({editor:t,controller:e,richText:e.getValue()})}},[e.id]);return st(()=>{if(!g||g.isDestroyed)return;const n=f(g),r={shapeId:e.id,editor:g,controller:n,formatting:n.formatting},o={shapeId:e.id,formatting:n.formatting},s=!1===i?()=>{}:function(t,e){const n=vp(t);return n.disposeApiSubscription?.(),n.api=e,n.disposeApiSubscription=e.subscribe(()=>{Sp(n)}),Sp(n),()=>{n.api===e&&(n.disposeApiSubscription?.(),n.disposeApiSubscription=null,n.api=null,Sp(n))}}(t,n.formatting);return l(r),a?.(o),()=>{s(),u.current?.editor===g&&(u.current=null),d(r),a?.(null)}},[f,i,t,d,l,a,e.id,g]),J(pt,{editor:g,className:o,style:s})}function Ph({editor:t,controller:e,shapeId:n,request:r,onApplied:o,attempt:s=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(s>=4)return;window.requestAnimationFrame(()=>{Ph({editor:t,controller:e,shapeId:n,request:r,onApplied:o,attempt:s+1})})}}function Mh({editor:t,shape:e,tiptapEditor:n,richTextController:r,latestShapeRef:o,fontCatalog:s}){const i=dt(e.props.richText),a=dt(!1),l=dt(null),d=rt(({controller:n,richText:r})=>{if(a.current||!n.isConnected())return;const d=pi(r);i.current=d,zi(t,e.id,d,n.measure(o.current)??jp(d,o.current,s,xa(t,o.current)),"user"),function(t,e,n,r){null!==r.current&&window.clearTimeout(r.current),r.current=window.setTimeout(()=>{r.current=null,th(t,e,n.current)},0)}(t,n,o,l)},[t,s,o,e.id]);return st(()=>()=>{null!==l.current&&(window.clearTimeout(l.current),l.current=null)},[]),at(()=>{n&&r&&!n.isDestroyed&&r.isConnected()&&th(t,r,e)},[t,r,e,n]),st(()=>{if(!n||!r||!r.isConnected())return;const t=e.props.richText;t!==i.current&&(JSON.stringify(i.current)!==JSON.stringify(t)?(a.current=!0,r.setValue(t),i.current=t,a.current=!1):i.current=t)},[r,e.props.richText,n]),st(()=>{if(r)return r.onCompositionStateChange(e=>{t.editing.setComposition(e,"system")})},[t,r]),d}function Th({editor:t,href:e,openExternal:n}){oi({href:e,openExternal:n,openInternal(e){t.viewport.centerOnShape(e,{source:"user",animation:{durationMs:240}})&&t.selection.set([e],{source:"user"})}})}function Ch({shapeId:t,operationKind:e,fontCatalog:n,formattingToolbar:r,openLink:o=()=>{},onTiptapEditorChange:s}){const i=q(),a=G(i.store.getRecordSignal(t)),l=G(i.state.$_shapeEditingSession);return Ri(a)&&l?.shapeId===a.id?J(Eh,{shape:a,session:l,fontCatalog:n,formattingToolbar:r,openLink:o,onTiptapEditorChange:s},`${a.id}:${e}`):null}function Eh({shape:t,session:e,fontCatalog:n,formattingToolbar:r,openLink:o,onTiptapEditorChange:s}){const i=q(),a=dt(t.props.richText),l=function(t){const e=dt(t);return st(()=>{e.current=t},[t]),e}(t),d=G(i.state.$_shapeEditingEntryRequest),c=dt(null),[u,p]=ct(null),[h,f]=ct(null),g=rt(({editor:t,controller:e})=>{p(t.isDestroyed?null:t),f(e)},[]),m=rt(({editor:t,controller:e})=>{p(e=>e===t?null:e),f(t=>t===e?null:t)},[]),y=Mh({editor:i,shape:t,tiptapEditor:u,richTextController:h,latestShapeRef:l,fontCatalog:n}),w=rt(()=>{u&&function(t,e){!(!e||t.isDestroyed||t.state.doc.textContent.length>0||t.getAttributes("textStyle").backgroundColor===e)&&t.commands.setBackgroundColor(e)}(u,H(t.props.backgroundColor)?null:W(t.props.backgroundColor))},[t.props.backgroundColor,u]);!function({editor:t,shapeId:e,session:n,tiptapEditor:r,richTextController:o,entryRequest:s,consumedEntryRequestIdRef:i,onEntryFocusApplied:a}){const l=dt(null),d=dt(null);st(()=>{if(!o||o.isDestroyed()||!o.isConnected())return;let t=!1,e=null,n=0;const r=()=>{t||o.isDestroyed()||null===i.current&&(o.isFocused()||(o.focus(),n+=1,o.isFocused()||n>=4||(e=window.setTimeout(r,16))))},s=window.requestAnimationFrame(()=>{r()});return()=>{t=!0,window.cancelAnimationFrame(s),null!==e&&window.clearTimeout(e)}},[i,o,e]),st(()=>{r&&!r.isDestroyed&&o&&null===i.current&&d.current!==n.operationKind&&(d.current=n.operationKind,window.setTimeout(()=>{Ph({editor:t,controller:o,shapeId:e,request:{id:-1,shapeId:n.shapeId,entryMode:n.entryMode,caretPagePoint:n.caretPagePoint},onApplied:a})},0))},[i,t,o,n.caretPagePoint,n.entryMode,n.operationKind,n.shapeId,e,r,a]),st(()=>{r&&!r.isDestroyed&&o&&s&&s.shapeId===e&&i.current!==s.id&&Ph({editor:t,controller:o,shapeId:e,request:s,onApplied(t){t&&(i.current=t.id),a?.()}})},[i,t,s,o,e,r,a]),st(()=>{if(!r||!o||r.isDestroyed||!o.isConnected())return;const e=o;"selectAll"===n.entryMode&&window.requestAnimationFrame(()=>{"Range"!==e.getSelectionSnapshot().type&&e.focusSelectAll()});const s=l.current,i=n.caretPagePoint;if("placeCaret"===n.entryMode&&i&&(s?.operationKind!==n.operationKind||s.entryMode!==n.entryMode)){l.current={operationKind:n.operationKind,entryMode:n.entryMode};const r={x:i.x,y:i.y};window.requestAnimationFrame(()=>{Ph({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:i,shapeId:t.id,session:e,tiptapEditor:u,richTextController:h,entryRequest:d,consumedEntryRequestIdRef:c,onEntryFocusApplied:w});const x=function({editor:t,shapeId:e,richTextController:n}){const r=dt(null);return{onPointerDownCapture:rt(o=>{if(0!==o.button||1!==o.detail||!n||n.isDestroyed())return void(r.current=null);const s=t.state.$_shapeEditingSession.get();s&&s.shapeId===e&&!s.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:rt(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:rt(o=>{const s=r.current;if(r.current=null,!s||s.pointerId!==o.pointerId||s.moved||!n||n.isDestroyed())return;const i=t.state.$_shapeEditingSession.get();if(!i||i.shapeId!==e||i.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:rt(()=>{r.current=null},[])}}({editor:i,shapeId:t.id,richTextController:h}),b=function(t,e,n=0){return lt(()=>({color:Y(t.props.color),fontFamily:Qi(t.props.font,e),fontSize:ta(t.props.size),lineHeight:na(t.props.size,t.props.lineHeight),textAlign:oa(t.props.textAlign),pointerEvents:"auto",userSelect:"text",cursor:"text",boxSizing:"border-box",position:"absolute",inset:0,width:"100%",height:"100%",paddingBlock:Gi(t.props.padding).y,paddingInline:Gi(t.props.padding).x+n,...qi(t.props,Y)}),[t.props.color,t.props.font,t.props.size,t.props.lineHeight,t.props.textAlign,t.props.padding,t.props.backgroundColor,t.props.fill,t.props.stroke,t.props.strokeWidth,t.props.cornerRadius,t.props.shadow,e,n])}(t,n,pa(ka(i,t),t.props.w)),k=rt(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&&u&&!u.isDestroyed&&(t.preventDefault(),t.stopPropagation(),Th({editor:i,href:e,openExternal:o}))},[i,o,u]);
|
|
13
|
+
return J("div",{"data-ui":"text-editing-box","data-shape-id":t.id,"data-mount-target-kind":"shape",onPointerDown:t=>{t.stopPropagation()},onClickCapture:k,onPointerDownCapture:x.onPointerDownCapture,onPointerMoveCapture:x.onPointerMoveCapture,onPointerUpCapture:x.onPointerUpCapture,onPointerCancel:x.onPointerCancel,onContextMenu:t=>{t.stopPropagation()},onDragStart:t=>{t.preventDefault()},style:b,children:J(Ih,{landEditor:i,shape:t,fontCatalog:n,initialRichText:a.current,className:"land-text-editor__content",formattingToolbar:r,editorStyle:{height:"100%",minHeight:"100%"},onReady:g,onDispose:m,onTiptapEditorChange:s,onRichTextChange:y})})}function Ah(t,e,n,r,o,s){const i=G(t.state.$_editingShapeId),a=G(t.editing.getShapeSessionSignal(e.id)),l=a?.shapeId===e.id,d=a&&l?J(Ch,{shapeId:a.shapeId,operationKind:a.operationKind,fontCatalog:n,formattingToolbar:r,openLink:o,onTiptapEditorChange:s},a.shapeId+":"+a.operationKind):null;return function({editor:t,shape:e,isEditingThisShape:n,fontCatalog:r}){const o=ka(t,e);at(()=>{n||eh(t,e,r)},[t,r,n,e,e.props.autoSize,e.props.font,e.props.richText,e.props.scale,e.props.size,e.props.lineHeight,e.props.textAlign,e.props.w,o?.paddingInline,o?.maxWidth])}({editor:t,shape:e,isEditingThisShape:l,fontCatalog:n}),{hasEditingSession:null!==i,isEditingThisShape:l,editingHost:d}}var Lh=Q(null);function $h({children:t,presenter:e}){
|
|
14
|
+
return J(Lh.Provider,{value:e,children:t})}function Rh(t,{shapeId:e,richText:n,path:r,checked:o}){if(t.state.$_readonly.get()||ca(t,e))return!1;const s=t.store.get(e);if(!Ri(s)||s.props.richText!==n)return!1;const i=function(t,e,n){if(0===e.length||e.some(t=>!Number.isInteger(t)||t<0))return t;const r=(t,o)=>{if(o===e.length)return"taskItem"===t.type&&t.attrs?.checked!==n?{...t,attrs:{...t.attrs,checked:n}}:t;const s=e[o],i=t.content?.[s];if(!i)return t;const a=r(i,o+1);if(a===i)return t;const l=[...t.content];return l[s]=a,{...t,content:l}};return r(t,0)}(s.props.richText,r,o);if(i===s.props.richText)return!1;if(t.state.$_shapeEditingSession.get()&&!t.editing.complete("user"))return!1;t.interaction.cancelForCommand();const a=t.store.get(e);return!(!Ri(a)||a.props.richText!==n)&&(t.operations.run({kind:"text.task.check",source:"user"},()=>{t.shapes.update([{id:e,props:{richText:i}}],{source:"user"})}),!0)}var Nh=Q({query:"",activeMatch:null});function Oh({activeMatch:t,children:e,query:n}){const r=lt(()=>({activeMatch:t,query:n}),[t,n]);
|
|
15
|
+
return J(Nh.Provider,{value:r,children:e})}function Bh(t,e,n=di(t)){if(0===e.length)return[];const r=[],o=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&"),"giu");for(const s of n.matchAll(o)){const t=s.index,e=s[0];void 0!==t&&0!==e.length&&r.push({from:t,to:t+e.length})}return r}var zh=new Set(["key_down","key_up","pointer_cancel","pointer_down","pointer_move","pointer_up"]),Hh={id:"land.text.dom-events",handle({event:t,name:e}){if(!zh.has(e))return"continue";const n=t.target;return n instanceof HTMLElement&&n.closest('[data-ui="text-editing-box"], [data-rich-text-task-checkbox="true"]')?"handled":"continue"},getCursor:({element:t})=>t?.closest('[data-rich-text-task-checkbox="true"]:not(:disabled)')?"pointer":t?.closest('[data-ui="text-editing-box"]')?"text":void 0};function Dh({fontCatalog:t=ji(),formattingToolbar:e,openLink:n=()=>{},onTiptapEditorChange:r}={}){return{domEventGuards:[Hh],canvasOverlays:[{id:"land.text.creation-indicator",component:_h,order:10}],shapeRenderers:[{type:"text",hoverComponent:Fh,component:function(o){
|
|
16
|
+
return J(jh,{...o,fontCatalog:t,formattingToolbar:e,openLink:n,onTiptapEditorChange:r})}}]}}var _h=nt(function(){const t=q(),e=G(t.state.$_tool),n=G(t.state.$_selectedShapes),r=G(t.state.$_editingShapeId),o=G(t.state.$_selectionPageBounds),s=G(t.state.$_cameraZoom),i=1===n.length?n[0]:null;if("text"!==e.activeToolId||null!==r||!Ri(i)||i.props.autoSize||!o)return null;const a=Math.max(s,1e-4),l=2/a,d=l/2;
|
|
17
|
+
return J("rect",{"data-ui":"text-creation-indicator",x:o.x-d,y:o.y-d,width:o.w+l,height:o.h+l,rx:3/a+d,ry:3/a+d,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeWidth:l,pointerEvents:"none"})});function jh({shape:t,editor:e,fontCatalog:n,formattingToolbar:r,openLink:o,onTiptapEditorChange:s}){const[i,a]=ct(null),l=dt(null),d=G(e.state.$_selectedShapeIds),c=G(e.state.$_readonly),u=G(e.state.$_tool),p=G(e.inputs.$_isSpacePressed),h=G(lt(()=>e.signalGraph.computed(`textTaskLocked(${t.id})`,()=>ca(e,t.id)),[e,t.id])),f=ot(Nh),g=lt(()=>Bh(t.props.richText,f.query,t.props.plainText),[t.props.plainText,t.props.richText,f.query]),m=f.activeMatch?.shapeId===t.id?f.activeMatch:null,y=ot(Lh),{hasEditingSession:w,isEditingThisShape:x,editingHost:b}=Ah(e,t,n,r,o,s),k=pa(ka(e,t),t.props.w),v=(Gi(t.props.padding).x>0||Gi(t.props.padding).y>0)&&!H(t.props.backgroundColor),S=null!==y&&function({isEditing:t,isOnlySelected:e}){return!t&&!e}({isEditing:w,isOnlySelected:1===d.length&&d[0]===t.id}),I=i?ri(i.href):null,P=null!==I&&void 0===e.store.get(I),M=rt(()=>{null!==l.current&&(window.clearTimeout(l.current),l.current=null)},[]),T=rt(()=>{M(),l.current=window.setTimeout(()=>{a(null),l.current=null},160)},[M]);return st(()=>()=>{M()},[M]),st(()=>{S||(M(),a(null))},[S,M]),Z("div",{"data-editing-hidden":x?"true":void 0,style:{position:"relative",left:Yi(t.props),top:Yi(t.props),boxSizing:"border-box",width:t.props.w,minHeight:t.props.h,transform:`scale(${t.props.scale})`,transformOrigin:"top left",color:Y(t.props.color),fontFamily:Qi(t.props.font,n),fontSize:ta(t.props.size),lineHeight:na(t.props.size,t.props.lineHeight),textAlign:oa(t.props.textAlign),whiteSpace:"pre-wrap",overflowWrap:"break-word",userSelect:"none",pointerEvents:"none",...qi(t.props,Y),...x?{boxShadow:void 0}:{}},children:[
|
|
18
|
+
J("div",{className:"land-rich-text",style:{boxSizing:"border-box",opacity:x?0:void 0,paddingBlock:Gi(t.props.padding).y,paddingInline:Gi(t.props.padding).x+k,width:"100%"},children:va(t.props.richText,{onTaskChecked:c||h||x||p||"select"!==u.activeToolId?void 0:({path:n,checked:r})=>{Rh(e,{shapeId:t.id,richText:t.props.richText,path:n,checked:r})},linkHandlers:S?{onPointerEnter({href:t,element:e}){M(),a({anchorElement:e,href:t})},onPointerLeave(){T()}}:void 0,defaultBackgroundColor:v||H(t.props.backgroundColor)?void 0:Y(t.props.backgroundColor),searchRanges:g,activeSearchRange:m})}),S&&i&&y?J(y,{anchorElement:i.anchorElement,href:i.href,kind:I?"internal":"external",unavailable:P,onOpen:()=>{Th({editor:e,href:i.href,openExternal:o})},onPopoverPointerEnter:M,onPopoverPointerLeave:T}):null,
|
|
19
|
+
J("div",{"data-ui":"text-editor-host-slot","data-shape-id":t.id,"data-active":x?"true":"false","aria-hidden":"true",style:{position:"absolute",inset:0,pointerEvents:"none"},children:b})]})}function Fh({shape:t,strokeWidth:e}){const n=Yi(t.props);
|
|
20
|
+
return J(u,{dataUi:"text-hover-outline",x:n,y:n,width:t.props.w*t.props.scale,height:t.props.h*t.props.scale,strokeWidth:e})}var Wh="text.create",Uh=class extends h{constructor(t){super(t,"text"),this.initial="idle",this.addChild(new Kh(t,this)),this.addChild(new Xh(t,this))}},Kh=class extends h{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})}},Xh=class extends h{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:Wh,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.store.get(this.info.shapeId):this.createTextShape(t.pagePoint);if(!Ri(e))return this.cancelOperation(),void this.transition("idle");let n;F(this.editor,e.id,{source:"user"}),this.editor.state.$_tool.get().isToolLocked||(this.isHandingOffOperation=!0,this.transition("idle"),this.editor.tools.select("select",{source:"system"}));try{n=this.editor.editing.start({shapeId:e.id,entryMode:"focusEnd",operationKind:Wh,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 s=Math.abs(r.x-n.x);return n.dist(r)<4||s<8?null:{x:Math.min(t.x,e.x),y:t.y-o.h/2,props:{...Yh(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.shapes.update([{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:Yh(e)}}(t,this.getDefaultTextProps()))}createTextShapeAt({x:t,y:e,props:n}){const r=Bi(this.editor,{x:t,y:e,props:n},"user");return this.editor.selection.set([r.id],{source:"system"}),r}getDefaultTextProps(){return Oi(this.editor)}};function Yh(t){return Ni(t)}var qh=["start","middle","end","justify"];function Gh(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function Vh(t){return Math.max(.01,t.props.scale)}function Jh(t){return t.props.w*Vh(t)}function Zh(t){return t.props.h*Vh(t)}function Qh(t){return new e(0,0,Jh(t),Zh(t))}function tf(t){return"left"===t||"right"===t}function ef(t,e){const n=function(t){return E({localWidth:Jh(t),localHeight:Zh(t),scaleX:t.scaleX,scaleY:t.scaleY})}(t),r=e.selectionLocalBounds.w/Math.max(o,n.width),s=e.selectionLocalBounds.h/Math.max(o,n.height);switch(e.handleId){case"left":case"right":return r;case"top":case"bottom":return s;default:return Math.max(r,s)}}var nf=class extends p{type="text";getDefaultProps(){return{richText:li(""),plainText:"",w:16,h:ra(Xi),autoSize:!0,scale:1,font:Hi,size:Xi,lineHeight:null,color:k("text-slate"),backgroundColor:x("transparent"),textAlign:"start",padding:0,fill:x("transparent"),stroke:x("transparent"),strokeWidth:0,cornerRadius:0,shadow:!1}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{richText:pi(e.richText),plainText:"string"==typeof e.plainText?e.plainText:n.plainText,w:Math.max(o,Gh(e.w,n.w)),h:Math.max(o,Gh(e.h,n.h)),autoSize:"boolean"==typeof e.autoSize?e.autoSize:n.autoSize,scale:Math.max(.01,Gh(e.scale,n.scale)),font:Wi(e.font)?e.font:n.font,size:Zi(e.size,n.size),lineHeight:Vp(e.lineHeight)??n.lineHeight,color:_(e.color,n.color),backgroundColor:_(e.backgroundColor,n.backgroundColor),textAlign:(r=e.textAlign,"string"==typeof r&&qh.includes(r)?e.textAlign:n.textAlign),padding:Vi(e.padding,n.padding),fill:_(e.fill,n.fill),stroke:_(e.stroke,n.stroke),strokeWidth:Math.max(0,Gh(e.strokeWidth,n.strokeWidth)),cornerRadius:Math.max(0,Gh(e.cornerRadius,n.cornerRadius)),shadow:"boolean"==typeof e.shadow?e.shadow:n.shadow};var r}getPositionedBounds(t){return function(t){return new e(t.x,t.y,Jh(t),Zh(t))}(t)}getLocalBounds(t){return Qh(t)}getRenderBounds(t){return Qh(t).expand(Yi(t.props))}getExportBounds(t){return this.getRenderBounds(t)}canSnap(t,e){return!e||(n=e.editor,r=t.id,ya(n,r)?.behavior.canSnap??null??!0);var n,r}canReceiveTerminalBinding(t,e){return!e||(n=e.editor,r=t.id,ya(n,r)?.behavior.canReceiveTerminalBinding??null??!0);var n,r}canEdit(t){return!0}contributesToSelectionFrame(t,e){return n=e.editor,r=t.id,ya(n,r)?.behavior.contributesToSelectionFrame??null??!0;var n,r}canUseSelectionHandle(t,e){switch(e.handle){case"resize":return e.editor.state.$_shapeEditingSession.get()?.shapeId!==t.id&&(n=e.editor,r=t.id,ya(n,r)?.behavior.canUseSelectionResizeHandles??null??!0);case"rotate":return e.editor.state.$_shapeEditingSession.get()?.shapeId!==t.id&&(function(t,e){return ya(t,e)?.behavior.canUseSelectionRotateHandle??null}(e.editor,t.id)??!0);default:return super.canUseSelectionHandle(t,e)}var n,r}getSelectionTargetId(t,e){return function(t,e){const n=ya(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=ya(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=ya(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=ya(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&&tf(e.handleId)){const r=M({width:e.selectionLocalBounds.w,height:e.selectionLocalBounds.h,scaleX:t.scaleX,scaleY:t.scaleY});n.w=Math.max(o,r.width/Vh(t)),n.autoSize=!1}else n.scale=Math.max(.01,t.props.scale*ef(t,e));const r=n.scale??Vh(t),s=(n.w??t.props.w)*r,i=t.props.h*r,a=E({localWidth:s,localHeight:i,scaleX:t.scaleX,scaleY:t.scaleY}),l=function(t,e){return 0===e.selectionRotation?t.clone():f.RotWith(t,e.selectionRotationCenter,e.selectionRotation)}(I({handleId:e.handleId,requestedBounds:e.selectionLocalBounds,actualWidth:a.width,actualHeight:a.height,scaleX:e.scaleX,scaleY:e.scaleY,isResizingFromCenter:e.isResizingFromCenter}).center,e),d=e.scaleX<0!=e.scaleY<0;return{id:t.id,x:l.x-s/2,y:l.y-i/2,rotation:d?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&&tf(e.handleId)?l:i}onEditEnd(t){if(!(t.props.plainText.trim().length>0||ci(t.props.richText)))return{deleteShapeIds:[t.id]}}},rf=class{fontCatalog;type="text";constructor(t){this.fontCatalog=t}toSvg(t,e){if(0===t.props.plainText.trim().length&&!ci(t.props.richText))return null;const n=pa(xa(e.editor,t),t.props.w),r=Yi(t.props);return{tag:"foreignObject",attrs:{x:-r,y:-r,width:t.props.w*t.props.scale+2*r,height:t.props.h*t.props.scale+2*r},children:[{tag:"div",attrs:{xmlns:"http://www.w3.org/1999/xhtml",dir:"auto",style:sf(t,e,this.fontCatalog,n)},children:(o=t.props.richText,s=H(t.props.backgroundColor)?void 0:e.resolveColor(t.props.backgroundColor),o.content.map(t=>of(t,s)))}]};var o,s}};function of(t,e){const n="codeBlock"===t.type?void 0:e,r=t.content?.map(t=>function(t,e){if(hi(t)){const n=function(t,e){const n=gi(t.marks,e);return n?wi(n):void 0}(t,e);return n?{tag:"span",attrs:{style:n},children:[t.text]}:t.text}return"hardBreak"===t.type?{tag:"br"}:of(t,e)}(t,n))??[];if("taskList"===t.type)return{tag:"ul",attrs:{style:"margin:0;padding:0;list-style:none"},children:r};if("taskItem"===t.type){const e=!0===t.attrs?.checked;return{tag:"li",attrs:{style:"display:flex;align-items:flex-start;gap:0.625em;padding-block:0.18em"},children:[{tag:"span",attrs:{style:`display:inline-flex;align-items:center;justify-content:center;flex:none;box-sizing:border-box;width:1em;height:1em;border:0.085em solid ${e?"#16a34a":"color-mix(in srgb, currentColor 38%, transparent)"};border-radius:0.28em;background:${e?"#16a34a":"color-mix(in srgb, currentColor 3%, transparent)"};color:${e?"white":"inherit"};font-size:1em;margin-block:calc((1lh - 1em)/2)`},children:e?["✓"]:[]},{tag:"div",attrs:{style:"flex:1;min-width:0"},children:r.map((n,r)=>e&&"paragraph"===t.content?.[r]?.type&&"string"!=typeof n?{...n,attrs:{...n.attrs,style:`${n.attrs?.style??""};opacity:0.55;text-decoration:line-through;text-decoration-thickness:0.06em;text-decoration-color:color-mix(in srgb, currentColor 65%, transparent)`}}: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=fi(t);return{tag:"p",attrs:{style:o?`margin:0;text-align:${o}`:"margin:0"},children:r.length>0?r:[{tag:"br"}]}}function sf(t,e,n,r){const o=qi(t.props,t=>e.resolveColor(t));return[`color:${e.resolveColor(t.props.color)}`,`font-family:${Qi(t.props.font,n)}`,`font-size:${ta(t.props.size)}px`,`line-height:${na(t.props.size,t.props.lineHeight)}`,`text-align:${oa(t.props.textAlign)}`,"white-space:pre-wrap","overflow-wrap:break-word","box-sizing:border-box",`padding-block:${Gi(t.props.padding).y}px`,`padding-inline:${Gi(t.props.padding).x+r}px`,...o.backgroundColor?[`background-color:${o.backgroundColor}`]:[],...o.borderRadius?[`border-radius:${o.borderRadius}`]:[],...o.boxShadow?[`box-shadow:${o.boxShadow}`]:[],`width:${t.props.w}px`,`height:${t.props.h}px`,`transform:translate(${Yi(t.props)}px, ${Yi(t.props)}px) scale(${t.props.scale})`,"transform-origin:top left"].join(";")}var af=".label";function lf(t){return t.endpoints.find(({slot:t})=>"owner"===t)??null}function df(t){return"binding"===t?.typeName&&"path-label"===t.type}function cf(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):e}var uf=class extends t{type=sa;getDefaultEndpointProps(){return{labelPosition:.5}}validateEndpointProps(t,e){const n=this.getDefaultEndpointProps();return{labelPosition:cf((e&&"object"==typeof e?e:{}).labelPosition,n.labelPosition)}}canBind(t,e,n){return this.canUseShapeCompanion(e,n,t)}canUseShapeCompanion(t,e,n){return Ri(e.ownerShape)&&1===e.endpoints.length&&(!n||!!e.endpoints[0]&&null!==hf(n,e.endpoints[0].targetShape))}getExclusiveBindingKey(t){return lf(t)?.targetId??t.ownerId}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 n.endpointSlots.length>0?[e.ownerId]:[]}getTargetShapeContentCutoutLocalPolygons(t,e,n){if(!Ri(n.ownerShape)||!hf(t,n.targetShape))return[];const r=t.shapes.geometry.computeLocalToPageTransform(n.targetShape).tryInvert();if(!r)return[];const o=t.shapes.geometry.computeLocalBounds(n.ownerShape),s=r.compose(t.shapes.geometry.computeLocalToPageTransform(n.ownerShape));return[[new f(o.minX,o.minY),new f(o.maxX,o.minY),new f(o.maxX,o.maxY),new f(o.minX,o.maxY)].map(t=>s.applyToPoint(t))]}onAfterShapeChange(t,e,n){return this.syncLabelPosition(t,e)}onBeforeDeleteShape(t,e,n){return n.owner?{deleteBindingIds:[e.id]}:{deleteShapeIds:[e.ownerId],deleteBindingIds:[e.id]}}onBeforeDeleteBinding(t,e){return{deleteBindingIds:[e.id]}}getExportShapeIds(t,e){return[e.ownerId]}getShapeCompanionRootId(t,e){const n=lf(t);return e===t.ownerId?n?.targetId??null:null}getSelectionCompanionFrameGeometries(t,n,r){const o=lf(n);if(o?.targetId!==r.selectedShape.id)return[];if(!0!==function(t,e){return ya(t,e)?.behavior.showsCompanionFrameWhenOwnerSelected??null}(t,n.ownerId))return[];const s=t.store.get(n.ownerId),i=t.store.get(o.targetId);if(!(Ri(s)&&o&&i&&hf(t,i)))return[];const a=t.shapes.geometry.computeGeometry(s),l=t.shapes.geometry.computeLocalToPageTransform(s),d=Math.atan2(l.b,l.a);return[{bounds:e.FromPoints(a.outlineVertices.map(t=>f.RotWith(t,a.center,-d))),rotation:d,rotationCenter:a.center}]}syncLabelPosition(t,e){if(!df(e))return;const n=lf(e),r=t.store.get(e.ownerId),o=n?t.store.get(n.targetId):null;if(!(Ri(r)&&n&&o&&hf(t,o)))return{deleteBindingIds:[e.id]};const s=function(t,e,n,r){const o=pf(t,e,n,r),s=n.parentId,i=`${n.index}${af}`,a=!1,l=fa(t,e,s,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===s&&e.index===i&&e.props.w===o.props.w&&e.props.autoSize===a?null:{id:e.id,...l,parentId:s,index:i,props:{w:o.props.w,autoSize:a}}:null}(t,r,o,n.props.labelPosition);return s?{shapes:[{...r,...s,props:{...r.props,...s.props}}]}:void 0}};function pf(t,e,n,r=.5){const o=hf(t,n),s=o?ff(t,e,o):{start:0,end:1},i=Math.min(s.end,Math.max(s.start,r)),a=o?.getPointAt(i)??t.shapes.geometry.computePageCenter(n),l=wa(t,e,n,sa),d=Math.min(l.maxWidth,Math.max(l.minWidth,e.props.w));return{x:a.x-d*e.props.scale/2,y:a.y-e.props.h*e.props.scale/2,rotation:ha(t,n),props:{w:d}}}function hf(t,e){return t.shapes.getUtil(e).getLabelPathGeometry(e,{editor:t})}function ff(t,e,n){if(n.length<=1e-6)return{start:.5,end:.5};const r=t.shapes.geometry.getPageBounds(e.id);if(!r)return{start:0,end:1};const o=Math.hypot(r.w,r.h)/2,s=Math.min(.5,(o+8)/n.length);return{start:s,end:1-s}}var gf=".label";function mf(t){return t.endpoints.find(({slot:t})=>"owner"===t)??null}function yf(t){return"shape"===t?.typeName&&"geo"===t.type}function wf(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):e}var xf=class extends t{type=ia;getDefaultEndpointProps(){return{...aa(),normalizedAnchor:{x:.5,y:.5},ownerBaseHeight:0}}validateEndpointProps(t,e){const n=this.getDefaultEndpointProps(),r=e&&"object"==typeof e?e:{},o=r.normalizedAnchor&&"object"==typeof r.normalizedAnchor?r.normalizedAnchor:n.normalizedAnchor;return{...aa(r),normalizedAnchor:{x:wf(o.x,n.normalizedAnchor.x),y:wf(o.y,n.normalizedAnchor.y)},ownerBaseHeight:bf(r.ownerBaseHeight,n.ownerBaseHeight)}}canBind(t,e,n){return this.canUseShapeCompanion(e,n)}canUseShapeCompanion(t,e){return Ri(e.ownerShape)&&1===e.endpoints.length&&yf(e.endpoints[0]?.targetShape)}getExclusiveBindingKey(t){return mf(t)?.targetId??t.ownerId}onBindingCreate(t,e){return this.syncLabelPosition(t,e)}onBindingUpdate(t,e,n){return this.syncLabelPosition(t,n,mf(e)?.targetId===mf(n)?.targetId?void 0:{endpointSlots:["owner"]})}onBindingLoad(t,e){return this.syncLabelPosition(t,e)}getGeometryDependentShapeIds(t,e,n){const r=mf(e)?.targetId;return n.owner?r?[r]:[]:[e.ownerId]}onAfterShapeChange(t,e,n){return this.syncLabelPosition(t,e,n)}onBeforeDeleteShape(t,e,n){if(n.owner){const n=mf(e),r=n?t.store.get(n.targetId):null,o=r?vf(r,e):null;return{shapes:o?[o]:void 0,deleteBindingIds:[e.id]}}return{deleteShapeIds:[e.ownerId],deleteBindingIds:[e.id]}}onBeforeDeleteBinding(t,e){const n=mf(e),r=n?t.store.get(n.targetId):null,o=r?vf(r,e):null;return{shapes:o?[o]:void 0,deleteBindingIds:[e.id]}}getExportShapeIds(t,e){return[e.ownerId]}getShapeCompanionRootId(t,e){const n=mf(t);return e===t.ownerId?n?.targetId??null:null}syncLabelPosition(t,e,n){if(r=e,"binding"!==r?.typeName||"geo-label"!==r.type)return;var r;const o=mf(e),s=t.store.get(e.ownerId),i=o?t.store.get(o.targetId):null;if(!Ri(s)||!o||!yf(i))return{deleteBindingIds:[e.id]};const a=function(t,e,n){const r=mf(t),o=kf(e,"h")??1;return n?.endpointSlots.includes("owner")?o:r&&r.props.ownerBaseHeight>0?r.props.ownerBaseHeight:o}(e,i,n),l=o.props.ownerBaseHeight===a?null:{...e,endpoints:e.endpoints.map(t=>"owner"===t.slot?{...t,props:{...t.props,ownerBaseHeight:a}}:t)},d=function(t,e,n,r){const o=kf(t,"h");if(!o)return null;const s=Math.max(n,function(t,e){return Math.max(1,t.props.h*t.props.scale+2*e)}(e,r));return o===s?null:{...t,props:{...t.props,h:s}}}(i,s,a,o.props.padding.y),c=function(t,e,n){const r=Sf(t,e,n),o=n.parentId,s=`${n.index}${gf}`,i=!1,a=fa(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===s&&e.props.w===r.props.w&&e.props.autoSize===i?null:{id:e.id,...a,parentId:o,index:s,props:{w:r.props.w,autoSize:i}}:null}(t,s,d??i),u=[];return d&&u.push(d),c&&u.push({...s,...c,props:{...s.props,...c.props}}),u.length>0||l?{shapes:u.length>0?u:void 0,bindings:l?[l]:void 0}:void 0}};function bf(t,e){return"number"==typeof t&&Number.isFinite(t)&&t>0?t:e}function kf(t,e){const n=t.props[e];return"number"==typeof n&&Number.isFinite(n)?n:null}function vf(t,e){const n=mf(e),r=kf(t,"h");return!r||!n||n.props.ownerBaseHeight<=0||r===n.props.ownerBaseHeight?null:{...t,props:{...t.props,h:n.props.ownerBaseHeight}}}function Sf(t,e,n){const r=wa(t,e,n,ia),o=Math.min(r.maxWidth,Math.max(r.minWidth,e.props.w)),s=t.shapes.geometry.computeLocalBounds(n),{padding:i,verticalAlign:a}=da(t,n.id),l=e.props.h*e.props.scale,d="top"===a?s.minY+i.y+l/2:"bottom"===a?s.maxY-i.y-l/2:s.center.y,c=t.shapes.geometry.computeLocalToPageTransform(n).applyToPoint(new f(s.minX+s.w*(r.normalizedCenterX??.5),d));return{x:c.x-o*e.props.scale/2,y:c.y-l/2,rotation:ha(t,n),props:{w:o}}}var If="text.edit",Pf="path-label.create",Mf="path-label.drag",Tf="geo-label.edit",Cf="geo-label.create",Ef={propagation:"stop"};function Af(){let t=null,e=null;const n=()=>{t=null,e=null};return{id:"land.text.interactions",editorEvent:{handleEvent(r,o,s){if(r.state.$_readonly.get())n();else 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=s.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 s=e.screenPoint.x-r.originScreenPoint.x,i=e.screenPoint.y-r.originScreenPoint.y;if(s*s+i*i>9)return;const a=t.store.get(r.shapeId);if(!a||!Ri(a)||!t.editing.canEditShape(a)||ca(t,a.id))return;t.editing.start({shapeId:a.id,entryMode:"placeCaret",caretPagePoint:e.pagePoint,operationKind:If,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 s=e.screenPoint.x-r.originScreenPoint.x,i=e.screenPoint.y-r.originScreenPoint.y;if(s*s+i*i>9)return;const a=t.store.get(r.shapeId),l=t.selection.getIds();if(!a||!Rf(a)||t.layers.isLocked(a.id)||t.state.$_shapeEditingSession.get()||1!==l.length||l[0]!==a.id||ga(t,a.id,"geo-label"))return;const d=Of(t,a);d&&ba(t,d,{editOperationKind:Tf,createOperationKind:Cf,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||!Ri(e)||!r.editing.canEditShape(e)||ca(r,e.id))return;return r.editing.start({shapeId:e.id,entryMode:"selectAll",operationKind:If},"user"),Ef}if("double_click"===o.type)return n(),function(t,e){const n=t.shapes.hitTesting.atPoint(e.pagePoint);if(!n)return!1;if(Ri(n))return!(!t.editing.canEditShape(n)||ca(t,n.id))&&(t.editing.start({shapeId:n.id,entryMode:"selectAll",operationKind:If},"user"),!0);return Rf(n)?function(t,e){return!t.layers.isLocked(e.id)&&($f(t,e.id),!0)}(t,n):!!hf(t,n)&&function(t,e,n){return!t.layers.isLocked(e.id)&&(Lf(t,e.id,n),!0)}(t,n,e.pagePoint)}(r,o)?Ef:void 0;if("pointer"===o.type&&"pointer_down"===o.name){n();const i=function(t,e,n,r){const o=t.shapes.hitTesting.atPoint(e.pagePoint);if(!o||!Ri(o)||!t.editing.canEditShape(o)||ca(t,o.id))return;const s=t.state.$_shapeEditingSession.get();if(s&&s.shapeId!==o.id)return t.editing.complete("user")?(t.editing.start({shapeId:o.id,entryMode:"placeCaret",caretPagePoint:e.pagePoint,operationKind:If,preserveInteraction:!0},"user"),Ef):Ef;!s&&n<2&&function(t,e){const n=t.selection.getIds();if(1!==n.length)return!1;if(n[0]===e)return!0;const r=ya(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,s.pointer?.clickCount??1,e=>{t=e});return"stop"===i?.propagation||t?i:void function(t,e,n,r){const o=t.shapes.hitTesting.atPoint(e.pagePoint),s=t.selection.getIds();if(!o||!Rf(o)||t.layers.isLocked(o.id)||t.state.$_shapeEditingSession.get()||e.shiftKey||e.altKey||e.accelKey||n>=2||1!==s.length||s[0]!==o.id||ga(t,o.id,"geo-label"))return;r({pointerId:e.pointerId,shapeId:o.id,originScreenPoint:{x:e.screenPoint.x,y:e.screenPoint.y}})}(r,o,s.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()||!Ri(e.shape))return null;const n=t.bindings.relations.getOwnedByShape(e.shape.id).find(df),r=n?lf(n):null;if(!n||!r||r.targetId!==e.selectionTargetId)return null;const o=t.store.get(r.targetId),s=t.shapes.geometry.getPageBounds(e.shape.id);if(!o||!s||t.layers.isLocked(o.id)||!hf(t,o))return null;const i=s.center.sub(e.originPagePoint);return{shapeId:o.id,operationKind:Mf,onDragStart({editor:t}){t.selection.set([o.id],{source:"system"})},update({editor:t,pagePoint:e,source:r}){const o=t.store.get(n.id),s=df(o)?lf(o):null,a=t.store.get(n.ownerId),l=s?t.store.get(s.targetId):null;if(!(df(o)&&s&&Ri(a)&&l))return"stop";const d=hf(t,l);if(!d)return"stop";const c=Nf({editor:t,label:a,pathGeometry:d,pagePoint:e.add(i),hintPosition:s.props.labelPosition,snapToDefault:!0});return Math.abs(c-s.props.labelPosition)>1e-6&&t.bindings.setEndpoint({bindingId:o.id,endpoint:{...s,props:{...s.props,labelPosition:c}}},{source:r}),{status:"continue",finalPagePoint:d.getPointAt(c)}}}}(t,e)}}}function Lf(t,e,n){const r=t.store.get(e);if(!r||t.layers.isLocked(r.id))return!1;const o=hf(t,r);if(!o)return!1;const s=ga(t,r.id,sa),i=s??function(t,e,n){const r=hf(t,e);if(!r)return null;const o=Bf(e,{...Oi(t),autoSize:!1,textAlign:"middle"}),s=r.getNearestPosition(n,{hintPosition:r.defaultPosition}),i=pf(t,o,e,s),a=ma(t,{bindingType:sa,owner:e,operationKind:Pf,index:`${e.index}${af}`,layout:i,bindingProps:{labelPosition:s}});if(!a)return null;const l=t.store.get(a.id),d=t.bindings.relations.getOwnedByShape(a.id).find(df);if(!Ri(l)||!d)return a;const c=Nf({editor:t,label:l,pathGeometry:r,pagePoint:n,hintPosition:s,snapToDefault:!1});if(Math.abs(c-s)>1e-6){const e=lf(d);if(!e)return a;t.bindings.setEndpoint({bindingId:d.id,endpoint:{...e,props:{...e.props,labelPosition:c}}},{source:"user"})}return a}(t,r,n??o.getPointAt(o.defaultPosition));return!!i&&(ba(t,i,{editOperationKind:"path-label.edit",createOperationKind:Pf,isExisting:!!s}),!0)}function $f(t,e){const n=t.store.get(e);if(!n||!Rf(n)||t.layers.isLocked(n.id))return!1;const r=ga(t,n.id,ia),o=r??Of(t,n);return!!o&&(ba(t,o,{editOperationKind:Tf,createOperationKind:Cf,isExisting:!!r,entryMode:r?"selectAll":"focusEnd"}),!0)}function Rf(t){return"geo"===t.type}function Nf({editor:t,label:e,pathGeometry:n,pagePoint:r,hintPosition:o,snapToDefault:s}){let i=n.getNearestPosition(r,{hintPosition:o});if(s){const e=n.defaultPosition,r=n.getPointAt(e),o=n.getPointAt(i),s=Math.max(t.state.$_cameraZoom.get(),1e-4);o.dist(r)*s<=10&&(i=e)}const a=ff(t,e,n);return Math.min(a.end,Math.max(a.start,i))}function Of(t,e){const n=Sf(t,Bf(e,{...Oi(t),autoSize:!1,textAlign:"middle"}),e);return ma(t,{bindingType:ia,owner:e,operationKind:Cf,index:`${e.index}${gf}`,layout:n,bindingProps:{normalizedAnchor:{x:.5,y:.5}}})}function Bf(t,e){return{id:"shape:draft",typeName:"shape",scope:"document",type:"text",subType:null,parentId:t.parentId,index:`${t.index}.label`,x:0,y:0,rotation:0,scaleX:1,scaleY:1,opacity:1,isHidden:!1,lockMode:"none",meta:{},props:e}}function zf({fontCatalog:t=ji()}={}){return{shapeUtils:[new nf],shapeSvgExporters:[new rf(t)],bindingUtils:[new xf,new uf],interactionHandlers:[Af()],tools:{text:t=>new Uh(t)}}}function Hf({editor:t,fontCatalog:e}){return function({editor:t,fontCatalog:e}){return{createGeoLabel:(n,r)=>function(t,e,n,r){const o=t.store.get(n);return!o||"geo"!==o.type||t.state.$_readonly.get()||t.layers.isLocked(n)||la(t,n)?null:t.operations.run({kind:"geo-label.create",source:"user"},()=>{const n=Bi(t,{x:o.x,y:o.y,parentId:o.parentId,index:`${o.index}${gf}`,props:{richText:pi(r.richText),autoSize:!1,...void 0!==r.font?{font:r.font}:{},...void 0!==r.size?{size:r.size}:{},...void 0!==r.lineHeight?{lineHeight:r.lineHeight}:{},...void 0!==r.color?{color:r.color}:{},textAlign:r.textAlign??"middle",padding:0,fill:x("transparent"),stroke:x("transparent"),backgroundColor:x("transparent"),strokeWidth:0,cornerRadius:0,shadow:!1}});t.bindings.create({type:ia,ownerId:n.id,endpoints:[{slot:"owner",targetId:o.id,props:{...aa(r)}}]},{source:"user"});const s=t.store.get(n.id);return Ri(s)&&eh(t,s,e,"user"),{id:n.id,type:"text"}})}(t,e,n,r),getGeoLabelLayout:e=>la(t,e)?da(t,e):null,setGeoLabelLayout:(n,r)=>function(t,e,n,r){const o=la(t,n);return!(!o||t.state.$_readonly.get()||t.layers.isLocked(n)||t.layers.isLocked(o.ownerId))&&t.operations.run({kind:"geo-label.layout",source:"user"},()=>{const s=aa({...da(t,n),...r});t.bindings.update({id:o.id,endpoints:o.endpoints.map(t=>({...t,props:{...t.props,...s}}))},{source:"user"});const i=t.store.get(o.ownerId);return Ri(i)&&eh(t,i,e,"user"),!0})}(t,e,n,r),create(e){const n=t.shapes.getDefaultProps("text"),r=e.richText?pi(e.richText):li(e.text??""),[o]=t.shapes.create([{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,autoSize:e.autoSize??n.autoSize,font:e.font??n.font,color:e.color??n.color,size:e.size??n.size,lineHeight:void 0===e.lineHeight?n.lineHeight:e.lineHeight,textAlign:e.textAlign??n.textAlign,padding:e.padding??n.padding,fill:e.fill??n.fill,stroke:e.stroke??n.stroke,strokeWidth:e.strokeWidth??n.strokeWidth,cornerRadius:e.cornerRadius??n.cornerRadius,shadow:e.shadow??n.shadow,richText:r,plainText:di(r)}}],{source:"user"});return"text"===o?.type?{id:o.id,type:o.type}:null},resolveLayoutSize(t){const n={w:t.w,h:t.h};return"undefined"!=typeof document&&document.body?function(t,e){return Fp(t.richText,{props:t},e)}(t,e)??n:n},startEditing(e){const n=e??t.selection.getIds()[0],r=n?t.store.get(n):null;return!(!r||"text"!==r.type||ca(t,r.id))&&(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&&$f(t,r)},startEditingPathLabel(e){const n=t.selection.getIds(),r=e??(1===n.length?n[0]:void 0);return!!r&&Lf(t,r)},getBoundTextLabel(e){const n=ga(t,e,"geo-label")??ga(t,e,"path-label");return n&&n.props.plainText.trim().length>0?{id:n.id,type:n.type}:null},getFormattingSnapshot:()=>function(t){return kp(t)?.getSnapshot()??null}(t),subscribeFormatting:e=>function(t,e){const n=vp(t);return n.listeners.add(e),()=>{n.listeners.delete(e)}}(t,e),setSelectionStyle(e,n){if(void 0!==e.lineHeight&&void 0===Vp(e.lineHeight))return[];const r=n?null:kp(t);if(r){const n={...void 0!==e.fill?{fill:e.fill}:{},...void 0!==e.stroke?{stroke:e.stroke}:{},...void 0!==e.strokeWidth?{strokeWidth:e.strokeWidth}:{},...void 0!==e.cornerRadius?{cornerRadius:e.cornerRadius}:{},...void 0!==e.shadow?{shadow:e.shadow}:{},...void 0!==e.padding?{padding:e.padding}:{}};return Object.keys(n).length>0&&t.shapes.update([{id:r.shapeId,props:n}],{source:"user"}),void 0!==e.color&&r.setColor(_f(e.color)),void 0!==e.backgroundColor&&r.setBackgroundColor(_f(e.backgroundColor)),void 0!==e.font&&r.setFont(e.font),void 0!==e.size&&r.setSize(e.size),void 0!==e.lineHeight&&r.setLineHeight(e.lineHeight),void 0!==e.textAlign&&r.setTextAlign(e.textAlign),[r.shapeId]}const o=Df(t,n).filter(e=>!ca(t,e.id)).map(t=>({id:t.id,props:{...e,...void 0!==e.lineHeight?{richText:Ap(t.props.richText,"lineHeight")}:{}}}));return o.length>0&&t.shapes.update(o.map(({id:t,props:e})=>({id:t,props:{...e}})),{source:"user"}),o.map(({id:t})=>t)},getInlineFormatState(e,n){const r=n?null:kp(t);if(r)return r.getSnapshot()?.[e]??!1;const o=Df(t,n).map(t=>Tp(t.props.richText,e));if(0===o.length)return!1;const s=o[0]??!1;return o.every(t=>t===s)?s:"mixed"},toggleInlineFormat(e,n){const r=n?null:kp(t);if(r)return r.toggle(e);const o=Df(t,n).filter(e=>!ca(t,e.id)),s=!o.every(t=>!0===Tp(t.props.richText,e)),i=o.map(t=>({shape:t,richText:Cp(t.props.richText,e,s)})).filter(({shape:t,richText:e})=>e!==t.props.richText);return 0!==i.length&&(t.shapes.update(i.map(({shape:t,richText:e})=>({id:t.id,props:{richText:e}})),{source:"user"}),!0)},getBlockType(e){const n=e?null:kp(t);if(n)return n.getSnapshot()?.blockType??null;const r=Df(t,e).map(t=>Ip(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:kp(t);if(r)return r.setBlockType(e);const o=Df(t,n).filter(e=>!ca(t,e.id)).map(t=>({shape:t,richText:Pp(t.props.richText,e)})).filter(({shape:t,richText:e})=>e!==t.props.richText);return 0!==o.length&&(t.shapes.update(o.map(({shape:t,richText:e})=>({id:t.id,props:{richText:e,plainText:di(e)}})),{source:"user"}),!0)},clearFormatting(){const e=kp(t);if(e)return e.clearFormatting();const n=t.state.$_selectedShapes.get().filter(Ri).filter(e=>!ca(t,e.id)).map(t=>({shape:t,richText:Lp(t.props.richText)})).filter(({shape:t,richText:e})=>e!==t.props.richText||!H(t.props.backgroundColor));return 0!==n.length&&(t.shapes.update(n.map(({shape:t,richText:e})=>({id:t.id,props:{richText:e,backgroundColor:x("transparent")}})),{source:"user"}),!0)},getLinkHref(){const e=kp(t);if(e)return e.getSnapshot()?.linkHref??null;const n=t.state.$_selectedShapes.get().filter(Ri).map(t=>function(t){const e=[];if(Op(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=kp(t);if(n)return n.setLink(e);const r=null===e?null:Qs(e);if(null!==e&&null===r)return!1;const o=t.state.$_selectedShapes.get().filter(Ri).filter(e=>!ca(t,e.id)).map(t=>({shape:t,richText:Ep(t.props.richText,r)})).filter(({shape:t,richText:e})=>e!==t.props.richText);return 0!==o.length&&(t.shapes.update(o.map(({shape:t,richText:e})=>({id:t.id,props:{richText:e}})),{source:"user"}),!0)},toolDefaultsState:w(t.signalGraph.computed("Text.toolDefaults",()=>t.shapes.getDefaultProps("text"))),setToolDefaults:e=>(t.shapes.updateDefaultProps("text",e),t.shapes.getDefaultProps("text"))}}({editor:t,fontCatalog:e})}function Df(t,e){if(e){const n=t.store.get(e);return Ri(n)?[n]:[]}return t.state.$_selectedShapes.get().filter(Ri)}function _f(t){const e=W(t);return"transparent"===e?null:e}function jf(t={}){const{fontCatalog:e,openLink:n,...r}=t,o={..._i(),...r},s=e??Fi(o);return v({id:"text",editor:zf({fontCatalog:s}),render:Dh({fontCatalog:s,formattingToolbar:o.formattingToolbar,openLink:n,onTiptapEditorChange:o.onTiptapEditorChange}),setup:({editor:t})=>({api:Hf({editor:t,fontCatalog:s})})})}var Ff=jf();function Wf(t){ei(t)&&window.open(t,"_blank","noopener,noreferrer")}function Uf(t){return{kind:"svg-inliner",id:"text.svg-inliner",async inline({exportedShapes:e,svg:n}){const r=e.filter(Ri),o=r.map(t=>t.props.plainText).join(""),s=new Set(r.map(t=>t.props.font)),i=[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("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}`));var o}({definition:e,isDefault:e===t.defaultFont,svg:n,usedFontIds:s})),a=(await Promise.all(i.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=Vf(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 qf(r,t.id);return Yf(Xf(await Kf(await o.text(),o.url||r,t.id)),t.id)}return async function(t,e){const n="string"==typeof t.src?Yf(Xf(await Kf(t.src,void 0,e)),e):`url("${await Gf(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("&","&").replaceAll("<","<").replaceAll(">",">")}</style>`;var o;return`${n[0]}${r}${t.slice(n[0].length)}`}(n,a.join("\n")):n}}}async function Kf(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 s of new Set(r)){if(s.startsWith("data:")||s.startsWith("#"))continue;const t=Vf(s,e).href,r=await Gf(await(await qf(t,n)).blob(),n);o.set(s,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 Xf(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 Yf(t,e){if(!/\burl\(\s*["']?data:/iu.test(t))throw new Error(`Font resource "${e}" has no embeddable source.`);return t}async function qf(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 Gf(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 Vf(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 Jf(t={}){const e=t.fontCatalog??Fi({..._i(),...t});return oe({id:"text.host",setup({editor:t,run:n}){const r=new Set,o=async n=>{for(const r of t.shapes.getAll()){if(!Ri(r))continue;await Zp(r.props.font,e,{text:r.props.plainText}),await se(t,n),n.throwIfAborted();const o=t.store.get(r.id);Ri(o)&&o.props.font===r.props.font&&!t.state.$_readonly.get()&&eh(t,o,e)}},s=t.operations.subscribe(()=>{for(const e of t.shapes.getAll()){if(!Ri(e)||r.has(e.props.font))continue;const t=e.props.font;r.add(t),n(o).catch(()=>r.delete(t))}});return{api:{loadFont:({font:t,text:r})=>n(async n=>{const o=await Zp(t,e,{text:r});return n.throwIfAborted(),o})},exports:[Uf(e)],assetResolvers:[{id:"text.fonts",resolve:()=>null,async preload({signal:t}){await Zp(Hi,e),t.throwIfAborted(),await o(t)}}],dispose:s}}})}var Zf=["✍️ 双击此处输入文字..","可以在此输入提示词,比如画面描述、产品卖点、活动主题、场景描述、品牌 slogan 等内容。若暂时没有明确内容,也可先输入关键词或草稿,后续随时修改优化哦!","也可以在底部输入框输入需求,让AI自动完成文字生成。"].join("\n");function Qf(t,e){if("text"===e){const n=t.shapes.getDefaultProps("text"),r=360,o=8,s=n.h+2*o;return{kind:e,w:r,h:s,contentProps:{...n,w:r,h:s,autoSize:!1,backgroundColor:x("#ffffff"),padding:o,richText:li(Zf),plainText:Zf,textAlign:"start"}}}const n=t.shapes.getDefaultProps("image");return{kind:e,w:n.w,h:n.h,contentProps:{...n,altText:""}}}function tg(t,e){if(t.state.$_readonly.get())return null;const n=t.store.get(e);if(!n||rs(n)||"text"!==n.type&&"image"!==n.type||t.layers.isLocked(n.id)||t.shapes.isHidden(n.id))return null;const r=t.operations.begin({kind:"flow.wrap-shape",label:"shape.wrap-flow-node",source:"user",history:"record"});try{t.shapes.update([{id:n.id,subType:ts}],{source:"user"});const e=t.store.get(n.id);return rs(e)?(t.selection.set([e.id],{source:"system"}),r.commit(),{nodeId:e.id}):(r.cancel(),null)}catch(o){throw r.isActive&&r.cancel(),o}}function eg(t,e){if(t.state.$_readonly.get())return null;const n=t.store.get(e);if(!rs(n)||t.layers.isLocked(n.id)||t.shapes.isHidden(n.id)||t.bindings.relations.getTargetingShape(n.id).some(t=>ss(t)&&t.endpoints.some(({slot:t,targetId:e})=>"end"===t&&e===n.id)))return null;const r=t.operations.begin({kind:"flow.unwrap-node",label:"shape.unwrap-flow-node",source:"user",history:"record"});try{t.shapes.update([{id:n.id,subType:null}],{source:"user"});const e=t.store.get(n.id);return e&&null===e.subType?(t.selection.set([e.id],{source:"system"}),r.commit(),e):(r.cancel(),null)}catch(o){throw r.isActive&&r.cancel(),o}}var ng=96;function rg(t,e,n,r={}){if(t.state.$_readonly.get())return null;const o=t.store.get(e.shape.id);if(!o||t.layers.isLocked(o.id)||t.shapes.isHidden(o.id))return null;const i=T(t,o,e.port.id);if(!i||!Hs({shape:o,port:i}))return null;const a=function(t,e,n,r,o,i){const a=Qf(t,r),l=i?.w??a.w,d=i?.h??a.h,c=e.parentId,u=c.startsWith("shape:")?t.store.get(c):null,p=u?t.shapes.geometry.computeLocalToPageTransform(u):s.Identity(),h=p.tryInvert();let g;if(o){const t=h?.applyToPoint(o)??o;g=new f(t.x,t.y-d/2)}else{const t=n.pageOutwardNormal.normalize(),e=new f(l/2,d/2),r=p.applyToPoint(e),o=p.applyToPoint(e.add(new f(l/2,0))),s=p.applyToPoint(e.add(new f(0,d/2))),i=Math.abs(og(o.sub(r),t))+Math.abs(og(s.sub(r),t)),a=n.pagePoint.add(t.mul(96+i));g=(h?.applyToPoint(a)??a).sub(new f(l/2,d/2))}return{type:r,subType:ts,parentId:c,x:g.x,y:g.y,rotation:0,props:{...a.contentProps,w:l,h:d}}}(t,o,i,n,r.inputPortPagePoint,r.initialSize),l=r.inputPortPagePoint?a:Ms(t,{shape:o,port:i},a,function(t,e){const n=[],r=new Set;for(const o of t.state.$_shapeIds.get()){const s=t.store.get(o);if(!ns(s))continue;const i=Fs(t,s.id);if(i.start?.targetId!==e.shape.id||i.start.props.portId!==e.port.id||!i.end||r.has(i.end.targetId))continue;const a=t.store.get(i.end.targetId);a&&(r.add(a.id),n.push(a))}return n}(t,{shape:o,port:i})),d=t.operations.begin({kind:`flow.create-${n}-node`,label:"shape.create",source:"user",history:"record"});try{const e=t.shapes.create([l],{source:"user",autoReparent:!1})[0];if(!rs(e))return d.cancel(),null;const n=T(t,e,Bs);return n&&Ks(t,{start:fs(o.id,i),end:fs(e.id,n),selectionAfter:[e.id]})?(d.commit(),{nodeId:e.id}):(d.cancel(),null)}catch(c){throw d.isActive&&d.cancel(),c}}function og(t,e){return t.x*e.x+t.y*e.y}var sg=class extends Error{code;nodeId;edgeId;constructor(t,e,n){super(e),this.name="FlowConnectionError",this.code=t,this.nodeId=n.nodeId,this.edgeId=n.edgeId}};function ig({editor:t}){const e=new Map;let n=!1;const r=()=>{if(n)throw new Error("Disposed Flow API rejected connection operation.")},o=t.operations.subscribe(({diff:t})=>{for(const n of function(t,e){if(0===e.size)return new Set;const n=new Set,r=t=>{e.has(t)&&n.add(t)},o=t=>{if(ss(t))for(const{targetId:e}of t.endpoints)r(e)};for(const s of t.added)z(s)&&r(s.id),o(s);for(const s of t.removed)z(s)&&r(s.id),o(s);for(const{before:s,after:i}of t.updated)z(s)&&z(i)&&(s.type!==i.type||s.subType!==i.subType)&&r(i.id),o(s),o(i);return n}(t,e))e.get(n)?.refresh()});return{value:{connections:{forNode(n){r();let o=e.get(n);return o||(o=function(t,e){const n=new Set;let r={snapshot:ug(t,e)},o=!1;return{readable:{getSnapshot(){if(r.error)throw r.error;return r.snapshot},subscribe:t=>o?()=>{}:(n.add(t),()=>n.delete(t))},refresh(){if(o)return;const s=function(t,e){try{return{snapshot:ug(t,e)}}catch(n){if(n instanceof sg)return{error:n};throw n}}(t,e);if(a=s,!((i=r).error||a.error?i.error?.code===a.error?.code&&i.error?.nodeId===a.error?.nodeId&&i.error?.edgeId===a.error?.edgeId:i.snapshot.node.id===a.snapshot.node.id&&i.snapshot.node.type===a.snapshot.node.type&&fg(i.snapshot.inputs,a.snapshot.inputs)&&fg(i.snapshot.outputs,a.snapshot.outputs))){var i,a;r=s;for(const t of[...n])t()}},dispose(){o||(o=!0,n.clear())}}}(t,n),e.set(n,o)),o.readable},connect:e=>(r(),function(t,e){pg(t,e.targetNodeId),dg(t,{nodeId:e.targetNodeId,shapeIds:[e.sourceShapeId,e.targetNodeId]});const n=ag(e.sourceShapeId,zs),r=ag(e.targetNodeId,Bs);lg(t,n,r,{nodeId:e.targetNodeId});const o=Ks(t,{start:n,end:r,selectionAfter:"none"});o||cg("operation_failed","Flow connection creation failed.",{nodeId:e.targetNodeId});return hg(t,e.targetNodeId,o.id)}(t,e)),reconnect:e=>(r(),function(t,e){t.store.get(e.edgeId)||cg("connection_not_found",`Flow connection "${e.edgeId}" was not found.`,{nodeId:e.shapeId,edgeId:e.edgeId});const n=hg(t,e.shapeId,e.edgeId),r="start"===e.terminal?e.shapeId:n.source.shape.id,o="end"===e.terminal?e.shapeId:n.target.shape.id;pg(t,o),dg(t,{nodeId:o,edgeId:e.edgeId,shapeIds:[e.edgeId,r,o]});const s=ag(r,zs),i=ag(o,Bs);lg(t,s,i,{nodeId:o,edgeId:e.edgeId}),t.operations.run({kind:"flow-edge.reconnect",label:"shape.update",source:"user",history:"record"},()=>Ys(t,e.edgeId,e.terminal,"start"===e.terminal?s:i))||cg("operation_failed",`Flow connection "${e.edgeId}" terminal update failed.`,{nodeId:o,edgeId:e.edgeId});return hg(t,o,e.edgeId)}(t,e)),disconnect(e){r(),function(t,e){pg(t,e.nodeId);const n=t.store.get(e.edgeId);if(!n)throw new sg("connection_not_found",`Flow connection "${e.edgeId}" was not found.`,e);if(!ns(n))throw new sg("unsupported_link",`Shape "${e.edgeId}" is not a supported Flow connection.`,e);const r=hg(t,e.nodeId,e.edgeId);if(r.source.shape.id!==e.nodeId&&r.target.shape.id!==e.nodeId)throw new sg("connection_not_attached",`Flow connection "${e.edgeId}" is not attached to node "${e.nodeId}".`,e);if(t.state.$_readonly.get())throw new sg("readonly","Readonly canvas rejected Flow connection disconnect.",e);if(t.layers.isLocked(e.edgeId)||t.layers.isLocked(r.source.shape.id)||t.layers.isLocked(r.target.shape.id))throw new sg("locked",`Locked Flow connection "${e.edgeId}" cannot be disconnected.`,e);t.operations.run({kind:"flow-edge.disconnect",label:"shape.delete",source:"user",history:"record"},()=>t.shapes.delete([e.edgeId],{source:"user"}))}(t,e)}},createNodeFromPort:e=>(r(),function(t,e){dg(t,{nodeId:e.sourceShapeId,shapeIds:[e.sourceShapeId]});const n=t.store.get(e.sourceShapeId),r=n?T(t,n,zs):null;n&&r||cg("missing_endpoint",`Flow source "${e.sourceShapeId}" output port was not found.`,{nodeId:e.sourceShapeId});const o=rg(t,{shape:n,port:r},e.kind,{inputPortPagePoint:e.inputPortPagePoint?new f(e.inputPortPagePoint.x,e.inputPortPagePoint.y):void 0}),s=o?t.store.get(o.nodeId):null;rs(s)||cg("operation_failed",`Flow ${e.kind} node creation failed.`,{nodeId:e.sourceShapeId});return{id:s.id,type:s.type}}(t,e)),wrapShape(e){const n=tg(t,e),r=n?t.store.get(n.nodeId):null;return!r||"text"!==r.type&&"image"!==r.type?null:{id:r.id,type:r.type}},unwrapNode(e){const n=eg(t,e);return n?{id:n.id,type:n.type}:null}},dispose(){if(!n){n=!0,o();for(const t of e.values())t.dispose();e.clear()}}}}function ag(t,e){return{kind:"bound",shapeId:t,attachment:{kind:"port",portId:e}}}function lg(t,e,n,r){const o=Us(t,e,n,r.edgeId);o&&cg("locked_source"===o?"locked":o,`Flow connection rejected: ${o}.`,r)}function dg(t,e){t.state.$_readonly.get()&&cg("readonly","Readonly canvas rejected Flow connection mutation.",e);const n=e.shapeIds.find(e=>t.layers.isLocked(e));n&&cg("locked",`Locked shape "${n}" rejected Flow connection mutation.`,e)}function cg(t,e,n){throw new sg(t,e,n)}function ug(t,e){const n=pg(t,e),r=new Set;for(const s of t.bindings.relations.getTargetingShape(e))ss(s)&&r.add(s.ownerId);const o=[...r].flatMap(n=>{const r=Fs(t,n);return r.start&&r.end?[hg(t,e,n)]:[]}).sort((t,e)=>y(t.edgeId,e.edgeId));return{node:n,inputs:o.filter(({target:t})=>t.shape.id===e),outputs:o.filter(({source:t})=>t.shape.id===e)}}function pg(t,e){const n=t.store.get(e);if(!n)throw new sg("node_not_found",`Flow node "${e}" was not found.`,{nodeId:e});if(!rs(n))throw new sg("unsupported_node",`Shape "${e}" does not support Flow connections.`,{nodeId:e});return{id:n.id,type:n.type}}function hg(t,e,n){const r=t.store.get(n),o=Ws(t,n),s=Fs(t,n),i=s.start?t.store.get(s.start.targetId):null,a=s.end?t.store.get(s.end.targetId):null;if(!ns(r)||1!==o.length||2!==o[0].endpoints.length||!s.start||!s.end||"right"!==s.start.props.portId||"left"!==s.end.props.portId||!i||"text"!==i.type&&"image"!==i.type||!rs(a))throw new sg("unsupported_link",`Flow connection "${n}" has unsupported endpoints.`,{nodeId:e,edgeId:n});return{edgeId:n,source:{shape:{id:i.id,type:i.type},portId:s.start.props.portId},target:{shape:{id:a.id,type:a.type},portId:s.end.props.portId}}}function fg(t,e){return t.length===e.length&&t.every((t,n)=>{const r=e[n];return!!r&&t.edgeId===r.edgeId&&t.source.shape.id===r.source.shape.id&&t.source.shape.type===r.source.shape.type&&t.source.portId===r.source.portId&&t.target.shape.id===r.target.shape.id&&t.target.shape.type===r.target.shape.type&&t.target.portId===r.target.portId})}function gg(t,e){if(e){const n=new Map;if("bound"===e.start.kind){const r=t.store.get(e.start.shapeId);r&&n.set(r.id,r)}return e.target&&n.set(e.target.shape.id,e.target.shape),{visibleShapes:[...n.values()],sourceShapeIds:"bound"===e.start.kind?new Set([e.start.shapeId]):new Set}}const n=t.state.$_selectedShapes.get(),r=1===n.length?n[0]:null;return r&&wg(r)?{visibleShapes:[r],sourceShapeIds:new Set([r.id])}:{visibleShapes:[],sourceShapeIds:new Set}}function mg(t,e,n){return n.has(e.id)?rs(t)&&"left"===e.id?"input":"right"!==e.id||"text"!==t.type&&"image"!==t.type?null:"output":null}function yg(t,e,n={}){const r=vs(t,e,{portFilter:t=>Ds(t)&&(n.portFilter?.(t)??!0)});if(r)return r;const o=t.shapes.hitTesting.allAtPoint(e,{hitTest:"bindingTarget",filter:rs});for(const s of o){const e=T(t,s,Bs);if(!e)continue;const r={shape:s,port:e};if(!n.portFilter||n.portFilter(r))return r}return null}function wg(t){return"text"===t.type||"image"===t.type}var xg={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"}},bg=(t,e,n,r)=>{const o=et(({color:n="currentColor",size:o=24,stroke:s=2,title:i,className:a,children:l,...d},c)=>tt("svg",{ref:c,...xg[t],width:o,height:o,className:["tabler-icon",`tabler-icon-${e}`,a].join(" "),..."filled"===t?{fill:n}:{strokeWidth:s,stroke:n},...d},[i&&tt("title",{key:"svg-title"},i),...r.map(([t,e])=>tt(t,e)),...Array.isArray(l)?l:[l]]));return o.displayName=`${n}`,o},kg=bg("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"}]]),vg=bg("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"}]]),Sg=bg("outline","plus","Plus",[["path",{d:"M12 5l0 14",key:"svg-0"}],["path",{d:"M5 12l14 0",key:"svg-1"}]]),Ig=bg("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"}]]),Pg=bg("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"}]]),Mg=new WeakMap;var Tg=184,Cg="var(--land-shape-stroke-muted, #94a3b8)",Eg={heading:"flow-node-canvas-heading",dragHandle:"flow-node-drag-handle",name:"flow-node-canvas-name",input:"flow-node-canvas-name-input"},Ag=()=>{},Lg={id:"land.flow.dom-events",handle:({event:t,name:e})=>t.target instanceof Element?t.target.closest("[data-flow-node-menu]")?"handled":"key_down"!==e&&"key_up"!==e||!t.target.closest("[data-flow-port-button]")?"continue":"handled":"continue",getCursor:({element:t})=>t?.closest("[data-flow-connector-port]")?"pointer":void 0};function $g(t={}){const e=new Set(t.visiblePortIds??es);return{shapeRenderers:[{type:"flow-edge",component:Rg,hoverComponent:Ng}],shapeDecorations:[{id:"land.flow.node-chrome",subType:ts,component:Bg}],canvasOverlays:[{id:"land.flow.connector-ports",order:110,component:()=>J(zg,{visiblePortIds:e})}],domEventGuards:[Lg]}}function Rg({editor:t,shape:e}){const n=G(t.state.$_selectedShapeIds);
|
|
21
|
+
return J(Og,{editor:t,shape:e,stroke:G(t.bindings.relations.getOwnedByShapeSignal(e.id)).some(t=>ss(t)&&t.endpoints.some(({targetId:t})=>n.includes(t)))?"var(--land-shape-stroke-slate, #334155)":Cg})}function Ng({editor:t,shape:e,strokeWidth:n}){
|
|
22
|
+
return J(Og,{dataUi:"flow-edge-hover-outline",editor:t,shape:e,stroke:d,strokeWidth:n,vectorEffect:"non-scaling-stroke"})}function Og({dataUi:t,editor:e,shape:n,stroke:r,strokeWidth:o=n.props.strokeWidth,vectorEffect:s}){const i=Is(e,n),a=e.shapes.geometry.computeRenderBounds(n),l=r??Y(n.props.stroke);
|
|
23
|
+
return Z("svg",{"data-ui":t,width:"100%",height:"100%",viewBox:`${a.x} ${a.y} ${a.w} ${a.h}`,overflow:"visible",children:[J("path",{"data-flow-edge-path":"body",d:i.path,fill:"none",stroke:l,strokeWidth:o,strokeDasharray:"dashed"===n.props.strokeStyle?"8 6":void 0,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:s}),i.markerPath?J("path",{"data-flow-edge-path":"marker",d:i.markerPath,fill:"none",stroke:l,strokeWidth:o,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:s}):null]})}function Bg({editor:t,shape:e}){if(!rs(e))return null;const n="text"===e.type?Ig:kg;
|
|
24
|
+
return J(c,{editor:t,shape:e,isEditing:!1,value:os(e),fallback:os(e),bodyWidth:e.props.w,bodyHeight:e.props.h,renderHeight:0,operationKind:"flow-node.edit",editAriaLabel:"Flow node title",inputAriaLabel:"Flow node title",dataUi:Eg,onValueChange:Ag,leading:J(n,{"data-ui":"flow-node-title-icon","data-flow-node-kind":e.type,size:14,stroke:1.7}),color:"var(--land-text-muted, #64748b)",offsetX:0,editable:!1,showDragHandle:!1})}var zg=nt(function({visiblePortIds:t}){const e=q(),n=G(e.state.$_readonly),r=G(e.state.$_tool).activeToolId;G(e.state.$_selectedShapes);const o=G(e.state.$_shapeEditingSession),s=G(e.inputs.$_isSpacePressed),i=G(e.render.interaction.$_selectionTranslationActive),a=G(e.state.$_cameraZoom),l=Os(e),d=G(l.$_preview),c=G(l.$_nodeCreationRequest),u=d??c?.preview??null,p=Math.max(a,1e-4),h=gg(e,u),f="select"===r?h.visibleShapes.filter(wg):[],g=f.filter(t=>h.sourceShapeIds.has(t.id)),m=c?function(t,e,n,r){const o=e.find(t=>t.id===n.shapeId);if(!o)return null;const s=T(t,o,n.portId);return s&&"output"===mg(o,s,r)?{shape:o,port:s}:null}(e,g,c.source,t):null,y=null!==m,w=null!==c&&null===m;st(()=>{w&&l.$_nodeCreationRequest.set(null)},[w,l]);const x=rt(()=>{l.$_nodeCreationRequest.set(null)},[l]);st(()=>{if(!y)return;const t=t=>{var e;(e=t.target)instanceof Element&&e.closest("[data-flow-ui]")||x()},e=t=>{"Escape"===t.key&&x()};return document.addEventListener("pointerdown",t),document.addEventListener("keydown",e),()=>{document.removeEventListener("pointerdown",t),document.removeEventListener("keydown",e)}},[x,y]);const b=rt(t=>{const e=l.$_nodeCreationRequest.get();l.$_nodeCreationRequest.set(e?.source.shapeId===t.shapeId&&e.source.portId===t.portId?null:{source:t})},[l]),k=rt(t=>{m&&(rg(e,m,t,{initialSize:Hg(e,t),inputPortPagePoint:c?.inputPortPagePoint}),x())},[x,e,c,m]);return n||o||s||i||0===f.length?null:Z("g",{"data-ui":"flow-connector-ports-overlay",children:[
|
|
25
|
+
J("style",{children:Xg}),u?.isDragging?J(Dg,{preview:u}):null,f.flatMap(n=>C(e,n).map(e=>{const r=mg(n,e,t);if(!r)return null;const o="output"===r&&h.sourceShapeIds.has(n.id),s="input"===r&&u?.target?.shape.id===n.id&&u.target.port.id===e.id;if("input"===r&&!s)return null;const i={shapeId:n.id,portId:e.id};
|
|
26
|
+
return J(_g,{isInteractive:o,isOpen:m?.shape.id===n.id&&m.port.id===e.id,isTargeted:s,onToggle:()=>b(i),port:e,role:r,shape:n,zoom:p},`${n.id}:${e.id}`)})),m?J(jg,{anchor:c?.inputPortPagePoint,onCreate:k,port:m.port,zoom:p}):null]})});function Hg(t,e){const n=Qf(t,e);if("text"===n.kind)return function(t){const e=Mg.get(t);if(!e)throw new Error("FlowNodeCreationRuntime is not initialized for this editor.");return e}(t).resolveTextLayoutSize(n.contentProps)??{w:n.w,h:n.h}}function Dg({preview:t}){const e=q().shapes.getDefaultProps("flow-edge"),n=Ps({start:{point:t.startPoint,outwardNormal:t.startNormal},end:{point:t.endPoint,outwardNormal:t.endNormal},props:e}),r=t.target?"var(--land-selection, #2563eb)":Cg;
|
|
27
|
+
return Z("g",{"data-flow-edge-preview":"true",pointerEvents:"none",children:[J("path",{d:n.path,fill:"none",stroke:r,strokeWidth:e.strokeWidth,strokeLinecap:"round",strokeLinejoin:"round"}),n.markerPath?J("path",{d:n.markerPath,fill:"none",stroke:r,strokeWidth:e.strokeWidth,strokeLinecap:"round",strokeLinejoin:"round"}):null]})}function _g({isInteractive:t,isOpen:e,isTargeted:n,onToggle:r,port:o,role:s,shape:i,zoom:a}){const[l,d]=ct(!1),c="input"===s?o.pagePoint:ks(o,a),u=12/a;
|
|
28
|
+
return J("g",{"data-flow-connector-port":"true","data-flow-connector-port-id":o.id,"data-flow-connector-port-shape-id":i.id,"data-flow-port-role":s,"data-flow-ui":t?"true":void 0,pointerEvents:t?"all":"none",onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:t?Z("g",{"aria-expanded":e,"aria-haspopup":"menu","aria-label":"新增节点","data-flow-port-button":"true",role:"button",tabIndex:0,onKeyDown:t=>{"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),r())},style:{cursor:"pointer"},children:[J("circle",{"data-flow-port-hit-area":"true",cx:c.x,cy:c.y,r:u,fill:"transparent",pointerEvents:"all"}),J(Wg,{active:l||e,outwardNormal:o.pageOutwardNormal,point:c,role:s,zoom:a})]}):J(Wg,{active:n,outwardNormal:o.pageOutwardNormal,point:c,role:s,zoom:a})})}function jg({anchor:t,onCreate:e,port:n,zoom:r}){const o=q(),s=G(o.state.$_viewportScreenSize),i=function(t,e,n,r){const o=t.viewport.pageToScreen(new f(e.x,e.y)),s=Tg,i=120,a=16,l=8,d=n.pageOutwardNormal;let c,u;if(Math.abs(d.x)>=Math.abs(d.y)){const t=d.x>=0?o.x+a:o.x-a-s,e=d.x>=0?o.x-a-s:o.x+a;c=Ug(t,s,r.w,l)?t:e,u=o.y-i/2}else{const t=d.y>=0?o.y+a:o.y-a-i,e=d.y>=0?o.y-a-i:o.y+a;c=o.x-s/2,u=Ug(t,i,r.h,l)?t:e}const p=t.viewport.screenToPage(new f(Kg(c,s,r.w,l),Kg(u,i,r.h,l)));return{x:p.x,y:p.y}}(o,t??ks(n,r),n,s);
|
|
29
|
+
return J("foreignObject",{"data-flow-node-menu":"true",height:120/r,overflow:"visible",pointerEvents:"all",width:Tg/r,x:i.x,y:i.y,children:Z("div",{"aria-label":"新增节点","data-flow-ui":"true",onPointerDown:t=>{t.stopPropagation()},role:"menu",style:{...Yg,transform:`scale(${1/r})`},children:[
|
|
30
|
+
J("div",{"data-flow-menu-title":"true",style:qg,children:"新增节点"}),
|
|
31
|
+
J(Fg,{icon:Pg,label:"文字生成",onSelect:()=>e("text")}),
|
|
32
|
+
J(Fg,{icon:vg,label:"图片生成",onSelect:()=>e("image")})]})})}function Fg({icon:t,label:e,onSelect:n}){
|
|
33
|
+
return Z("button",{"data-flow-menu-item":e,onClick:n,role:"menuitem",style:Gg,type:"button",children:[J(t,{"aria-hidden":"true",size:16,strokeWidth:2}),J("span",{children:e})]})}function Wg({active:t,outwardNormal:e,point:n,role:r,zoom:o}){if("input"===r){if(!t)return null;const r=new f(-e.y,e.x).normalize(),s=12/o,i=n.sub(r.mul(s)),a=n.add(r.mul(s));
|
|
34
|
+
return J("line",{"data-flow-port-input-highlight":"true",x1:i.x,y1:i.y,x2:a.x,y2:a.y,stroke:"var(--land-selection, #2563eb)",strokeWidth:3/o,strokeLinecap:"round",pointerEvents:"none",style:{filter:"drop-shadow(0 1px 2px rgba(37, 99, 235, 0.3))"}})}const s=20/o/2*(t?1.2:1),i=14/o;
|
|
35
|
+
return Z("g",{pointerEvents:"none",children:[J("circle",{"data-flow-port-visual":"true",cx:n.x,cy:n.y,r:s,fill:"var(--land-selection, #2563eb)",style:{filter:"drop-shadow(0 1px 1.5px rgba(15, 23, 42, 0.24))"}}),J(Sg,{"aria-hidden":"true","data-flow-port-plus-icon":"true",x:n.x-i/2,y:n.y-i/2,width:i,height:i,color:"#ffffff",strokeWidth:2.5})]})}function Ug(t,e,n,r){return t>=r&&t+e<=n-r}function Kg(t,e,n,r){return Math.min(Math.max(t,r),Math.max(r,n-e-r))}var Xg="\n [data-flow-port-visual] {\n transition: r 120ms ease;\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",Yg={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:Tg},qg={color:"var(--muted-foreground, #64748b)",fontSize:12,fontWeight:600,lineHeight:"18px",padding:"2px 8px 4px"},Gg={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%"},Vg=class extends t{type="flow-edge";getDefaultEndpointProps(){return{portId:"right"}}validateEndpointProps(t,e){return function(t,e){const n=t&&"object"==typeof t?t:{};return{portId:"string"==typeof n.portId&&n.portId.length>0?n.portId:e}}(e,"right")}canBind(t,e,n){if(!ns(n.ownerShape)||e.endpoints.some(({slot:t})=>"start"!==t&&"end"!==t))return!1;for(const{endpoint:s,targetShape:i}of n.endpoints){const e=ws(t,i,s.props);if(!e||!_s(s.slot,{shape:i,port:e}))return!1}const r=e.endpoints.find(({slot:t})=>"start"===t),o=e.endpoints.find(({slot:t})=>"end"===t);return!(r&&o&&this.changesGraphTopology(t,e)&&js(t,r.targetId,o.targetId,e.ownerId))}getExclusiveBindingKey(t){return t.ownerId}onBindingCreate(t,e){return Jg(e)||Os(t).rebindEdgeId===e.ownerId?this.getSyncEffect(t,e.ownerId):{deleteShapeIds:[e.ownerId]}}onBindingUpdate(t,e,n){return Jg(n)||Os(t).rebindEdgeId===n.ownerId?this.getSyncEffect(t,n.ownerId):{deleteShapeIds:[n.ownerId]}}onBindingLoad(t,e){return this.getSyncEffect(t,e.ownerId)}onInvalidBindingLoad(t,e){return{deleteShapeIds:[e.ownerId]}}onAfterShapeChange(t,e){return this.getSyncEffect(t,e.ownerId)}onBeforeDeleteShape(t,e,n){return n.owner?{deleteBindingIds:[e.id]}:{deleteShapeIds:[e.ownerId]}}onBeforeDeleteBinding(t,e){if(Os(t).rebindEdgeId!==e.ownerId)return{deleteShapeIds:[e.ownerId]};const n=t.store.get(e.ownerId);if(!ns(n))return{deleteBindingIds:[e.id]};const r=Ss(t,n);let o=n;for(const s of e.endpoints)o=Xs(t,o,s.slot,"start"===s.slot?r.startPoint:r.endPoint)??o;return{shapes:[o],deleteBindingIds:[e.id],suppressBindingIds:[e.id]}}getGeometryDependentShapeIds(t,e,n){return n.endpointSlots.length>0?[e.ownerId]:[]}changesGraphTopology(t,e){const n=t.store.get(e.id);return!ss(n)||(n.ownerId!==e.ownerId||["start","end"].some(t=>{const r=n.endpoints.find(e=>e.slot===t),o=e.endpoints.find(e=>e.slot===t);return r?.targetId!==o?.targetId}))}getSyncEffect(t,e){const n=t.store.get(e);if(!ns(n))return;const r=function(t,e){return qs(t,e)}(t,n);var o,s;return r&&(s=r,(o=n).parentId!==s.parentId||o.x!==s.x||o.y!==s.y||o.rotation!==s.rotation||o.scaleX!==s.scaleX||o.scaleY!==s.scaleY||JSON.stringify(o.props)!==JSON.stringify(s.props))?{shapes:[r],suppressBindingIds:Ws(t,e).map(({id:t})=>t)}:void 0}};function Jg(t){return t.endpoints.some(({slot:t})=>"start"===t)&&t.endpoints.some(({slot:t})=>"end"===t)}var Zg="flow-edge.rebind",Qg={propagation:"stop"},tm={propagation:"stop",clickSequence:"break"};function em(){return{id:"land.flow-edge.interactions",priority:100,editorEvent:{handleEvent(t,e){const n=Os(t),r=n.pointerSession;if("cancel"===e.type)return r?.cancel(e.reason),r?Qg:void 0;if(!r){if("pointer"!==e.type||"pointer_down"!==e.name||0!==e.button)return;const r=function(t,e){if("select"!==t.state.$_tool.get().activeToolId||t.state.$_readonly.get()||t.state.$_shapeEditingSession.get()||t.inputs.$_isSpacePressed.get())return null;const n=gg(t,null),r=n.visibleShapes[0];if(!r||!n.sourceShapeIds.has(r.id)||t.layers.isLocked(r.id)||t.shapes.isHidden(r.id)||null===t.shapes.geometry.getClippedPageBounds(r.id))return null;if(!Os(t).isPortVisible("right"))return null;const o=T(t,r,"right");if(!o)return null;const s=Math.max(t.state.$_cameraZoom.get(),1e-4),i=12/s;return e.dist(ks(o,s))<=i?{shape:r,port:o}:null}(t,e.pagePoint);if(!r)return;const o=new nm(t,r,e.screenPoint,e.pointerId);return n.setPointerSession(o),Qg}if("tick"===e.type){const n=t.inputs.$_state.get();if(n.pointerId===r.pointerId&&n.currentScreenPoint){const o=P(n.currentScreenPoint,t.state.$_viewportScreenSize.get(),e.elapsed);0===o.x&&0===o.y||(t.viewport.pan(o),r.update(n.currentScreenPoint,t.viewport.screenToPage(n.currentScreenPoint),n.accelKey))}return Qg}if("pointer"!==e.type||e.pointerId!==r.pointerId)return Qg;if("pointer_move"===e.name)r.update(e.screenPoint,e.pagePoint,e.accelKey);else{if("pointer_up"===e.name)return r.complete(e.screenPoint,e.pagePoint,e.accelKey)?tm:Qg;"pointer_cancel"===e.name&&r.cancel("pointer_cancel")}return Qg}},selectionHandle:{createSession:(t,{handle:e,shape:n})=>"binding_terminal"===e.kind&&ns(n)?function(t,e,n){if(!ns(t.store.get(e)))return null;const r=n.terminal,o="start"===r?"end":"start";let s=null;return{shapeId:e,operationKind:Zg,onDragStart(){Os(t).setRebindEdgeId(e)},update({pagePoint:n,accelKey:i,source:a}){Os(t).setRebindEdgeId(e);const l=Fs(t,e)[o],d=i?null:("end"===r?yg:vs)(t,n,{portFilter:n=>_s(r,n)&&(!l||!js(t,"start"===r?n.shape.id:l.targetId,"start"===r?l.targetId:n.shape.id,e))&&("start"!==r||!t.layers.isLocked(n.shape.id))}),c=d&&!function(t,e,n,r,o){return!!r&&("start"===n?Gs(t,o.shape.id,o.port.id,r.targetId,r.props.portId,e):Gs(t,r.targetId,r.props.portId,o.shape.id,o.port.id,e))}(t,e,r,l,d)?d:null;s=c;const u=Fs(t,e)[r];if(!c&&u){const n=Ws(t,e)[0];n&&t.bindings.clearEndpoint({bindingId:n.id,slot:r},{source:a})}const p=t.store.get(e);if(!ns(p))return{status:"stop"};const h=c?.port.pagePoint??n,f=Xs(t,p,r,h);return f&&function(t,e,n){t.shapes.update([{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:new Set(Ws(t,e.id).map(t=>t.id))})}(t,f,a),c&&!Ys(t,e,r,fs(c.shape.id,c.port),a)?{status:"stop"}:{status:"continue",finalPagePoint:h}},onCancel(){Os(t).setRebindEdgeId(null)},onComplete(){Os(t).setRebindEdgeId(null),!s&&t.store.get(e)&&t.shapes.delete([e],{source:"user"})}}}(t,n.id,e):null}}}var nm=class{editor;source;originScreenPoint;pointerId;preview;initialSelectedShapeIds;operation;props;didClearSelection=!1;constructor(t,e,n,r){this.editor=t,this.source=e,this.originScreenPoint=n,this.pointerId=r,this.initialSelectedShapeIds=t.selection.getIds(),this.props=t.shapes.getDefaultProps("flow-edge");const o=gs(t,fs(e.shape.id,e.port));if(!o?.port)throw new Error("Flow edge creation requires a resolvable output port");this.preview={start:o.draft,end:{kind:"free",pagePoint:o.pagePoint.clone()},startPoint:o.pagePoint,endPoint:o.pagePoint,startNormal:o.port.pageOutwardNormal,endNormal:o.port.pageOutwardNormal.mul(-1),isDragging:!1,invalidReason:null,target:null},this.operation=t.operations.begin({kind:"flow-edge.create",label:"shape.create",source:"user",history:"record"}),Os(t).$_preview.set(this.preview)}update(t,e,n){const r=this.originScreenPoint.dist(t)>4;r&&!this.didClearSelection&&(this.initialSelectedShapeIds.length>0&&this.editor.selection.set([],{source:"user"}),this.didClearSelection=!0);const o=r&&!n?yg(this.editor,e,{portFilter:t=>!js(this.editor,this.source.shape.id,t.shape.id)}):null,s=fs(this.source.shape.id,this.source.port),i=o?fs(o.shape.id,o.port):{kind:"free",pagePoint:e},a=gs(this.editor,s),l=gs(this.editor,i);if(!a?.port||!l)return void this.cancel("command");const d={start:s,end:i,startPoint:a.pagePoint,endPoint:l.pagePoint,startNormal:a.port.pageOutwardNormal,endNormal:l.port?l.port.pageOutwardNormal:a.port.pageOutwardNormal.mul(-1),isDragging:r,invalidReason:Us(this.editor,s,i),target:o};Object.assign(this.preview,d),Os(this.editor).$_preview.set({...d})}complete(t,e,n){if(this.update(t,e,n),Os(this.editor).pointerSession!==this)return!1;if(!this.preview.isDragging)return this.clear(),this.operation.cancel(),this.toggleNodeCreationRequest(),!1;if(!this.preview.target&&!this.editor.shapes.hitTesting.atPoint(e)){const t={...this.preview};return this.clear(),this.operation.cancel(),this.restoreSelection(),Os(this.editor).$_nodeCreationRequest.set({inputPortPagePoint:e.clone(),preview:t,source:{shapeId:this.source.shape.id,portId:this.source.port.id}}),!0}const r=!this.preview.invalidReason&&!!Ks(this.editor,{start:this.preview.start,end:this.preview.end,props:this.props,selectionAfter:"edge"});return this.clear(),r?(Os(this.editor).$_nodeCreationRequest.set(null),this.operation.commit()):(this.operation.cancel(),this.restoreSelection()),r}cancel(t){this.clear(),this.operation.isActive&&this.operation.cancel(),this.restoreSelection()}clear(){const t=Os(this.editor);t.$_preview.set(null),t.setPointerSession(null)}toggleNodeCreationRequest(){const t=Os(this.editor),e=t.$_nodeCreationRequest.get(),n={shapeId:this.source.shape.id,portId:this.source.port.id};t.$_nodeCreationRequest.set(e?.source.shapeId===n.shapeId&&e.source.portId===n.portId?null:{source:n})}restoreSelection(){this.didClearSelection&&this.editor.selection.set(this.initialSelectedShapeIds,{source:"system"})}};var rm=new Set(["straight","orthogonal","curved"]),om=new Set(["solid","dashed"]),sm=new Set(["none","arrow"]),im=class extends p{type="flow-edge";getDefaultProps(){return{w:1,h:1,start:{x:0,y:.5},end:{x:1,y:.5},routing:"curved",stroke:k("stroke-muted"),strokeWidth:2,strokeStyle:"solid",headStart:"none",headEnd:"arrow",cornerRadius:5}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:am(e.w,n.w,1),h:am(e.h,n.h,1),start:lm(e.start,n.start),end:lm(e.end,n.end),routing:rm.has(e.routing)?e.routing:n.routing,stroke:B(e.stroke)?_(e.stroke,n.stroke):n.stroke,strokeWidth:am(e.strokeWidth,n.strokeWidth,.5),strokeStyle:om.has(e.strokeStyle)?e.strokeStyle:n.strokeStyle,headStart:sm.has(e.headStart)?e.headStart:n.headStart,headEnd:sm.has(e.headEnd)?e.headEnd:n.headEnd,cornerRadius:am(e.cornerRadius,n.cornerRadius,0)}}getLocalBounds(t){return new e(0,0,t.props.w,t.props.h).expand(Math.max(6,4*t.props.strokeWidth))}canSnap(){return!1}canTransformSelection(){return!1}canUseSelectionHandle(){return!1}canStartTranslateFromSelectionBounds(){return!1}contributesToSelectionFrame(t,e){return!0}getSelectionHandleAnchors(t,e){if(!e.isOnlySelected)return{terminalHandleAnchors:[],middleHandleAnchors:[]};const n=Ss(e.editor,t);return{terminalHandleAnchors:[{kind:"binding_terminal",terminal:"start",point:n.startPoint},{kind:"binding_terminal",terminal:"end",point:n.endPoint}],middleHandleAnchors:[],customHandleAnchors:[]}}getSelectionOverlayInfo(t,e){const n=Ss(e.editor,t),r=Is(e.editor,t);return{usesSelectionPathOverlay:!0,startPagePoint:n.startPoint,endPagePoint:n.endPoint,middlePagePoint:null,path:n.path,pathStyle:{localPath:r.path,localDecorationPaths:r.markerPath?[r.markerPath]:[],localBounds:r.bounds,localToPage:e.editor.shapes.geometry.computeLocalToPageTransform(t),strokeWidth:t.props.strokeWidth,strokeDasharray:"dashed"===t.props.strokeStyle?"8 6":void 0},bindingSegments:[]}}canCopyToClipboard(t,e){const n=Fs(e.editor,t.id);return!!(n.start&&n.end&&e.copiedShapeIds.has(n.start.targetId)&&e.copiedShapeIds.has(n.end.targetId))}isValidAfterBindingLoad(t,e){const n=Fs(e.editor,t.id);return!!(n.start&&n.end&&Ws(e.editor,t.id).some(t=>e.editor.bindings.reactions.canBind(t)))}isWrappedByBrush(t,e){return Ss(e.editor,t).points.every(t=>e.brushBounds.containsPoint(t))}hitTest(t,e,n){const r=n?.editor?Ss(n.editor,t).points:[new f(t.x+t.props.start.x,t.y+t.props.start.y),new f(t.x+t.props.end.x,t.y+t.props.end.y)],o=n?.editor?Math.max(8/Math.max(n.editor.state.$_cameraZoom.get(),1e-4),4):8;return function(t,e){let n=1/0;for(let r=1;r<t.length;r+=1)n=Math.min(n,dm(e,t[r-1],t[r]));return n}(r,n?.pagePoint??e)<=o}hitTestLineSegment(t,e){const n=e.editor?Ss(e.editor,t).points:[new f(t.x+t.props.start.x,t.y+t.props.start.y),new f(t.x+t.props.end.x,t.y+t.props.end.y)],r=e.editor?e.pageStart:e.positionedStart,o=e.editor?e.pageEnd:e.positionedEnd,s=e.editor?e.pageMargin:e.positionedMargin;for(let i=1;i<n.length;i+=1)if(Math.min(dm(n[i-1],r,o),dm(n[i],r,o),dm(r,n[i-1],n[i]),dm(o,n[i-1],n[i]))<=s)return!0;return!1}};function am(t,e,n=-1/0){return"number"==typeof t&&Number.isFinite(t)?Math.max(t,n):e}function lm(t,e){const n=t&&"object"==typeof t?t:{};return{x:am(n.x,e.x),y:am(n.y,e.y)}}function dm(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist(e);const s=t.sub(e),i=Math.max(0,Math.min(1,(s.x*r.x+s.y*r.y)/o));return t.dist(e.add(r.mul(i)))}var cm=34;function um(t){return new e(0,-34,t.props.w,t.props.h+34)}var pm=class{id="land.flow.node-chrome";subType=ts;getExportBounds(t){return rs(t)?um(t):null}getPointHitTestBounds(t,n){return rs(t)?A({bodyHeight:t.props.h,bodyWidth:t.props.w,headingHeight:34,shape:t}):new e(t.x,t.y,0,0)}hitTest(t,e,n){return rs(t)&&L({bodyHeight:t.props.h,bodyWidth:t.props.w,editor:n.editor,headingHeight:34,shape:t}).containsPoint(e)}toSvg(t,e){return rs(t)?{tag:"g",children:[{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:[os(t)]}]}:null}},hm=class{type="flow-edge";toSvg(t,e){const n=Is(e.editor,t),r=e.resolveColor(t.props.stroke),o=[{tag:"path",attrs:{d:n.path,fill:"none",stroke:r,"stroke-width":t.props.strokeWidth,"stroke-dasharray":"dashed"===t.props.strokeStyle?"8 6":void 0,"stroke-linecap":"round","stroke-linejoin":"round"}}];return n.markerPath&&o.push({tag:"path",attrs:{d:n.markerPath,fill:"none",stroke:r,"stroke-width":t.props.strokeWidth,"stroke-linecap":"round","stroke-linejoin":"round"}}),{tag:"g",children:o}}};function fm(){const t=new pm;return{shapeUtils:[new im],shapeSvgExporters:[new hm],shapeSvgDecorations:[t],shapeHitTestDecorations:[t],bindingUtils:[new Vg],interactionHandlers:[em()]}}function gm(t){const e=[...t.visiblePortIds??es],{image:n,text:r}=t;return v({id:"flow",requires:[n,r],editor:fm(),render:$g({visiblePortIds:e}),setup({api:n,editor:o}){const s=n(r),i=function(t){let e=null;const n={resolveTextLayoutSize:t=>e?.(t),setTextLayoutResolver(t){e=t},dispose(){Mg.delete(t),e=null}};return Mg.set(t,n),n}(o),a=function(t,e){const n=t.signalGraph.atom("flow.edge-preview",null),r=t.signalGraph.atom("flow.node-creation-request",null),o=new Set(e.visiblePortIds);let s=null,i=null;const a={allowCycles:e.allowCycles,$_nodeCreationRequest:r,$_preview:n,get pointerSession(){return s},get rebindEdgeId(){return i},isPortVisible:t=>o.has(t),setPointerSession(t){s=t},setRebindEdgeId(t){i=t},dispose(){Ns.delete(t),s?.cancel("dispose"),s=null,i=null,r.set(null),n.set(null)}};return Ns.set(t,a),a}(o,{allowCycles:t.allowCycles??!0,visiblePortIds:e});try{i.setTextLayoutResolver(t=>s.resolveLayoutSize(t));const t=ig({editor:o});return{api:t.value,dispose(){try{t.dispose()}finally{try{a.dispose()}finally{i.dispose()}}}}}catch(l){try{a.dispose()}finally{i.dispose()}throw l}}})}var mm=["rectangle","ellipse","message-circle","summary","summary-left","burst","rhombus","triangle","pentagon","hexagon","star","trapezoid","arrow-left","arrow-right"],ym=["solid","dashed","dotted","none"],wm=["none","solid","tint","pattern","linear","radial"];function xm(t){return z(t)&&"geo"===t.type}function bm(t){return"string"==typeof t&&mm.includes(t)}function km(t){return"string"==typeof t&&ym.includes(t)}function vm(t){return"string"==typeof t&&wm.includes(t)}var Sm=new WeakMap;function Im(t){const e=Sm.get(t);if(!e)throw new Error("GeoCreationRuntime is not initialized for this editor.");return e}function Pm(t,n){return new e(t.x,t.y,n.w,n.h)}var Mm=class extends h{kind;constructor(t,e,n){super(t,e),this.kind=n,this.initial="idle",this.addChild(new Tm(t,this)),this.addChild(new Cm(t,this))}getDefaultProps(){return{...this.editor.shapes.getDefaultProps("geo"),kind:this.kind}}onEnter(){this.editor.shapes.updateDefaultProps("geo",{kind:this.kind})}},Tm=class extends h{tool;constructor(t,e){super(t,"idle",e),this.tool=e}onEnter(){this.editor.interaction.clearSelection()}onExit(){Im(this.editor).clearHover()}onPointerMove(t){const e=Im(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})}},Cm=class extends h{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(Pm(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&&F(this.editor,this.info.shapeId,{source:"user"}),this.commitOperation(),this.editor.state.$_tool.get().isToolLocked?this.transition("idle"):this.editor.tools.select("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,n,r){if(!this.info)return;const o=this.info.originScreenPoint.dist(n);if(!this.info.isDragCreating){if(o<4)return;this.info.isDragCreating=!0}const s=function(t,n,r){let o=n.x-t.x,s=n.y-t.y;if(r){const t=Math.max(Math.abs(o),Math.abs(s));o=(o<0?-1:1)*t,s=(s<0?-1:1)*t}const i=new f(t.x+o,t.y+s);return new e(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,r),i=this.info.shapeId;i&&this.editor.shapes.update([{id:i,x:s.x,y:s.y,props:{w:s.w,h:s.h}}],{source:"user"})}createShape(t,e){const[n]=this.editor.shapes.create([{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.selection.set([n.id],{source:"system"}),n}},Em=class extends Mm{constructor(t){super(t,"rectangle","rectangle")}},Am=class extends Mm{constructor(t){super(t,"ellipse","ellipse")}},Lm=class extends Mm{constructor(t){super(t,"message-circle","message-circle")}},$m=class extends Mm{constructor(t){super(t,"summary","summary")}},Rm=class extends Mm{constructor(t){super(t,"summary-left","summary-left")}},Nm=class extends Mm{constructor(t){super(t,"burst","burst")}},Om=class extends Mm{constructor(t){super(t,"rhombus","rhombus")}},Bm=class extends Mm{constructor(t){super(t,"triangle","triangle")}},zm=class extends Mm{constructor(t){super(t,"pentagon","pentagon")}},Hm=class extends Mm{constructor(t){super(t,"hexagon","hexagon")}},Dm=class extends Mm{constructor(t){super(t,"star","star")}},_m=class extends Mm{constructor(t){super(t,"trapezoid","trapezoid")}},jm=class extends Mm{constructor(t){super(t,"arrow-left","arrow-left")}},Fm=class extends Mm{constructor(t){super(t,"arrow-right","arrow-right")}},Wm=/[AaCcHhLlMmVvZz]|[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?/g,Um=/^[AaCcHhLlMmVvZz]$/,Km=Math.PI/6,Xm=1e-8;function Ym(t){const e=t.match(Wm)??[],n=t.replace(Wm,"").replace(/[\s,]/g,"");if(n.length>0)throw new Error(`Unsupported SVG path content: ${n}`);const r=[];let o=null,s=null,i=new f(0,0),a=0;for(;a<e.length;){const t=e[a];if(t&&Um.test(t)&&(s=t,a+=1,"z"===s.toLowerCase())){if(!o)throw new Error("SVG path closes before starting a subpath.");o.closed=!0,i=o.start.clone(),s=null;continue}if(!s)throw new Error("SVG path data is missing a command.");const n=s,l=qm(n),d=Gm(e,a,l);a+=l;const c=n===n.toLowerCase();switch(n.toLowerCase()){case"m":i=Jm(i,d[0],d[1],c),o={start:i.clone(),segments:[],closed:!1},r.push(o),s=c?"l":"L";break;case"l":{const t=Jm(i,d[0],d[1],c);Zm(o,{type:"line",start:i,end:t}),i=t;break}case"h":{const t=new f(c?i.x+d[0]:d[0],i.y);Zm(o,{type:"line",start:i,end:t}),i=t;break}case"v":{const t=new f(i.x,c?i.y+d[0]:d[0]);Zm(o,{type:"line",start:i,end:t}),i=t;break}case"c":{const t=Jm(i,d[0],d[1],c),e=Jm(i,d[2],d[3],c),n=Jm(i,d[4],d[5],c);Zm(o,{type:"cubic",start:i,control1:t,control2:e,end:n}),i=n;break}case"a":{const t=Vm(d[3]),e=Vm(d[4]),n=Jm(i,d[5],d[6],c);Zm(o,{type:"arc",start:i,end:n,radiusX:Math.abs(d[0]),radiusY:Math.abs(d[1]),rotation:d[2],largeArc:t,sweep:e}),i=n;break}}}return r}function qm(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 Gm(t,e,n){const r=[];for(let o=0;o<n;o+=1){const n=t[e+o];if(!n||Um.test(n))throw new Error("SVG path command has incomplete numeric values.");const s=Number(n);if(!Number.isFinite(s))throw new Error(`Invalid SVG path number: ${n}`);r.push(s)}return r}function Vm(t){if(0!==t&&1!==t)throw new Error(`SVG arc flag must be 0 or 1, received ${t}.`);return 1===t}function Jm(t,e,n,r){return r?new f(t.x+e,t.y+n):new f(e,n)}function Zm(t,e){if(!t)throw new Error("SVG path draws before starting a subpath.");t.segments.push(e)}function Qm(t){const e=[t.start.clone()];for(const n of t.segments)switch(n.type){case"line":dy(e,n.end);break;case"cubic":{const t=[...Array.from({length:8},(t,e)=>(e+1)/8),...ey(n)].sort((t,e)=>t-e).filter((t,e,n)=>0===e||Math.abs(t-(n[e-1]??t))>Xm);for(const r of t)dy(e,ty(n,r));break}case"arc":for(const t of ry(n))dy(e,t)}return t.closed&&e.length>1&&cy(e[0],e[e.length-1])&&e.pop(),e}function ty(t,e){const n=1-e,r=n*n*n,o=3*n*n*e,s=3*n*e*e,i=e*e*e;return new f(t.start.x*r+t.control1.x*o+t.control2.x*s+t.end.x*i,t.start.y*r+t.control1.y*o+t.control2.y*s+t.end.y*i)}function ey(t){return[...ny(t.start.x,t.control1.x,t.control2.x,t.end.x),...ny(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))>Xm)}function ny(t,e,n,r){const o=3*e-t-3*n+r,s=2*(t-2*e+n),i=e-t;if(Math.abs(o)<=Xm)return Math.abs(s)<=Xm?[]:[-i/s];const a=s*s-4*o*i;if(a<-1e-8)return[];const l=Math.sqrt(Math.max(0,a));return[(-s-l)/(2*o),(-s+l)/(2*o)]}function ry(t){const e=oy(t);if(!e)return[t.end.clone()];const n=Math.max(1,Math.ceil(Math.abs(e.deltaAngle)/Km)),r=[...Array.from({length:n},(t,e)=>(e+1)/n),...sy(e).map(t=>function(t,e){return iy(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))>Xm),o=[];for(const s of r){const t=e.startAngle+e.deltaAngle*s;o.push(ly(e,t))}return o[o.length-1]=t.end.clone(),o}function oy(t){if(0===t.radiusX||0===t.radiusY||cy(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,s=(t.start.y-t.end.y)/2,i=n*o+r*s,a=-r*o+n*s;let l=t.radiusX,d=t.radiusY;const c=i*i/(l*l)+a*a/(d*d);if(c>1){const t=Math.sqrt(c);l*=t,d*=t}const u=l*l,p=d*d,h=i*i,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,w=0===g?0:y*Math.sqrt(m/g),x=w*(l*a/d),b=w*(-d*i/l),k=n*x-r*b+(t.start.x+t.end.x)/2,v=r*x+n*b+(t.start.y+t.end.y)/2,S=(i-x)/l,I=(a-b)/d,P=(-i-x)/l,M=(-a-b)/d,T=Math.atan2(I,S);let C=(E=S,A=I,L=P,$=M,Math.atan2(E*$-A*L,E*L+A*$));var E,A,L,$;return!t.sweep&&C>0?C-=2*Math.PI:t.sweep&&C<0&&(C+=2*Math.PI),{centerX:k,centerY:v,radiusX:l,radiusY:d,cosRotation:n,sinRotation:r,startAngle:T,deltaAngle:C}}function sy(t){const{radiusX:e,radiusY:n,cosRotation:r,sinRotation:o}=t,s=Math.atan2(-n*o,e*r),i=Math.atan2(n*r,e*o);return[s,s+Math.PI,i,i+Math.PI].filter(e=>function(t,e){return iy(t,e)<=Math.abs(t.deltaAngle)+Xm}(t,e))}function iy(t,e){return t.deltaAngle>=0?ay(e-t.startAngle):ay(t.startAngle-e)}function ay(t){const e=2*Math.PI;return(t%e+e)%e}function ly(t,e){const n=t.radiusX*Math.cos(e),r=t.radiusY*Math.sin(e);return new f(t.centerX+t.cosRotation*n-t.sinRotation*r,t.centerY+t.sinRotation*n+t.cosRotation*r)}function dy(t,e){const n=t[t.length-1];n&&cy(n,e)||t.push(e.clone())}function cy(t,e){return Math.abs(t.x-e.x)<=Xm&&Math.abs(t.y-e.y)<=Xm}var uy=24,py=3.222,hy=12.443999999999999+Math.max(3.191,3.19)+1,fy="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",gy=function(t){const e=function(t){return Ym(t).map(t=>({closed:t.closed,points:Qm(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}(fy),my=function(t){const n=[];for(const e of Ym(t)){n.push(e.start.clone());for(const t of e.segments)switch(n.push(t.end.clone()),t.type){case"line":break;case"cubic":for(const e of ey(t))n.push(ty(t,e));break;case"arc":{const e=oy(t);if(!e)break;for(const t of sy(e))n.push(ly(e,t));break}}}if(0===n.length)throw new Error("SVG path does not contain any points.");return e.FromPoints(n)}(fy),yy=[[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]],wy=[[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]],xy=[[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 by(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 f(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=[_y(t,Py),_y(t,My)];let n=My;for(const r of Ty){for(let o=1;o<=Iy;o+=1)e.push(_y(t,Dy(n,r.control1,r.control2,r.end,o/Iy)));n=r.end}return e}(t);case"summary":case"summary-left":return Xy(t);case"burst":return function(t){return gy.map(e=>Wy(t,(e.x-my.minX)/my.w,(e.y-my.minY)/my.h))}(t);case"rhombus":return[new f(t.center.x,t.minY),new f(t.maxX,t.center.y),new f(t.center.x,t.maxY),new f(t.minX,t.center.y)];case"triangle":return[new f(t.center.x,t.minY),new f(t.maxX,t.maxY),new f(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 f(Math.cos(t),Math.sin(t)))}return Uy(n,t)}(t,5);case"hexagon":return[new f(t.minX+.25*t.w,t.minY),new f(t.maxX-.25*t.w,t.minY),new f(t.maxX,t.center.y),new f(t.maxX-.25*t.w,t.maxY),new f(t.minX+.25*t.w,t.maxY),new f(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 f(Math.cos(t)*r,Math.sin(t)*r))}return Uy(e,t)}(t);case"trapezoid":return function(t){return yy.map(([e,n])=>Wy(t,e/uy,n/uy))}(t);case"arrow-left":return Ry(t,"left").outline;case"arrow-right":return Ry(t,"right").outline;case"rectangle":return function(t,e=vy(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 Xy(t);const o=[];return Ky(o,{centerX:t.maxX-r,centerY:t.minY+r,radius:r,startAngle:-Math.PI/2,endAngle:0,segments:n}),Ky(o,{centerX:t.maxX-r,centerY:t.maxY-r,radius:r,startAngle:0,endAngle:Math.PI/2,segments:n}),Ky(o,{centerX:t.minX+r,centerY:t.maxY-r,radius:r,startAngle:Math.PI/2,endAngle:Math.PI,segments:n}),Ky(o,{centerX:t.minX+r,centerY:t.minY+r,radius:r,startAngle:Math.PI,endAngle:3*Math.PI/2,segments:n}),o}(t,vy({cornerRadiusPercent:n.cornerRadiusPercent,w:t.w,h:t.h}))}return qy(e)}function ky(t,e=12){return Math.min(50,Math.max(0,"number"==typeof t&&Number.isFinite(t)?t:e))}function vy({cornerRadiusPercent:t=12,h:e,w:n}){return Math.min(Math.max(0,n),Math.max(0,e))*ky(t)/100}var Sy=24,Iy=8,Py=new f(3,20),My=new f(4.3,16.1),Ty=[{control1:new f(1.976,12.663),control2:new f(2.874,8.228),end:new f(6.4,5.726)},{control1:new f(9.926,3.225),control2:new f(14.99,3.43),end:new f(18.245,6.206)},{control1:new f(21.5,8.983),control2:new f(21.94,13.472),end:new f(19.274,16.707)},{control1:new f(16.608,19.942),control2:new f(11.659,20.922),end:new f(7.7,19)}];function Cy(t){const e=_y(t,Py),n=_y(t,My),r=[`M${jy(e)}`,`L${jy(n)}`];for(const o of Ty)r.push(`C${jy(_y(t,o.control1))} ${jy(_y(t,o.control2))} ${jy(_y(t,o.end))}`);return r.push(`L${jy(e)}`),r.join(" ")}function Ey(t){const e=t.w/uy,n=t.h/uy;return`translate(${Fy(t.x)} ${Fy(t.y)}) scale(${Fy(e)} ${Fy(n)})`}function Ay(t){const e=t.w/my.w,n=t.h/my.h,r=t.minX-my.minX*e,o=t.minY-my.minY*n;return`translate(${Fy(r)} ${Fy(o)}) scale(${Fy(e)} ${Fy(n)})`}function Ly(t,e){const n=Math.min(t.w/uy,t.h/18),r=t.h/18,o="left"===e?t.minX-3*n:t.maxX-20*n,s=t.minY-3*r;return`translate(${Fy(o)} ${Fy(s)}) scale(${Fy(n)} ${Fy(r)})`}function $y(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:Cy(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:Ly(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:Ly(t,"left"),vectorEffect:"non-scaling-stroke"};case"burst":return{tag:"path",d:fy,transform:Ay(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:Ey(t),vectorEffect:"non-scaling-stroke"};case"arrow-left":return{tag:"path",d:Ry(t,"left").path};case"arrow-right":return{tag:"path",d:Ry(t,"right").path};case"rectangle":{const e=vy({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:by(t,e,n)}}return qy(e)}function Ry(t,e){const n=Math.min(t.h/uy,t.w/hy),r=t.center.y-12*n,o="left"===e?t.minX+py*n:t.maxX-py*n,s="left"===e?o+9.222*n:o-9.222*n;return{outline:("left"===e?wy:xy).map(([o,i])=>function(t,e,n){const{neckX:r,originY:o,scale:s,x:i,y:a}=n;let l;l="left"===e?i<=12.444?r+(i-12.444)*s:i>=20.709?t.maxX-(uy-i)*s:By(i,12.444,20.709,r,t.maxX-3.2910000000000004*s):i>=11.556?r+(i-11.556)*s:i<=3.29?t.minX+i*s:By(i,3.29,11.556,t.minX+3.29*s,r);return new f(l,o+a*s)}(t,e,{neckX:s,originY:r,scale:n,x:o,y:i})),path:"left"===e?Ny(t,{neckX:s,originY:r,scale:n}):Oy(t,{neckX:s,originY:r,scale:n})}}function Ny(t,e){if(Hy(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,s=t.maxX-3.2910000000000004*o;return[`M${jy(new f(n,r+6.416*o))}`,`v${Fy(.9*o)}`,`H${Fy(s)}`,`a${zy(o,[.1,.1,0,0,1,.1,.1])}`,`v${Fy(8.455*o)}`,`a${zy(o,[.1,.1,0,0,1,-.1,.1])}`,`H${Fy(n)}`,`v${Fy(4.314*o)}`,`c${zy(o,[0,.034,-.008,.048,-.014,.056])}`,`a${zy(o,[.1,.1,0,0,1,-.047,.036])}`,`a${zy(o,[.1,.1,0,0,1,-.058,.009])}`,`c${zy(o,[-.01,-.002,-.025,-.005,-.05,-.029])}`,`l${zy(o,[-9.053,-8.641])}`,`a${zy(o,[.1,.1,0,0,1,0,-.145])}`,`l${zy(o,[9.053,-8.641])}`,`c${zy(o,[.025,-.024,.04,-.028,.05,-.03])}`,`a${zy(o,[.1,.1,0,0,1,.058,.01])}`,`a${zy(o,[.1,.1,0,0,1,.047,.036])}`,`c${zy(o,[.006,.008,.014,.022,.014,.056])}`,"z"].join(" ")}function Oy(t,e){if(Hy(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,s=t.minX+3.29*o;return[`M${jy(new f(n-.9*o,r+7.316*o))}`,`H${Fy(n)}`,`V${Fy(r+3.002*o)}`,`c${zy(o,[0,-.034,.008,-.048,.014,-.056])}`,`a${zy(o,[.1,.1,0,0,1,.046,-.036])}`,`a${zy(o,[.1,.1,0,0,1,.059,-.01])}`,`c${zy(o,[.01,.002,.025,.006,.05,.03])}`,`l${zy(o,[9.053,8.641])}`,`a${zy(o,[.1,.1,0,0,1,0,.145])}`,`l${zy(o,[-9.053,8.641])}`,`c${zy(o,[-.025,.024,-.04,.027,-.05,.029])}`,`a${zy(o,[.1,.1,0,0,1,-.059,-.01])}`,`a${zy(o,[.1,.1,0,0,1,-.046,-.035])}`,`c${zy(o,[-.006,-.008,-.014,-.022,-.014,-.056])}`,`V${Fy(r+15.97*o)}`,`H${Fy(s)}`,`a${zy(o,[.1,.1,0,0,1,-.1,-.1])}`,`V${Fy(r+7.416*o)}`,`a${zy(o,[.1,.1,0,0,1,.1,-.1])}`,"z"].join(" ")}function By(t,e,n,r,o){const s=n-e;return 0===s?r:r+(t-e)/s*(o-r)}function zy(t,e){const n=7===e.length;return e.map((e,r)=>Fy(n&&r>=2&&r<=4?e:e*t)).join(" ")}function Hy(t){return 0===t.x&&0===t.y&&t.w===uy&&t.h===uy}function Dy(t,e,n,r,o){const s=1-o,i=s*s*s,a=3*s*s*o,l=3*s*o*o,d=o*o*o;return new f(t.x*i+e.x*a+n.x*l+r.x*d,t.y*i+e.y*a+n.y*l+r.y*d)}function _y(t,e){return Wy(t,e.x/Sy,e.y/Sy)}function jy(t){return`${Fy(t.x)} ${Fy(t.y)}`}function Fy(t){return Number.isFinite(t)?Number(t.toFixed(4)).toString():"0"}function Wy(t,e,n){return new f(t.minX+t.w*e,t.minY+t.h*n)}function Uy(t,n){const r=e.FromPoints([...t]);return 0===r.w||0===r.h?[n.center]:t.map(t=>new f(n.minX+(t.x-r.minX)/r.w*n.w,n.minY+(t.y-r.minY)/r.h*n.h))}function Ky(t,{centerX:e,centerY:n,endAngle:r,radius:o,segments:s,startAngle:i}){const a=Math.max(1,Math.floor(s));for(let l=0;l<=a;l+=1){const s=i+(r-i)*(l/a);t.push(new f(e+Math.cos(s)*o,n+Math.sin(s)*o))}}function Xy(t){return[new f(t.minX,t.minY),new f(t.maxX,t.minY),new f(t.maxX,t.maxY),new f(t.minX,t.maxY)]}function Yy(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist(e);const s=t.sub(e),i=Math.max(0,Math.min(1,(s.x*r.x+s.y*r.y)/o));return t.dist(e.add(r.mul(i)))}function qy(t){throw new Error(`Unsupported geo shape kind: ${String(t)}`)}function Gy(t){return[{id:"start",offset:0,color:t,midpoint:.5},{id:"end",offset:1,color:x("#a855f7"),midpoint:.5}]}function Vy(t,e){if(!Array.isArray(t))return e;const n=new Set,r=[];for(const o of t){if(!o||"object"!=typeof o||!B(o.color)||!Number.isFinite(o.offset))continue;let t="string"==typeof o.id&&o.id?o.id:`stop-${r.length}`;for(;n.has(t);)t+="-copy";n.add(t),r.push({id:t,offset:Math.max(0,Math.min(1,o.offset)),color:o.color,midpoint:Number.isFinite(o.midpoint)?Math.max(.01,Math.min(.99,o.midpoint)):.5})}return r.length>=2?r.sort((t,e)=>t.offset-e.offset):e}function Jy(t,e){return t===e||t.length===e.length&&t.every((t,n)=>{const r=e[n];return t.offset===r.offset&&t.midpoint===r.midpoint&&g(t.color,r.color)})}function Zy(t){if("transparent"===t)return[0,0,0,0];const e=/^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i.exec(t);if(!e)return null;const n=e[1].length<=4?[...e[1]].map(t=>t+t).join(""):e[1];return[0,2,4].map(t=>parseInt(n.slice(t,t+2),16)).concat(8===n.length?parseInt(n.slice(6),16)/255:1)}function Qy(t,e,n){if(n<=0)return t;if(n>=1)return e;const r=Zy(t),o=Zy(e);if(!r||!o)return`color-mix(in srgb, ${t} ${100*(1-n)}%, ${e})`;const s=r[3]*(1-n)+o[3]*n;return`#${[...[0,1,2].map(t=>r[t]*(1-n)+o[t]*n),255*s].map(t=>Math.round(t).toString(16).padStart(2,"0")).join("")}`}function tw(t,e){return t.flatMap((n,r)=>{const o=e(n.color),s=t[r+1],i=[{offset:n.offset,color:o}];return s&&s.offset>n.offset&&.5!==n.midpoint&&i.push({offset:n.offset+(s.offset-n.offset)*n.midpoint,color:Qy(o,e(s.color),.5)}),i})}function ew(t,e){const n=tw(t,W);let r=n[0];for(const o of n.slice(1)){if(o.offset>e){const t=Math.max(0,(e-r.offset)/(o.offset-r.offset));return x(Qy(r.color,o.color,t))}r=o}return x(r.color)}var nw="drop-shadow(0px 2px 4px rgba(0, 0, 0, 0.04)) drop-shadow(0px 1px 1px rgba(0, 0, 0, 0.02))";function rw(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function ow(t,e){return t.x*e.y-t.y*e.x}function sw(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist(e);const s=t.sub(e),i=Math.max(0,Math.min(1,(s.x*r.x+s.y*r.y)/o));return t.dist(e.add(r.mul(i)))}function iw(t,e,n,r){return aw(t,e,n,r)?0:Math.min(sw(t,n,r),sw(e,n,r),sw(n,t,e),sw(r,t,e))}function aw(t,e,n,r){const o=e.sub(t),s=r.sub(n),i=ow(o,s);if(Math.abs(i)<1e-8)return null;const a=n.sub(t),l=ow(a,s)/i,d=ow(a,o)/i;return l<0||l>1||d<0||d>1?null:{point:t.add(o.mul(l)),t:l}}function lw(t,n,r){const o=new e(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,s=t.h/2;if(o<=0||s<=0)return null;const i=e.sub(r),a=n.sub(e),l=a.x/o,d=a.y/s,c=i.x/o,u=i.y/s,p=l*l+d*d,h=2*(c*l+u*d),f=h*h-4*p*(c*c+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))}(o,n,r):function(t,e,n){let r=null;for(let o=0;o<n.length;o+=1){const s=n[o],i=n[(o+1)%n.length]??n[0];if(!s||!i)continue;const a=aw(t,e,s,i);!a||a.t<=1e-6||(!r||a.t<r.t)&&(r=a)}return r?.point??null}(n,r,by(o,t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent}))}function dw(t){return by(new e(0,0,t.props.w,t.props.h),t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent})}var cw=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"];function uw(t){const n=new e(0,0,t.props.w,t.props.h);return[new f(n.minX,n.minY),new f(n.center.x,n.minY),new f(n.maxX,n.minY),new f(n.minX,n.center.y),n.center,new f(n.maxX,n.center.y),new f(n.minX,n.maxY),new f(n.center.x,n.maxY),new f(n.maxX,n.maxY)].map((t,e)=>({point:t,kind:cw[e]??"custom"}))}function pw(t){return"arrow-left"===t.props.kind||"arrow-right"===t.props.kind}function hw(t){return e.FromPoints(by(new e(0,0,t.w,t.h),t.kind,{cornerRadiusPercent:t.cornerRadiusPercent}))}var fw=class extends p{type="geo";getDefaultProps(){return{w:160,h:108,kind:"rectangle",fill:k("fill-slate"),fillStyle:"solid",gradientStops:Gy(k("fill-slate")),gradientAngle:0,stroke:k("stroke-slate"),strokeStyle:"solid",strokeWidth:2,cornerRadiusPercent:12,shadow:!1}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:Math.max(o,rw(e.w,n.w)),h:Math.max(o,rw(e.h,n.h)),kind:bm(e.kind)?e.kind:n.kind,fill:_(e.fill,n.fill),fillStyle:vm(e.fillStyle)?e.fillStyle:n.fillStyle,gradientStops:Vy(e.gradientStops,Gy(_(e.fill,n.fill))),gradientAngle:(rw(e.gradientAngle,n.gradientAngle)%360+360)%360,stroke:_(e.stroke,n.stroke),strokeStyle:km(e.strokeStyle)?e.strokeStyle:n.strokeStyle,strokeWidth:Math.max(1,rw(e.strokeWidth,n.strokeWidth)),cornerRadiusPercent:ky(e.cornerRadiusPercent,n.cornerRadiusPercent),shadow:"boolean"==typeof e.shadow?e.shadow:n.shadow}}getLocalBounds(t){return new e(0,0,t.props.w,t.props.h)}getRenderBounds(t){return this.getLocalBounds(t).expand(t.props.shadow?14:0)}getExportBounds(t){return this.getRenderBounds(t)}canReceiveTerminalBinding(t){return!0}getPositionedOutlineVertices(t){return by(this.getPositionedBounds(t),t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent})}getSelectionResizeLocalBounds(t){return pw(t)?hw(t.props):this.getLocalBounds(t)}resizeSelectionBounds(t,n){if(!pw(t))return super.resizeSelectionBounds(t,n);const r=hw(t.props).w*Math.abs(n.scaleX),s=Math.max(o,t.props.h*Math.abs(n.scaleY)),i=function({direction:t,height:e,selectionWidth:n}){const r=py+("left"===t?3.191:3.19),o=e/uy,s=n+r*o;return s>=hy*o?s:n/(1-r/hy)}({direction:"arrow-left"===t.props.kind?"left":"right",height:s,selectionWidth:r}),a=this.validateProps({...t.props,w:i,h:s}),l=hw(a),d=E({localWidth:l.w,localHeight:l.h,scaleX:t.scaleX,scaleY:t.scaleY}),c=K(I({requestedBounds:n.selectionLocalBounds,handleId:n.handleId,actualWidth:d.width,actualHeight:d.height,scaleX:n.scaleX,scaleY:n.scaleY,isResizingFromCenter:n.isResizingFromCenter}).center,{rotation:n.selectionRotation,rotationCenter:n.selectionRotationCenter}),u=n.scaleX<0!=n.scaleY<0?2*n.selectionRotation-t.rotation:t.rotation,p=n.scaleX<0?-t.scaleX:t.scaleX,h=n.scaleY<0?-t.scaleY:t.scaleY,g=new e(0,0,a.w,a.h).center,m=l.center.sub(g),y=new f(m.x*p,m.y*h).rot(u);return{id:t.id,x:c.x-g.x-y.x,y:c.y-g.y-y.y,rotation:u,scaleX:p,scaleY:h,props:a}}getHandleSnapGeometry(t){return{points:uw(t),outline:dw(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,s=e.y-n.center.y;return o*o/(t*t)+s*s/(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 s=e[r],i=e[o];if(!s||!i)continue;if(Yy(t,s,i)<=1e-6)return!0;if(s.y>t.y==i.y>t.y)continue;const a=(i.x-s.x)*(t.y-s.y)/(i.y-s.y)+s.x;t.x<a&&(n=!n)}return n}(e,by(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,s=t.w/2+r,i=t.h/2+r;if(s<=0||i<=0)return!1;const a=n.sub(e),l=e.sub(o),d=a.x/s,c=a.y/i,u=l.x/s,p=l.y/i,h=d*d+c*c,f=2*(u*d+p*c),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),w=(-f-y)/(2*h),x=(-f+y)/(2*h);return w>=0&&w<=1||x>=0&&x<=1}(n,e.positionedStart,e.positionedEnd,e.positionedMargin);{const r=by(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 s=n[o],i=n[(o+1)%n.length];if(s&&i&&iw(t,e,s,i)<=r)return!0}return!1}(e.positionedStart,e.positionedEnd,r,e.positionedMargin)}}resolveBindingPoint(t,e){const n=e.editor.shapes.geometry.computePositionedToPageTransform(t),r=n.tryInvert();if(!r)return e.rawPagePoint;const o=lw(t,r.applyToPoint(e.rawPagePoint),r.applyToPoint(e.oppositePagePoint));return o?n.applyToPoint(o):e.rawPagePoint}};function gw(t,e){switch(t){case"dashed":return`${4*e} ${2*e}`;case"dotted":return"0 "+2*e;default:return}}var mw=8,yw="M0 8 8 0",ww=8,xw=1.25,bw="4 4",kw=-2,vw=.08,Sw=.5;function Iw(t){return"linear"===t||"radial"===t}function Pw({style:t,angle:e,width:n,height:r,x:o=0,y:s=0}){if("radial"===t)return{gradientUnits:"objectBoundingBox",cx:.5,cy:.5,r:.5};const i=e*Math.PI/180,a=Math.cos(i),l=Math.sin(i),d=Math.max(1,n),c=Math.max(1,r),u=(Math.abs(d*a)+Math.abs(c*l))/2;return{gradientUnits:"userSpaceOnUse",x1:o+d/2-a*u,y1:s+c/2-l*u,x2:o+d/2+a*u,y2:s+c/2+l*u}}function Mw({stops:t,resolveColor:e,...n}){return{tag:"linear"===n.style?"linearGradient":"radialGradient",attrs:Pw(n),children:tw(t,e).map(({offset:t,color:e})=>({tag:"stop",attrs:{offset:t,"stop-color":e}}))}}function Tw({color:t,style:e,definitionId:n}){return{fill:"none"===e?"none":"pattern"===e||Iw(e)?`url(#${n})`:t,fillOpacity:"tint"===e?.18:1}}function Cw(t,e,n){return{tag:"pattern",attrs:{width:mw/Math.max(1,e),height:mw/Math.max(1,n),patternUnits:"objectBoundingBox",viewBox:`0 0 ${mw} ${mw}`,preserveAspectRatio:"none"},children:[{tag:"rect",attrs:{width:mw,height:mw,fill:t,"fill-opacity":vw}},{tag:"path",attrs:{d:yw,fill:"none",stroke:t,pathLength:ww,"stroke-width":xw,"stroke-dasharray":bw,"stroke-dashoffset":kw,"stroke-opacity":Sw}}]}}var Ew=class{type="geo";toSvg(t,n){const{kind:r,fill:o,fillStyle:s,stroke:i,strokeStyle:a,strokeWidth:l,w:d,h:c}=t.props,u=n.resolveColor(o),p="none"===a?0:l,h=p/2,f=Math.max(d-p,0),g=Math.max(c-p,0),m=Tw({color:u,style:s,definitionId:"pattern"===s?n.addDef(Cw(u,f,g)):Iw(s)?n.addDef(Mw({stops:t.props.gradientStops,resolveColor:t=>n.resolveColor(t),style:s,angle:t.props.gradientAngle,width:f,height:g,x:h,y:h})):""}),y={fill:m.fill,"fill-opacity":m.fillOpacity,stroke:"none"===a?"none":n.resolveColor(i),"stroke-width":p,"stroke-dasharray":gw(a,l),"stroke-linejoin":"round","stroke-linecap":"round",style:t.props.shadow?`filter:${nw}`:void 0};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=>`${Lw(t.x)},${Lw(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}}}}($y(new e(h,h,f,g),r,{cornerRadiusPercent:t.props.cornerRadiusPercent}),y)}};function Aw(){return{shapeUtils:[new fw],shapeSvgExporters:[new Ew],tools:{rectangle:t=>new Em(t),ellipse:t=>new Am(t),"message-circle":t=>new Lm(t),summary:t=>new $m(t),"summary-left":t=>new Rm(t),burst:t=>new Nm(t),rhombus:t=>new Om(t),triangle:t=>new Bm(t),pentagon:t=>new zm(t),hexagon:t=>new Hm(t),star:t=>new Dm(t),trapezoid:t=>new _m(t),"arrow-left":t=>new jm(t),"arrow-right":t=>new Fm(t)}}}function Lw(t){return Number.isFinite(t)?Number(t.toFixed(4)).toString():"0"}function $w({id:t,stops:e,resolveColor:n=Y,...r}){
|
|
36
|
+
return J("linear"===r.style?"linearGradient":"radialGradient",{id:t,...Pw(r),children:tw(e,n).map((t,e)=>J("stop",{offset:t.offset,stopColor:t.color},e))})}function Rw({id:t,color:e,width:n,height:r,spacing:o=mw}){
|
|
37
|
+
return Z("pattern",{id:t,width:o/Math.max(1,n),height:o/Math.max(1,r),patternUnits:"objectBoundingBox",viewBox:`0 0 ${mw} ${mw}`,preserveAspectRatio:"none",children:[J("rect",{width:mw,height:mw,fill:e,fillOpacity:vw}),J("path",{d:yw,fill:"none",stroke:e,pathLength:ww,strokeDasharray:bw,strokeDashoffset:kw,strokeWidth:xw,strokeOpacity:Sw})]})}function Nw(){return{canvasOverlays:[{id:"land.geo.creation-preview",component:Hw,order:10}],shapeRenderers:[{type:"geo",component:Ow,hoverComponent:Dw}]}}function Ow({shape:t}){const e=t.props.shadow?14:0;
|
|
38
|
+
return J("div",{style:{position:"absolute",left:e,top:e,width:t.props.w,height:t.props.h},children:J(zw,{props:t.props})})}function Bw({geometry:t,fill:e,fillOpacity:n,stroke:r,strokeWidth:o,strokeDasharray:s,vectorEffect:i}){const a={fill:"path"===t.tag&&"none"===t.fill?"none":e,fillOpacity:n,stroke:r,strokeWidth:o,strokeDasharray:s,strokeLinejoin:"round",strokeLinecap:"round",vectorEffect:"path"===t.tag&&t.vectorEffect?t.vectorEffect:i};switch(t.tag){case"ellipse":return J("ellipse",{...a,cx:t.cx,cy:t.cy,rx:t.rx,ry:t.ry});case"path":return J("path",{...a,d:t.d,transform:t.transform});case"polygon":return J("polygon",{...a,points:t.points.map(t=>`${t.x},${t.y}`).join(" ")});case"rect":return J("rect",{...a,x:t.x,y:t.y,width:t.width,height:t.height,rx:t.rx,ry:t.ry})}}function zw({props:t,fill:n=t.fill,stroke:r=t.stroke,strokeStyle:o=t.strokeStyle,strokeWidth:s=t.strokeWidth,width:i="100%",height:a="100%"}){const l=it(),d=Y(n),c=Tw({color:d,style:t.fillStyle,definitionId:l}),u="none"===o?0:s,p=u/2,h=Math.max(t.w-u,0),f=Math.max(t.h-u,0),g=$y(new e(p,p,h,f),t.kind,{cornerRadiusPercent:t.cornerRadiusPercent});
|
|
39
|
+
return Z("svg",{width:i,height:a,viewBox:`0 0 ${t.w} ${t.h}`,style:{display:"block",overflow:"visible",filter:t.shadow?nw:void 0},shapeRendering:"geometricPrecision",children:["pattern"===t.fillStyle?J("defs",{children:J(Rw,{id:l,color:d,width:h,height:f})}):null,Iw(t.fillStyle)?J("defs",{children:J($w,{id:l,stops:t.gradientStops,style:t.fillStyle,angle:t.gradientAngle,width:h,height:f,x:p,y:p})}):null,
|
|
40
|
+
J(Bw,{geometry:g,...c,stroke:"none"===o?"none":Y(r),strokeWidth:u,strokeDasharray:gw(o,s)})]})}var Hw=nt(function(){const t=G(Im(q()).$_preview);return t?J("g",{"data-ui":"geo-creation-preview",transform:`translate(${t.bounds.x} ${t.bounds.y})`,opacity:.48,pointerEvents:"none",children:J(zw,{props:t.props,width:t.bounds.w,height:t.bounds.h})}):null});function Dw({shape:t,strokeWidth:n}){const{h:r,w:o}=t.props,s=t.props.shadow?14:0,i=$y(new e(0,0,o,r),t.props.kind,{cornerRadiusPercent:t.props.cornerRadiusPercent});
|
|
41
|
+
return J("svg",{"data-ui":"geo-hover-outline",x:s,y:s,width:o,height:r,viewBox:`0 0 ${o} ${r}`,style:{display:"block",overflow:"visible",pointerEvents:"none"},shapeRendering:"geometricPrecision",children:J(Bw,{geometry:i,fill:"none",stroke:d,strokeWidth:n,strokeDasharray:void 0,vectorEffect:"non-scaling-stroke"})})}function _w({editor:t,text:e}){return function({editor:t,text:e}){return{create:n=>t.state.$_readonly.get()||n.label&&!e?null:t.operations.run({kind:"geo.create",source:"user"},()=>{const r=function(t,e){const n=t.shapes.getDefaultProps("geo"),[r]=t.shapes.create([{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,fillStyle:e.fillStyle??n.fillStyle,gradientStops:e.gradientStops??(e.fill?Gy(e.fill):n.gradientStops),gradientAngle:e.gradientAngle??n.gradientAngle,stroke:e.stroke??n.stroke,strokeStyle:e.strokeStyle??n.strokeStyle,strokeWidth:e.strokeWidth??n.strokeWidth,cornerRadiusPercent:e.cornerRadiusPercent??n.cornerRadiusPercent,shadow:e.shadow??n.shadow}}],{source:"user"});return"geo"===r?.type?{id:r.id,type:r.type}:null}(t,n);if(r&&n.label&&!e.createGeoLabel(r.id,n.label))throw new Error("Could not create the Geo text label.");return r}),getSelectionLabelLayout(){if(!e)return null;const n=t.state.$_selectedShapes.get().filter(xm).map(t=>e.getGeoLabelLayout(t.id)).filter(t=>null!==t);return 0===n.length?null:{paddingX:jw(n.map(t=>t.padding.x)),paddingY:jw(n.map(t=>t.padding.y)),verticalAlign:jw(n.map(t=>t.verticalAlign))}},setSelectionLabelLayout:n=>!e||t.state.$_readonly.get()?[]:t.operations.run({kind:"geo-label.layout",source:"user"},()=>{const r=[];for(const o of t.state.$_selectedShapes.get().filter(xm)){const t=e.getGeoLabelLayout(o.id);t&&e.setGeoLabelLayout(o.id,{padding:{x:n.paddingX??t.padding.x,y:n.paddingY??t.padding.y},verticalAlign:n.verticalAlign??t.verticalAlign})&&r.push(o.id)}return r}),getSelectionStyle:()=>function(t){const e=t.state.$_selectedShapes.get().filter(xm);return 0===e.length?null:{kind:jw(e.map(t=>t.props.kind)),fill:jw(e.map(t=>t.props.fill),g),fillStyle:jw(e.map(t=>t.props.fillStyle)),gradientStops:jw(e.map(t=>t.props.gradientStops),Jy),gradientAngle:jw(e.map(t=>t.props.gradientAngle)),stroke:jw(e.map(t=>t.props.stroke)),strokeStyle:jw(e.map(t=>t.props.strokeStyle)),strokeWidth:jw(e.map(t=>t.props.strokeWidth)),cornerRadiusPercent:jw(e.map(t=>t.props.cornerRadiusPercent)),shadow:jw(e.map(t=>t.props.shadow))}}(t),beginSelectionStyleEdit(){if(t.state.$_readonly.get()||t.operations.getActive())return null;const e=t.state.$_selectedShapes.get().filter(xm).filter(e=>!t.layers.isLocked(e.id)).map(t=>t.id);if(!e.length)return null;const n=t.operations.begin({kind:"geo.style",source:"user"});return{update(r){if(!n.isActive)return;const o=e.filter(e=>xm(t.store.get(e))&&!t.layers.isLocked(e)).map(t=>({id:t,props:{...r}}));o.length&&t.shapes.update(o,{source:"user"})},commit(){n.isActive&&n.commit()},cancel(){n.isActive&&n.cancel()}}},setSelectionStyle(e){const n=t.state.$_selectedShapes.get().filter(xm).filter(e=>!t.layers.isLocked(e.id)).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.shapes.update(n,{source:"user"}),n.map(({id:t})=>t)},toolDefaultsState:w(t.signalGraph.computed("Geo.toolDefaults",()=>t.shapes.getDefaultProps("geo"))),setToolDefaults:e=>(t.shapes.updateDefaultProps("geo",{...e}),t.shapes.getDefaultProps("geo"))}}({editor:t,text:e})}function jw(t,e=Object.is){const[n,...r]=t;return void 0!==n&&r.every(t=>e(t,n))?n:null}function Fw({text:t}={}){return v({id:"geo",requires:t?[t]:[],editor:Aw(),render:Nw(),setup:({editor:e,api:n})=>(function(t){const e=t.signalGraph.atom("geo.creation-hover",null,{isEqual:(t,e)=>t===e||null!==t&&null!==e&&t.timestamp===e.timestamp&&t.pagePoint.equals(e.pagePoint)}),n={$_preview:t.signalGraph.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)||!bm(o.activeToolId))return null;const s={...t.shapes.getDefaultProps("geo"),kind:o.activeToolId};return{bounds:Pm(n.pagePoint,s),props:s}}),setHover(t){e.set({pagePoint:t.pagePoint.clone(),timestamp:t.timestamp})},clearHover(){null!==e.get()&&e.set(null)}};Sm.set(t,n)}(e),{api:_w({editor:e,text:t?n(t):void 0})})})}var Ww=Fw();function Uw(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.max(o,t):e}var Kw=class extends p{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:Uw(e.w,n.w),h:Uw(e.h,n.h)}}getLocalBounds(t){return new e(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}},Xw=class{type="group";toSvg(t){return{tag:"g"}}};function Yw(){return{shapeUtils:[new Kw],shapeSvgExporters:[new Xw]}}function qw(){return{shapeRenderers:[{type:"group",component:Gw,hoverComponent:Jw}]}}function Gw({editor:t,shape:e,isSelected:n}){const r=G(t.state.$_selectedShapeIds),o=t.layers.tree.getDescendantIds(e.id),s=r.some(t=>o.includes(t));
|
|
42
|
+
return J(Vw,{shape:e,showSelectionBoundary:n||s})}function Vw({shape:t,showSelectionBoundary:e=!1}){const{h:n,w:r}=t.props,o=Y(x("#64748b"));
|
|
43
|
+
return J("svg",{width:"100%",height:"100%",viewBox:`0 0 ${r} ${n}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:e?J("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 Jw({shape:t,strokeWidth:e}){const{h:n,w:r}=t.props;
|
|
44
|
+
return J("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:J("rect",{x:0,y:0,width:r,height:n,fill:"none",stroke:d,strokeWidth:e,vectorEffect:"non-scaling-stroke"})})}var Zw=v({id:"group",editor:Yw(),render:qw()});function Qw(t){return z(t)&&"html"===t.type}var tx="html.interact",ex={propagation:"stop"};function nx(t,e){const n=t.store.get(e);return!(!Qw(n)||!t.editing.canEditShape(n))&&!!t.editing.start({shapeId:e,entryMode:"focusEnd",operationKind:tx},"user")}function rx(){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&&nx(t,e[0])?ex:void 0}if("double_click"===e.type){const n=t.shapes.hitTesting.atPoint(e.pagePoint);if(n&&nx(t,n.id))return ex}}}}}}function ox({editor:t}){return{create(e){const n=t.shapes.getDefaultProps("html"),[r]=t.shapes.create([{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.store.get(e);return!(!Qw(r)||t.layers.isLocked(r.id))&&(t.shapes.update([{id:e,props:{...n}}],{source:"user"}),!0)},startInteracting:e=>nx(t,e)}}function sx(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.max(o,t):e}var ix=class extends p{type="html";getDefaultProps(){return{w:480,h:320,html:"",title:""}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{w:sx(e.w,n.w),h:sx(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 e(0,0,t.props.w,t.props.h)}canEdit(t){return!0}canReceiveTerminalBinding(t){return!0}};function ax(t){return t.trim()||"Embedded HTML"}function lx(){return{shapeUtils:[new ix],interactionHandlers:[rx()]}}var dx="allow-forms allow-pointer-lock allow-presentation allow-scripts";function cx(t={}){return{shapeRenderers:[{type:"html",component:(e=t.sandbox??"allow-forms allow-pointer-lock allow-presentation allow-scripts",function({editor:t,shape:n,shapeEditingSession:r}){const o=dt(null),s=G(t.state.$_readonly),i=s||r?.shapeId===n.id;return st(()=>{i&&!s&&o.current?.focus()},[i,s]),J("iframe",{ref:o,"data-ui":"html-shape-frame",loading:"lazy",referrerPolicy:"no-referrer",sandbox:e,srcDoc:n.props.html,tabIndex:i?0:-1,title:ax(n.props.title),style:{background:"#fff",border:0,display:"block",height:n.props.h,pointerEvents:i?"auto":"none",width:n.props.w}})}),hoverComponent:ux}]};var e}function ux({shape:t,strokeWidth:e}){
|
|
45
|
+
return J("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:J("rect",{x:0,y:0,width:t.props.w,height:t.props.h,fill:"none",stroke:d,strokeWidth:e,vectorEffect:"non-scaling-stroke"})})}function px(t={}){return v({id:"html",editor:lx(),render:cx(t),setup:({editor:t})=>({api:ox({editor:t})})})}var hx=px(),fx=1e-4,gx=1e-4,mx="image.crop",yx=[{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}],wx={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"},xx=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"];function bx(t){return Math.min(1,Math.max(0,t))}function kx(t,e,n){return Math.min(n,Math.max(e,t))}function vx(t){return!!t&&"object"==typeof t&&"number"==typeof t.x&&Number.isFinite(t.x)&&"number"==typeof t.y&&Number.isFinite(t.y)}function Sx(t,e){const n=bx(t),r=bx(e);let o=Math.min(n,r),s=Math.max(n,r);if(s-o<fx){const t=(o+s)/2;o=Math.max(0,Math.min(.9999,t-5e-5)),s=o+fx}return{min:o,max:s}}function Ix(t){if(!t||"object"!=typeof t)return null;const e=t;if(!vx(e.topLeft)||!vx(e.bottomRight))return null;const n=Sx(e.topLeft.x,e.bottomRight.x),r=Sx(e.topLeft.y,e.bottomRight.y);return{topLeft:{x:n.min,y:r.min},bottomRight:{x:n.max,y:r.max}}}function Px(t){const e=Ix(t);if(!e)return null;const n=e.topLeft.x,r=e.topLeft.y,o=e.bottomRight.x,s=e.bottomRight.y;return{left:n,top:r,right:o,bottom:s,width:o-n,height:s-r}}function Mx(t){return Px(t)??{left:0,top:0,right:1,bottom:1,width:1,height:1}}function Tx(t,e){return Math.abs(t.left-e.left)<=gx&&Math.abs(t.top-e.top)<=gx&&Math.abs(t.right-e.right)<=gx&&Math.abs(t.bottom-e.bottom)<=gx}function Cx(t){return function(t){return Math.abs(t.left)<=gx&&Math.abs(t.top)<=gx&&Math.abs(1-t.right)<=gx&&Math.abs(1-t.bottom)<=gx}(t)?null:Ix({topLeft:{x:t.left,y:t.top},bottomRight:{x:t.right,y:t.bottom}})}function Ex({centerX:t,centerY:e,height:n,width:r}){const o=kx(r,fx,1),s=kx(n,fx,1),i=kx(t-o/2,0,1-o),a=kx(e-s/2,0,1-s);return{left:i,top:a,right:i+o,bottom:a+s,width:o,height:s}}function Ax(t){return{x:t.left+t.width/2,y:t.top+t.height/2}}function Lx({crop:t,shape:e}){const n=Mx(t);return{w:e.props.w/n.width,h:e.props.h/n.height}}function $x(t){const e=t.props.w/t.props.h;for(const n of yx)if(Math.abs(e-n.ratio)<=.01)return n.value;return null}function Rx(t,e){return e===Nx(t.id)}function Nx(t){return`image.crop:edit:${t}`}function Ox({localToPage:t,shape:e}){const n=e.props.w,r=e.props.h,o=(0+n)/2,s=(0+r)/2,i={top_left:new f(0,0),top:new f(o,0),top_right:new f(n,0),right:new f(n,s),bottom_right:new f(n,r),bottom:new f(o,r),bottom_left:new f(0,r),left:new f(0,s)};return xx.map(e=>{return{kind:"custom",type:mx,id:e,point:t.applyToPoint(i[e]),cursor:(n=e,wx[n])};var n})}function Bx({change:t,crop:e,shape:n}){const r=Lx({crop:e,shape:n}),o=e.bottomRight.x-e.topLeft.x,s=e.bottomRight.y-e.topLeft.y,i=kx(e.topLeft.x-t.x/r.w,0,1-o),a=kx(e.topLeft.y-t.y/r.h,0,1-s),l=Ix({topLeft:{x:i,y:a},bottomRight:{x:i+o,y:a+s}});return l?{id:n.id,props:{crop:l}}:null}function zx({preset:t,shape:e}){const n=Ax(Mx(e.props.crop)),r=Lx({crop:e.props.crop,shape:e}),o=yx.find(e=>e.value===t)?.ratio??null;if(!o)return null;const s=o*(r.h/r.w);let i=1,a=i/s;return a>1&&(a=1,i=a*s),function({nextRect:t,shape:e}){const n=Mx(e.props.crop);if(Tx(n,t))return null;const r=Lx({crop:e.props.crop,shape:e}),o=new f((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:Cx(t)}}}({nextRect:Ex({centerX:n.x,centerY:n.y,width:i,height:a}),shape:e})}function Hx(t){return Number.isFinite(t)?Number(t.toFixed(4)).toString():"0"}var Dx=new WeakMap;function _x(t,e){return Dx.get(t)?.get(e)??null}function jx(t,e){const n=Dx.get(t);n&&(n.delete(e),0===n.size&&Dx.delete(t))}function Fx(t){return N(t)&&"image"===t.type}function Wx(t){return z(t)&&"image"===t.type}var Ux={propagation:"stop"};function Kx({handleId:t,shapeId:e,startPagePoint:n,startPageToLocal:r,startShape:o,startCrop:s}){return{shapeId:e,operationKind:"image.crop.handle",update({editor:i,pagePoint:a,source:l}){if(!Wx(i.store.get(e)))return"stop";const d=function({handleId:t,pageToLocal:e,shape:n,startCrop:r,startPagePoint:o,currentPagePoint:s}){const i=Ix(r)??{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},a=Lx({crop:i,shape:n});if(a.w<8||a.h<8)return null;const l=e.applyToPoint(o),d=e.applyToPoint(s).sub(l);if(0===d.x&&0===d.y)return null;const c={x:i.topLeft.x*a.w,y:i.topLeft.y*a.h,w:(i.bottomRight.x-i.topLeft.x)*a.w,h:(i.bottomRight.y-i.topLeft.y)*a.h},u=c.x+c.w,p=c.y+c.h;let h=c.x,g=c.y,m=c.w,y=c.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=kx(u+d.x,c.x+8,a.w)-h):(h=kx(h+d.x,0,u-8),m=u-h),function(t){return"top_left"===t||"top"===t||"top_right"===t}(t)?(g=kx(g+d.y,0,p-8),y=p-g):function(t){return"bottom_left"===t||"bottom"===t||"bottom_right"===t}(t)&&(y=kx(p+d.y,c.y+8,a.h)-g);const w=Ix({topLeft:{x:h/a.w,y:g/a.h},bottomRight:{x:(h+m)/a.w,y:(g+y)/a.h}});if(!w)return null;const x=new f(h-i.topLeft.x*a.w,g-i.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:y,crop:w}}}({handleId:t,currentPagePoint:a,pageToLocal:r,shape:o,startCrop:s,startPagePoint:n});return d?(i.shapes.update([d],{source:l}),"continue"):"continue"}}}function Xx(){return{createSession(t,{handle:e,shape:n,originPagePoint:r}){return Wx(n)&&"custom"===e.kind&&"image.crop"===e.type&&(o=e.id,xx.some(t=>t===o))?Kx({handleId:e.id,shapeId:n.id,startPagePoint:r,startPageToLocal:t.shapes.geometry.computeLocalToPageTransform(n).invert(),startShape:n,startCrop:n.props.crop}):null;var o}}}function Yx(){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=qx(t);if(!n)return;if("Escape"===e.key&&!e.altKey&&!e.accelKey)return t.editing.cancel("user")&&jx(t,n.id),Ux;if("Enter"===e.key&&!e.altKey&&!e.accelKey)return t.editing.complete("user")&&jx(t,n.id),Ux;const r=function(t){if(t.altKey||t.accelKey)return null;const e=t.shiftKey?10:1;switch(t.key){case"ArrowLeft":return new f(e,0);case"ArrowRight":return new f(-e,0);case"ArrowUp":return new f(0,e);case"ArrowDown":return new f(0,-e);default:return null}}(e);if(r){const e=function({pageDelta:t,shape:e,startCrop:n}){const r=Ix(n);return!r||t.equals(f.Zero())?null:Bx({change:t.rot(-e.rotation),crop:r,shape:e})}({pageDelta:r,shape:n,startCrop:n.props.crop});return e&&t.shapes.update([e],{source:"user"}),Ux}}(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=qx(n);if(!o)return;return function(t,e,n){const r=t.shapes.geometry.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.geometry.computeLocalToPageTransform(o).invert(),startShape:o,hasDragged:!1,operation:null},Ux):n.editing.complete("user")?(jx(n,o.id),n.handleEvent(r),Ux):void 0}if(t&&r.pointerId===t.pointerId)return"pointer_move"===r.name?(Gx(n,r,t),Ux):"pointer_up"===r.name?(Gx(n,r,t),t.operation?.isActive&&t.operation.commit(),e(),Ux):void 0}else e()}else e()}},selectionHandle:Xx()}}function qx(t){const[e]=t.state.$_selectedShapes.get();if(!Wx(e))return null;const n=t.state.$_shapeEditingSession.get();return n&&n.shapeId===e.id&&Rx(e,n.operationKind)?e:null}function Gx(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(!Wx(t.store.get(n.shapeId)))return;const r=function({currentPagePoint:t,pageToLocal:e,shape:n,startCrop:r,startPagePoint:o,shiftKey:s}){const i=Ix(r);if(!i)return null;const a=e.applyToPoint(o);let l=e.applyToPoint(t).sub(a);return s&&(l=Math.abs(l.x)<Math.abs(l.y)?new f(0,l.y):new f(l.x,0)),0===l.x&&0===l.y?null:Bx({change:l,crop:i,shape:n})}({currentPagePoint:e.pagePoint,pageToLocal:n.startPageToLocal,shape:n.startShape,shiftKey:e.shiftKey,startCrop:n.startCrop,startPagePoint:n.startPagePoint});r&&t.shapes.update([r],{source:"user"})}function Vx(t,e=0){return Math.max(0,"number"==typeof t&&Number.isFinite(t)?t:e)}function Jx({cornerRadius:t,h:e,w:n}){return Math.min(Vx(t),Math.max(0,n)/2,Math.max(0,e)/2)}var Zx=24,Qx="#ffff00",tb=1,eb=128,nb=24,rb=Qx,ob=.45,sb=class{editor;confirmHandler=null;deactivateHistoryScope=null;session=null;snapshot=null;subscribers=new Set;constructor(t){this.editor=t,j("image.smudgeSession.lifecycle",t.state.$_shapeEditingSession,()=>{this.clearIfEditingSessionInvalid()},{fireImmediately:!1})}start(t,e){if(this.editor.layers.isLocked(t.id))return!1;const n=db(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&&cb(t,r.operationKind))return this.updateSession({...this.session,brush:ub({...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:ub(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===db(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===db(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=ub({...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.store.get(this.session.shapeId),e=this.editor.state.$_shapeEditingSession.get();return t&&e&&e.shapeId===this.session.shapeId&&e.operationKind===db(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=ib(this.session),n={id:`${e.shapeId}:smudge:${e.nextStrokeIndex}`,points:[Sb(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,Sb(t)]}})}endStroke(){this.session?.activeStroke&&this.updateSession(ib(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(ib(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):void 0}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===db(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 ib(t){return t.activeStroke?{...t,strokes:[...t.strokes,t.activeStroke],activeStroke:null,redoStrokes:[]}:t}var ab=new WeakMap;function lb(t){const e=ab.get(t);if(e)return e;const n=new sb(t);return ab.set(t,n),n}function db(t){return`image.smudge:edit:${t}`}function cb(t,e){return e===db(t.id)}function ub(t){const e="number"==typeof t?.size&&Number.isFinite(t.size)?t.size:nb,n="number"==typeof t?.opacity&&Number.isFinite(t.opacity)?t.opacity:ob??.45;return{size:Math.min(128,Math.max(1,e)),color:"string"==typeof t?.color&&t.color.trim().length>0?t.color:rb,opacity:Math.min(1,Math.max(0,n))}}function pb({brush:t,editor:e,shape:n}){return lb(e).start(n,t)}function hb(t){lb(t).cancel()}function fb(t){lb(t).complete()}function gb(t){return lb(t).cancelIfActive()}function mb(t,e){return lb(t).updateBrush(e)}function yb(t){return lb(t).getActiveSession()}function wb(t){return lb(t).undo()}function xb(t){return lb(t).redo()}function bb(t,e){return lb(t).registerConfirmHandler(e)}function kb(t,e){return lb(t).requestConfirm(e)}function vb(t){return t.map(t=>({id:t.id,brush:{...t.brush},points:t.points.map(Sb)}))}function Sb(t){return{x:t.x,y:t.y,...void 0===t.pressure?{}:{pressure:t.pressure}}}function Ib(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}var Pb=class extends p{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(),{width:r,height:o}=m({width:Ib(e.w,n.w),height:Ib(e.h,n.h),preserveAspectRatio:!0});return{w:r,h:o,assetId:(s=e.assetId,"string"==typeof s&&s.startsWith("asset:")?e.assetId:null),crop:Ix(e.crop),cornerRadius:Vx(e.cornerRadius,n.cornerRadius),altText:"string"==typeof e.altText?e.altText:n.altText};var s}getLocalBounds(t){return new e(0,0,t.props.w,t.props.h)}canReceiveTerminalBinding(t){return!0}getAllowedSelectionResizeModes(t,e){return i}canEdit(t){return!0}onEditEnd(t,e){var n,r;n=e.editor,r=t.id,lb(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&&Rx(t,r.operationKind)?{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:Ox({crop:t.props.crop,localToPage:e.editor.shapes.geometry.computeLocalToPageTransform(t),shape:t})}:n}},Mb=class{type="image";toSvg(t,e){const{assetId:n,altText:r,crop:o,h:s,w:i}=t.props;if(!n)return null;const a=e.resolveAssetUrl(n);if(!a)return null;const l=Px(o),d=l?{tag:"svg",attrs:{x:0,y:0,width:i,height:s,viewBox:(c=l,[Hx(c.left),Hx(c.top),Hx(c.width),Hx(c.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:i,height:s,preserveAspectRatio:"none","aria-label":r||void 0}};var c;const u=Jx({cornerRadius:t.props.cornerRadius,h:s,w:i});return u<=0?d:{tag:"g",attrs:{"clip-path":`url(#${e.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:[{tag:"rect",attrs:{x:0,y:0,width:i,height:s,rx:u,ry:u}}]})})`},children:[d]}}},Tb={propagation:"stop"};function Cb(){let t=null;const e=e=>{t=null,function(t){lb(t).endStroke()}(e)},n=e=>{t=null,function(t){lb(t).cancelStroke()}(e)};return{id:"land.image.smudge.interactions",editorEvent:{handleEvent(r,o){if("keyboard"===o.type)return(Ab(o)||Eb(o))&&Lb(r)&&e(r),function(t,e){if("key_down"!==e.name)return;if(!Lb(t))return;if("Escape"===e.key&&!e.altKey&&!e.accelKey)return hb(t),Tb;if(Eb(e))return kb(t,{replace:!0}),Tb;if(Ab(e))return e.shiftKey?t.history.redo():t.history.undo(),Tb;return Tb}(r,o);if("cancel"===o.type)return Lb(r)?(n(r),"command"!==o.reason&&hb(r),Tb):void 0;if("pointer"!==o.type)return;const s=Lb(r);if(s){if("pointer_down"===o.name){if(e(r),0!==o.button)return 1===o.button?void 0:Tb;const n=Rb(r,s,o.pagePoint),i=Nb(n,s);return t={mode:i?"draw":"pan",originCamera:i?null:r.state.$_camera.get(),originScreenPoint:i?null:o.screenPoint.clone(),pointerId:o.pointerId,acceptsDrawPoints:i},i&&function(t,e){lb(t).beginStroke(e)}(r,{x:n.x,y:n.y,pressure:o.pressure}),Tb}return t&&t.pointerId===o.pointerId?"pointer_move"===o.name?("draw"===t.mode&&1&o.buttons?t.acceptsDrawPoints&&(t.acceptsDrawPoints=$b(r,s,o)):"pan"===t.mode&&t.originCamera&&t.originScreenPoint&&1&o.buttons?Ob(r,o,t):e(r),Tb):"pointer_up"===o.name?("draw"===t.mode&&t.acceptsDrawPoints?$b(r,s,o):"pan"===t.mode&&Ob(r,o,t),e(r),Tb):"pointer_cancel"===o.name?(n(r),Tb):Tb:Tb}n(r)}}}}function Eb(t){return"key_down"===t.name&&"Enter"===t.key&&!t.altKey&&!t.accelKey}function Ab(t){return"key_down"===t.name&&"z"===t.key.toLowerCase()&&t.accelKey&&!t.altKey}function Lb(t){const[e]=t.state.$_selectedShapes.get();if(!Wx(e))return null;const n=t.state.$_shapeEditingSession.get();return n&&n.shapeId===e.id&&cb(e,n.operationKind)?e:null}function $b(t,e,n){const r=Rb(t,e,n.pagePoint);return!!Nb(r,e)&&(function(t,e){lb(t).appendPoint(e)}(t,{x:r.x,y:r.y,pressure:n.pressure}),!0)}function Rb(t,e,n){return t.shapes.geometry.computeLocalToPageTransform(e).invert().applyToPoint(n)}function Nb(t,e){return t.x>=0&&t.y>=0&&t.x<=e.props.w&&t.y<=e.props.h}function Ob(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 Bb(){return{shapeUtils:[new Pb],shapeSvgExporters:[new Mb],interactionHandlers:[Yx(),Cb()]}}var zb=new WeakMap;function Hb(t){return zb.get(t)??null}var Db={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(!Wx(e))return null;const n=t.state.$_shapeEditingSession.get();return n&&n.shapeId===e.id&&Rx(e,n.operationKind)?e:null}(e);if(!o)return;if(n?.closest('[data-selection-custom-handle-type="image.crop"]'))return;if(!t)return;const s=r.getBoundingClientRect(),i=new f(t.x-s.left,t.y-s.top);return Gb(e,o,e.viewport.screenToPage(i))?0!==e.inputs.$_state.get().buttons?"grabbing":"grab":void 0}},_b={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(!Wx(e))return null;const n=t.state.$_shapeEditingSession.get();return n&&n.shapeId===e.id&&cb(e,n.operationKind)?e:null}(n);if(!r||!t)return;const o=e.getBoundingClientRect(),s=new f(t.x-o.left,t.y-o.top);return Gb(n,r,n.viewport.screenToPage(s))?"crosshair":0!==n.inputs.$_state.get().buttons?"grabbing":"grab"}};function jb(){return{domEventGuards:[Db,_b],selectionCustomHandleRenderers:[{type:mx,component:Xb}],shapeRenderers:[{type:"image",component:Fb,hoverComponent:Kb}]}}function Fb({editor:t,shape:e,shapeEditingSession:r}){const{altText:o,assetId:s,crop:i,h:a,w:l}=e.props;G(t.assets.getUrlVersionSignal());const d=s?t.assets.resolveUrl(s):null,c=Jx({cornerRadius:e.props.cornerRadius,h:a,w:l}),u=function(t,e){return ut(e=>function(t,e){return lb(t).subscribe(e)}(t,e),()=>function(t,e){return lb(t).getSnapshot(e)}(t,e),()=>null)}(t,e.id);if(!d)return J("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:a,justifyContent:"center",overflow:"hidden",width:l},children:Z("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:[
|
|
46
|
+
J("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"}),
|
|
47
|
+
J("path",{d:"M20 2v4"}),
|
|
48
|
+
J("path",{d:"M22 4h-4"}),
|
|
49
|
+
J("circle",{cx:"4",cy:"20",r:"2"})]})});const p=function({crop:t,shapeHeight:e,shapeWidth:n}){const r=Px(t);if(!r)return null;const o=n/r.width,s=e/r.height;return{imageX:-r.left*o,imageY:-r.top*s,imageWidth:o,imageHeight:s,rect:r}}({crop:i,shapeHeight:a,shapeWidth:l});if(p){const s=r?.shapeId===e.id&&Rx(e,r.operationKind),i={display:"block",height:p.imageHeight,left:p.imageX,maxWidth:"none",objectFit:"fill",pointerEvents:"none",position:"absolute",top:p.imageY,userSelect:"none",width:p.imageWidth};
|
|
50
|
+
return Z("div",{"data-ui":"image-shape",style:{display:"block",height:a,overflow:s?"visible":"hidden",pointerEvents:"none",position:"relative",transform:"translateZ(0)",userSelect:"none",width:l},children:[s?J("img",{alt:"","aria-hidden":"true","data-ui":"image-crop-preview",draggable:!1,src:d,style:{...i,opacity:.1}}):null,Z("div",{"data-ui":"image-crop-window",style:{height:a,overflow:"hidden",position:"absolute",borderRadius:c,inset:0,width:l},children:[J(n,{kind:"image",label:o,presenter:Hb(t),src:d,style:i}),J(Wb,{shape:e,session:u})]})]})}
|
|
51
|
+
return Z("div",{"data-ui":"image-shape",style:{borderRadius:c,display:"block",height:a,overflow:"hidden",pointerEvents:"none",position:"relative",transform:"translateZ(0)",userSelect:"none",width:l},children:[J(n,{kind:"image",label:o,presenter:Hb(t),src:d,style:{display:"block",height:a,objectFit:"fill",width:l}}),J(Wb,{shape:e,session:u})]})}function Wb({shape:t,session:e}){return e&&e.shapeId===t.id&&0!==e.strokes.length?J("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=>J(Ub,{stroke:t},t.id))}):null}function Ub({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 J("circle",{cx:e.x,cy:e.y,r:o/2,fill:n,opacity:r});const s=function(t){const[e,...n]=t.points;return e?[`M ${qb(e.x)} ${qb(e.y)}`,...n.map(t=>`L ${qb(t.x)} ${qb(t.y)}`)].join(" "):null}(t);return s?J("path",{d:s,fill:"none",opacity:r,stroke:n,strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:o}):null}function Kb({shape:t,strokeWidth:e}){const n=Jx({cornerRadius:t.props.cornerRadius,h:t.props.h,w:t.props.w});
|
|
52
|
+
return J(u,{dataUi:"image-hover-outline",width:t.props.w,height:t.props.h,radius:n,strokeWidth:e})}function Xb({handle:t,strokeWidth:e}){const{x:n,y:r,w:o,h:s,center:i}=t.bounds,a=1.35*Math.max(o,s),l=Math.max(2.5*e,2),d=l/2,c={fill:"none",stroke:"rgba(37, 99, 235, 0.96)",strokeLinecap:"butt",strokeLinejoin:"miter",strokeWidth:l,pointerEvents:"none"},u=function({id:t,extension:e,outwardOffset:n,centerX:r,centerY:o}){switch(t){case"top_left":return{kind:"corner",points:[Yb(r-n,o+e),Yb(r-n,o-n),Yb(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:[Yb(r-e,o-n),Yb(r+n,o-n),Yb(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:[Yb(r+n,o-e),Yb(r+n,o+n),Yb(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:[Yb(r+e,o+n),Yb(r-n,o+n),Yb(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:d,centerX:i.x,centerY:i.y});
|
|
53
|
+
return Z("g",{children:[J("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*s,width:2.6*o,height:2.6*s,fill:"transparent",style:{cursor:t.cursor??"grab",pointerEvents:"auto"}}),"corner"===u.kind?J("polyline",{points:u.points,...c}):J("line",{x1:u.x1,y1:u.y1,x2:u.x2,y2:u.y2,...c})]})}function Yb(t,e){return`${t},${e}`}function qb(t){return Number.isFinite(t)?Number(t.toFixed(2)).toString():"0"}function Gb(t,e,n){const r=t.shapes.geometry.computeLocalToPageTransform(e).invert().applyToPoint(n);return r.x>=0&&r.y>=0&&r.x<=e.props.w&&r.y<=e.props.h}function Vb({editor:t}){return function({editor:t}){return{setMediaPresenter(e){!function(t,e){e?zb.set(t,e):zb.delete(t),t.assets.invalidateUrls()}(t,e)},getSelectionState(){const e=Qb(t);if(!e)return null;const n=t.state.$_shapeEditingSession.get();return{shapeId:e.id,cornerRadius:Vx(e.props.cornerRadius),crop:e.props.crop,cropPreset:$x(e),isCropping:n?.shapeId===e.id&&Rx(e,n.operationKind),smudge:yb(t)}},setSelectionStyle(e){const n=t.state.$_selectedShapes.get().filter(Wx).filter(e=>!t.layers.isLocked(e.id)).map(t=>({id:t.id,props:{...void 0===e.cornerRadius?{}:{cornerRadius:Vx(e.cornerRadius)}}}));return n.length>0&&t.shapes.update(n,{source:"user"}),n.map(({id:t})=>t)},startCrop(e){const n=Zb(t,e);return!(!n||t.layers.isLocked(n.id))&&(!!t.editing.start({shapeId:n.id,operationKind:Nx(n.id),entryMode:"focusEnd"},"user")&&(function(t,e){const n=Dx.get(t)??new Map;Dx.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=Qb(t);if(!e||!tk(t,e))return!1;const n=t.editing.complete("user");return n&&jx(t,e.id),n},cancelCrop(){const e=Qb(t);if(!e||!tk(t,e))return!1;const n=t.editing.cancel("user");return n&&jx(t,e.id),n},zoomCrop:e=>Jb(t,t=>function({direction:t,shape:e}){const n=Mx(e.props.crop),r=Ax(n),o=kx("in"===t?.8:1.25,Math.max(fx/n.width,fx/n.height),Math.min(1/n.width,1/n.height)),s=Ex({centerX:r.x,centerY:r.y,width:n.width*o,height:n.height*o});return Tx(n,s)?null:{id:e.id,props:{crop:Cx(s)}}}({direction:e,shape:t})),setCropAspectRatio:e=>Jb(t,t=>zx({preset:e,shape:t})),resetCrop:()=>Jb(t,e=>function({baselineShape:t,shape:e}){const n=t.x,r=t.y,o=t.props.w,s=t.props.h,i=Ix(t.props.crop);return Math.abs(e.x-n)<=gx&&Math.abs(e.y-r)<=gx&&Math.abs(e.props.w-o)<=gx&&Math.abs(e.props.h-s)<=gx&&(null===e.props.crop&&null===i||null!==e.props.crop&&null!==i&&Math.abs(e.props.crop.topLeft.x-i.topLeft.x)<=gx&&Math.abs(e.props.crop.topLeft.y-i.topLeft.y)<=gx&&Math.abs(e.props.crop.bottomRight.x-i.bottomRight.x)<=gx&&Math.abs(e.props.crop.bottomRight.y-i.bottomRight.y)<=gx)?null:{id:e.id,x:n,y:r,props:{w:o,h:s,crop:i}}}({baselineShape:_x(t,e.id)??e,shape:e})),smudge:{start(e){const n=Zb(t,e?.shapeId);return!!n&&!!n.props.assetId&&!t.layers.isLocked(n.id)&&pb({brush:e?.brush,editor:t,shape:n})},setBrush:e=>mb(t,e),cancel(){hb(t)},undo:()=>wb(t),redo:()=>xb(t),getSnapshot:()=>yb(t)}}}({editor:t})}function Jb(t,e){const n=Qb(t);if(!n||t.layers.isLocked(n.id)||!tk(t,n))return!1;const r=e(n);return!!r&&(t.shapes.update([r],{source:"user"}),!0)}function Zb(t,e){const n=e?t.store.get(e):t.state.$_selectedShapes.get()[0];return Wx(n)?n:null}function Qb(t){return 1===t.selection.getIds().length?Zb(t):null}function tk(t,e){const n=t.state.$_shapeEditingSession.get();return n?.shapeId===e.id&&Rx(e,n.operationKind)}var ek=v({id:"image",editor:Bb(),render:jb(),setup({editor:t}){const e=function(t){let e=null;return j("image.cropSession.lifecycle",t.state.$_shapeEditingSession,()=>{const n=t.state.$_shapeEditingSession.get(),r=n?.shapeId,o=r&&n?.operationKind===Nx(r)?r:null;e&&e!==o&&jx(t,e),e=o})}(t);try{return{api:Vb({editor:t}),dispose:e}}catch(n){throw e(),n}}});async function nk(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 rk="blobs",ok=null;function sk(){return"undefined"==typeof indexedDB?Promise.resolve(null):(ok||(ok=new Promise((t,e)=>{const n=indexedDB.open("land.plugin-image",1);n.addEventListener("upgradeneeded",()=>{n.result.objectStoreNames.contains(rk)||n.result.createObjectStore(rk)}),n.addEventListener("success",()=>{const e=n.result;e.addEventListener("versionchange",()=>{e.close(),ok=null}),t(e)}),n.addEventListener("error",()=>{ok=null,e(n.error)})})),ok)}var ik="image-blob:";function ak(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?`${ik}${crypto.randomUUID()}`:`${ik}${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}async function lk(t){const e=ak();if("undefined"==typeof indexedDB)throw new Error("IndexedDB is not available for image storage.");return await async function(t,e){const n=await sk();n&&await new Promise((r,o)=>{const s=n.transaction(rk,"readwrite");s.addEventListener("complete",()=>r()),s.addEventListener("abort",()=>o(s.error)),s.addEventListener("error",()=>o(s.error)),s.objectStore(rk).put(e,t)})}(e,t),{storageKey:e}}async function dk(t){const e=await async function(t){const e=await sk();return e?new Promise((n,r)=>{const o=e.transaction(rk,"readonly").objectStore(rk).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 ck(t){const e=await dk(t);return e?nk(e):null}async function uk(t){await async function(t){const e=await sk();e&&await new Promise((n,r)=>{const o=e.transaction(rk,"readwrite");o.addEventListener("complete",()=>n()),o.addEventListener("abort",()=>r(o.error)),o.addEventListener("error",()=>r(o.error)),o.objectStore(rk).delete(t)})}(t)}async function pk(){return(await async function(){const t=await sk();return t?new Promise((e,n)=>{const r=t.transaction(rk,"readonly").objectStore(rk).getAllKeys();r.addEventListener("success",()=>e([...r.result])),r.addEventListener("error",()=>n(r.error))}):null}())?.map(String)??[]}function hk(t,e){const n=t.store.get(e);if(!Fx(n)||"local"!==n.props.source.kind)return null;const{storageKey:r}=n.props.source;return r.length>0?r:null}function fk(t,e){const n=t.store.get(e);return Fx(n)&&"remote"===n.props.source.kind&&n.props.source.url.length>0?n.props.source.url:null}function gk(t){const e=new Set;for(const n of t.assets.getAll())Fx(n)&&"local"===n.props.source.kind&&n.props.source.storageKey.length>0&&e.add(n.props.source.storageKey);return e}async function mk({editor:t,objectUrls:e}){const n=gk(t),r=await pk(),o=[];for(const s of r)n.has(s)||(e?.release(s),await uk(s),o.push(s));return o}function yk(){const t=new Map,e=new Map;let n=0,r=!1;const o=async(o,s={})=>{if(s.signal?.throwIfAborted(),r)return null;const i=t.get(o);if(i)return i;const a=e.get(o);if(a){const t=await a;return s.signal?.throwIfAborted(),t}const l=n,d=dk(o).then(e=>{if(!e||r||l!==n)return null;const s=URL.createObjectURL(e);return t.set(o,s),s}).finally(()=>{e.delete(o)});e.set(o,d);const c=await d;return s.signal?.throwIfAborted(),c};return{async preloadForEditor(t,e={}){e.signal?.throwIfAborted(),await Promise.all(Array.from(gk(t)).map(t=>o(t,e)))},preload:o,resolve:e=>t.get(e)??null,resolveAssetUrl(e,n){const r=fk(e,n);if(r)return r;const o=hk(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 wk(){const t=yk(),e={objectUrls:t,preloadForEditor:(e,{signal:n})=>t.preloadForEditor(e,{signal:n}),resolveAssetUrl:(e,n)=>t.resolveAssetUrl(e,n)};return{value:e,dispose(){e.objectUrls.releaseAll()}}}function xk(t,{signal:e}={}){return e?.throwIfAborted(),new Promise((n,r)=>{const o=new Image,s=()=>{o.removeEventListener("load",i),o.removeEventListener("error",a),e?.removeEventListener("abort",l)},i=()=>{s(),n({width:o.naturalWidth||o.width,height:o.naturalHeight||o.height})},a=()=>{s(),r(new Error("Could not decode image file."))},l=()=>{s(),r(e?.reason)};o.addEventListener("load",i),o.addEventListener("error",a),e?.addEventListener("abort",l,{once:!0}),o.src=t,e?.aborted&&l()})}async function bk(t,{signal:e}={}){e?.throwIfAborted();const n=vk(t)?t:t.blob,r=(vk(t),t.name),o=vk(t)?t.type:t.mimeType||t.blob.type,s=URL.createObjectURL(n),i=await xk(s,{signal:e}).finally(()=>{URL.revokeObjectURL(s)});e?.throwIfAborted();const{storageKey:a}=await lk(n);try{e?.throwIfAborted()}catch(l){try{await uk(a)}catch(d){throw new AggregateError([l,d],"Could not discard an aborted image blob write.")}throw l}return{name:r||"Image",source:{kind:"local",storageKey:a,...!vk(t)&&t.originalUrl?{originalUrl:t.originalUrl}:{}},mimeType:o||"image/png",fileSize:n.size,width:i.width,height:i.height}}async function kk({name:t,signal:e,url:n}){const r=await xk(n,{signal:e});return{name:t||Sk(n)||"Image",source:{kind:"remote",url:n},mimeType:null,width:r.width,height:r.height}}function vk(t){return"undefined"!=typeof File&&t instanceof File}function Sk(t){try{const e=new URL(t).pathname.split("/").filter(Boolean).at(-1);return e?decodeURIComponent(e):null}catch{return null}}function Ik(t){for(const e of t)if(e.type.startsWith("image/"))return e;return null}function Pk({filename:t,url:e}){const n=document.createElement("a");n.href=e,n.download=t,n.click()}async function Mk({blob:t,filename:e}){const n=URL.createObjectURL(t);try{Pk({filename:e,url:n})}finally{window.setTimeout(()=>URL.revokeObjectURL(n),0)}}var Tk=1;function Ck(t,e){return t.assets.create({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 Ek({editor:t,imageObjectUrls:e,pagePoint:n,signal:r,size:o,source:s}){return"file"===s.type?Bk(s.file)?Ak({editor:t,imageObjectUrls:e,input:await bk(s.file,{signal:r}),pagePoint:n,size:o,signal:r,altText:s.altText}):null:"blob"===s.type?Bk(s.blob)?Ak({editor:t,imageObjectUrls:e,input:await bk(s,{signal:r}),pagePoint:n,size:o,signal:r,altText:s.altText}):null:async function({editor:t,imageObjectUrls:e,pagePoint:n,signal:r,size:o,source:s}){return Ak({editor:t,imageObjectUrls:e,input:await kk({...s,signal:r}),pagePoint:n,size:o,signal:r,altText:s.altText})}({editor:t,imageObjectUrls:e,source:s,pagePoint:n,size:o,signal:r})}async function Ak({editor:t,imageObjectUrls:e,input:n,pagePoint:r,size:o,signal:s,altText:i}){const a="local"===n.source.kind?n.source.storageKey:null;try{return a&&await e.preload(a,{signal:s}),await se(t,s),s.throwIfAborted(),t.operations.run({kind:"image.insert",source:"user"},()=>{const e=Ck(t,n),s=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(),l=r??a?.center??t.viewport.screenToPage(new f(360,240)),[d]=t.shapes.create([{type:"image",x:Math.round(l.x-s.w/2),y:Math.round(l.y-s.h/2),props:{...s,assetId:e.id,crop:null,altText:i??n.name}}],{source:"user"});return d?(t.selection.set([d.id],{source:"user"}),d.id):null})}catch(l){throw a&&(e.release(a),await uk(a)),l}}async function Lk({editor:t,file:e,imageObjectUrls:n,signal:r}){if(!Bk(e))return;const[o]=t.state.$_selectedShapes.get();if(!Wx(o)||t.layers.isLocked(o.id))return;const s=await bk(e,{signal:r});await Rk({editor:t,imageObjectUrls:n,input:s,nextProps:{crop:null,altText:s.name},signal:r,shape:o})}async function $k({editor:t,imageObjectUrls:e,onError:n,signal:r}){r.throwIfAborted();const[o]=t.state.$_selectedShapes.get();if(!Wx(o)||!o.props.assetId)return;const s=t.store.get(o.props.assetId);if(!Fx(s))return;const i="string"==typeof s.props.name&&s.props.name.length>0?s.props.name:"land-image";if("remote"===s.props.source.kind)return void(await async function({filename:t,onError:e,signal:n,url:r}){try{const e=await fetch(r,{signal:n});if(!e.ok)throw new Error(`Could not download image URL (${e.status}).`);const o=await e.blob();n.throwIfAborted(),await Mk({blob:o,filename:t})}catch(o){n.throwIfAborted(),e?.(new Error("Could not download remote image; opening URL instead.",{cause:o})),function(t){const e=document.createElement("a");e.href=t,e.rel="noreferrer",e.target="_blank",e.click()}(r)}}({filename:i,onError:n,signal:r,url:s.props.source.url}));const a=s.props.source.storageKey;if(!a)return;const l=await dk(a);if(r.throwIfAborted(),l)return void(await Mk({blob:l,filename:i}));const d=e.resolve(a);d&&Pk({filename:i,url:d})}async function Rk({canCommit:t,editor:e,imageObjectUrls:n,input:r,nextProps:o,shape:s,signal:i}){const a=s.props.assetId,l="local"===r.source.kind?r.source.storageKey:null;try{i.throwIfAborted(),l&&await n.preload(l,{signal:i}),t||await se(e,i),i.throwIfAborted()}catch(d){throw await Nk({imageObjectUrls:n,storageKey:l}),d}try{const i=e.store.get(s.id);if(!Wx(i)||e.layers.isLocked(i.id)||i.props.assetId!==a||t&&!t())return await Nk({imageObjectUrls:n,storageKey:l}),null;const c=`image.asset.replace:${s.id}:${Tk++}`,u=e.operations.begin({kind:c,label:"image.asset.replace",source:"user",history:"record"});try{const t=Ck(e,r);return e.shapes.update([{id:s.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.assets.delete(a,{source:"user"}),u.commit(),{assetId:t.id,storageKey:l}}catch(d){throw u.isActive&&u.cancel(),d}}catch(d){throw await Nk({imageObjectUrls:n,storageKey:l}),d}}async function Nk({imageObjectUrls:t,storageKey:e}){e&&(t.release(e),await uk(e))}async function Ok(t){try{const e=await fetch(t);if(!e.ok)return null;const n=await e.blob();return Bk(n)?n:null}catch{return null}}function Bk(t){return!t.type||t.type.startsWith("image/")}var zk=new WeakSet;async function Hk({editor:t,imageObjectUrls:e,replace:n=!0,signal:r}){r.throwIfAborted();const o=yb(t);if(!o)return null;const s=vb(o.strokes);if(0===s.length)return fb(t),null;if(zk.has(o))return null;zk.add(o);try{return await async function({editor:t,imageObjectUrls:e,replace:n,session:r,signal:o,strokes:s}){o.throwIfAborted();const i=t.store.get(r.shapeId);if(!Wx(i)||t.layers.isLocked(i.id)||!i.props.assetId)return null;const a=t.store.get(i.props.assetId);if(!Fx(a))return null;const l=i.props.assetId,d=await async function({asset:t,imageObjectUrls:e}){if("remote"===t.props.source.kind)return Ok(t.props.source.url);const n=t.props.source.storageKey,r=await dk(n);if(r)return r;const o=e.resolve(n);return o?Ok(o):null}({asset:a,imageObjectUrls:e});if(o.throwIfAborted(),!d)return null;if(!Dk(t,r,l,i)||t.store.get(l)!==a)return null;const{imageBlob:c,maskBlob:u,height:p,width:h}=await async function({crop:t,shape:e,signal:n,sourceBlob:r,strokes:o}){n.throwIfAborted();const s=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=s.width,i=s.height,a=_k(r,i);a.context.drawImage(s.source,0,0,r,i),jk({context:a.context,crop:t,imageHeight:i,imageWidth:r,mask:!1,shape:e,strokes:o});const l=_k(r,i);jk({context:l.context,crop:t,imageHeight:i,imageWidth:r,mask:!0,shape:e,strokes:o});const d=await a.toBlob("image/png");n.throwIfAborted();const c=await l.toBlob("image/png");return n.throwIfAborted(),{imageBlob:d,maskBlob:c,width:r,height:i}}finally{s.dispose()}}({crop:i.props.crop,shape:i,signal:o,sourceBlob:d,strokes:s});if(o.throwIfAborted(),!Dk(t,r,l,i)||t.store.get(l)!==a)return null;const f={shapeId:i.id,sourceAssetId:l,imageBlob:c,maskBlob:u,width:h,height:p,crop:i.props.crop?{topLeft:{...i.props.crop.topLeft},bottomRight:{...i.props.crop.bottomRight}}:null,strokes:s};if(n){o.throwIfAborted();const n=await async function({blob:t,canCommit:e,editor:n,imageObjectUrls:r,name:o,shape:s,signal:i}){i.throwIfAborted();const a=await bk({blob:t,name:o},{signal:i});return i.throwIfAborted(),Rk({editor:n,imageObjectUrls:r,input:a,nextProps:{},shape:s,canCommit:e,signal:i})}({blob:c,canCommit:()=>!o.aborted&&Dk(t,r,l,i)&&t.store.get(l)===a,editor:t,imageObjectUrls:e,name:Uk(a.props.name),shape:i,signal:o});if(o.throwIfAborted(),!n)return null;if(!Dk(t,r,n.assetId,i)){const o=yb(t),s=t.store.get(r.shapeId);return o?.shapeId===r.shapeId&&Wx(s)&&s.props.assetId===n.assetId&&hb(t),await async function({assetId:t,editor:e,imageObjectUrls:n,storageKey:r}){if(!r||t&&e.store.get(t))return;n.release(r),await uk(r)}({assetId:n.assetId,editor:t,imageObjectUrls:e,storageKey:n.storageKey}),null}return o.throwIfAborted(),fb(t),f}return o.throwIfAborted(),fb(t),f}({editor:t,imageObjectUrls:e,replace:n,session:o,signal:r,strokes:s})}finally{zk.delete(o)}}function Dk(t,e,n,r){if(yb(t)!==e)return!1;const o=t.store.get(e.shapeId);return Wx(o)&&!t.layers.isLocked(o.id)&&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 _k(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 jk({context:t,crop:e,imageHeight:n,imageWidth:r,mask:o,shape:s,strokes:i}){if(0===i.length)return;const a=Mx(e),l={x:a.left*r,y:a.top*n,w:a.width*r,h:a.height*n},d=l.w/s.props.w,c=l.h/s.props.h,u=(Math.abs(d)+Math.abs(c))/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 i){const e=p.points[0];if(!e)continue;const n=Wk(p.brush.opacity),r=Math.max(1,p.brush.size*u),s=p.brush.color??"#ffff00";t.globalAlpha=n,t.strokeStyle=o?"#ffffff":s,t.fillStyle=o?"#ffffff":s,t.lineWidth=r;const i=Fk({cropPixelRect:l,point:e,scaleX:d,scaleY:c});if(1!==p.points.length){t.beginPath(),t.moveTo(i.x,i.y);for(const e of p.points.slice(1)){const n=Fk({cropPixelRect:l,point:e,scaleX:d,scaleY:c});t.lineTo(n.x,n.y)}t.stroke()}else t.beginPath(),t.arc(i.x,i.y,r/2,0,2*Math.PI),t.fill()}t.restore()}function Fk({cropPixelRect:t,point:e,scaleX:n,scaleY:r}){return{x:t.x+e.x*n,y:t.y+e.y*r}}function Wk(t){return"number"==typeof t&&Number.isFinite(t)?Math.min(1,Math.max(0,t)):.45}function Uk(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 Kk({editor:t,imageAssetService:e,imageApi:n,onError:r,run:o}){let s,i=!1;const a=Xk(t=>s.insert({source:{type:"file",file:t}}),r),l=Xk(t=>s.replaceSelection({file:t}),r),d={start:t=>n.smudge.start(t),setBrush:t=>n.smudge.setBrush(t),cancel(){n.smudge.cancel()},confirm:n=>o(async r=>{const o=await Hk({editor:t,imageObjectUrls:e.objectUrls,replace:n?.replace??!0,signal:r});return r.throwIfAborted(),o}),isActive:()=>null!==n.smudge.getSnapshot()};s={openInsertFilePicker(){a.open()},openReplaceFilePicker(){l.open()},insert:({source:n,pagePoint:r,size:s,signal:i})=>o(async o=>{const a=i?AbortSignal.any([o,i]):o;a.throwIfAborted();const l=await Ek({editor:t,imageObjectUrls:e.objectUrls,source:n,pagePoint:r,size:s,signal:a});return a.throwIfAborted(),l}),replaceSelection:({file:n})=>o(async r=>{if(!n.type.startsWith("image/"))return!1;const[o]=t.state.$_selectedShapes.get();return!(!Wx(o)||t.layers.isLocked(o.id))&&(await Lk({editor:t,file:n,imageObjectUrls:e.objectUrls,signal:r}),r.throwIfAborted(),!0)}),downloadSelectionOriginal:()=>o(async n=>{await $k({editor:t,imageObjectUrls:e.objectUrls,onError:r,signal:n}),n.throwIfAborted()}),smudge:d};const c=bb(t,t=>{d.confirm(t).catch(t=>r?.(t))});return{value:s,dispose(){i||(i=!0,a.dispose(),l.dispose(),c())}}}function Xk(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 Yk(t){return{kind:"svg-inliner",id:"image.svg-inliner",async prepare({editor:e,requestedShapeIds:n}){const r=qk(e,e.layers.getExportTraversalIds(n).flatMap(t=>{const n=e.store.get(t);return n?[n]:[]})),o=new Set;for(const s of r.values()){if("local"!==s.props.source.kind)continue;const{storageKey:e}=s.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 "${s.id}".`)}},async inline({editor:e,exportedShapes:n,svg:r}){let o=r;const s=qk(e,n),i=new Set;for(const a of s.values()){const e=Vk(a,t);if(!e)throw new Error(`Could not resolve image asset "${a.id}".`);if(i.has(e))continue;const n=await Gk(a,e);if(n.href===n.dataUrl){i.add(e);continue}const r=`href="${Jk(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}"`),i.add(e)}return o}}}function qk(t,e){const n=new Map;for(const r of e){if(!Wx(r)||!r.props.assetId)continue;const e=t.store.get(r.props.assetId);if(!Fx(e))throw new Error(`Image asset "${r.props.assetId}" is unavailable.`);n.set(e.id,e)}return n}async function Gk(t,e){const{source:n}=t.props;if("local"===n.kind){const r=await ck(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(s){throw new Error(`Could not download image asset "${t.id}".`,{cause:s})}if(!r.ok)throw new Error(`Could not download image asset "${t.id}" (${r.status}).`);const o=await nk(await r.blob());if(!o)throw new Error(`Could not embed remote image asset "${t.id}".`);return{href:e,dataUrl:o}}function Vk(t,e){return"local"===t.props.source.kind?e.objectUrls.resolve(t.props.source.storageKey):t.props.source.url}function Jk(t){return t.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}function Zk(t={}){return oe({id:"image.host",requires:[ek],setup({api:e,canvas:n,editor:r,run:o}){const s=e(ek),i=(t.createAssetService??wk)();let a=!1;const l=()=>s.setMediaPresenter(re({run:o,onError:t.onError})),d=n.snapshots.revision.subscribe(()=>{queueMicrotask(()=>{a||l()})});let c=null;const u=()=>{a=!0,d(),s.setMediaPresenter(null);const t=[];try{c?.()}catch(e){t.push(e)}try{i.dispose()}catch(e){t.push(e)}if(t.length)throw new AggregateError(t,"Failed to dispose image host resources.")};try{l();const e=Kk({editor:r,imageApi:s,imageAssetService:i.value,onError:t.onError,run:o});return c=e.dispose,{api:e.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!==Ik(t.files)||(t.urls?.some(Qk)??!1),async import(t){const n=Ik(t.files),r=t.urls?.find(Qk);return(n||r)&&await e.value.insert({source:n?{type:"file",file:n}:{type:"url",url:r},pagePoint:t.pagePoint})?"handled":"ignored"}}],assetResolvers:[{id:"image.host.asset-resolver",resolve:t=>i.value.resolveAssetUrl(r,t),preload:({signal:t})=>i.value.preloadForEditor(r,{signal:t})}],exports:[Yk(i.value)],dispose:u}}catch(p){try{u()}catch(h){throw new AggregateError([p,h],"image host setup and cleanup failed.",{cause:p})}throw p}}})}function Qk(t){return t.startsWith("data:image/")||/\.(?:avif|bmp|gif|jpe?g|png|svg|webp)(?:[?#].*)?$/i.test(t)}var tv=new WeakMap;function ev(t){const e=tv.get(t);if(!e)throw new Error("LaserRuntime is not initialized for this editor.");return e}function nv(t,e){const n=t.trail[t.trail.length-1];n&&n.dist2(e)<=1e-6||t.trail.push(e.clone())}function rv(t,e){ev(t).set(e.sessionId,e.trail)}var ov=class extends h{constructor(t){super(t,"laser"),this.initial="idle",this.addChild(new sv(t,this)),this.addChild(new iv(t,this)),this.addChild(new av(t,this))}},sv=class extends h{constructor(t,e){super(t,"idle",e)}onPointerDown(t){0===t.button&&this.transition("pointing",function(t,e){const n={sessionId:ev(t).start(),originScreenPoint:e.screenPoint.clone(),trail:[e.pagePoint.clone()]};return rv(t,n),n}(this.editor,t))}},iv=class extends h{info=null;constructor(t,e){super(t,"pointing",e)}onEnter(t){this.info=t}onPointerMove(t){var e,n;this.info&&(e=this.info.originScreenPoint,n=t.screenPoint,e.dist2(n)>=9&&(nv(this.info,t.pagePoint),rv(this.editor,this.info),this.transition("drawing",this.info)))}onPointerUp(){this.info&&ev(this.editor).finish(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&ev(this.editor).finish(this.info.sessionId),this.transition("idle")}onExit(){this.info&&ev(this.editor).finish(this.info.sessionId),this.info=null}},av=class extends h{info=null;constructor(t,e){super(t,"drawing",e)}onEnter(t){this.info=t}onPointerMove(t){this.info&&(nv(this.info,t.pagePoint),rv(this.editor,this.info))}onPointerUp(){this.info&&ev(this.editor).finish(this.info.sessionId),this.transition("idle")}onCancel(){this.info&&ev(this.editor).finish(this.info.sessionId),this.transition("idle")}onExit(){this.info&&ev(this.editor).finish(this.info.sessionId),this.info=null}};function lv(){return{canvasOverlays:[{id:"land.laser.trail-overlay",component:dv}]}}var dv=nt(function(){return G(ev(q()).$_active)?J(cv,{}):null}),cv=nt(function(){const t=q(),e=ev(t),n=G(e.$_trail),r=G(t.state.$_cameraZoom),o=Math.max(r,1e-4),s=function(){const[t,e]=ct(()=>Mv());return st(()=>{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}(),i=dt({sessionId:0,samples:[],sourceLength:0}),a=Math.max(s,Mv());let l,d=[];n&&(!function(t,e,n,r){e.sessionId!==t.sessionId&&(t.sessionId=e.sessionId,t.samples=[],t.sourceLength=0);const o=e.points;Cv(t,r),o.length<t.sourceLength&&(t.samples=[],t.sourceLength=0);if(o.length===t.sourceLength)return;const s=t.sourceLength,i=o.length-s,a=t.samples[t.samples.length-1]?.time??r-bv*i;for(let l=s;l<o.length;l++){const e=o[l],d=(l-s+1)/i;Tv(t,{x:e.x,y:e.y},n,_v(a,r,d))}t.sourceLength=o.length,Cv(t,r)}(i.current,n,o,a),d=function(t,e){const n=Ev(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(Dv(r[r.length-1],t[o],n));return r}(n.length>fv?n.slice(-64):n,yv)}(i.current.samples,a),l=i.current.samples[i.current.samples.length-1]?.time);const c="ending"===n?.phase,u=0===d.length,p=c&&u?n.sessionId:null;if(st(()=>{null!==p&&e.clear(p)},[p,e]),!n||u)return null;const h=c&&void 0!==l?jv(1-(a-l)/Pv,0,1):1,f=(m=mv/o,0===(g=d).length||m<=0?null:1===g.length?Wv($v(g[0],m/2,xv))??"":Wv(function(t){if(0===t.length)return[];if(1===t.length)return $v(t[0].point,Math.max(t[0].radius,.01),xv);const e=[],n=[];for(const a of t){const t=Ov(a.direction);Fv(e,zv(a.point,Hv(t,a.radius))),Fv(n,Bv(a.point,Hv(t,a.radius)))}const r=[];for(const a of e)Fv(r,a);const o=t[t.length-1],s=Ov(o.direction),i=function({center:t,direction:e,normal:n,radius:r}){if(r<=0)return[];const o=[];for(let s=1;s<wv;s++){const i=s/wv;o.push(Bv(t,Bv(Hv(e,Math.sin(Math.PI*i)*r),Hv(n,-Math.cos(Math.PI*i)*r))))}return o}({center:o.point,direction:o.direction,normal:s,radius:o.radius});for(const a of i)Fv(r,a);for(let a=n.length-1;a>=0;a--)Fv(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]+Rv(t[n-1],t[n]));return e}(t),r=n[n.length-1]??0,o=Math.max(e,r);return t.map((r,s)=>{const i=n[s]??0,a=jv(i/o,0,1);return{point:r,direction:Lv(t,s),radius:e/2*a,runningLength:i}})}(g,m))));var g,m;return f?Z("g",{"data-ui":"laser-trail-overlay",style:{opacity:h},children:[J("path",{"data-ui":"laser-trail-glow",d:f,fill:pv,style:{filter:`blur(${hv/o}px)`}}),J("path",{"data-ui":"laser-trail-beam",d:f,fill:uv})]}):null}),uv="rgb(255, 38, 38)",pv="rgba(255, 48, 48, 0.55)",hv=4,fv=64,gv=1,mv=6,yv=.32,wv=8,xv=13,bv=16,kv=8,vv=600,Sv=300,Iv=1400,Pv=400;function Mv(){return"undefined"==typeof performance?Date.now():performance.now()}function Tv(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 s=gv/n,i=Rv(o,e);if(i<s)return void(t.samples[t.samples.length-1]={...o,...e,time:r});const a=i*n/Math.max(kv,r-o.time);t.samples.push({...e,time:r,velocity:_v(o.velocity,a,.68)})}function Cv(t,e){t.samples=Ev(t.samples,e)}function Ev(t,e){const n=t[t.length-1];if(!n)return[];const r=e-jv(vv+n.velocity*Sv,vv,Iv);if(n.time<r)return[];const o=t.findIndex(t=>t.time>=r);if(-1===o)return[];const s=t.slice(o),i=t[o-1],a=s[0];return i&&a.time>r?[Av(i,a,jv((r-i.time)/(a.time-i.time),0,1)),...s]:s}function Av(t,e,n){return{...Dv(t,e,n),time:_v(t.time,e.time,n),velocity:_v(t.velocity,e.velocity,n)}}function Lv(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?zv(r,t[e]):e===t.length-1?zv(t[e],n):zv(r,n))}function $v(t,e,n){const r=[];for(let o=0;o<n;o++){const s=2*Math.PI*o/n;r.push({x:t.x+Math.cos(s)*e,y:t.y+Math.sin(s)*e})}return r}function Rv(t,e){return Math.sqrt(Nv(t,e))}function Nv(t,e){const n=t.x-e.x,r=t.y-e.y;return n*n+r*r}function Ov(t){return{x:-t.y,y:t.x}}function Bv(t,e){return{x:t.x+e.x,y:t.y+e.y}}function zv(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Hv(t,e){return{x:t.x*e,y:t.y*e}}function Dv(t,e,n){return{x:_v(t.x,e.x,n),y:_v(t.y,e.y,n)}}function _v(t,e,n){return t+(e-t)*n}function jv(t,e,n){return Math.max(e,Math.min(n,t))}function Fv(t,e){const n=t[t.length-1];!n||Nv(n,e)>.04?t.push(e):t[t.length-1]=e}function Wv(t){if(t.length<2)return null;if(2===t.length)return`M ${Kv(t[0])} L ${Kv(t[1])} Z`;const e=[`M ${Kv(Uv(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 ${Kv(r)} ${Kv(Uv(r,o))}`)}return e.push("Z"),e.join(" ")}function Uv(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}function Kv(t){return`${Xv(t.x)},${Xv(t.y)}`}function Xv(t){return Number.isInteger(t)?`${t}`:t.toFixed(3)}function Yv(){return{tools:{laser:t=>new ov(t)}}}var qv=v({id:"laser",editor:Yv(),render:lv(),setup({editor:t}){!function(t){const{atom:e,computed:n}=t.signalGraph,r=e("laser.trail",null);let o=1;const s={$_trail:r,$_active: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)}};tv.set(t,s)}(t)}}),Gv="path.node",Vv="path.control";function Jv(t,e){return["node",t,e].map(encodeURIComponent).join("|")}function Zv(t,e,n){return["control",n,t,e].map(encodeURIComponent).join("|")}function Qv(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:Gv,subpathId:n[1],nodeId:n[2]}:"path.control"!==t||4!==n.length||"control"!==n[0]||"in"!==n[1]&&"out"!==n[1]?null:{type:Vv,handle:n[1],subpathId:n[2],nodeId:n[3]}}var tS=new WeakMap;function eS(t,e){e?tS.set(t,nS(e)):tS.delete(t)}function nS(t){return{...t,pagePoint:t.pagePoint.clone()}}var rS=["nonzero","evenodd"],oS=["corner","smooth","symmetric"];function sS(t){return z(t)&&"path"===t.type}function iS(t){return"string"==typeof t&&rS.includes(t)}function aS(t){return"string"==typeof t&&oS.includes(t)}function lS(){const t=q(),e=G(t.state.$_tool),n=G(t.state.$_shapeEditingSession),r=G(t.state.$_selectedShapes);if("select"!==e.activeToolId||!n)return null;const o=1===r.length?r[0]:null;return sS(o)&&o.id===n.shapeId?J(dS,{shapeId:o.id}):null}function dS({shapeId:t}){const e=q(),n=G(e.state.$_cameraZoom);G(e.inputs.$_state);const r=function(t){const e=tS.get(t);return e?nS(e):null}(e);if(!r||r.shapeId!==t)return null;const o=8/n,s=o/2,i=1.5/n;
|
|
54
|
+
return J("g",{"data-ui":"path-edit-insert-preview",pointerEvents:"none",children:J("rect",{"data-ui":"path-edit-insert-preview-control-point",x:r.pagePoint.x-s,y:r.pagePoint.y-s,width:o,height:o,rx:2,ry:2,fill:"rgba(219, 234, 254, 0.72)",stroke:"var(--land-selection, #2563eb)",strokeDasharray:`${3/n} ${2/n}`,strokeWidth:i})})}function cS(t){return Number.isInteger(t)?`${t}`:`${Number(t.toFixed(2))}`}function uS(t){return new f(t.x,t.y)}function pS(t,e){const n=uS(e);if(!function(t,e){return!!t.out||!!e.in}(t,e))return`L ${cS(n.x)} ${cS(n.y)}`;const r=function(t){const e=uS(t);return t.out?e.add(new f(t.out.dx,t.out.dy)):e}(t),o=function(t){const e=uS(t);return t.in?e.add(new f(t.in.dx,t.in.dy)):e}(e);return["C",cS(r.x),cS(r.y),cS(o.x),cS(o.y),cS(n.x),cS(n.y)].join(" ")}function hS(t){const e=t.nodes[0];if(!e)return null;const n=[`M ${cS(e.x)} ${cS(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(pS(e,o))}if(t.closed&&t.nodes.length>1){const r=t.nodes[t.nodes.length-1];r&&n.push(pS(r,e)),n.push("Z")}return n.join(" ")}function fS(t){const e=t.map(hS).filter(t=>null!==t);return e.length>0?e.join(" "):null}var gS=1e-6,mS=1/3,yS=Math.PI/8,wS=new WeakMap;function xS(t){return Number.isFinite(t)}function bS(t){return{dx:t.dx,dy:t.dy}}function kS(t){return{id:t.id,x:t.x,y:t.y,kind:t.kind,...t.in?{in:bS(t.in)}:null,...t.out?{out:bS(t.out)}:null}}function vS(t){return{id:t.id,closed:t.closed,nodes:t.nodes.map(kS)}}function SS(t){return t.map(vS)}function IS(t){return new f(t.x,t.y)}function PS(t){const e=IS(t);return t.in?e.add(new f(t.in.dx,t.in.dy)):e}function MS(t){const e=IS(t);return t.out?e.add(new f(t.out.dx,t.out.dy)):e}function TS(t,e,n,r,o){const s=1-o,i=s*s*s,a=3*s*s*o,l=3*s*o*o,d=o*o*o;return new f(t.x*i+e.x*a+n.x*l+r.x*d,t.y*i+e.y*a+n.y*l+r.y*d)}function CS(t,e,n){return new f(t.x+(e.x-t.x)*n,t.y+(e.y-t.y)*n)}function ES(t,e){return[IS(t),MS(t),PS(e),IS(e)]}function AS(t,e){return!!t.out||!!e.in}function LS(t,e,n){return AS(t,e)?TS(...ES(t,e),n):CS(IS(t),IS(e),n)}function $S(t,e,n){const r=IS(e),o=MS(e),s=PS(n),i=IS(n);if(e.out||n.in)for(let a=1;a<=18;a+=1)t.push(TS(r,o,s,i,a/18));else t.push(i)}function RS(t){const e=t.nodes[0];if(!e)return{id:t.id,closed:t.closed,points:[]};const n=[IS(e)];for(let r=1;r<t.nodes.length;r+=1){const e=t.nodes[r-1],o=t.nodes[r];e&&o&&$S(n,e,o)}if(t.closed&&t.nodes.length>1){const r=t.nodes[t.nodes.length-1];r&&$S(n,r,e)}return{id:t.id,closed:t.closed,points:n}}function NS(t){const e=t.props,n=wS.get(e);if(n)return n;const r=OS(t.props);return wS.set(e,r),r}function OS(t){const n=t.subpaths.map(RS),r=n.flatMap(t=>t.points),o=t.subpaths.flatMap(t=>t.nodes.flatMap(t=>[IS(t),...t.in?[PS(t)]:[],...t.out?[MS(t)]:[]])),s=o.length>0?e.FromPoints(o):new e(0,0,1,1),i=Math.max(t.strokeWidth/2,1),a=r.length>0?e.FromPoints(r).expand(i):s.expand(i),l=new e(a.x,a.y,Math.max(a.w,1),Math.max(a.h,1));return{path:fS(t.subpaths),pointBounds:s,localBounds:a,renderBounds:l,outlineVertices:r.map(t=>t.clone()),flattenedSubpaths:n}}function BS(t,e){return t.map(t=>({...t,nodes:t.nodes.map(t=>function(t,e){const n=e(IS(t)),r=t.in?e(PS(t)):null,o=t.out?e(MS(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 zS(t,e){const n=OS({...e,subpaths:SS(t)}).pointBounds,r=Number.isFinite(n.x)?n.x:0,o=Number.isFinite(n.y)?n.y:0,s=function(t,e,n){return BS(t,t=>new f(t.x+e,t.y+n))}(t,-r,-o);return{x:r,y:o,subpaths:s,geometry:OS({...e,subpaths:s})}}function HS(t,e){return BS(t.props.subpaths,t=>e.applyToPoint(t))}function DS(t,e){return fS(HS(t,e))}function _S(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return{distanceSquared:t.dist2(e),t:0};const s=t.sub(e),i=Math.max(0,Math.min(1,(s.x*r.x+s.y*r.y)/o)),a=e.add(r.mul(i));return{distanceSquared:t.dist2(a),t:i}}function jS(t,e,n){return _S(t,e,n).distanceSquared}function FS(t,e,n){const r=n*n;let o=null;for(const s of t){if(s.nodes.length<2)continue;const t=s.closed?s.nodes.length:s.nodes.length-1;for(let n=0;n<t;n+=1){const t=s.nodes[n],i=s.nodes[(n+1)%s.nodes.length];if(!t||!i)continue;const a=AS(t,i)?32:1;let l=IS(t);for(let n=1;n<=a;n+=1){const d=LS(t,i,n/a),c=_S(e,l,d),u=(n-1+c.t)/a;u>.02&&u<.98&&c.distanceSquared<=r&&(!o||c.distanceSquared<o.distanceSquared)&&(o={subpathId:s.id,startNodeId:t.id,endNodeId:i.id,t:u,point:LS(t,i,u),distanceSquared:c.distanceSquared}),l=d}}}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 WS(t,e){return t.find(t=>t.id===e)??null}function US(t,e,n){return WS(t,e)?.nodes.find(t=>t.id===n)??null}function KS(t,e,n,r){return t.map(t=>t.id!==e?vS(t):{...t,nodes:t.nodes.map(t=>t.id===n?r(kS(t)):kS(t))})}function XS(t,e,n){const r=JS(e);return 0===r.size?SS(t):t.map(t=>{const e=r.get(t.id);return e?{...t,nodes:t.nodes.map(t=>e.has(t.id)?n(kS(t)):kS(t))}:vS(t)})}function YS(t,e,n){return t.map(t=>{if(t.id!==e)return vS(t);const r=t.nodes.findIndex(t=>t.id===n),o=t.nodes[r];if(!o)return vS(t);const s=r>0?t.nodes[r-1]:t.closed?t.nodes[t.nodes.length-1]:null,i=r<t.nodes.length-1?t.nodes[r+1]:t.closed?t.nodes[0]:null,a=IS(o),l=function(t,e,n){const r=e?IS(e):null,o=n?IS(n):null;if(r&&o){const e=o.sub(r);if(e.len()<=gS)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<=gS||n/r<=.001}(r.sub(t),o.sub(t))?n.rot(yS):n}const s=o?o.sub(t):r?t.sub(r):null;return!s||s.len()<=gS?null:s.normalize().rot(yS)}(a,s,i),d=t.nodes.map(kS);return d[r]={...kS(o),kind:"smooth",in:s&&l?dI(l.mul(-a.dist(IS(s))*mS)):null,out:i&&l?dI(l.mul(a.dist(IS(i))*mS)):null},{...t,nodes:d}})}function qS(t,e,n){return KS(t,e,n,t=>({...t,kind:"corner",in:null,out:null}))}function GS(t,e,n){return null!==VS(t,e,n)}function VS(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 s;switch(n){case"merge":s=function(t,e){const n=ZS(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 s=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 s=(o[0]+1)%r.length;return[...r.slice(s),...r.slice(0,s)]}(o,n);if(!s||s.length<2)return null;const i=new Set(s),a=s.map(t=>o.nodes[t]),l=s[0],d=a[0],c=a[a.length-1],u=a.reduce((t,e)=>t.add(IS(e)),f.Zero()).div(a.length),p={...kS(d),x:u.x,y:u.y,kind:"corner",in:sI(d.in,IS(d),u),out:sI(c.out,IS(c),u)},h=o.nodes.flatMap((t,e)=>i.has(e)?e===l?[p]:[]:[kS(t)]),g=o.closed&&h.length>=3;o.closed&&!g&&oI(h);return{subpaths:aI(t,r,[{...o,closed:g,nodes:h}]),selectedNodes:[{subpathId:e,nodeId:p.id}]}}(t,n,e);const r=QS(t,e);return r?function(t,e){const[n,r]=e,o=eI(n),s=nI(r),i=o[o.length-1],a=s[0],l=IS(i).add(IS(a)).div(2),d={...kS(i),x:l.x,y:l.y,kind:"corner",in:sI(i.in,IS(i),l),out:sI(a.out,IS(a),l)},{nodes:c}=iI(s.slice(1),new Set([...o.slice(0,-1).map(t=>t.id),d.id]),"merged"),u={...n.subpath,closed:!1,nodes:[...o.slice(0,-1),d,...c]};return{subpaths:lI(t,e,u),selectedNodes:[{subpathId:u.id,nodeId:d.id}]}}(t,r):null}(t,o);break;case"join":s=function(t,e){if(2!==e.length)return null;const n=ZS(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 s=new Set([o.nodes[0].id,o.nodes[o.nodes.length-1].id]);if(2!==n.length||n.some(t=>!s.has(t.nodeId)))return null;const i=o.nodes.map(kS);return i[0]={...i[0],kind:"corner",in:null},i[i.length-1]={...i[i.length-1],kind:"corner",out:null},{subpaths:aI(t,r,[{...o,closed:!0,nodes:i}]),selectedNodes:n.map(t=>({...t}))}}(t,n,e);const r=QS(t,e);return r?function(t,e){const[n,r]=e,o=eI(n),{nodes:s,nodeIdMap:i}=iI(nI(r),new Set(o.map(t=>t.id)),"joined"),a=o[o.length-1],l=s[0];o[o.length-1]={...a,kind:"corner",out:null},s[0]={...l,kind:"corner",in:null};const d={...n.subpath,closed:!1,nodes:[...o,...s]};return{subpaths:lI(t,e,d),selectedNodes:[{subpathId:d.id,nodeId:n.node.id},{subpathId:d.id,nodeId:i.get(r.node.id)??r.node.id}]}}(t,r):null}(t,o);break;case"separate":s=function(t,e){if(2!==e.length)return null;const n=ZS(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 s=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(s<0)return null;if(o.closed){const n=[...o.nodes.slice(s+1).map(kS),...o.nodes.slice(0,s+1).map(kS)];return oI(n),{subpaths:aI(t,r,[{...o,closed:!1,nodes:n}]),selectedNodes:e.map(t=>({...t}))}}const i=o.nodes.slice(0,s+1).map(kS),a=o.nodes.slice(s+1).map(kS);oI(i),oI(a);const l=i.length>=2?{...o,closed:!1,nodes:i}:null,d=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`),c=a.length>=2?{...o,id:d,closed:!1,nodes:a}:null,u=[l,c].filter(t=>null!==t),p=new Set(i.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}]:c&&h.has(t.nodeId)?[{subpathId:c.id,nodeId:t.nodeId}]:[]);return{subpaths:aI(t,r,u),selectedNodes:f}}(t,o)}if(!s)return null;const i=r?o.findIndex(t=>{return n=r,(e=t).subpathId===n.subpathId&&e.nodeId===n.nodeId;var e,n}):-1;return{...s,primaryNode:s.selectedNodes[i]??s.selectedNodes.at(-1)??null}}function JS(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 ZS(t){const e=t[0];return e&&t.every(t=>t.subpathId===e.subpathId)?e.subpathId:null}function QS(t,e){if(2!==e.length)return null;const n=tI(t,e[0]),r=tI(t,e[1]);return n&&r&&n.subpathIndex!==r.subpathIndex?[n,r]:null}function tI(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),s=r.nodes[o];return!s||0!==o&&o!==r.nodes.length-1?null:{subpath:r,subpathIndex:n,endpoint:0===o?"start":"end",node:s}}function eI(t){return"end"===t.endpoint?t.subpath.nodes.map(kS):rI(t.subpath.nodes)}function nI(t){return"start"===t.endpoint?t.subpath.nodes.map(kS):rI(t.subpath.nodes)}function rI(t){return[...t].reverse().map(t=>({...kS(t),in:t.out?bS(t.out):null,out:t.in?bS(t.in):null}))}function oI(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 sI(t,e,n){return t?dI(e.add(new f(t.dx,t.dy)).sub(n)):null}function iI(t,e,n){const r=new Map;return{nodes:t.map(t=>{let o=t.id;if(e.has(o)){let r=1,s=`${o}:${n}`;for(;e.has(s);)r+=1,s=`${t.id}:${n}:${r}`;o=s}return e.add(o),r.set(t.id,o),{...kS(t),id:o}}),nodeIdMap:r}}function aI(t,e,n){return t.flatMap((t,r)=>r===e?n.map(vS):[vS(t)])}function lI(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)?[]:[vS(t)])}function dI(t){return t.len2()<=1e-12?null:{dx:t.x,dy:t.y}}function cI(t,e,n){return t.map(t=>{if(t.id!==e.subpathId)return vS(t);const r=t.nodes.findIndex(t=>t.id===e.startNodeId);if(r<0)return vS(t);const o=(r+1)%t.nodes.length,s=t.nodes[r],i=t.nodes[o];if(!s||!i||i.id!==e.endNodeId)return vS(t);const a=function(t,e,n,r){if(!AS(t,e)){const o=CS(IS(t),IS(e),n);return{start:kS(t),node:{id:r,x:o.x,y:o.y,kind:"corner"},end:kS(e)}}const[o,s,i,a]=ES(t,e),l=CS(o,s,n),d=CS(s,i,n),c=CS(i,a,n),u=CS(l,d,n),p=CS(d,c,n),h=CS(u,p,n);return{start:{...kS(t),out:dI(l.sub(o))},node:{id:r,x:h.x,y:h.y,kind:"smooth",in:dI(u.sub(h)),out:dI(p.sub(h))},end:{...kS(e),in:dI(c.sub(a))}}}(s,i,e.t,n),l=t.nodes.map(kS);return l[r]=a.start,l[o]=a.end,l.splice(r+1,0,a.node),{...t,nodes:l}})}var uI=new WeakMap;function pI(t){const e=uI.get(t);return e?function(t){return{shapeId:t.shapeId,nodes:t.nodes.map(t=>({...t})),primary:{...t.primary}}}(e):null}function hI(t){const e=uI.get(t);if(!e)return null;if(t.state.$_shapeEditingSession.get()?.shapeId!==e.shapeId)return null;const n=t.store.get(e.shapeId);if(!sS(n))return null;const r=e.nodes.flatMap(t=>{const e=WS(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})=>bI(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 fI(t,{syncCaret:e=!0}={}){const n=uI.get(t);uI.delete(t),e&&t.state.$_shapeEditingSession.get()?.shapeId===n?.shapeId&&xI(t,null)}function gI(t,e,n,r){const o={subpathId:n,nodeId:r};mI(t,e,[o],o)}function mI(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!==wI(t,e));if(0===r.length)return null;const o=(n&&r.find(t=>bI(t,n)))??r[r.length-1];return{shapeId:t.id,nodes:r,primary:{...o}}}(e,n,r);if(!o)return void fI(t);uI.set(t,o);const s=wI(e,o.primary);xI(t,s?t.shapes.geometry.computeLocalToPageTransform(e).applyToPoint(IS(s)):null)}function yI(t,e,n){return t.nodes.some(t=>t.subpathId===e&&t.nodeId===n)}function wI(t,e){return WS(t.props.subpaths,e.subpathId)?.nodes.find(t=>t.id===e.nodeId)??null}function xI(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 bI(t,e){return t.subpathId===e.subpathId&&t.nodeId===e.nodeId}var kI="land.path.draftSubpathId",vI="land.path.previewNodeId";function SI(t){const e=t.meta[kI],n=t.meta[vI];return{subpathId:"string"==typeof e?e:null,previewNodeId:"string"==typeof n?n:null}}function II(t,e){const n=PI(t);return e.subpathId&&(n[kI]=e.subpathId),e.previewNodeId&&(n[vI]=e.previewNodeId),n}function PI(t){const e={...t};return delete e[kI],delete e[vI],e}var MI="var(--land-selection, #2563eb)",TI="rgba(255, 255, 255, 0.98)";function CI(){const t=q(),e=G(t.state.$_tool),n=G(t.inputs.$_state),r=G(t.state.$_selectedShapes),o=G(t.state.$_camera);if("path"!==e.activeToolId)return null;const s=1===r.length?r[0]:null,i=sS(s)?s:null,a=8/o.z,l=1.5/o.z,d=6/o.z,c=1/o.z,u=n.currentPagePoint;if(!i)return u?J(LI,{point:u,size:a,strokeWidth:l,variant:"candidate"}):null;const p=function(t,e){const n=SI(e);if(!n.subpathId)return null;const r=WS(HS(e,t.shapes.geometry.computeLocalToPageTransform(e)),n.subpathId);if(!r)return null;const o=n.previewNodeId?r.nodes.findIndex(t=>t.id===n.previewNodeId):-1,s=o>=0?r.nodes[o]??null:null,i=o>0?r.nodes[o-1]??null:null,a=i&&s?hS({id:`${r.id}:preview`,closed:!1,nodes:[i,s]}):null;return{closed:r.closed,committedNodes:r.nodes.filter(t=>t.id!==n.previewNodeId),previewNode:s,previewPath:a}}(t,i);if(!p)return u?J(LI,{point:u,size:a,strokeWidth:l,variant:"candidate"}):null;const h=p.previewNode?IS(p.previewNode):n.isPointing?null:u,f=h&&!p.committedNodes.some(t=>IS(t).dist2(h)<=.25/(o.z*o.z));
|
|
55
|
+
return Z("g",{"data-ui":"path-draft-overlay",pointerEvents:"none",children:[p.previewPath?J("path",{"data-ui":"path-draft-preview-segment",d:p.previewPath,fill:"none",stroke:MI,strokeWidth:Math.max(l,1/o.z),strokeDasharray:`${6/o.z} ${4/o.z}`,strokeLinecap:"round",strokeLinejoin:"round"}):null,f?J(LI,{point:h,size:a,strokeWidth:l,variant:"candidate"}):null,p.committedNodes.map((t,e)=>J(EI,{node:t,showIn:p.closed||e>0,size:d,strokeWidth:c},t.id)),p.committedNodes.map(t=>J(LI,{point:IS(t),size:a,strokeWidth:l,variant:"committed"},t.id))]})}function EI({node:t,showIn:e,size:n,strokeWidth:r}){const o=IS(t);
|
|
56
|
+
return Z(V,{children:[e&&t.in?J(AI,{anchor:o,point:PS(t),size:n,strokeWidth:r,variant:"in"}):null,t.out?J(AI,{anchor:o,point:MS(t),size:n,strokeWidth:r,variant:"out"}):null]})}function AI({anchor:t,point:e,size:n,strokeWidth:r,variant:o}){const s=n/2;
|
|
57
|
+
return Z("g",{"data-ui":"path-draft-curve-handle","data-path-draft-curve-handle":o,children:[J("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}),J("rect",{"data-ui":"path-draft-control-handle",x:e.x-s,y:e.y-s,width:n,height:n,fill:TI,stroke:MI,strokeWidth:r})]})}function LI({point:t,size:e,strokeWidth:n,variant:r}){const o=e/2;
|
|
58
|
+
return J("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)":TI,stroke:MI,strokeWidth:n})}function $I({shape:t,shapeEditingSession:e=null,fill:n=t.props.fill,stroke:r=t.props.stroke,strokeWidth:o=t.props.strokeWidth}){const{renderBounds:s}=NS({props:{...t.props,strokeWidth:o}}),i=NI(t);if(!i)return null;const a=e?.shapeId===t.id;
|
|
59
|
+
return Z("svg",{width:"100%",height:"100%",viewBox:`${s.x} ${s.y} ${Math.max(s.w,1)} ${Math.max(s.h,1)}`,style:{display:"block",overflow:"visible"},shapeRendering:"geometricPrecision",children:[H(n)?null:J("path",{d:i,fill:Y(n),fillRule:t.props.fillRule,clipRule:t.props.fillRule,stroke:"none"}),
|
|
60
|
+
J("path",{d:i,fill:"none",stroke:Y(r),strokeWidth:o,strokeLinecap:"round",strokeLinejoin:"round"}),a?J(OI,{shape:t}):null]})}function RI({shape:t,strokeWidth:e}){const{renderBounds:n}=NS(t),r=NI(t);return r?J("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:J("path",{d:r,fill:"none",stroke:d,strokeWidth:e,strokeLinecap:"round",strokeLinejoin:"round",vectorEffect:"non-scaling-stroke"})}):null}function NI(t){const e=function(t){return SI(t).previewNodeId}(t);return fS(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 OI({shape:t}){
|
|
61
|
+
return J(V,{children:t.props.subpaths.flatMap(t=>t.nodes.flatMap(e=>{const n=IS(e),r=[];if(e.in){const o=PS(e);r.push(J("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=MS(e);r.push(J("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 BI(){return{canvasOverlays:[{id:"land.path.draft-overlay",component:CI,order:20},{id:"land.path.edit-insert-preview-overlay",component:lS,order:21}],shapeRenderers:[{type:"path",component:zI,hoverComponent:HI}],selectionCustomHandleRenderers:[{type:Gv,component:DI},{type:Vv,component:_I}]}}function zI({shape:t,shapeEditingSession:e}){
|
|
62
|
+
return J($I,{shape:t,shapeEditingSession:e})}function HI({shape:t,strokeWidth:e}){
|
|
63
|
+
return J(RI,{shape:t,strokeWidth:e})}function DI({handle:t,strokeWidth:e}){const n=jI(t.type,t.id);
|
|
64
|
+
return J("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 _I({handle:t,strokeWidth:e}){const n=jI(t.type,t.id);
|
|
65
|
+
return J("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 jI(t,e){const n=q();G(n.state.$_shapeEditingSession);const r=pI(n),o=Qv(t,e);return!!r&&!!o&&yI(r,o.subpathId,o.nodeId)}var FI=class{editor;deactivateHistoryScope=null;session=null;subscribers=new Set;constructor(t){this.editor=t}start(t,e,n){const r=this.editor.store.get(e);if(!sS(r))return!1;if(this.session?.mode===t&&this.session.shapeId===e)return!0;this.clear();const o=[WI(this.editor,r,t)];this.session={mode:t,shapeId:e,snapshots:o,index:o.length-1,initialShapeSignature:UI(r),onApply:n?.onApply,onBoundaryUndo:n?.onBoundaryUndo};const s={getState:()=>this.getState(),subscribe:t=>this.subscribe(t),undo:()=>this.undo(),redo:()=>this.redo()};return this.deactivateHistoryScope=this.editor.history.activateScope(s),this.notify(),!0}record(t){const e=this.session,n=this.editor.store.get(t);if(!e||e.shapeId!==t||!sS(n))return!1;const r=WI(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.store.get(t);if(!e||e.shapeId!==t||!sS(n))return!1;const r=WI(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.store.get(e);return!(!n||n.mode!==t||n.shapeId!==e)&&(!sS(r)||n.initialShapeSignature!==UI(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.store.get(e.shapeId);if(!sS(r))return this.clear(),!1;e.index=t;const o=pI(this.editor);this.editor.shapes.update([{id:e.shapeId,..."create"===e.mode&&n.draftMeta?{meta:II(r.meta,n.draftMeta)}:{},props:{subpaths:SS(n.subpaths)}}],{source:"user"});const s=this.editor.store.get(e.shapeId);sS(s)&&e.onApply?.(s);const i=n.selection??o;return i&&sS(s)&&this.editor.state.$_shapeEditingSession.get()?.shapeId===e.shapeId?mI(this.editor,s,i.nodes,i.primary):fI(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 WI(t,e,n){const r=SS(e.props.subpaths),o="create"===n?SI(e):null;return{subpaths:r,draftMeta:o,selection:pI(t),signature:JSON.stringify({subpaths:r,draftMeta:o})}}function UI(t){return JSON.stringify(function(t){return{...t,meta:{...t.meta},props:{...t.props,fill:{...t.props.fill},stroke:{...t.props.stroke},subpaths:SS(t.props.subpaths)}}}(t))}var KI=new WeakMap;function XI(t){const e=KI.get(t);if(e)return e;const n=new FI(t);return KI.set(t,n),n}function YI(t,e,n,r){return XI(t).start(e,n,r)}function qI(t,e){return XI(t).record(e)}function GI(t,e,n){return XI(t).end(e,n)}var VI=new WeakMap;function JI(t){return VI.get(t)??!1}function ZI(t){return function(t,e){const n=t.state.$_shapeEditingSession.get(),r=n?t.store.get(n.shapeId):null;return!(!n||!sS(r))&&(JI(t)===e||(VI.set(t,e),e||t.snaps.clearIndicators(),t.session.update({shapeEditingSession:{...n}},"system")),e)}(t,!JI(t))}function QI(t){VI.delete(t),t.snaps.clearIndicators()}function tP(t){let e=null;const n=j("path.editSnap.lifecycle",t.state.$_shapeEditingSession,()=>{const n=t.state.$_shapeEditingSession.get(),r=n?t.store.get(n.shapeId):null,o=sS(r)?r.id:null;if(o!==e){if(e){const n=function(t,e,n){return XI(t).hasNetChanges(e,n)}(t,"edit",e);GI(t,"edit",e),n||t.editing.cancelOperation()}e=o,fI(t),QI(t),o&&YI(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.tools.select("select",{source:"system"}),e}})}});return()=>{n(),e&&GI(t,"edit",e),fI(t,{syncCaret:!1}),QI(t)}}var eP="path.edit",nP=Math.PI/4,rP={propagation:"stop"},oP=1,sP=new WeakMap,iP=new WeakMap;function aP(t){const e=t.state.$_shapeEditingSession.get();if(!e)return null;const n=t.store.get(e.shapeId);return sS(n)?n:null}function lP(t,e,n){return t.shapes.geometry.computeLocalToPageTransform(e).invert().applyToPoint(n)}function dP(t){eS(t,null)}function cP(t){dP(t),fI(t)}function uP(t){return t.shiftKey}function pP(t){return JSON.stringify([t.subpathId,t.nodeId])}function hP(t,n){const r=sP.get(t);if(!r)return;if(n.pointerId!==r.pointerId)return;const o=t.store.get(r.shapeId);if(!sS(o))return void fP(t);if(!(r.isActive||(s=r.originScreenPoint,i=n.screenPoint,s.dist2(i)>=9)))return;var s,i;r.isActive=!0;const a=function(t,n){const r=Math.min(t.x,n.x),o=Math.min(t.y,n.y),s=Math.max(t.x,n.x),i=Math.max(t.y,n.y);return new e(r,o,s-r,i-o)}(r.originPagePoint,n.pagePoint),l=function(t,e,n){const r=t.shapes.geometry.computeLocalToPageTransform(e);return e.props.subpaths.flatMap(t=>t.nodes.flatMap(e=>{const o=r.applyToPoint(IS(e));return n.containsPoint(o)?[{subpathId:t.id,nodeId:e.id}]:[]}))}(t,o,a),d=uP(n)?function(t,e){const n=new Map(t.map(t=>[pP(t),{...t}]));for(const r of e){const t=pP(r);n.has(t)?n.delete(t):n.set(t,{...r})}return Array.from(n.values())}(r.previousEntries,l):l;t.interaction.setBrushBox(a),mI(t,o,d,d.at(-1)??null)}function fP(t){const e=sP.get(t);if(!e)return;const n=t.store.get(e.shapeId);sS(n)&&t.state.$_shapeEditingSession.get()?.shapeId===e.shapeId?mI(t,n,e.previousEntries,e.previousPrimary):fI(t),sP.delete(t),t.interaction.setBrushBox(null)}function gP(t,e,n,r){const o=t.store.get(e);sS(o)&&mI(t,o,n,r)}function mP(t){return t.filter(t=>t.nodes.length>=2)}function yP(t,e){t.editing.complete("user"),t.store.get(e.id)&&t.operations.run({kind:"path.shape-delete",label:"shape.delete",source:"user",history:"record"},()=>{t.shapes.delete([e.id],{source:"user",preserveInteraction:!0})})}function wP(t,e,n){const r=mP(function(t,e){const n=JS(e);return 0===n.size?SS(t):t.map(t=>{const e=n.get(t.id);if(!e)return vS(t);const r=t.nodes.filter(t=>!e.has(t.id)).map(kS),o=t.closed&&r.length>=3;return t.closed&&!o&&oI(r),{...t,closed:o,nodes:r}}).filter(t=>t.nodes.length>0)}(e.props.subpaths,n));0!==r.length?(t.shapes.update([{id:e.id,props:{subpaths:r}}],{source:"user"}),fI(t),qI(t,e.id)):yP(t,e)}function xP(t,e){const n=hI(t);if(!n||t.layers.isLocked(n.shape.id))return!1;const{shape:r,selection:o}=n,s=VS(r.props.subpaths,o.nodes,e,o.primary);if(!s)return!1;const i=mP(s.subpaths);return 0===i.length?(yP(t,r),!0):(t.operations.run({kind:"path.node-operation",label:"shape.edit",source:"user",history:"record"},()=>{t.shapes.update([{id:r.id,props:{subpaths:i}}],{source:"user"}),gP(t,r.id,s.selectedNodes,s.primaryNode)}),qI(t,r.id),!0)}function bP(t,e){const n=hI(t);if(!n||t.layers.isLocked(n.shape.id))return!1;const{shape:r,selection:o}=n,s=function(t,e,n){const r=t.shapes.geometry.computeLocalToPageTransform(e).invert(),o=r.applyToPoint(new f(0,0));return r.applyToPoint(n).sub(o)}(t,r,e),i=XS(r.props.subpaths,o.nodes,t=>IP(t,s));return t.operations.run({kind:"path.node-nudge",label:"shape.edit",source:"user",history:"record"},()=>{t.shapes.update([{id:r.id,props:{subpaths:i}}],{source:"user"}),gP(t,r.id,o.nodes,o.primary)}),qI(t,r.id),!0}function kP(t,e,n){const r=aP(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||!sS(n)||!t.editing.canEditShape(n)||(cP(t),QI(t),!t.editing.start({shapeId:n.id,operationKind:eP,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&&!t.layers.isLocked(r.id))return ZI(t),t.inputs.$_state.get().isPointing&&t.tools.dispatch(e,n),!0;if(e.accelKey&&"j"===e.key.toLowerCase()&&!e.altKey&&r&&!t.layers.isLocked(r.id))return xP(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 f(-e,0);case"ArrowRight":return new f(e,0);case"ArrowUp":return new f(0,-e);case"ArrowDown":return new f(0,e);default:return null}}(e);if(o)return bP(t,o);if(e.altKey||e.ctrlKey||e.metaKey||e.accelKey)return!1;const s=hI(t);if(!s||t.layers.isLocked(s.shape.id))return!1;const i=e.key.toLowerCase();return"backspace"===i||"delete"===i?(wP(t,s.shape,s.selection.nodes),!0):"c"===i?function(t,e,n){const r=n.filter(t=>{const n=US(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)=>YS(t,e.subpathId,e.nodeId),e.props.subpaths);return t.shapes.update([{id:e.id,props:{subpaths:o}}],{source:"user"}),gP(t,e.id,n,n.at(-1)??null),qI(t,e.id),!0}(t,s.shape,s.selection.nodes):"x"===i?(function(t,e,n){const r=n.reduce((t,e)=>qS(t,e.subpathId,e.nodeId),e.props.subpaths);t.shapes.update([{id:e.id,props:{subpaths:r}}],{source:"user"}),gP(t,e.id,n,n.at(-1)??null),qI(t,e.id)}(t,s.shape,s.selection.nodes),!0):"j"===i?xP(t,"join"):"k"===i&&xP(t,"separate")}function vP(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 SP(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)/nP)*nP;return t.add(new f(Math.cos(o)*r,Math.sin(o)*r))}function IP(t,e){return{...t,x:t.x+e.x,y:t.y+e.y}}function PP(){return{createSession(t,{handle:e,shape:n,originPagePoint:r}){if(!sS(n)||"custom"!==e.kind)return null;const o=Qv(e.type,e.id);if(!o)return null;if(t.state.$_shapeEditingSession.get()?.shapeId!==n.id)return null;const s=iP.get(t),i="path.node"===o.type&&s?.shapeId===n.id&&s.nodeId===o.nodeId;i&&iP.delete(t);const a=n,l=US(a.props.subpaths,o.subpathId,o.nodeId),d=lP(t,a,r),c=hI(t),u=c?.selection.shapeId===n.id?c.selection.nodes.map(t=>({...t})):[],p=c?.selection.shapeId===n.id?{...c.selection.primary}:null,h={subpathId:o.subpathId,nodeId:o.nodeId},f=!!c&&c.selection.shapeId===n.id&&yI(c.selection,o.subpathId,o.nodeId),g="path.node"===o.type&&f,m="path.node"===o.type&&t.inputs.$_state.get().shiftKey,y=m&&!g?[...c?.selection.shapeId===n.id?c.selection.nodes:[],h]:null;y?mI(t,n,y,h):t.inputs.$_state.get().shiftKey||f||gI(t,n,o.subpathId,o.nodeId);const w="path.node"===o.type&&(y||g)?y??c.selection.nodes:[h],x=t.shapes.geometry.computeLocalToPageTransform(a),b=l?x.applyToPoint(IS(l)):r,k=e.point.sub(r),v="path.node"===o.type?w.flatMap(t=>{const e=US(a.props.subpaths,t.subpathId,t.nodeId);return e?[x.applyToPoint(IS(e))]:[]}):[e.point],S=(v.length>0?v:[e.point]).map(t=>t.sub(r)),I=function(t,e,n){const r=new Set(n.map(pP)),o=t.shapes.geometry.computeLocalToPageTransform(e);return{points:e.props.subpaths.flatMap(t=>t.nodes.flatMap(n=>{const s={subpathId:t.id,nodeId:n.id};return r.has(pP(s))?[]:[{id:`${e.id}:${t.id}:${n.id}`,nodeId:e.id,point:o.applyToPoint(IS(n)),kind:"custom"}]})),outlines:[]}}(t,a,"path.node"===o.type?w:[]);return{shapeId:n.id,operationKind:"path.handle",onClick:m&&g?({editor:t})=>{const e=t.store.get(n.id);sS(e)&&function(t,e,n,r){const o=pI(t);if(!o||o.shapeId!==e.id)return void gI(t,e,n,r);const s={subpathId:n,nodeId:r},i=yI(o,n,r),a=i?o.nodes.filter(t=>!bI(t,s)):[...o.nodes,s];mI(t,e,a,i?a.at(-1)??null:s)}(t,e,o.subpathId,o.nodeId)}:void 0,onCancel({editor:t,reason:e}){if("pointer_cancel"!==e&&"escape"!==e)return;const r=t.store.get(n.id);sS(r)&&t.state.$_shapeEditingSession.get()?.shapeId===n.id&&(0!==u.length?mI(t,r,u,p):fI(t))},onComplete({editor:t}){i?function(t,e){XI(t).replaceCurrent(e)}(t,n.id):qI(t,n.id)},update({editor:t,pagePoint:e,accelKey:s,source:i}){if(!sS(t.store.get(n.id)))return"stop";const c=t.inputs.$_state.get(),u=c.shiftKey?"path.node"===o.type?SP(r,e):SP(b,e.add(k)).sub(k):e,p=JI(t)&&!s&&!c.shiftKey&&I.points.length>0,h=p?t.snaps.snapHandle({mode:"align",pagePoint:u,sourcePointOffsets:S,snapshot:I,threshold:10/t.state.$_camera.get().z}):null;p||t.snaps.clearIndicators();const f=h?.snappedPagePoint??u,g=lP(t,a,"path.node"===o.type?f:f.add(k)),m="path.node"===o.type?l?XS(a.props.subpaths,w,t=>IP(t,g.sub(d))):SS(a.props.subpaths):KS(a.props.subpaths,o.subpathId,o.nodeId,t=>function(t,e,n,r){const o=IS(t),s=r.altKey?{...t,kind:"corner"}:{...t},i=n.sub(o);return"in"===e?(s.in={dx:i.x,dy:i.y},r.altKey||"corner"===t.kind||(s.out=vP(i,t.out?MS(t).sub(o):null,"symmetric"===t.kind))):(s.out={dx:i.x,dy:i.y},r.altKey||"corner"===t.kind||(s.in=vP(i,t.in?PS(t).sub(o):null,"symmetric"===t.kind))),s}(t,o.handle,g,{altKey:c.altKey}));if(t.shapes.update([{id:n.id,props:{subpaths:m}}],{source:i}),"path.node"===o.type){const e=t.store.get(n.id);sS(e)&&mI(t,e,w,{subpathId:o.subpathId,nodeId:o.nodeId})}return"continue"}}}}}function MP(){return{id:"land.path.interactions",editorEvent:{handleEvent(t,e,n){if("pointer"===e.type&&"pointer_move"===e.name&&sP.get(t)?.pointerId===e.pointerId)return dP(t),hP(t,e),rP;if("pointer"===e.type&&"pointer_up"===e.name&&(iP.delete(t),dP(t),sP.get(t)?.pointerId===e.pointerId))return function(t,e){const n=sP.get(t);n&&(n.isActive?hP(t,e):uP(e)||fI(t),sP.delete(t),t.interaction.setBrushBox(null))}(t,e),rP;if("pointer"===e.type&&"pointer_cancel"===e.name&&(iP.delete(t),dP(t),sP.get(t)?.pointerId===e.pointerId))return fP(t),rP;if("double_click"===e.type&&!e.shiftKey&&!e.altKey&&!e.accelKey){cP(t);const n=t.shapes.hitTesting.atPoint(e.pagePoint);if(sS(n))return QI(t),t.editing.start({shapeId:n.id,operationKind:eP,entryMode:"focusEnd"},"user"),rP}if("cancel"===e.type)return iP.delete(t),sP.has(t)?(fP(t),rP):"command"===e.reason?void dP(t):"escape"===e.reason&&t.tools.isInInitialState()&&aP(t)&&t.editing.complete("user")?rP:void cP(t);if("keyboard"===e.type&&"key_down"===e.name)return kP(t,e,n)?rP:void 0;if("pointer"!==e.type||"pointer_move"!==e.name){if("pointer"===e.type&&"pointer_down"===e.name&&0===e.button&&e.altKey){dP(t);const n=aP(t);if(!n)return;const r=t.selection.hitTestHandle(e.pagePoint);if("custom"===r?.kind&&"path.node"===r.type){const e=Qv(r.type,r.id);if("path.node"===e?.type){const r=hI(t);return wP(t,n,r?.selection.shapeId===n.id&&yI(r.selection,e.subpathId,e.nodeId)?r.selection.nodes:[{subpathId:e.subpathId,nodeId:e.nodeId}]),rP}}}if("pointer"===e.type&&"pointer_down"===e.name&&0===e.button&&!e.altKey){dP(t);const n=aP(t);if(!n)return;const r=t.selection.hitTestHandle(e.pagePoint);if("custom"===r?.kind)return void(Qv(r.type,r.id)||fI(t));const o=lP(t,n,e.pagePoint),s=FS(n.props.subpaths,o,7/t.state.$_camera.get().z);if(!s)return function(t,e,n){const r=hI(t);sP.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),rP;const i=`insert-node:${oP+=1}`;return t.operations.run({kind:"path.insert-node",label:"shape.edit",source:"user",history:"record"},()=>{const e=cI(n.props.subpaths,s,i);t.shapes.update([{id:n.id,props:{subpaths:e}}],{source:"user"});const r=t.store.get(n.id);sS(r)&&gI(t,r,s.subpathId,i)}),qI(t,n.id),void iP.set(t,{shapeId:n.id,nodeId:i})}}else"mouse"!==e.pointerType||0!==e.buttons||e.altKey?dP(t):function(t,e){const n=aP(t);if(!n||"select"!==t.state.$_tool.get().activeToolId||!t.tools.isInInitialState())return void dP(t);if("custom"===t.selection.hitTestHandle(e.pagePoint)?.kind)return void dP(t);const r=lP(t,n,e.pagePoint),o=FS(n.props.subpaths,r,7/t.state.$_camera.get().z);if(!o)return void dP(t);const s=t.shapes.geometry.computeLocalToPageTransform(n);eS(t,{shapeId:n.id,subpathId:o.subpathId,startNodeId:o.startNodeId,endNodeId:o.endNodeId,t:o.t,pagePoint:s.applyToPoint(o.point)})}(t,e)}},selectionHandle:PP()}}function TP(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}function CP(t){if(!t||"object"!=typeof t)return null;const e=t,n=TP(e.dx,NaN),r=TP(e.dy,NaN);return Number.isFinite(n)&&Number.isFinite(r)?e.dx===n&&e.dy===r?t:{dx:n,dy:r}:null}function EP(t,e,n){if(!t||"object"!=typeof t)return null;const r=t,o=new Set,s=Array.isArray(r.nodes)?r.nodes.map((t,e)=>function(t,e,n){if(!t||"object"!=typeof t)return null;const r=t,o=TP(r.x,NaN),s=TP(r.y,NaN);return Number.isFinite(o)&&Number.isFinite(s)?{id:LP("string"==typeof r.id&&r.id.length>0?r.id:`node:${e}`,n),x:o,y:s,kind:aS(r.kind)?r.kind:"corner",in:CP(r.in),out:CP(r.out)}:null}(t,e,o)).filter(t=>null!==t):[];return 0===s.length?null:{id:LP("string"==typeof r.id&&r.id.length>0?r.id:`subpath:${e}`,n),closed:"boolean"==typeof r.closed&&r.closed,nodes:s}}function AP(t,e){if(!Array.isArray(t))return e;const n=new Set,r=t.map((t,e)=>EP(t,e,n)).filter(t=>null!==t);return r.length>0?r:e}function LP(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 $P(t,e,n){const r=n.sub(e),o=r.len2();if(0===o)return t.dist2(e);const s=t.sub(e),i=Math.max(0,Math.min(1,(s.x*r.x+s.y*r.y)/o));return t.dist2(e.add(r.mul(i)))}var RP=class extends p{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:x("transparent"),stroke:k("stroke-slate"),strokeWidth:3,fillRule:"nonzero"}}validateProps(t){const e=t&&"object"==typeof t?t:{},n=this.getDefaultProps();return{subpaths:(r=AP(e.subpaths,n.subpaths),r.map(t=>({...t,nodes:t.nodes.filter(t=>xS(t.x)&&xS(t.y))})).filter(t=>t.nodes.length>0).map(vS)),fill:_(e.fill,n.fill),stroke:_(e.stroke,n.stroke),strokeWidth:Math.max(1,TP(e.strokeWidth,n.strokeWidth)),fillRule:iS(e.fillRule)?e.fillRule:n.fillRule};var r}getPositionedBounds(t){const n=NS(t).localBounds;return new e(t.x+n.x,t.y+n.y,n.w,n.h)}getLocalBounds(t){return NS(t).localBounds}getRenderBounds(t){return NS(t).renderBounds}getExportBounds(t){return this.getRenderBounds(t)}getSelectionResizeLocalBounds(t){return NS(t).pointBounds}resizeSelectionBounds(t,e){const n=HS(t,$(t,this.getLocalBounds(t))).map(t=>({...t,nodes:t.nodes.map(t=>OP(t,t=>function(t,e){return 0===e.selectionRotation?t:f.RotWith(t,e.selectionRotationCenter,-e.selectionRotation)}(t,e)))})),r=zS(function(t,e){const n=NS(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 BS(t.props.subpaths,t=>new f(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=>OP(t,t=>function(t,e){return 0===e.selectionRotation?t:f.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 NS(t).outlineVertices.map(e=>new f(t.x+e.x,t.y+e.y))}getTerminalBindingOutlines(t){return NS(t).flattenedSubpaths.filter(t=>t.points.length>0).map(e=>({points:e.points.map(e=>new f(t.x+e.x,t.y+e.y)),closed:e.closed}))}resolveBindingPoint(t,e){const n=e.editor.shapes.geometry.computePositionedToPageTransform(t),r=n.tryInvert();if(!r)return e.rawPagePoint;const o=r.applyToPoint(e.rawPagePoint),s=r.applyToPoint(e.oppositePagePoint),i=s.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=NP(o,s,t,n);null!==r&&r>1e-6&&r<a&&(a=r)}}return Number.isFinite(a)?n.applyToPoint(o.add(i.mul(a))):e.rawPagePoint}getHandleSnapGeometry(t){return{points:t.props.subpaths.flatMap(t=>t.nodes.flatMap(t=>[{point:IS(t),kind:"custom"},...t.in?[{point:PS(t),kind:"custom"}]:[],...t.out?[{point:MS(t),kind:"custom"}]:[]])),outline:NS(t).outlineVertices}}canReceiveTerminalBinding(t){return!0}canEdit(t){return!0}canUseSelectionHandle(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.geometry.computeLocalToPageTransform(t);return{terminalHandleAnchors:[],middleHandleAnchors:[],customHandleAnchors:t.props.subpaths.flatMap(t=>t.nodes.flatMap(e=>{const n=[{kind:"custom",type:Gv,id:Jv(t.id,e.id),point:o.applyToPoint(IS(e)),cursor:"grab"}];return e.in&&n.push({kind:"custom",type:Vv,id:Zv(t.id,e.id,"in"),point:o.applyToPoint(PS(e)),cursor:"grab"}),e.out&&n.push({kind:"custom",type:Vv,id:Zv(t.id,e.id,"out"),point:o.applyToPoint(MS(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:DS(t,e.editor.shapes.geometry.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 f(e.x-t.x,e.y-t.y),o=NS(t);return!H(t.props.fill)&&function(t,e,n){let r=0,o=0;for(const s of t)if(s.closed&&!(s.points.length<3))for(let t=0;t<s.points.length;t+=1){const n=s.points[t],i=s.points[(t+1)%s.points.length];n&&i&&(n.y<=e.y&&i.y>e.y||n.y>e.y&&i.y<=e.y)&&n.x+(e.y-n.y)/(i.y-n.y)*(i.x-n.x)>e.x&&(o+=1,r+=i.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],s=o.points[t];if(n&&s&&jS(e,n,s)<=r)return!0}return!1}(o.flattenedSubpaths,r,t.props.strokeWidth/2+6)}hitTestLineSegment(t,e){const n=new f(e.positionedStart.x-t.x,e.positionedStart.y-t.y),r=new f(e.positionedEnd.x-t.x,e.positionedEnd.y-t.y),o=e.positionedMargin+t.props.strokeWidth/2;return NS(t).flattenedSubpaths.some(t=>function(t,e,n,r){const o=r*r;for(let s=1;s<n.length;s+=1){const r=n[s-1],i=n[s];if(r&&i&&($P(r,t,e)<=o||$P(i,t,e)<=o||$P(t,r,i)<=o||$P(e,r,i)<=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 NP(t,e,n,r){const o=e.sub(t),s=r.sub(n),i=o.x*s.y-o.y*s.x;if(Math.abs(i)<1e-8)return null;const a=n.sub(t),l=(a.x*s.y-a.y*s.x)/i,d=(a.x*o.y-a.y*o.x)/i;return l>=0&&l<=1&&d>=0&&d<=1?l:null}function OP(t,e){const n=e(IS(t)),r=t.in?e(PS(t)):null,o=t.out?e(MS(t)):null;return{...kS(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 BP=Math.PI/4,zP=1,HP=1;function DP(){return`node:${zP+=1}`}function _P(t,e,n){return t.shapes.geometry.computeLocalToPageTransform(e).invert().applyToPoint(n)}function jP(t,e,n,r){const o=(WS(e.props.subpaths,n)?.nodes.filter(t=>t.id!==r))?.at(-1);return o?t.shapes.geometry.computeLocalToPageTransform(e).applyToPoint(new f(o.x,o.y)):null}function FP(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)/BP)*BP;return t.add(new f(Math.cos(o)*r,Math.sin(o)*r))}function WP(t,e,n,r,o){const s=function(t,e,n){const r=WS(e.props.subpaths,n)?.nodes[0];return r?t.shapes.geometry.computeLocalToPageTransform(e).applyToPoint(new f(r.x,r.y)):null}(t,e,n),i=WS(e.props.subpaths,n),a=i?.nodes.filter(t=>t.id!==r).length??0;return!(!s||!i||a<3)&&s.dist(o)<=10/t.state.$_camera.get().z}function UP(t,e){return e.previewNodeId?t.map(t=>t.id===e.subpathId?{...t,nodes:t.nodes.filter(t=>t.id!==e.previewNodeId)}:t):SS(t)}function KP(t,e){return WS(t.props.subpaths,e.subpathId)?.nodes.filter(t=>t.id!==e.previewNodeId).length??0}var XP=class extends h{draft=null;operation=null;constructor(t){super(t,"path"),this.initial="idle",this.addChild(new YP(t,this)),this.addChild(new qP(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:${HP+=1}`,o=DP(),s={id:o,x:0,y:0,kind:"corner"},[i]=this.editor.shapes.create([{type:"path",x:t.x,y:t.y,meta:II({},{subpathId:r,previewNodeId:null}),props:{...n,subpaths:[{id:r,closed:!1,nodes:[s]}]}}],{source:"user",autoReparent:!1});if(!sS(i))throw this.cancelOperation(),new Error("Failed to create path shape");return this.editor.selection.set([i.id],{source:"system"}),this.draft={shapeId:i.id,subpathId:r,lastNodeId:o,createdShape:!0,previewNodeId:null},YI(this.editor,"create",i.id,{onBoundaryUndo:()=>this.draft?.shapeId===i.id&&(this.cancelDraft(),this.editor.tools.select("select",{source:"system"}),!0),onApply:t=>{const e=this.draft;if(!e||e.shapeId!==t.id)return;const n=WS(t.props.subpaths,e.subpathId);this.draft={...e,lastNodeId:n?.nodes.at(-1)?.id??e.lastNodeId,previewNodeId:null}}}),{shapeId:i.id,subpathId:r,nodeId:o,originPagePoint:t.clone(),originScreenPoint:e.clone(),startNode:kS(s),finishOnPointerUp:!1}}const r=this.editor.store.get(this.draft.shapeId);if(!sS(r))return this.cancelDraft(),null;const o=n.shiftKey?jP(this.editor,r,this.draft.subpathId,this.draft.previewNodeId)??t:t,s=n.shiftKey?FP(o,t):t;if(WP(this.editor,r,this.draft.subpathId,this.draft.previewNodeId,t)){const n=this.draft,o=WS(r.props.subpaths,n.subpathId)?.nodes.find(t=>t.id!==n.previewNodeId);return o?(this.editor.shapes.update([{id:r.id,meta:II(r.meta,{subpathId:n.subpathId,previewNodeId:null}),props:{subpaths:UP(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:kS(o),finishOnPointerUp:!0}):null}const i=_P(this.editor,r,s),a=this.draft.previewNodeId??DP(),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:i.x,y:i.y,kind:"corner"}:t)}:{...t,nodes:[...t.nodes,{id:a,x:i.x,y:i.y,kind:"corner"}]}:t);return this.editor.shapes.update([{id:r.id,meta:II(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:i.x,y:i.y,kind:"corner"},finishOnPointerUp:!1}}updateNodeDrag(t,e,n,r){const o=this.editor.store.get(t.shapeId);if(!sS(o))return;const s=r.shiftKey?FP(t.originPagePoint,e):e,i=_P(this.editor,o,t.originPagePoint),a=_P(this.editor,o,s),l=t.originScreenPoint.dist(n)>=3,d=KS(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(i),r):kS(t.startNode));this.editor.shapes.update([{id:o.id,meta:II(o.meta,{subpathId:t.subpathId,previewNodeId:this.draft?.previewNodeId??null}),props:{subpaths:d}}],{source:"user"})}updatePreview(t,e){if(!this.draft)return;const n=this.editor.store.get(this.draft.shapeId);if(!sS(n)||KP(n,this.draft)<1)return;const r=e.shiftKey?jP(this.editor,n,this.draft.subpathId,this.draft.previewNodeId):null,o=r?FP(r,t):t,s=_P(this.editor,n,o),i=this.draft.previewNodeId??DP(),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:i,x:s.x,y:s.y,kind:"corner"}:t)}:{...t,nodes:[...t.nodes,{id:i,x:s.x,y:s.y,kind:"corner"}]});this.editor.shapes.update([{id:n.id,meta:II(n.meta,{subpathId:this.draft.subpathId,previewNodeId:i}),props:{subpaths:a}}],{source:"user"}),this.draft={...this.draft,previewNodeId:i}}canFinishDraft(){if(!this.draft)return!1;const t=this.editor.store.get(this.draft.shapeId);return!!sS(t)&&KP(t,this.draft)>=2}finishDraft(t={}){if(!this.draft)return;const e=t.switchToSelect??!0,n=this.editor.store.get(this.draft.shapeId);if(sS(n)){const t=UP(n.props.subpaths,this.draft),e=zS(HS({...n,props:{...n.props,subpaths:t}},this.editor.shapes.geometry.computeLocalToPageTransform(n)),n.props);this.editor.shapes.update([{id:n.id,x:e.x,y:e.y,rotation:0,scaleX:1,scaleY:1,meta:PI(n.meta),props:{subpaths:e.subpaths}}],{source:"user"}),this.draft.createdShape&&F(this.editor,n.id,{source:"user"})}GI(this.editor,"create",this.draft.shapeId),this.commitOperation(),this.draft=null,e&&!this.editor.state.$_tool.get().isToolLocked&&this.editor.tools.select("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.tools.select("select",{source:"system"}));this.finishDraft({switchToSelect:!1}),sS(this.editor.store.get(t))&&(this.editor.tools.select("select",{source:"system"}),this.editor.editing.start({shapeId:t,operationKind:"path.edit",entryMode:"focusEnd"},"user"))}}cancelDraft(){this.draft&&(GI(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()}},YP=class extends h{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()}},qP=class extends h{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}),qI(this.editor,e.shapeId)),this.transition("idle"),e?.finishOnPointerUp&&this.tool.finishDraft()}onCancel(){this.tool.cancelDraft(),this.transition("idle")}onExit(){this.info=null}},GP=class{type="path";toSvg(t,e){const n=NS(t);return n.path?{tag:"path",attrs:{d:n.path,fill:H(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 VP(){return{shapeUtils:[new RP],shapeSvgExporters:[new GP],interactionHandlers:[MP()],tools:{path:t=>new XP(t)}}}var{difference:JP,intersection:ZP,union:QP,xor:tM}=ie,eM=1,nM=1;function rM(t,e){return Math.abs(t[0]-e[0])<1e-6&&Math.abs(t[1]-e[1])<1e-6}function oM(t){return HS(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&&rM(r,t)||e.push(t)}return e.length>1&&rM(e[0],e[e.length-1])&&e.pop(),e.length>=3?e:null}(RS(t).points)).filter(t=>null!==t).map(t=>[t])}function sM(t){const e=t.length>1&&rM(t[0],t[t.length-1])?t.slice(0,-1):t;return e.length<3?null:{id:`boolean-subpath:${eM+=1}`,closed:!0,nodes:e.map(([t,e])=>({id:`boolean-node:${nM+=1}`,x:t,y:e,kind:"corner"}))}}function iM(t,e){const n=e.map(oM).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 QP(n,...r);case"subtract":return JP(n,...r);case"intersect":return ZP(n,...r);case"xor":return tM(n,...r)}}(t,n).flatMap(t=>t).map(sM).filter(t=>null!==t)}function aM({editor:t}){return function({editor:t}){return{getSelectionStyle:()=>function(t){const e=t.state.$_selectedShapes.get().filter(sS);return 0===e.length?null:{fill:fM(e.map(t=>t.props.fill)),stroke:fM(e.map(t=>t.props.stroke)),strokeWidth:hM(e.map(t=>t.props.strokeWidth))}}(t),setSelectionStyle(e){const n=t.state.$_selectedShapes.get().filter(sS).filter(e=>!t.layers.isLocked(e.id)).map(t=>({id:t.id,props:{...e}}));return n.length>0&&t.shapes.update(n,{source:"user"}),n.map(({id:t})=>t)},toolDefaultsState:w(t.signalGraph.computed("Path.toolDefaults",()=>t.shapes.getDefaultProps("path"))),setToolDefaults:e=>(t.shapes.updateDefaultProps("path",e),t.shapes.getDefaultProps("path")),canBeginEdit:()=>null!==lM(t),beginEdit(){const e=lM(t);return!!e&&(fI(t),QI(t),t.editing.start({shapeId:e.id,operationKind:"path.edit",entryMode:"focusEnd"},"user"),!0)},isEditing:()=>null!==dM(t),completeEdit:()=>!!dM(t)&&(t.editing.complete("user"),!0),isNodeSnapEnabled:()=>JI(t),canToggleNodeSnap:()=>{const e=dM(t);return!!e&&!t.layers.isLocked(e.id)},toggleNodeSnap(){const e=dM(t);return!(!e||t.layers.isLocked(e.id))&&(ZI(t),!0)},canDeleteSelectedNodes:()=>cM(t,()=>!0),deleteSelectedNodes(){const e=hI(t);return!(!e||t.layers.isLocked(e.shape.id))&&(wP(t,e.shape,e.selection.nodes),!0)},canMakeSelectedNodesCurve:()=>cM(t,t=>t.entries.some(({node:t})=>!t.in&&!t.out)),makeSelectedNodesCurve:()=>uM(t,"make-curve"),canRemoveSelectedNodeHandles:()=>cM(t,t=>t.entries.some(({node:t})=>!!t.in||!!t.out)),removeSelectedNodeHandles:()=>uM(t,"remove-handles"),canRunSelectedNodeOperation:e=>cM(t,t=>GS(t.shape.props.subpaths,t.selection.nodes,e)),runSelectedNodeOperation(e){const n=hI(t);return!(!n||t.layers.isLocked(n.shape.id)||!GS(n.shape.props.subpaths,n.selection.nodes,e))&&(xP(t,e),!0)},canRunBooleanOperation:()=>pM(t).length>=2,runBooleanOperation:e=>function(t,e){const n=pM(t),r=n[0];if(!r||n.length<2)return null;const o=function(t,e,n){const r=iM(t,e);return 0===r.length?null:zS(r,{...n,fillRule:"evenodd"})}(e,n.map(e=>({shape:e,localToPage:t.shapes.geometry.computeLocalToPageTransform(e)})),{fill:r.props.fill,stroke:r.props.stroke,strokeWidth:r.props.strokeWidth});if(!o)return null;let s=null;return t.operations.run({kind:`path.boolean.${e}`,label:"shape.boolean",source:"user",history:"record"},()=>{const[e]=t.shapes.create([{type:"path",x:o.x,y:o.y,parentId:r.parentId,props:{...r.props,subpaths:o.subpaths,fillRule:"evenodd"}}],{source:"user"});t.shapes.delete(n.map(t=>t.id),{source:"user",preserveInteraction:!0}),e&&(s=e.id,t.selection.set([e.id],{source:"system"}))}),s}(t,e)}}({editor:t})}function lM(t){const e=t.state.$_selectedShapes.get(),n=1===e.length?e[0]:null;return sS(n)&&!t.layers.isLocked(n.id)?n:null}function dM(t){const e=t.state.$_shapeEditingSession.get(),n=e?t.store.get(e.shapeId):null;return sS(n)?n:null}function cM(t,e){const n=hI(t);return!!n&&!t.layers.isLocked(n.shape.id)&&e(n)}function uM(t,e){const n=hI(t);if(!n||t.layers.isLocked(n.shape.id))return!1;const r="make-curve"===e?n.entries.filter(({node:t})=>!t.in&&!t.out).reduce((t,{ref:e})=>YS(t,e.subpathId,e.nodeId),n.shape.props.subpaths):n.selection.nodes.reduce((t,e)=>qS(t,e.subpathId,e.nodeId),n.shape.props.subpaths);t.shapes.update([{id:n.shape.id,props:{subpaths:r}}],{source:"user"});const o=t.store.get(n.shape.id);return sS(o)&&mI(t,o,n.selection.nodes,n.selection.primary),qI(t,n.shape.id),!0}function pM(t){return t.state.$_selectedShapes.get().filter(sS).filter(e=>!t.layers.isLocked(e.id)&&!e.isHidden)}function hM(t){const[e,...n]=t;return void 0!==e&&n.every(t=>t===e)?e:null}function fM(t){const[e,...n]=t;return void 0!==e&&n.every(t=>g(e,t))?e:null}var gM=v({id:"path",editor:VP(),render:BI(),setup({editor:t}){const e=tP(t);try{return{api:aM({editor:t}),dispose:e}}catch(n){throw e(),n}}});function mM(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 yM({assetInliners:t=[],editor:e,padding:n=16,resolveThemeColor:r,shapeIds:o}){e.exports.repairIntegrity(o);const s=Array.from(e.shapeSvgExporters.values(),t=>t.type).sort();let i,a=e.exports.getIntegrityReport(o);try{i=await async function({assetInliners:t,editor:e,padding:n,resolveThemeColor:r,shapeIds:o}){const s=3;for(let a=0;a<s;a+=1){const s=e.store.getRevision();try{for(const n of t)await(n.prepare?.({editor:e,requestedShapeIds:o}))}catch(i){if(e.store.getRevision()!==s)continue;throw i}if(e.store.getRevision()!==s)continue;const a=e.exports.getSvgString(o,{padding:n,resolveThemeColor:r}),l=a?.exportedShapeIds.flatMap(t=>{const n=e.store.get(t);return n?[n]:[]})??[];if(e.store.getRevision()===s)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),wM({cause:p,integrity:a,supportedShapeTypes:s})}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:s}),{exportedShapes:d,result:c}=i;if(!c)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=c.svg;try{for(const n of t)u=await n.inline({editor:e,exportedShapes:d,exportedShapeIds:c.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,s=Array.from(t.matchAll(n));for(const a of s){const t=vM(a[1]??""),n=IM(a[2]??"");for(const r of SM(t)){const t=n.get(r)?.trim();if(!t)continue;const o="srcset"===r?PM(t):[t];for(const n of o)MM(n)||e.add(n)}}const i=[...s.map(t=>t[0]),...Array.from(t.matchAll(r),t=>t[1]??"")];for(const a of i){for(const t of a.matchAll(o)){const n=t[2]?.trim();n&&!MM(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 wM({cause:p,exportedShapeIds:c.exportedShapeIds,integrity:a,skippedShapes:c.skippedShapes,supportedShapeTypes:s})}return{status:l,svg:u,width:c.width,height:c.height,exportedShapeIds:c.exportedShapeIds,skippedShapes:c.skippedShapes}}function wM({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 xM={audio:["src"],embed:["src"],iframe:["src"],img:["src","srcset"],input:["src"],object:["data"],script:["src"],source:["src","srcset"],track:["src"],video:["poster","src"]},bM=["href","xlink:href"],kM=new Set(["a","area"]);function vM(t){return(t.split(":").pop()??t).toLowerCase()}function SM(t){const e=xM[t]??[];return kM.has(t)?e:[...bM,...e]}function IM(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 PM(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 s=t.slice(o,n);const i=r&&s.endsWith(",");if(i&&(s=s.replace(/,+$/u,"")),s&&e.push(s),!i)for(;n<t.length&&","!==t[n];)n+=1}return e}function MM(t){return t.startsWith("#")||/^data:/iu.test(t)}var TM=16384,CM=67108864;async function EM({background:t,pixelRatio:e=2,...n}){const r=await yM(n);if(!r.svg||null===r.width||null===r.height)return{status:"error"===r.status.tone?LM(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 s=Math.ceil(o*n),i=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>TM||t>TM||o*t>CM)throw new Error(`PNG dimensions ${o}×${t} exceed the browser export limit.`)}({height:i,pixelRatio:n,sourceHeight:e,sourceWidth:o,width:s}),"undefined"==typeof document||"undefined"==typeof Image||"undefined"==typeof FileReader)throw new Error("PNG export requires a browser environment.");const a=await mM(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(c=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=c})),d=document.createElement("canvas");var c;d.width=s,d.height=i;const u=d.getContext("2d");if(!u)throw new Error("A 2D canvas context is unavailable.");t&&(u.fillStyle=t,u.fillRect(0,0,s,i));return u.drawImage(l,0,0,s,i),{blob:await AM(d),width:s,height:i}}({background:t,height:r.height,pixelRatio:e,svg:r.svg,width:r.width});return{status:LM(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 AM(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 LM(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 $M(t,e){return(await t.export("svg",{...zM(e),options:e})).result}async function RM(t,e){return(await t.export("png",{...zM(e),options:e})).result}function NM(){return{kind:"provider",id:"canvas-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??{},s=await yM({assetInliners:[BM(n,r.inlineSvg)],editor:t,padding:o.padding,resolveThemeColor:o.appearance?.resolveThemeColor,shapeIds:n});return{data:s.svg,result:s,status:s.status}}}}function OM(){return{kind:"provider",id:"canvas-export.png",format:"png",label:"PNG",mimeType:"image/png",fileExtension:"png",async export({editor:t,options:e,shapeIds:n},r){const o=e??{},s=await EM({assetInliners:[BM(n,r.inlineSvg)],background:o.background,editor:t,padding:o.padding,pixelRatio:o.pixelRatio,resolveThemeColor:o.appearance?.resolveThemeColor,shapeIds:n});return{data:s.blob,result:s,status:s.status}}}}function BM(t,e){return{inline:n=>e({...n,requestedShapeIds:t})}}function zM(t){return t.scope?{scope:t.scope}:{shapeIds:t.shapeIds}}function HM(){return oe({id:"canvas-export",setup:()=>({exports:[NM(),OM()]})})}var DM=new WeakMap;function _M(t){return DM.get(t)??null}function jM(t,e=0){return Math.max(0,"number"==typeof t&&Number.isFinite(t)?t:e)}function FM({cornerRadius:t,h:e,w:n}){return Math.min(jM(t),Math.max(0,n)/2,Math.max(0,e)/2)}function WM(t){return N(t)&&"video"===t.type}function UM(t){return z(t)&&"video"===t.type}function KM({editor:t}){return{setMediaPresenter(e){!function(t,e){e?DM.set(t,e):DM.delete(t),t.assets.invalidateUrls()}(t,e)},getSelectionState(){if(1!==t.selection.getIds().length)return null;const[e]=t.state.$_selectedShapes.get();return UM(e)?{shapeId:e.id,cornerRadius:jM(e.props.cornerRadius),loop:e.props.loop}:null},setSelectionStyle(e){const n=t.state.$_selectedShapes.get().filter(UM).filter(e=>!t.layers.isLocked(e.id)).map(t=>({id:t.id,props:{...void 0===e.cornerRadius?{}:{cornerRadius:jM(e.cornerRadius)},...void 0===e.loop?{}:{loop:e.loop}}}));return n.length>0&&t.shapes.update(n,{source:"user"}),n.map(({id:t})=>t)}}}function XM(t,e){return"number"==typeof t&&Number.isFinite(t)?t:e}var YM=class extends p{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(),{width:r,height:o}=m({width:XM(e.w,n.w),height:XM(e.h,n.h),preserveAspectRatio:!0});return{w:r,h:o,assetId:(s=e.assetId,"string"==typeof s&&s.startsWith("asset:")?e.assetId:null),name:"string"==typeof e.name?e.name:"",loop:!0===e.loop,cornerRadius:jM(e.cornerRadius)};var s}getLocalBounds(t){return new e(0,0,t.props.w,t.props.h)}getRenderBounds(t){return JM(t)}getExportBounds(t){return this.getLocalBounds(t)}getPointHitTestBounds(t,e){return A({bodyHeight:t.props.h,bodyWidth:t.props.w,headingHeight:34,shape:t})}canEdit(t){return!0}hitTest(t,n,r){return this.getPositionedBounds(t).containsPoint(n)||(r?L({bodyHeight:t.props.h,bodyWidth:t.props.w,editor:r.editor,headingHeight:34,shape:t}).containsPoint(n):new e(t.x,t.y-34,t.props.w,t.props.h+34).containsPoint(n))}hitTestBindingTarget(t,e){return this.getPositionedBounds(t).containsPoint(e)}canReceiveTerminalBinding(t){return!0}getAllowedSelectionResizeModes(t,e){return i}},qM="Video",GM=34;function VM(t){return/^\s*$/.test(t)?qM:t}function JM(t){return new e(0,-34,t.props.w,t.props.h+34)}function ZM(){return{shapeUtils:[new YM]}}var QM='[data-ui="video-shape-player"]',tT=new Set(["key_down","key_up","pointer_cancel","pointer_down","pointer_move","pointer_up"]),eT=["Inter","ui-sans-serif","system-ui","-apple-system","BlinkMacSystemFont","'Segoe UI'","sans-serif"].join(", "),nT={id:"land.video.player.dom-events",handle({event:t,name:e}){if(!tT.has(e))return"continue";const n=t.target;return n instanceof Element&&n.closest(QM)?"handled":"continue"},getCursor:({element:t})=>t?.closest(QM)?"default":void 0},rT=b({id:"land.video.name.dom-events",selector:'[data-ui="video-canvas-name"]'});function oT(){return{domEventGuards:[nT,rT],shapeRenderers:[{type:"video",component:sT,hoverComponent:iT}]}}function sT({editor:t,isSelected:e,shape:r,shapeEditingSession:o}){const{assetId:s,h:i,loop:a,name:l,w:d}=r.props;G(t.assets.getUrlVersionSignal());const c=s?t.assets.resolveUrl(s):null,u=o?.shapeId===r.id;
|
|
66
|
+
return Z("div",{style:{height:"100%",overflow:"visible",pointerEvents:"none",position:"relative",width:"100%"},children:[J("div",{"data-ui":"video-shape",style:{borderRadius:FM(r.props),display:"block",height:i,left:0,overflow:"hidden",pointerEvents:"none",position:"absolute",top:34,width:d},children:c?J(n,{kind:"video",label:VM(l),presenter:_M(t),controls:e,dataUi:"video-shape-player",loop:a,src:c,style:{background:"#000",display:"block",height:i,objectFit:"contain",pointerEvents:e?"auto":"none",userSelect:"none",width:d}}):J("div",{"data-ui":"video-shape-missing-asset",style:{alignItems:"center",background:"#0f172a",border:"1px solid #334155",boxSizing:"border-box",color:"#cbd5e1",display:"flex",fontFamily:eT,fontSize:12,height:i,justifyContent:"center",overflow:"hidden",width:d},children:"Missing video"})}),J(aT,{editor:t,shape:r,isEditing:u})]})}function iT({shape:t,strokeWidth:e}){const n=JM(t);
|
|
67
|
+
return J("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:J("rect",{x:0,y:0,width:t.props.w,height:t.props.h,rx:FM(t.props),ry:FM(t.props),fill:"none",stroke:d,strokeWidth:e,vectorEffect:"non-scaling-stroke"})})}function aT({editor:t,shape:e,isEditing:n}){
|
|
68
|
+
return J(c,{editor:t,shape:e,isEditing:n,value:e.props.name,fallback:VM(""),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.shapes.update([{id:e.id,props:{name:n}}],{source:"user"})}})}var lT=v({id:"video",editor:ZM(),render:oT(),setup:({editor:t})=>({api:KM({editor:t})})}),dT="blobs",cT=null;function uT(){return"undefined"==typeof indexedDB?Promise.resolve(null):(cT||(cT=new Promise((t,e)=>{const n=indexedDB.open("land.plugin-video",1);n.addEventListener("upgradeneeded",()=>{n.result.objectStoreNames.contains(dT)||n.result.createObjectStore(dT)}),n.addEventListener("success",()=>{const e=n.result;e.addEventListener("versionchange",()=>{e.close(),cT=null}),t(e)}),n.addEventListener("error",()=>{cT=null,e(n.error)})})),cT)}var pT="video-blob:";function hT(){return"undefined"!=typeof crypto&&"randomUUID"in crypto?`${pT}${crypto.randomUUID()}`:`${pT}${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}async function fT(t){if("undefined"==typeof indexedDB)throw new Error("IndexedDB is not available for video storage.");const e=hT();return await async function(t,e){const n=await uT();n&&await new Promise((r,o)=>{const s=n.transaction(dT,"readwrite");s.addEventListener("complete",()=>r()),s.addEventListener("abort",()=>o(s.error)),s.addEventListener("error",()=>o(s.error)),s.objectStore(dT).put(e,t)})}(e,t),{storageKey:e}}async function gT(t){const e=await async function(t){const e=await uT();return e?new Promise((n,r)=>{const o=e.transaction(dT,"readonly").objectStore(dT).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 mT(t){await async function(t){const e=await uT();e&&await new Promise((n,r)=>{const o=e.transaction(dT,"readwrite");o.addEventListener("complete",()=>n()),o.addEventListener("abort",()=>r(o.error)),o.addEventListener("error",()=>r(o.error)),o.objectStore(dT).delete(t)})}(t)}async function yT(){return(await async function(){const t=await uT();return t?new Promise((e,n)=>{const r=t.transaction(dT,"readonly").objectStore(dT).getAllKeys();r.addEventListener("success",()=>e([...r.result])),r.addEventListener("error",()=>n(r.error))}):null}())?.map(String)??[]}function wT(t,e){const n=t.store.get(e);return WM(n)&&"local"===n.props.source.kind&&n.props.source.storageKey||null}function xT(t,e){const n=t.store.get(e);return WM(n)&&"remote"===n.props.source.kind&&n.props.source.url||null}function bT(t){const e=new Set;for(const n of t.assets.getAll())WM(n)&&"local"===n.props.source.kind&&n.props.source.storageKey&&e.add(n.props.source.storageKey);return e}async function kT({editor:t,objectUrls:e}){const n=bT(t),r=await yT(),o=[];for(const s of r)n.has(s)||(e?.release(s),await mT(s),o.push(s));return o}function vT(){const t=new Map,e=new Map;let n=0,r=!1;const o=async(o,s={})=>{if(s.signal?.throwIfAborted(),r)return null;const i=t.get(o);if(i)return i;const a=e.get(o);if(a)return a;const l=n,d=gT(o).then(e=>{if(!e||r||l!==n)return null;const s=URL.createObjectURL(e);return t.set(o,s),s}).finally(()=>{e.delete(o)});e.set(o,d);const c=await d;return s.signal?.throwIfAborted(),c};return{async preloadForEditor(t,e={}){e.signal?.throwIfAborted(),await Promise.all(Array.from(bT(t)).map(t=>o(t,e)))},preload:o,resolve:e=>t.get(e)??null,resolveAssetUrl(e,n){const r=xT(e,n);if(r)return r;const o=wT(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 ST(t,{signal:e}){if("url"===t.type)return{...await IT(t.url,{signal:e}),name:t.name||AT(t.url)||"Video",source:{kind:"remote",url:t.url},mimeType:null};const n="file"===t.type?t.file:t.blob;if(!TT(n))throw new Error("The selected file is not a video.");const r=URL.createObjectURL(n),o=await IT(r,{signal:e}).finally(()=>URL.revokeObjectURL(r));e.throwIfAborted();const{storageKey:s}=await fT(n);try{e.throwIfAborted()}catch(i){throw await mT(s),i}return{...o,name:"file"===t.type?t.file.name||"Video":t.name||"Video",source:{kind:"local",storageKey:s},mimeType:"file"===t.type?t.file.type||"video/mp4":t.mimeType||t.blob.type||"video/mp4",fileSize:n.size}}function IT(t,{signal:e}={}){return e?.throwIfAborted(),new Promise((n,r)=>{const o=document.createElement("video"),s=()=>{o.removeEventListener("loadedmetadata",i),o.removeEventListener("error",a),e?.removeEventListener("abort",l),o.removeAttribute("src"),o.load()},i=()=>{const t=o.videoWidth||320,e=o.videoHeight||180,r=Number.isFinite(o.duration)&&o.duration>=0?o.duration:null;s(),n({width:t,height:e,duration:r})},a=()=>{s(),r(new Error("Could not decode video metadata."))},l=()=>{s(),r(e?.reason??new Error("Video metadata decoding aborted."))};o.preload="metadata",o.addEventListener("loadedmetadata",i),o.addEventListener("error",a),e?.addEventListener("abort",l,{once:!0}),o.src=t,o.load(),e?.aborted&&l()})}function PT({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 MT(t){for(const e of t)if(e.type.startsWith("video/"))return e;return null}function TT(t){return!t.type||t.type.startsWith("video/")}function CT({filename:t,url:e}){const n=document.createElement("a");n.href=e,n.download=t,n.click()}async function ET({blob:t,filename:e}){const n=URL.createObjectURL(t);try{CT({filename:e,url:n})}finally{window.setTimeout(()=>URL.revokeObjectURL(n),0)}}function AT(t){try{const e=new URL(t).pathname.split("/").filter(Boolean).at(-1);return e?decodeURIComponent(e):null}catch{return null}}var LT=1;function $T(t,e){return t.assets.create({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 RT({editor:t,objectUrls:e,pagePoint:n,signal:r,size:o,source:s}){return NT({editor:t,input:await ST(s,{signal:r}),objectUrls:e,pagePoint:n,signal:r,size:o})}async function NT({editor:t,input:e,objectUrls:n,pagePoint:r,signal:o,size:s}){const i="local"===e.source.kind?e.source.storageKey:null;try{i&&await n.preload(i,{signal:o}),await se(t,o),o.throwIfAborted()}catch(a){throw await zT({objectUrls:n,storageKey:i}),a}try{const o=t.operations.run({kind:"video.insert",source:"user"},()=>{const n=$T(t,e),o=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)}}(s)??PT({width:n.props.w,height:n.props.h}),i=t.state.$_viewportPageBounds.get(),a=r??i?.center??t.viewport.screenToPage(new f(360,240)),[l]=t.shapes.create([{type:"video",x:Math.round(a.x-o.w/2),y:Math.round(a.y-o.h/2),props:{...o,assetId:n.id,name:e.name}}],{source:"user"});return l?(t.selection.set([l.id],{source:"user"}),l.id):(t.assets.delete(n.id,{source:"system"}),null)});return o||await zT({objectUrls:n,storageKey:i}),o}catch(a){throw await zT({objectUrls:n,storageKey:i}),a}}async function OT({editor:t,file:e,objectUrls:n,signal:r}){if(!TT(e))return!1;const[o]=t.state.$_selectedShapes.get();return!(1!==t.selection.getIds().length||!UM(o)||t.layers.isLocked(o.id))&&async function({editor:t,input:e,objectUrls:n,shape:r,signal:o}){const s=r.props.assetId,i="local"===e.source.kind?e.source.storageKey:null;try{o.throwIfAborted(),i&&await n.preload(i,{signal:o}),await se(t,o),o.throwIfAborted()}catch(a){throw await zT({objectUrls:n,storageKey:i}),a}try{const o=t.store.get(r.id);if(!UM(o)||t.layers.isLocked(o.id)||o.props.assetId!==s)return await zT({objectUrls:n,storageKey:i}),!1;const l=t.operations.begin({kind:`video.asset.replace:${r.id}:${LT++}`,label:"video.asset.replace",source:"user",history:"record"});try{const n=$T(t,e);return t.shapes.update([{id:r.id,props:{assetId:n.id,name:e.name}}],{source:"user"}),s&&!function(t,e){return t.snapshots.getDocument().records.some(t=>"shape"===t.typeName&&t.props.assetId===e)}(t,s)&&t.assets.delete(s,{source:"user"}),l.commit(),!0}catch(a){throw l.isActive&&l.cancel(),a}}catch(a){throw await zT({objectUrls:n,storageKey:i}),a}}({editor:t,input:await ST({type:"file",file:e},{signal:r}),objectUrls:n,shape:o,signal:r})}async function BT({editor:t,objectUrls:e,onError:n,signal:r}){if(r.throwIfAborted(),1!==t.selection.getIds().length)return;const[o]=t.state.$_selectedShapes.get();if(!UM(o)||!o.props.assetId)return;const s=t.store.get(o.props.assetId);if(!WM(s))return;const i=s.props.name||"land-video";if("remote"===s.props.source.kind)return void(await async function({filename:t,onError:e,signal:n,url:r}){n.throwIfAborted();try{const e=await fetch(r,{signal:n});if(!e.ok)throw new Error(`Could not download video URL (${e.status}).`);const o=await e.blob();n.throwIfAborted(),await ET({blob:o,filename:t})}catch(o){n.throwIfAborted(),e?.(new Error("Could not download remote video; opening URL instead.",{cause:o})),function(t){const e=document.createElement("a");e.href=t,e.rel="noreferrer",e.target="_blank",e.click()}(r)}}({filename:i,onError:n,signal:r,url:s.props.source.url}));const a=s.props.source.storageKey,l=await gT(a);if(r.throwIfAborted(),l)return void(await ET({blob:l,filename:i}));const d=e.resolve(a);d&&CT({filename:i,url:d})}async function zT({objectUrls:t,storageKey:e}){e&&(t.release(e),await mT(e))}function HT({editor:t,onError:e,run:n,videoAssetService:r}){let o;const s=DT(t=>o.insert({source:{type:"file",file:t}}),e),i=DT(t=>o.replaceSelection({file:t}),e);return o={openInsertFilePicker(){s.open()},openReplaceFilePicker(){i.open()},insert:({pagePoint:e,size:o,source:s})=>n(async n=>{n.throwIfAborted();const i=await RT({editor:t,objectUrls:r.objectUrls,pagePoint:e,signal:n,size:o,source:s});return n.throwIfAborted(),i}),replaceSelection:({file:e})=>n(async n=>{if(!e.type.startsWith("video/"))return!1;const[o]=t.state.$_selectedShapes.get();if(!UM(o)||t.layers.isLocked(o.id))return!1;const s=await OT({editor:t,file:e,objectUrls:r.objectUrls,signal:n});return n.throwIfAborted(),s}),downloadSelectionOriginal:()=>n(async n=>{await BT({editor:t,objectUrls:r.objectUrls,onError:e,signal:n}),n.throwIfAborted()})},{value:o,dispose(){s.dispose(),i.dispose()}}}function DT(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 _T(){const t=vT();return{value:{objectUrls:t,preloadForEditor:(e,{signal:n})=>t.preloadForEditor(e,{signal:n}),resolveAssetUrl:(e,n)=>t.resolveAssetUrl(e,n)},dispose(){t.releaseAll()}}}function jT(t={}){return oe({id:"video.host",requires:[lT],setup({api:e,canvas:n,editor:r,run:o}){const s=e(lT),i=(t.createAssetService??_T)();let a=!1;const l=()=>s.setMediaPresenter(re({run:o,onError:t.onError})),d=n.snapshots.revision.subscribe(()=>{queueMicrotask(()=>{a||l()})});let c=null;const u=()=>{a=!0,d(),s.setMediaPresenter(null);const t=[];try{c?.()}catch(e){t.push(e)}try{i.dispose()}catch(e){t.push(e)}if(t.length)throw new AggregateError(t,"Failed to dispose video host resources.")};try{l();const e=HT({editor:r,onError:t.onError,run:o,videoAssetService:i.value});return c=e.dispose,{api:e.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!==MT(t.files)||(t.urls?.some(FT)??!1),async import(t){const n=MT(t.files),r=t.urls?.find(FT);return(n||r)&&await e.value.insert({source:n?{type:"file",file:n}:{type:"url",url:r},pagePoint:t.pagePoint})?"handled":"ignored"}}],assetResolvers:[{id:"video.host.asset-resolver",resolve:t=>i.value.resolveAssetUrl(r,t),preload:({signal:t})=>i.value.preloadForEditor(r,{signal:t})}],dispose:u}}catch(p){try{u()}catch(h){throw new AggregateError([p,h],"video host setup and cleanup failed.",{cause:p})}throw p}}})}function FT(t){return t.startsWith("data:video/")||/\.(?:m4v|mov|mp4|ogv|webm)(?:[?#].*)?$/i.test(t)}function WT({toolIds:t,shortcutOverrides:e}){return de([...t.map(KT),{id:"standard.history.undo",repeat:!0,shortcut:{key:"z",accelKey:!0},isEnabled:t=>YT(t)&&t.history.canUndoState.getSnapshot(),run:t=>{t.history.undo()}},{id:"standard.history.redo",repeat:!0,shortcut:{key:"z",accelKey:!0,shiftKey:!0},isEnabled:t=>YT(t)&&t.history.canRedoState.getSnapshot(),run:t=>{t.history.redo()}},{id:"standard.selection.select-all",shortcut:{key:"a",accelKey:!0},isEnabled:t=>t.shapes.getAll().length>0,run:t=>t.selection.selectAll()},{id:"standard.selection.duplicate",shortcut:{key:"d",accelKey:!0},isEnabled:t=>YT(t)&&qT(t),run:t=>{t.selection.duplicate()}},{id:"standard.selection.delete",shortcut:["Backspace","Delete"],isEnabled:t=>YT(t)&&qT(t)&&t.shapes.canDelete(t.selection.idsState.getSnapshot()),run:t=>t.selection.delete()},{id:"standard.layer.move-selection-backward",shortcut:{key:"ArrowDown",altKey:!0},isEnabled:t=>YT(t)&>(t).canMoveBackward,run:t=>{t.layers.move(t.selection.idsState.getSnapshot(),"backward")}},{id:"standard.layer.move-selection-forward",shortcut:{key:"ArrowUp",altKey:!0},isEnabled:t=>YT(t)&>(t).canMoveForward,run:t=>{t.layers.move(t.selection.idsState.getSnapshot(),"forward")}},{id:"standard.view.zoom-in",repeat:!0,shortcut:{key:"="},isEnabled:()=>!0,run:t=>t.viewport.zoomIn()},{id:"standard.view.zoom-out",repeat:!0,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 UT(t){return de([{id:"standard.clipboard.copy",shortcut:{key:"c",accelKey:!0},isEnabled:qT,run:async t=>{await(le(t).api(ae)?.copy())}},{id:"standard.clipboard.cut",shortcut:{key:"x",accelKey:!0},isEnabled:t=>YT(t)&&qT(t)&&t.shapes.canDelete(t.selection.idsState.getSnapshot()),run:async t=>{await(le(t).api(ae)?.cut())}},{id:"standard.clipboard.paste",shortcut:{key:"v",accelKey:!0},isEnabled:t=>YT(t)&&(le(t).api(ae)?.hasContent()??!1),run:async t=>{await(le(t).api(ae)?.paste())}}],t)}function KT(t){return{id:`standard.tool.${t}`,shortcut:VT(t),isEnabled:e=>YT(e)||XT.has(t),run:e=>e.tools.setCurrent(t)}}var XT=new Set(["select","hand","laser"]);function YT(t){return!t.document.readonlyState.getSnapshot()}function qT(t){return t.selection.idsState.getSnapshot().length>0}function GT(t){return t.layers.getActionState(t.selection.idsState.getSnapshot())}function VT(t){const e=JT[t];return e?{key:e}:void 0}var JT={select:"v",hand:"h",rectangle:"r",ellipse:"o",rhombus:"d",triangle:"3",pentagon:"5",hexagon:"6",star:"8",draw:"p",eraser:"e",laser:"l",path:"b",text:"t",frame:"f"};function ZT(t={}){const e=!1!==t.flow&&!1!==t.image&&!1!==t.text,n=jf("object"==typeof t.text?t.text:{}),r=Zk({onError:t.onError}),o=jT({onError:t.onError}),s=Jf("object"==typeof t.text?t.text:{}),i=Fw({text:!1===t.text?void 0:n}),a=gm({..."object"==typeof t.flow?t.flow:{},image:ek,text:n}),l=["select","hand",...!1===t.geo?[]:mm,...!1===t.draw?[]:["draw"],...!1===t.eraser?[]:["eraser"],...!1===t.laser?[]:["laser"],...!1===t.path?[]:["path"],...!1===t.text?[]:["text"],...!1===t.frame?[]:["frame"]];return{text:n,geo:i,flow:a,imageHost:r,videoHost:o,textHost:s,plugins:[...!1===t.geo?[]:[i],...!1===t.draw?[]:[br],...!1===t.eraser?[]:[Co],...!1===t.laser?[]:[qv],...!1===t.path?[]:[gM],...!1===t.html?[]:[hx],...!1===t.image?[]:[ek],...!1===t.video?[]:[lT],...!1===t.text?[]:[n],...e?[a]:[],...!1===t.frame?[]:[Qo],...!1===t.group?[]:[Zw]],hostModules:[...!1===t.image?[]:[r],...!1===t.video?[]:[o],...!1===t.text?[]:[s],ae,HM()],hostActions:UT(QT(t.shortcutOverrides,"standard.clipboard.")),actions:WT({toolIds:l,shortcutOverrides:QT(t.shortcutOverrides,"standard.clipboard.",!1)})}}function QT(t,e,n=!0){return t&&Object.fromEntries(Object.entries(t).filter(([t])=>t.startsWith(e)===n))}export{jm as ArrowLeftTool,Fm as ArrowRightTool,Nm as BurstTool,dx as DEFAULT_HTML_IFRAME_SANDBOX,Qx as DEFAULT_IMAGE_SMUDGE_BRUSH_COLOR,Zx as DEFAULT_IMAGE_SMUDGE_BRUSH_SIZE,Hi as DEFAULT_TEXT_FONT,br as Draw,pr as DrawShapeSvg,cr as DrawShapeSvgExporter,dr as DrawShapeUtil,Kn as DrawTool,Am as EllipseTool,Co as Eraser,Dr as EraserTool,Bs as FLOW_INPUT_PORT_ID,ng as FLOW_NODE_GAP_PAGE,ts as FLOW_NODE_SUB_TYPE,cm as FLOW_NODE_TITLE_RENDER_HEIGHT,zs as FLOW_OUTPUT_PORT_ID,sg as FlowConnectionError,Ng as FlowEdgeShapeHoverRenderer,pm as FlowNodeSvgDecoration,Qo as Frame,_o as FrameShapeSvgExporter,$o as FrameShapeUtil,zo as FrameTool,wm as GEO_FILL_STYLES,mm as GEO_SHAPE_KINDS,ym as GEO_STROKE_STYLES,Ww as Geo,$w as GeoFillGradient,Rw as GeoFillPattern,Ew as GeoShapeSvgExporter,fw as GeoShapeUtil,Zw as Group,Xw as GroupShapeSvgExporter,Kw as GroupShapeUtil,Di as HOST_TEXT_FONT,tx as HTML_INTERACTION_OPERATION_KIND,Hm as HexagonTool,hx as Html,ix as HtmlShapeUtil,yx as IMAGE_CROP_ASPECT_RATIO_PRESETS,eb as IMAGE_SMUDGE_BRUSH_SIZE_MAX,tb as IMAGE_SMUDGE_BRUSH_SIZE_MIN,ek as Image,Mb as ImageShapeSvgExporter,Pb as ImageShapeUtil,qv as Laser,ov as LaserTool,Lm as MessageCircleTool,Vv as PATH_CONTROL_HANDLE_TYPE,rS as PATH_FILL_RULES,Gv as PATH_NODE_HANDLE_TYPE,oS as PATH_NODE_KINDS,gM as Path,GP as PathShapeSvgExporter,RP as PathShapeUtil,XP as PathTool,zm as PentagonTool,Em as RectangleTool,Om as RhombusTool,Dm as StarTool,Rm as SummaryLeftTool,$m as SummaryTool,Ki as TEXT_SIZE_PRESETS,Ff as Text,$h as TextLinkPopoverPresenterProvider,Oh as TextSearchHighlightProvider,_m as TrapezoidTool,Bm as TriangleTool,qM as VIDEO_NAME_FALLBACK,GM as VIDEO_NAME_RENDER_HEIGHT,lT as Video,YM as VideoShapeUtil,hb as cancelImageSmudgeSession,gb as cancelImageSmudgeSessionIfActive,mk as cleanupUnreferencedImageBlobs,kT as cleanupUnreferencedVideoBlobs,vb as cloneImageSmudgeStrokes,Ks as commitFlowEdgeCreation,fb as completeImageSmudgeSession,Hk as confirmImageSmudgeSession,HM as createCanvasExportHostModule,ni as createCanvasShapeLinkHref,ji as createDefaultTextFontCatalog,_i as createDefaultTextPluginOptions,fr as createDrawCanvasRenderContributions,ur as createDrawEditorContributions,Ur as createEraserCanvasRenderContributions,To as createEraserEditorContributions,$g as createFlowCanvasRenderContributions,fs as createFlowEdgeBoundEndpoint,fm as createFlowEditorContributions,rg as createFlowNodeFromPort,gm as createFlowPlugin,Yo as createFrameCanvasRenderContributions,jo as createFrameEditorContributions,Nw as createGeoCanvasRenderContributions,Aw as createGeoEditorContributions,Gy as createGeoGradientStops,Fw as createGeoPlugin,qw as createGroupCanvasRenderContributions,Yw as createGroupEditorContributions,cx as createHtmlCanvasRenderContributions,lx as createHtmlEditorContributions,rx as createHtmlInteractionHandler,px as createHtmlPlugin,ox as createHtmlPluginApi,jb as createImageCanvasRenderContributions,Yx as createImageCropInteractionHandler,Xx as createImageCropSelectionHandleInteractionHandler,Bb as createImageEditorContributions,Kk as createImageHostApi,Zk as createImageHostModule,yk as createImageObjectUrlStore,Cb as createImageSmudgeInteractionHandler,ak as createImageStorageKey,Yk as createImageSvgAssetInliner,lv as createLaserCanvasRenderContributions,Yv as createLaserEditorContributions,wk as createLocalImageAssetService,_T as createLocalVideoAssetService,BI as createPathCanvasRenderContributions,Zv as createPathControlHandleId,VP as createPathEditorContributions,Jv as createPathNodeHandleId,OM as createPngExportFormatProvider,li as createRichTextFromPlainText,WT as createStandardCanvasActions,UT as createStandardCanvasHostActions,ZT as createStandardCanvasKitProfile,NM as createSvgExportFormatProvider,Dh as createTextCanvasRenderContributions,zf as createTextEditorContributions,Fi as createTextFontCatalog,Jf as createTextHostModule,jf as createTextPlugin,oT as createVideoCanvasRenderContributions,ZM as createVideoEditorContributions,HT as createVideoHostApi,jT as createVideoHostModule,vT as createVideoObjectUrlStore,hT as createVideoStorageKey,IT as decodeVideoMetadata,uk as deleteImageBlob,mT as deleteVideoBlob,$k as downloadSelectedImageOriginal,BT as downloadSelectedVideoOriginal,RM as exportCanvasPng,$M as exportCanvasSvg,EM as exportEditorPng,yM as exportEditorSvg,Bh as findRichTextSearchMatches,PT as fitVideoSize,Fn as flipDrawShapeInSelectionBounds,yb as getActiveImageSmudgeSession,pk as getAllImageBlobStorageKeys,yT as getAllVideoBlobStorageKeys,Un as getDrawShapeDiagnostics,Dn as getDrawShapeParentPoints,_n as getDrawShapeParentSegments,Cr as getEraserRuntime,Ik as getFirstImageFile,MT as getFirstVideoFile,Us as getFlowEdgeCreationInvalidReason,Fs as getFlowEdgeTerminalBindings,ks as getFlowEdgeVisualPortPoint,os as getFlowNodeDisplayTitle,um as getFlowNodeRenderBounds,ax as getHtmlDisplayTitle,Nx as getImageCropModeOperationKind,Mx as getImageCropRectOrDefault,db as getImageSmudgeModeOperationKind,ev as getLaserRuntime,hk as getLocalImageAssetStorageKey,wT as getLocalVideoAssetStorageKey,di as getPlainTextFromRichText,gk as getReferencedImageStorageKeys,bT as getReferencedVideoStorageKeys,fk as getRemoteImageAssetUrl,xT as getRemoteVideoAssetUrl,VM as getVideoDisplayName,JM as getVideoRenderBounds,Ek as insertImageIntoEditor,NT as insertPreparedVideoIntoEditor,RT as insertVideoIntoEditor,Pr as interpolateDrawShapeRecords,ti as isAllowedRichTextLinkHref,yr as isDrawShapeRecord,ei as isExternalRichTextLinkHref,ss as isFlowEdgeBindingRecord,ns as isFlowEdgeShapeRecord,rs as isFlowNodeShape,vm as isGeoFillStyle,Iw as isGeoGradientStyle,bm as isGeoShapeKind,xm as isGeoShapeRecord,km as isGeoStrokeStyle,Qw as isHtmlShapeRecord,Fx as isImageAssetRecord,Wx as isImageShapeRecord,cb as isImageSmudgeModeForShape,iS as isPathFillRule,aS as isPathNodeKind,sS as isPathShapeRecord,Ri as isTextShapeRecord,WM as isVideoAssetRecord,TT as isVideoBlob,UM as isVideoShapeRecord,Qs as normalizeRichTextLinkHref,Wf as openBrowserRichTextLink,oi as openRichTextLink,ri as parseCanvasShapeLinkHref,Qv as parsePathHandle,ST as prepareVideoAssetInput,mM as readBlobAsDataUrl,dk as readImageBlob,ck as readImageBlobAsDataUrl,gT as readVideoBlob,xb as redoImageSmudgeStroke,bb as registerImageSmudgeConfirmHandler,Lk as replaceSelectedImageFromFile,OT as replaceSelectedVideoFromFile,kb as requestImageSmudgeConfirm,Tw as resolveGeoFillPaint,ew as sampleGeoGradientColor,pb as startImageSmudgeSession,nx as startInteractingWithHtmlShape,wb as undoImageSmudgeStroke,eg as unwrapFlowNode,mb as updateImageSmudgeBrush,zi as updateTextShapeRichText,pi as validateRichTextDocument,tg as wrapShapeAsFlowNode,lk as writeImageBlob,fT as writeVideoBlob};
|