@aivex/ui 1.2.0-dev.11 → 1.2.0-dev.12

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.
@@ -1,2 +1,2 @@
1
- "use client";require(`./styles.css`),Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require(`./Button-C_GP2mJ-.cjs`),t=require(`./Switch-CMKBdqkX.cjs`);let n=require(`react`),r=require(`react/jsx-runtime`),i=require(`konva`);i=e.Ba(i,1);let a=require(`pixi.js`);var o={POINT:`POINT`,RECTANGLE:`RECTANGLE`,ROTATED_RECTANGLE:`ROTATED_RECTANGLE`,POLYGON:`POLYGON`,ELLIPSE:`ELLIPSE`,LINE:`LINE`};function s(e){return e.interaction?.visible!==!1}function c(e){return s(e)&&e.interaction?.hitTestDisabled!==!0}function l(e){return c(e)&&e.interaction?.selectable!==!1}function u(e){return l(e)&&!e.readOnly&&e.interaction?.editable!==!1}function d(e){return u(e)&&e.interaction?.draggable!==!1}function f(e){return e.map((e,t)=>({shape:e,index:t})).sort((e,t)=>{let n=e.shape.style?.zIndex??0,r=t.shape.style?.zIndex??0;return n===r?e.index-t.index:n-r}).map(e=>e.shape)}function p(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`id_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}var m=[`tl`,`t`,`tr`,`r`,`br`,`b`,`bl`,`l`];function h(e){let t=e.map(e=>e.x),n=e.map(e=>e.y);return{minX:Math.min(...t),minY:Math.min(...n),maxX:Math.max(...t),maxY:Math.max(...n)}}function g(e,t){let n=(t.minX+t.maxX)/2,r=(t.minY+t.maxY)/2;return{x:e.includes(`l`)?t.minX:e.includes(`r`)?t.maxX:n,y:e.includes(`t`)?t.minY:e.includes(`b`)?t.maxY:r}}function _(e,t,n,r){let i={...t};return e.includes(`l`)&&(i.minX=n),e.includes(`r`)&&(i.maxX=n),e.includes(`t`)&&(i.minY=r),e.includes(`b`)&&(i.maxY=r),i}function v(e,t){let n=t.x-e.x,r=t.y-e.y,i=Math.max(Math.abs(n),Math.abs(r));return{x:e.x+(n<0?-i:i),y:e.y+(r<0?-i:i)}}function y(e,t,n){let r=Math.cos(n),i=Math.sin(n),a=e.x-t.x,o=e.y-t.y;return{x:t.x+a*r-o*i,y:t.y+a*i+o*r}}function b(e){let t=h(e);return[{x:t.minX,y:t.minY},{x:t.maxX,y:t.minY},{x:t.maxX,y:t.maxY},{x:t.minX,y:t.maxY}]}function x(e,t,n=32){let r=(e.x+t.x)/2,i=(e.y+t.y)/2,a=Math.abs(t.x-e.x)/2,o=Math.abs(t.y-e.y)/2;return Array.from({length:n},(e,t)=>{let s=t/n*2*Math.PI;return{x:r+a*Math.cos(s),y:i+o*Math.sin(s)}})}function S(e){let t=[...e].sort((e,t)=>e.x-t.x||e.y-t.y);if(t.length<=2)return t;let n=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x),r=[];for(let e of t){for(;r.length>=2&&n(r[r.length-2],r[r.length-1],e)<=0;)r.pop();r.push(e)}let i=[];for(let e=t.length-1;e>=0;e--){let r=t[e];for(;i.length>=2&&n(i[i.length-2],i[i.length-1],r)<=0;)i.pop();i.push(r)}return r.pop(),i.pop(),r.concat(i)}function C(e){let t=S(e);if(t.length<3)return b(e);let n=1/0,r=b(e);for(let e=0;e<t.length;e++){let i=t[e],a=t[(e+1)%t.length],o=Math.hypot(a.x-i.x,a.y-i.y)||1,s=(a.x-i.x)/o,c=(a.y-i.y)/o,l=1/0,u=-1/0,d=1/0,f=-1/0;for(let e of t){let t=e.x*s+e.y*c,n=-e.x*c+e.y*s;t<l&&(l=t),t>u&&(u=t),n<d&&(d=n),n>f&&(f=n)}let p=(u-l)*(f-d);if(p<n){n=p;let e=(e,t)=>({x:e*s-t*c,y:e*c+t*s});r=[e(l,d),e(u,d),e(u,f),e(l,f)]}}return r}var w=(e,t)=>({x:e.x-t.x,y:e.y-t.y}),T=(e,t)=>e.x*t.x+e.y*t.y,E=e=>Math.hypot(e.x,e.y),D=e=>{let t=E(e)||1;return{x:e.x/t,y:e.y/t}},O=(e,t)=>({x:(e.x+t.x)/2,y:(e.y+t.y)/2}),k=e=>{let t=e.reduce((e,t)=>({x:e.x+t.x,y:e.y+t.y}),{x:0,y:0});return{x:t.x/e.length,y:t.y/e.length}};function A(e){return[e[0],O(e[0],e[1]),e[1],O(e[1],e[2]),e[2],O(e[2],e[3]),e[3],O(e[3],e[0])]}function j(e,t){let n=O(e[0],e[1]),r=D(w(e[0],e[3]));return{x:n.x+r.x*t,y:n.y+r.y*t}}function M(e,t,n,r){let i=(e,i)=>({x:t.x+e*n.x+i*r.x,y:t.y+e*n.y+i*r.y});return[i(e.minX,e.minY),i(e.maxX,e.minY),i(e.maxX,e.maxY),i(e.minX,e.maxY)]}function N(e,t,n){if(e.length<4)return e;let r=e[0],i=D(w(e[1],e[0])),a=D(w(e[3],e[0])),o=T(w(e[1],r),i),s=T(w(e[3],r),a),c=w(n,r);return M(_(t,{minX:0,minY:0,maxX:o,maxY:s},T(c,i),T(c,a)),r,i,a)}function P(e,t,n){let r=t.maxX-t.minX||1,i=t.maxY-t.minY||1,a=n.maxX-n.minX,o=n.maxY-n.minY;return e.map(e=>({x:n.minX+(e.x-t.minX)/r*a,y:n.minY+(e.y-t.minY)/i*o}))}var F={contextMenu:{copy:`복사`,paste:`붙여넣기`,duplicate:`복제`,delete:`삭제`,bringToFront:`맨 앞으로`,sendToBack:`맨 뒤로`,editVertices:`정점 편집`,merge:`레이블 합치기`,assistExpand:`이 지점 포함하기`,assistExclude:`이 지점 제외하기`,undo:`실행 취소`,redo:`다시 실행`,zoomToSelection:`선택 영역으로 확대`,selectAll:`전체 선택`,clearSelection:`선택 해제`},viewSettings:{title:`보기 설정`,reset:`보기설정 초기화`,brightness:`밝기`,contrast:`대비`,strokeSize:`선 두께`,simplifyStrength:`단순화 강도`,pixelation:`이미지 픽셀화`,cursorGuide:`커서 가이드라인`,guideMask:`가이드 마스크`,regionMask:`ROI 표시`,keepZoomOnImageChange:`이미지 변경 시 줌 유지`,wheelZoom:`스크롤로 확대·축소`},minimap:{zoomIn:`확대`,zoomOut:`축소`,zoom100:`100%로 초기화`,viewSettings:`보기 설정`,toggleMinimap:`미니맵 접기/펼치기`},imageLoading:`이미지를 불러오는 중…`,imageLoadError:`이미지를 불러올 수 없습니다`};function I(e){return e?{contextMenu:{...F.contextMenu,...e.contextMenu},viewSettings:{...F.viewSettings,...e.viewSettings},minimap:{...F.minimap,...e.minimap},imageLoading:e.imageLoading??F.imageLoading,imageLoadError:e.imageLoadError??F.imageLoadError}:F}var L={SELECT:`SELECT`,POLYGON:`POLYGON`,PATH:`PATH`,BRUSH:`BRUSH`,RECTANGLE:`RECTANGLE`,ROTATED_RECTANGLE:`ROTATED_RECTANGLE`,CIRCLE:`CIRCLE`,POINT:`POINT`,ASSISTANT_POLYGON:`ASSISTANT_POLYGON`,ASSISTANT_RECT:`ASSISTANT_RECT`,ASSISTANT_POINT:`ASSISTANT_POINT`},R={brightness:1,contrast:1,showCursorGuide:!1,imageSmoothing:!0,strokeSize:2,simplifyStrength:1.5,showGuide:!0,showRegionMask:!0,keepZoomOnImageChange:!1,wheelZoom:!0},ee=`var(--editor-overlay-inverse-scale, 1)`,te=`#377be2`,ne=`#e23c3c`;function re({point:e}){let t=e.positive?te:ne;return(0,r.jsx)(`div`,{style:{position:`absolute`,left:e.x,top:e.y,width:18,height:18,marginLeft:-9,marginTop:-9,borderRadius:`50%`,background:t,border:`2px solid #fff`,boxShadow:`0 0 3px rgba(0,0,0,0.5)`,color:`#fff`,fontSize:13,fontWeight:700,lineHeight:`14px`,display:`flex`,alignItems:`center`,justifyContent:`center`,transform:`scale(${ee})`,transformOrigin:`center`},children:e.positive?`+`:`−`})}function ie({image:e,points:t,boxes:n,status:i}){return(0,r.jsxs)(`div`,{style:{position:`absolute`,left:0,top:0,width:e.w,height:e.h,pointerEvents:`none`},children:[(0,r.jsx)(`style`,{children:`@keyframes editorv2-assistant-shimmer{from{background-position:200% 0}to{background-position:-200% 0}}`}),n.map((e,t)=>(0,r.jsx)(`div`,{style:{position:`absolute`,left:e.x,top:e.y,width:e.width,height:e.height,boxSizing:`border-box`,border:`calc(2px * var(--editor-overlay-inverse-scale, 1)) solid rgba(255,255,255,0.9)`,backgroundImage:`linear-gradient(90deg, rgba(255,255,255,0.10) 0%, rgba(255,255,255,0.30) 50%, rgba(255,255,255,0.10) 100%)`,backgroundSize:`200% 100%`,animation:`editorv2-assistant-shimmer 1.4s linear infinite`}},`box-${t}-${e.x}-${e.y}-${e.width}-${e.height}`)),i===`loading`&&t.map((e,t)=>(0,r.jsx)(re,{point:e},`pt-${t}-${e.x}-${e.y}`))]})}function z(e){let t=[];for(let n of e)if(`separator`in n){if(!t.length||`separator`in t[t.length-1])continue;t.push(n)}else t.push(n);for(;t.length&&`separator`in t[t.length-1];)t.pop();return t}function B({x:e,y:n,items:i,onClose:a}){let o=z(i);return(0,r.jsxs)(t.h,{open:!0,modal:!1,onOpenChange:e=>{e||a()},children:[(0,r.jsx)(t.h.Trigger,{asChild:!0,children:(0,r.jsx)(`span`,{"aria-hidden":!0,style:{position:`absolute`,left:e,top:n,width:0,height:0}})}),(0,r.jsx)(t.h.Content,{side:`bottom`,align:`start`,sideOffset:2,collisionPadding:8,style:{maxHeight:`var(--radix-dropdown-menu-content-available-height)`,overflowY:`auto`},onContextMenu:e=>e.preventDefault(),onCloseAutoFocus:e=>e.preventDefault(),children:o.map((e,n)=>`separator`in e?(0,r.jsx)(t.h.Separator,{className:`aivex:shrink-0`},`sep-${n}`):(0,r.jsx)(t.h.Item,{danger:e.danger,disabled:e.disabled,className:`aivex:shrink-0`,onSelect:()=>e.onClick(),children:(0,r.jsxs)(`span`,{className:`aivex:flex aivex:w-full aivex:items-center aivex:justify-between aivex:gap-6`,children:[(0,r.jsxs)(`span`,{className:`aivex:flex aivex:min-w-0 aivex:items-center aivex:gap-1.5`,children:[e.icon,(0,r.jsx)(`span`,{className:`aivex:truncate`,children:e.label})]}),e.shortcut&&(0,r.jsx)(t.h.Shortcut,{children:e.shortcut})]})},e.label))})]})}function V({color:e=`#1e88e5`}){let t=(0,n.useRef)(null),i=(0,n.useRef)(null),a=(0,n.useRef)(null);return(0,n.useEffect)(()=>{let e=t.current,n=i.current,r=a.current;if(!e||!n||!r)return;let o=t=>{let i=e.getBoundingClientRect(),a=t.clientX-i.left,o=t.clientY-i.top;if(a<0||o<0||a>i.width||o>i.height){n.style.display=`none`,r.style.display=`none`;return}n.style.display=`block`,r.style.display=`block`,n.style.transform=`translateX(${a}px)`,r.style.transform=`translateY(${o}px)`},s=()=>{n.style.display=`none`,r.style.display=`none`};return window.addEventListener(`mousemove`,o),e.parentElement?.addEventListener(`mouseleave`,s),()=>{window.removeEventListener(`mousemove`,o),e.parentElement?.removeEventListener(`mouseleave`,s)}},[]),(0,r.jsxs)(`div`,{ref:t,className:`aivex:pointer-events-none aivex:absolute aivex:inset-0 aivex:overflow-hidden`,children:[(0,r.jsx)(`div`,{ref:i,style:{position:`absolute`,top:0,left:0,width:1,height:`100%`,background:e,opacity:.6,display:`none`}}),(0,r.jsx)(`div`,{ref:a,style:{position:`absolute`,top:0,left:0,width:`100%`,height:1,background:e,opacity:.6,display:`none`}})]})}function ae({status:e,render:t,loadingLabel:n=F.imageLoading,errorLabel:i=F.imageLoadError}){return(0,r.jsx)(`div`,{"data-track-id":e===`loading`?`editor-image-loading-wrap`:`editor-image-error-wrap`,style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,background:e===`error`?`rgba(13,13,18,1)`:`rgba(13,13,18,0.6)`,backdropFilter:e===`loading`?`blur(2px)`:void 0,color:`#fff`,fontFamily:`Pretendard, sans-serif`,pointerEvents:e===`error`?`auto`:`none`},children:t?t(e):e===`loading`?(0,r.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10,fontSize:13},children:[(0,r.jsx)(`span`,{style:{width:18,height:18,borderRadius:`50%`,border:`2px solid rgba(255,255,255,0.3)`,borderTopColor:`#fff`,animation:`editorv2-image-spin 0.7s linear infinite`}}),n,(0,r.jsx)(`style`,{children:`@keyframes editorv2-image-spin{to{transform:rotate(360deg)}}`})]}):(0,r.jsxs)(`div`,{style:{textAlign:`center`,opacity:.85},children:[(0,r.jsx)(`div`,{style:{fontSize:28,marginBottom:6},children:`⚠`}),(0,r.jsx)(`div`,{style:{fontSize:13},children:i})]})})}Math.PI/12;var oe=`#669DEF`,H=.1,se=.7,ce=2.5;function le(e,t={}){let n=e.style?.color??`#00e5ff`,r=!!e.readOnly,i=e.style?.strokeWidth??t.strokeWidth??2,a=r?i*ce:i,o=r?se:e.style?.opacity??1,s=e.style?.fillOpacity??.12549019607843137,c=e.style?.dash??(r?[a,a*2]:void 0);return{color:n,strokeWidth:a,opacity:o,fillAlpha:s,fillVisible:!!e.style?.filled,dash:c,pointRadius:e.style?.pointRadius??t.pointRadius??5}}function ue(e,t){let n=Math.max(0,Math.min(1,t)),r=e.trim().replace(`#`,``);if(r.length===3||r.length===6){let e=r.length===3?r.replace(/./g,e=>e+e):r,t=Number.parseInt(e,16);if(!Number.isNaN(t))return`rgba(${t>>16&255}, ${t>>8&255}, ${t&255}, ${n})`}return e}function de({shape:e,strokeSize:t,register:n}){let{type:i,points:a}=e,s=le(e,{strokeWidth:t}),c=t=>n?.(e.id,t),l={ref:c,stroke:s.color,strokeWidth:s.strokeWidth,strokeDasharray:s.dash?.join(` `),opacity:s.opacity,fill:s.fillVisible&&i!==o.LINE?s.color:`none`,fillOpacity:s.fillAlpha,vectorEffect:`non-scaling-stroke`};if(i===o.POINT)return(0,r.jsx)(`circle`,{ref:c,cx:a[0].x,cy:a[0].y,r:s.pointRadius,fill:s.color,opacity:s.opacity});if(i===o.RECTANGLE||i===o.ELLIPSE){let e=h(a);return i===o.ELLIPSE?(0,r.jsx)(`ellipse`,{cx:(e.minX+e.maxX)/2,cy:(e.minY+e.maxY)/2,rx:(e.maxX-e.minX)/2,ry:(e.maxY-e.minY)/2,...l}):(0,r.jsx)(`rect`,{x:e.minX,y:e.minY,width:e.maxX-e.minX,height:e.maxY-e.minY,...l})}let u=a.map(e=>`${e.x},${e.y}`).join(` `);return i===o.LINE?(0,r.jsx)(`polyline`,{points:u,...l}):(0,r.jsx)(`polygon`,{points:u,...l})}function fe({image:e,region:t,maskId:n,width:i,height:a,strokeWidth:o,strokeDasharray:s,style:c}){let l=[...t.visibleOutline,...t.occludedOutline];return(0,r.jsxs)(`svg`,{width:i,height:a,viewBox:`0 0 ${e.w} ${e.h}`,style:c,"aria-hidden":!0,children:[(0,r.jsx)(`defs`,{children:(0,r.jsxs)(`mask`,{id:n,children:[(0,r.jsx)(`rect`,{x:0,y:0,width:e.w,height:e.h,fill:`white`}),t.rects.map((e,t)=>(0,r.jsx)(`rect`,{x:e.x,y:e.y,width:e.w,height:e.h,fill:`black`},e.id??`area-${t}`)),t.zones.map((e,t)=>(0,r.jsx)(`polygon`,{points:e.points.map(e=>`${e.x},${e.y}`).join(` `),fill:`white`},`occ-${t}`))]})}),(0,r.jsx)(`rect`,{x:0,y:0,width:e.w,height:e.h,fill:t.dim.color,fillOpacity:t.dim.opacity,mask:`url(#${n})`}),l.length>0&&(0,r.jsx)(`path`,{d:l.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),fill:`none`,stroke:`#fff`,strokeWidth:o,strokeDasharray:s,vectorEffect:`non-scaling-stroke`})]})}var pe={trackRootClassName:`aivex:h-1.5`,thumbClassName:`aivex:h-4 aivex:w-4 aivex:border`};function me({value:i,onChange:a,onClose:o,labels:s=F.viewSettings}){return(0,n.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()},t=()=>o();return window.addEventListener(`keydown`,e),window.addEventListener(`pointerdown`,t),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`pointerdown`,t)}},[o]),(0,r.jsxs)(`div`,{className:`aivex:absolute aivex:bottom-full aivex:left-0 aivex:mb-1 aivex:w-[220px] aivex:rounded-[8px] aivex:border aivex:border-border-default aivex:bg-bg-primary aivex:p-3 aivex:text-text-primary aivex:text-xs aivex:shadow-lg`,onPointerDown:e=>e.stopPropagation(),children:[(0,r.jsxs)(`div`,{className:`aivex:mb-2 aivex:flex aivex:items-center aivex:justify-between`,children:[(0,r.jsx)(`span`,{className:`aivex:font-semibold aivex:text-text-secondary`,children:s.title}),(0,r.jsx)(e.t,{variant:`ghost`,size:`sm`,onClick:()=>a({...R}),children:s.reset})]}),(0,r.jsx)(he,{label:`${s.brightness} ${i.brightness.toFixed(2)}`,children:(0,r.jsx)(t.n,{min:0,max:3,step:.05,value:[i.brightness],onValueChange:([e])=>a({brightness:e}),...pe})}),(0,r.jsx)(he,{label:`${s.contrast} ${i.contrast.toFixed(2)}`,children:(0,r.jsx)(t.n,{min:0,max:3,step:.05,value:[i.contrast],onValueChange:([e])=>a({contrast:e}),...pe})}),(0,r.jsx)(he,{label:`${s.strokeSize} ${i.strokeSize}`,children:(0,r.jsx)(t.n,{min:1,max:10,step:.5,value:[i.strokeSize],onValueChange:([e])=>a({strokeSize:e}),...pe})}),(0,r.jsx)(he,{label:`${s.simplifyStrength} ${i.simplifyStrength}`,children:(0,r.jsx)(t.n,{min:.5,max:5,step:.5,value:[i.simplifyStrength],onValueChange:([e])=>a({simplifyStrength:e}),...pe})}),(0,r.jsx)(`div`,{className:`aivex:my-2`,children:(0,r.jsx)(t.f,{})}),(0,r.jsx)(U,{label:s.pixelation,checked:!i.imageSmoothing,onChange:e=>a({imageSmoothing:!e})}),(0,r.jsx)(U,{label:s.cursorGuide,checked:i.showCursorGuide,onChange:e=>a({showCursorGuide:e})}),(0,r.jsx)(U,{label:s.guideMask,checked:i.showGuide,onChange:e=>a({showGuide:e})}),(0,r.jsx)(U,{label:s.regionMask,checked:i.showRegionMask,onChange:e=>a({showRegionMask:e})}),(0,r.jsx)(U,{label:s.keepZoomOnImageChange,checked:i.keepZoomOnImageChange,onChange:e=>a({keepZoomOnImageChange:e})}),(0,r.jsx)(U,{label:s.wheelZoom,checked:i.wheelZoom,onChange:e=>a({wheelZoom:e})})]})}function he({label:e,children:t}){return(0,r.jsxs)(`div`,{className:`aivex:mb-2 aivex:block`,children:[(0,r.jsx)(`span`,{className:`aivex:mb-1 aivex:block aivex:text-text-secondary`,children:e}),t]})}function U({label:e,checked:n,onChange:i}){return(0,r.jsxs)(`div`,{className:`aivex:flex aivex:items-center aivex:justify-between aivex:py-1`,children:[(0,r.jsx)(`span`,{children:e}),(0,r.jsx)(t.t,{size:`sm`,checked:n,onCheckedChange:i})]})}function ge({image:t,imageUrl:n,imageVisible:i=!0,maskDataUrl:a,region:o,roiMaskId:c,shapes:l,view:u,onChangeView:d,nav:p,registerShape:m,rectRef:h,zoomLabelRef:g,onZoom100:_,open:v,onToggleOpen:y,showSettings:b=!0,settingsOpen:x,onToggleSettings:S,onCloseSettings:C,labels:w=F.minimap,settingsLabels:T}){let{offX:E,offY:D,dispW:O,dispH:k,zoomCentered:A}=p,j={position:`absolute`,left:E,top:D,width:O,height:k};return(0,r.jsxs)(`div`,{className:`aivex:absolute aivex:bottom-2 aivex:left-2 aivex:w-[188px] aivex:rounded-[8px] aivex:border aivex:border-border-default aivex:bg-bg-primary aivex:p-[4px] aivex:shadow-lg`,children:[(0,r.jsx)(`div`,{className:`aivex:overflow-hidden aivex:rounded-[4px] aivex:transition-all aivex:duration-200 aivex:ease-in-out ${v?`aivex:mb-1 aivex:max-h-[180px] aivex:opacity-100`:`aivex:max-h-0 aivex:opacity-0`}`,children:(0,r.jsx)(`div`,{className:`aivex:relative aivex:h-[180px] aivex:w-[180px] aivex:cursor-grab aivex:touch-none aivex:overflow-hidden aivex:rounded-[4px] aivex:bg-black aivex:active:cursor-grabbing`,onPointerDown:p.handleMinimapPointerDown,onPointerMove:p.handleMinimapPointerMove,onPointerUp:p.endMinimapDrag,onPointerCancel:p.endMinimapDrag,onWheel:p.handleMinimapWheel,children:(0,r.jsxs)(`div`,{style:{position:`absolute`,inset:0,opacity:+!!i,transition:i?`opacity 0.3s ease`:`none`},children:[n&&(0,r.jsx)(`img`,{src:n,alt:``,draggable:!1,style:j}),a&&u.showGuide&&(0,r.jsx)(`img`,{src:a,alt:``,draggable:!1,style:{...j,opacity:.55,imageRendering:`pixelated`,pointerEvents:`none`}}),u.showRegionMask&&o&&o.rects.length>0&&(0,r.jsx)(fe,{image:t,region:o,maskId:c,width:O,height:k,strokeWidth:1,strokeDasharray:`4 4`,style:{position:`absolute`,left:E,top:D,pointerEvents:`none`}}),(0,r.jsx)(`svg`,{viewBox:`0 0 ${t.w} ${t.h}`,width:O,height:k,style:{position:`absolute`,left:E,top:D,pointerEvents:`none`},"aria-hidden":!0,children:f(l).filter(s).map(e=>(0,r.jsx)(de,{shape:e,strokeSize:u.strokeSize,register:m},e.id))}),(0,r.jsx)(`div`,{ref:h,style:{position:`absolute`,border:`1px solid #00ff00`,background:`rgba(0,255,0,0.1)`,boxSizing:`border-box`,pointerEvents:`none`}})]})})}),(0,r.jsxs)(`div`,{className:`aivex:flex aivex:items-center aivex:justify-between`,children:[(0,r.jsxs)(`div`,{className:`aivex:flex aivex:items-center aivex:gap-0.5`,children:[(0,r.jsx)(e.t,{variant:`ghost`,size:`icon-sm`,"aria-label":w.zoomOut,onClick:()=>A(1/1.2),children:(0,r.jsx)(e.cr,{size:16})}),(0,r.jsx)(e.t,{variant:`ghost`,size:`sm`,"aria-label":w.zoom100,onClick:_,className:`aivex:min-w-[44px] aivex:px-1 aivex:tabular-nums`,children:(0,r.jsx)(`span`,{ref:g,children:`100%`})}),(0,r.jsx)(e.t,{variant:`ghost`,size:`icon-sm`,"aria-label":w.zoomIn,onClick:()=>A(1.2),children:(0,r.jsx)(e.zr,{size:16})})]}),(0,r.jsxs)(`div`,{className:`aivex:relative aivex:flex aivex:items-center aivex:gap-0.5`,children:[b&&(0,r.jsx)(e.t,{variant:`ghost`,size:`icon-sm`,"aria-label":w.viewSettings,onClick:S,onPointerDown:e=>e.stopPropagation(),className:x?`aivex:text-text-brand`:void 0,children:(0,r.jsx)(e.ci,{size:16})}),(0,r.jsx)(e.t,{variant:`ghost`,size:`icon-sm`,"aria-label":w.toggleMinimap,title:`(M)`,onClick:y,children:v?(0,r.jsx)(e.nt,{size:16}):(0,r.jsx)(e.at,{size:16})}),b&&x&&(0,r.jsx)(me,{value:u,onChange:d,onClose:C,labels:T})]})]})]})}var _e=`var(--editor-overlay-inverse-scale, 1)`,ve=6,ye={fontFamily:`Pretendard, sans-serif`,fontSize:12,fontWeight:500,lineHeight:`16px`,color:`#fff`,textShadow:`0 0 4px #000, 0 0 4px #000`,whiteSpace:`nowrap`};function be(e,t){let n=h(t);return{shape:e,x:n.minX,y:n.minY,width:n.maxX-n.minX,height:n.maxY-n.minY}}function xe(e){return`${Math.round(e.width)} x ${Math.round(e.height)} px`}function Se({color:e,striped:t}){return(0,r.jsx)(`span`,{style:{display:`inline-block`,width:12,height:12,borderRadius:`50%`,...t?{border:`2px dashed ${e}`,background:`transparent`}:{background:e}}})}function Ce({shapes:e,getLabel:t,hideDot:n,formatInfo:i,register:a}){return(0,r.jsx)(r.Fragment,{children:e.map(e=>{let s=h(e.points),c=e.type===o.POINT,l=t?.(e),u=e.style?.color??`#00e5ff`,d=!!e.readOnly||!!e.style?.dash,f=be(e,e.points),p=i?i(f):xe(f);return(0,r.jsxs)(`div`,{ref:t=>a(e.id,t),style:{position:`absolute`,left:s.minX,top:s.minY,width:s.maxX-s.minX,height:s.maxY-s.minY,pointerEvents:`none`},children:[!!l&&(0,r.jsxs)(`div`,{style:{position:`absolute`,left:0,top:0,display:`flex`,alignItems:`center`,gap:4,transform:`scale(${_e}) translateY(calc(-100% - ${ve}px))`,transformOrigin:`left top`,...ye},children:[!n&&(0,r.jsx)(Se,{color:u,striped:d}),(0,r.jsx)(`span`,{children:l})]}),!c&&!!p&&(0,r.jsx)(`div`,{"data-selinfo-dim":!0,style:{position:`absolute`,right:0,top:`100%`,transform:`scale(${_e}) translateY(${ve}px)`,transformOrigin:`right top`,...ye},children:p})]},e.id)})})}var we=new Set([L.RECTANGLE,L.ROTATED_RECTANGLE,L.CIRCLE,L.POLYGON,L.PATH,L.BRUSH,L.POINT,L.ASSISTANT_POLYGON,L.ASSISTANT_RECT,L.ASSISTANT_POINT]),Te={tl:-135,t:-90,tr:-45,r:0,br:45,b:90,bl:135,l:180},Ee=[`ew-resize`,`nwse-resize`,`ns-resize`,`nesw-resize`];function De(e,t=0){let n=((Te[e]+t*180/Math.PI)%180+180)%180;return Ee[Math.round(n/45)%4]}function Oe({tool:e,externalToolCursor:t,isSpacePressed:n,isPolygonDrawing:r}){return n?`grab`:t||(e===L.SELECT?`default`:we.has(e)?r?`default`:`crosshair`:`default`)}function ke({tool:e,externalToolCursor:t,isSpacePressed:n,interactionMode:r,rendererCursorHint:i,isPolygonDrawing:a}){return r===`marquee`?`default`:r===`moving`||r===`panning`||r===`vertexDragging`?`grabbing`:r===`resizing`||r===`rotating`?i??`grabbing`:r===`drawing`?`crosshair`:n?`grab`:t||(e===L.SELECT&&i?i:Oe({tool:e,externalToolCursor:t,isSpacePressed:n,isPolygonDrawing:a}))}var Ae=e=>Math.min(255,Math.max(0,e)),W=e=>{let t=e.replace(`#`,``).trim();if(![3,4,6,8].includes(t.length))return null;let n=e=>e.length===1?`${e}${e}`:e,r=t.length<=4,i=n(t.slice(0,r?1:2)),a=n(t.slice(r?1:2,r?2:4)),o=n(t.slice(r?2:4,r?3:6)),s=t.length===4?n(t.slice(3,4)):t.length===8?n(t.slice(6,8)):`ff`,c=e=>Number.parseInt(e,16),l=[c(i),c(a),c(o),c(s)];return l.some(e=>Number.isNaN(e))?null:l.map(Ae)},je=(e,t)=>{let{width:n,height:r,indices:i,transparent:a}=e;if(!n||!r||i.length<n*r)return null;let o={};for(let[e,n]of Object.entries(t)){let t=W(n);t&&(o[Number(e)]=t)}if(!Object.keys(o).length)return null;let s=document.createElement(`canvas`);s.width=n,s.height=r;let c=s.getContext(`2d`);if(!c)return null;let l=new Uint8ClampedArray(n*r*4),u=n*r;for(let e=0;e<u;e+=1){let t=i[e];if(t===a)continue;let n=o[t];if(!n)continue;let r=e*4;l[r]=n[0],l[r+1]=n[1],l[r+2]=n[2],l[r+3]=n[3]}return c.putImageData(new ImageData(l,n,r),0,0),s};function Me(e,t){e.beginPath(),e.moveTo(t[0].x,t[0].y);for(let n=1;n<t.length;n+=1)e.lineTo(t[n].x,t[n].y);e.closePath()}var Ne=e=>[{x:e.x,y:e.y},{x:e.x+e.w,y:e.y},{x:e.x+e.w,y:e.y+e.h},{x:e.x,y:e.y+e.h}];function Pe(e,t){let n=!1;for(let r=0,i=t.length-1;r<t.length;i=r,r+=1){let a=t[r],o=t[i];if(a.y>e.y!=o.y>e.y){let t=(e.y-a.y)/(o.y-a.y);e.x<a.x+t*(o.x-a.x)&&(n=!n)}}return n}function Fe(e,t,n){let r=[],i=t.x-e.x,a=t.y-e.y;for(let t=0;t<n.length;t+=1){let o=n[t],s=n[(t+1)%n.length],c=s.x-o.x,l=s.y-o.y,u=i*l-a*c;if(!u)continue;let d=((o.x-e.x)*l-(o.y-e.y)*c)/u,f=((o.x-e.x)*a-(o.y-e.y)*i)/u;d>0&&d<1&&f>=0&&f<=1&&r.push(d)}return r}function G(e,t,n){let r=.001,i=[],a=(e,t,n)=>({x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n});for(let o of e)if(!(o.length<2))for(let e=0;e<o.length;e+=1){let s=o[e],c=o[(e+1)%o.length],l=[0,1];for(let e of t)e!==o&&l.push(...Fe(s,c,e));if(n)for(let e of n)l.push(...Fe(s,c,e));let u=Math.hypot(c.x-s.x,c.y-s.y);if(!u)continue;let d=-(c.y-s.y)/u*r,f=(c.x-s.x)/u*r;l.sort((e,t)=>e-t);for(let e=0;e+1<l.length;e+=1){let r=l[e],u=l[e+1];if(u-r<1e-9)continue;let p=a(s,c,(r+u)/2),m={x:p.x+d,y:p.y+f},h={x:p.x-d,y:p.y-f},g=Pe(m,o)?m:h,_=g===m?h:m;t.some(e=>e!==o&&Pe(_,e))||n&&!n.some(e=>Pe(g,e))||i.push([a(s,c,r),a(s,c,u)])}}return i}function Ie(e){let t=[...new Set(e.flatMap(e=>[e.x,e.x+e.w]))].sort((e,t)=>e-t),n=[];for(let r=0;r+1<t.length;r+=1){let i=t[r],a=t[r+1];if(a<=i)continue;let o=e.filter(e=>e.x<=i&&e.x+e.w>=a).map(e=>[e.y,e.y+e.h]).sort((e,t)=>e[0]-t[0]),s=null;for(let[e,t]of o)!s||e>s[1]?(s&&n.push({x:i,y:s[0],w:a-i,h:s[1]-s[0]}),s=[e,t]):s[1]=Math.max(s[1],t);s&&n.push({x:i,y:s[0],w:a-i,h:s[1]-s[0]})}return n}function Le(e,t,n,r){e.save(),e.globalAlpha*=t.dim.opacity,e.fillStyle=t.dim.color,e.beginPath(),e.rect(0,0,n,r);for(let n of t.dimHoles)e.moveTo(n.x,n.y),e.lineTo(n.x,n.y+n.h),e.lineTo(n.x+n.w,n.y+n.h),e.lineTo(n.x+n.w,n.y),e.closePath();if(e.fill(),t.zones.length){e.beginPath();for(let n of t.rects)e.rect(n.x,n.y,n.w,n.h);e.clip();for(let n of t.zones)Me(e,n.points),e.fill()}e.restore()}function Re(e){let t=[];for(let n of e)if(!(n.length<2))for(let e=0;e<n.length;e+=1)t.push([n[e],n[(e+1)%n.length]]);return t}var K={color:`#000000`,opacity:.5},ze={color:`#ffffff`,opacity:1,width:2,dash:[6,6],underlayColor:`#000000`},Be={color:`#dc2626`,opacity:.8,width:2,dash:[6,6],underlayColor:`#000000`},Ve=(e,t,n)=>{let r=e.occludedAreas?.filter(e=>e.points.length>=3)??[];if(!t||!n||!e.visibleAreas.length&&!r.length)return null;let i=e.visibleAreas,a=i.length?i:[{x:0,y:0,w:t,h:n}],o=Ie(a),s={...K,...e.dim},c=e.outline;if(c===!1)return{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:[],occludedOutline:[],outlineStyles:null};let l={visible:{...ze,...c?.visibleStyle},occluded:{...Be,...c?.occludedStyle}},u=i.map(Ne),d=a.map(Ne),f=r.map(e=>e.points);return c?.mode===`separate`?{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:Re(u),occludedOutline:Re(f),outlineStyles:l}:{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:[...G(u,[...u,...f],null),...G(f,f,d)],occludedOutline:[],outlineStyles:l}},He=.3,Ue=.05;function We(e){return 1-(1-e)**3}function Ge(e){return{x:e.minX,y:e.minY,width:Math.max(0,e.maxX-e.minX),height:Math.max(0,e.maxY-e.minY)}}function Ke(e,t){if(!t.length)return null;if(e===o.POINT){let e=t[0];return{x:e.x-8,y:e.y-8,width:16,height:16}}let n=h(t),r=Math.max(1,n.maxX-n.minX),i=Math.max(1,n.maxY-n.minY);return{x:n.minX,y:n.minY,width:r,height:i}}function qe(e){if(!e.length)return null;let t=e.map(e=>Ke(e.type,e.points)).filter(e=>e!==null);return t.length?Ge(h(t.flatMap(e=>[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y+e.height}]))):null}function Je(e,t,n,r={}){let{containerRatio:i=He,minScale:a=Ue,maxScale:o=20}=r;if(!t||!n||e.width<=0||e.height<=0)return null;let s=Math.min(t*i/e.width,n*i/e.height),c=Math.max(a,Math.min(o,s)),l=e.x+e.width/2,u=e.y+e.height/2;return{scale:c,x:t/2-l*c,y:n/2-u*c}}function Ye(e,t,n,r=80){if(!t||!n)return null;let i=Math.max(1,e.maxX-e.minX),a=Math.max(1,e.maxY-e.minY),o=Math.max(Ue,Math.min(20,Math.min((t-r)/i,(n-r)/a))),s=(e.minX+e.maxX)/2,c=(e.minY+e.maxY)/2;return{scale:o,x:t/2-s*o,y:n/2-c*o}}function Xe(e,t,n,r=300){let i=Date.now(),a=0,o=()=>{let s=Date.now()-i,c=Math.min(s/r,1),l=We(c);n({scale:e.scale+(t.scale-e.scale)*l,x:e.x+(t.x-e.x)*l,y:e.y+(t.y-e.y)*l}),c<1&&(a=requestAnimationFrame(o))};return a=requestAnimationFrame(o),()=>cancelAnimationFrame(a)}function Ze(e){let{engineRef:t,toolRef:n,externalToolMapRef:r,spaceRef:i,shiftRef:a,docRef:s,selRef:c,draftRef:u,readOnlyRef:p,disableMarqueeRef:m,lockedRef:g,onLockedInteraction:_,createRef:y,selectRef:S,enterEditRef:C,drawSessionRef:w,assistantRef:T,setCursorHint:E,setInteractionMode:D,syncMinimap:O,onTransformPreview:k,onDrawPreview:A}=e,j=()=>w.current,M=()=>T.current,N=null,P=null,F=null,I=null,R=null,ee=``,te=null,ne=e=>e===L.RECTANGLE||e===L.ROTATED_RECTANGLE||e===L.CIRCLE,re=e=>e===L.ASSISTANT_POLYGON||e===L.ASSISTANT_RECT,ie=e=>e===L.POLYGON,z=()=>r.current.get(n.current),B=(e,t,n,r)=>({point:t,targetId:r,event:n,readOnly:p.current,viewport:e.viewport});return{onCursorHint:E,onInteractionModeChange:D,onPointerDown:(e,r,m)=>{let v=t.current;if(!v)return;let y=n.current;if(m.button===1||i.current){D(`panning`),E(null),N={x:v.viewport.x,y:v.viewport.y,px:m.global.x,py:m.global.y};return}if(m.button===2&&!(y===L.ASSISTANT_POINT&&m.altKey))return;let b=z();if(b){j().reset(),S.current([]),b.onPointerDown?.(B(v,e,m,r));return}if(g.current){_();return}if(y===L.ASSISTANT_POINT){m.altKey?M().addPoint(e,m.button!==2):M().newPolygon(e);return}if(re(y)&&u.current){P=e,D(`drawing`);return}if(y===L.SELECT&&m.altKey){let t=f(s.current.getShapes()).filter(t=>{if(!l(t))return!1;let n=h(t.points);return e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY});if(t.length){let e=[...t].reverse(),n=[e[(e.findIndex(e=>c.current.includes(e.id))+1)%e.length].id];S.current(n);return}}if(r&&y===L.SELECT){let t=s.current.getShapes().find(e=>e.id===r);if(!t||!l(t))return;let n=typeof performance<`u`?performance.now():0,i=!!te&&te.id===r&&n-te.t<300;te={id:r,t:n};let u=(t.type===o.POLYGON||t.type===o.LINE)&&!p.current&&t.interaction?.editable!==!1&&!t.readOnly;if(i&&u){S.current([r]),C.current(r);return}let f=c.current;if(a.current){let e=new Set(f);e.has(r)?e.delete(r):e.add(r),f=[...e]}else f.includes(r)||(f=[r]);S.current(f),!p.current&&d(t)&&v.beginMove(e,f);return}if(ne(y)&&u.current){P=e,D(`drawing`);return}if(ie(y)&&u.current){if(!j().getDraftPointsSnapshot().length&&c.current.length&&S.current([]),j().tryClosePolygon(e,12/v.viewport.scale))return;let t=j().hitDraftPoint(e);if(t>=0){if(m.altKey){j().removeDraftPoint(t);return}let n=j().selectDraftPointForDrag(t,m.shiftKey||m.ctrlKey||m.metaKey);if(!n)return;I={start:e,base:n.base,indices:n.indices,moved:!1},D(`vertexDragging`);return}j().appendPolygonPoint(e);return}if(y===L.PATH&&u.current){c.current.length&&S.current([]),F=`path`,D(`drawing`),j().beginStroke(e);return}if(y===L.BRUSH&&u.current&&!p.current){F=`scalar`,D(`drawing`),j().beginStroke(e);return}if(y===L.SELECT){if(!a.current&&!p.current&&c.current.length>=2){let t=s.current.getShapes().filter(e=>c.current.includes(e.id)&&d(e));if(t.length){let n=h(t.flatMap(e=>e.points));if(e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY){v.beginMove(e,c.current);return}}}R=e,ee=``,D(`marquee`),E(null)}},onPointerMove:(e,r)=>{let i=t.current;if(!i)return;if(N){i.applyViewport({scale:i.viewport.scale,x:N.x+(r.global.x-N.px),y:N.y+(r.global.y-N.py)});return}let s=n.current,c=z();if(c){c.onPointerMove?.(B(i,e,r));return}if(I){let t=e.x-I.start.x,n=e.y-I.start.y;I.moved=I.moved||Math.hypot(t,n)>.5,j().moveDraftPoints(I.base,I.indices,t,n);return}if(P&&(ne(s)||re(s))){let t=a.current?v(P,e):e;i.previewBox(s===L.CIRCLE?`ellipse`:`rect`,P,t,{...u.current,color:u.current?.color??`#00e5ff`}),ne(s)&&A({type:s===L.CIRCLE?o.ELLIPSE:o.RECTANGLE,points:[P,t]});return}if(F){j().appendStrokePoint(e,2/i.viewport.scale);return}if(ie(s)&&j().hasDraftPoints()){j().setDraftCursor(e);return}if(R){if(m?.current)return;let t={minX:Math.min(R.x,e.x),minY:Math.min(R.y,e.y),maxX:Math.max(R.x,e.x),maxY:Math.max(R.y,e.y)};i.previewMarquee(R,e);let n=i.shapesIntersecting(t),r=n.join(`,`);r!==ee&&(ee=r,S.current(n))}},onPointerUp:e=>{let r=t.current;if(!r)return;if(N){N=null,D(`idle`);return}if(I){j().commitDraftPointDrag(I.moved),I=null,D(`idle`);return}let i=n.current,s=z();if(s){s.onPointerUp?.(B(r,e,{}));return}if(i===L.POINT&&u.current){y.current(o.POINT,[e]);return}if(F){let e=F;F=null,D(`idle`),e===`path`?j().completeFreehandStroke():j().finishScalarStroke();return}if(P&&re(i)){let t=P;P=null,D(`idle`),r.clearPreview();let n={x:Math.min(t.x,e.x),y:Math.min(t.y,e.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)};n.width>2&&n.height>2&&M().beginBox(n,i===L.ASSISTANT_RECT?`rect`:`polygon`);return}if(P&&ne(i)){let t=a.current?v(P,e):e,n=P;P=null,D(`idle`),r.clearPreview(),A(null),Math.abs(t.x-n.x)>2&&Math.abs(t.y-n.y)>2&&(i===L.ROTATED_RECTANGLE?y.current(o.ROTATED_RECTANGLE,b([n,t])):i===L.CIRCLE?y.current(o.POLYGON,x(n,t)):y.current(o.RECTANGLE,[n,t]));return}if(R){let t=Math.abs(e.x-R.x)>3||Math.abs(e.y-R.y)>3;R=null,r.clearMarquee(),D(`idle`),!t&&c.current.length&&S.current([])}},onViewportChange:O,onTransformPreview:k,onTransformCommit:e=>{let t=s.current.getShapes(),n=e.map(e=>{let n=t.find(t=>t.id===e.id);return n?{...n,points:e.points}:null}).filter(e=>!!e);n.length&&s.current.update(n)}}}function Qe({docRef:e,draftRef:t,draftMeta:r,changeSelection:i,assistantRef:a}){let[s,c]=(0,n.useState)(`idle`),[l,u]=(0,n.useState)([]),[d,f]=(0,n.useState)([]),m=(0,n.useRef)([]),g=(0,n.useRef)([]),_=(0,n.useRef)([]),v=(0,n.useRef)(`idle`),y=(0,n.useRef)(0),b=(0,n.useRef)(null),x=(0,n.useRef)(null),S=(0,n.useRef)(0),w=(0,n.useCallback)(e=>{m.current=e(m.current),f(m.current)},[]),T=(0,n.useCallback)(e=>{v.current=e,c(e)},[]),E=(0,n.useCallback)((e,t,n)=>{let i=a.current?.rectResult===`rotatedRect`;return e.map(e=>{if(t===`rect`&&i)return{id:p(),type:o.ROTATED_RECTANGLE,points:C(e),style:n,meta:r};if(t===`rect`){let t=h(e);return{id:p(),type:o.RECTANGLE,points:[{x:t.minX,y:t.minY},{x:t.maxX,y:t.maxY}],style:n,meta:r}}return{id:p(),type:o.POLYGON,points:e,style:n,meta:r}})},[r,a]),D=(0,n.useCallback)(()=>{y.current++,g.current=[],_.current=[],b.current=null,x.current=null,u([]),T(`idle`)},[T]),O=(0,n.useCallback)(()=>{S.current++,w(()=>[]);let t=x.current;t?e.current.update([t]):_.current.length&&e.current.remove(_.current),D()},[e,D,w]),k=(0,n.useCallback)(n=>{let r=_.current;if(!n.length){r.length&&(e.current.remove(r),_.current=[]);return}if(r.length===n.length){let t=e.current.getShapes(),i=n.map((e,n)=>{let i=t.find(e=>e.id===r[n]);return i?{...i,points:e}:null}).filter(e=>!!e);i.length&&e.current.update(i);return}b.current=null,x.current=null,r.length&&e.current.remove(r);let a=t.current;if(!a)return;let o=E(n,`polygon`,a);o?.length&&(e.current.create(o),_.current=o.map(e=>e.id),i(_.current))},[e,t,i,E]),A=(0,n.useCallback)(async()=>{let e=a.current?.infer;if(!e)return;let t={kind:`points`,points:g.current,base:b.current??void 0},n=++y.current;T(`loading`);let r=[];try{r=(await e(t)??[]).filter(e=>e.length>=3)}catch{r=[]}n===y.current&&(k(r),T(`ready`))},[a,k,T]),j=(0,n.useCallback)((e,t)=>{g.current=[...g.current,{x:e.x,y:e.y,positive:t}],u([{x:e.x,y:e.y,positive:t}]),A()},[A]),M=(0,n.useCallback)(e=>{D();let t=[{x:e.x,y:e.y,positive:!0}];g.current=t,u(t),A()},[D,A]),N=(0,n.useCallback)((e,t,n)=>{(_.current.length!==1||_.current[0]!==e.id)&&(D(),_.current=[e.id],b.current=e.points,x.current=e),g.current=[...g.current,{x:t.x,y:t.y,positive:n}],u([{x:t.x,y:t.y,positive:n}]),A()},[D,A]);return{status:s,points:l,boxes:d,beginBox:(0,n.useCallback)((n,r=`polygon`)=>{let o=a.current?.infer,s=t.current;if(!o||!s)return;let c=S.current;w(e=>[...e,n]),(async()=>{let t=[];try{t=(await o({kind:`box`,box:n})??[]).filter(e=>e.length>=3)}catch{t=[]}if(w(e=>e.filter(e=>e!==n)),c!==S.current)return;let a=E(t,r,s);a?.length&&(e.current.create(a),i(a.map(e=>e.id)))})()},[a,t,E,i,e,w]),addPoint:j,newPolygon:M,refineShape:N,finalize:D,cancel:O,isActive:(0,n.useCallback)(()=>v.current===`loading`||g.current.length>0||m.current.length>0||_.current.length>0,[])}}function $e(e,t,n){let r=Math.abs(.5*(t.x*n.y+n.x*e.y+e.x*t.y-n.x*t.y-e.x*n.y-t.x*e.y)),i=Math.hypot(t.x-n.x,t.y-n.y);return i===0?0:r*2/i}function q(e,t=1.5){if(e.length<=2)return e;let n=(e,t)=>{if(e.length<3)return e;let r=0,i=0,a=e.length-1;for(let t=1;t<a;t++){let n=$e(e[t],e[0],e[a]);n>r&&(i=t,r=n)}if(r>t){let r=n(e.slice(0,i+1),t),a=n(e.slice(i),t);return r.slice(0,-1).concat(a)}return[e[0],e[a]]},r=n(e,t),i=e[e.length-1],a=r[r.length-1];return(i.x!==a.x||i.y!==a.y)&&r.push(i),r}var et=4096,tt=4;function J(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n],i=e[(n+1)%e.length];t+=r.x*i.y-i.x*r.y}return Math.abs(t/2)}function nt(e,t,n){let r=new Uint8Array(t*n);for(let i=0;i<t*n;i++)r[i]=e[i*4+3]>128?255:0;return r}function rt(e){let t=new Uint8ClampedArray(e.length*4);for(let n=0;n<e.length;n++)e[n]>128&&(t[n*4+3]=255);return t}function it(e,t,n,r,i){let a=new Uint8Array(t*n),o=[[r,i]];for(;o.length;){let[r,i]=o.pop(),s=i*t+r;r<0||i<0||r>=t||i>=n||e[s]<=128||(e[s]=0,a[s]=255,o.push([r+1,i],[r-1,i],[r,i+1],[r,i-1]))}return a}function at(e,t,n){let r=nt(e,t,n),i=[];for(;;){let e=-1,a=-1;outer:for(let i=0;i<n;i++)for(let n=0;n<t;n++)if(r[i*t+n]>128){e=n,a=i;break outer}if(e<0)break;let o=ot(rt(it(r,t,n,e,a)),t,n);o.length>=3&&i.push(o)}return i}function Y(e,t,n,r,i){return r<0||i<0||r>=t||i>=n?!1:e[(i*t+r)*4+3]>128}function ot(e,t,n){let r=-1,i=-1;outer:for(let a=0;a<n;a++)for(let o=0;o<t;o++)if(Y(e,t,n,o,a)){r=o,i=a;break outer}if(r<0)return[];let a=[1,1,0,-1,-1,-1,0,1],o=[0,1,1,1,0,-1,-1,-1],s=[],c=r,l=i,u=7,d={x:c,y:l},f=0;do{s.push({x:c,y:l});let r=!1;for(let i=0;i<8;i++){let s=(u+i)%8,d=c+a[s],f=l+o[s];if(Y(e,t,n,d,f)){c=d,l=f,u=(s+6)%8,r=!0;break}}if(!r||(f+=1,f>t*n*4))break}while(c!==d.x||l!==d.y||s.length===1);return s}function st(e,t){let n=[];for(let t of e)for(let e of t.points)n.push(e);for(let e of t)for(let t of e)n.push(t);return n}function X(e){switch(e.type){case o.RECTANGLE:return e.points.length<2?null:b(e.points);case o.POLYGON:case o.ROTATED_RECTANGLE:case o.ELLIPSE:return e.points.length>=3?e.points:null;case o.POINT:{let t=e.points[0];return t?x({x:t.x-6,y:t.y-6},{x:t.x+6,y:t.y+6}):null}default:return null}}function ct(e){return e.map(X).filter(e=>!!e&&e.length>=3)}function lt(e,t,n=[]){if(t<=0||!e.length&&!n.length)return null;let r=st(e,n);if(!r.length)return null;let i=t+4,a=h(r),o=Math.ceil(a.maxX-a.minX+i*2),s=Math.ceil(a.maxY-a.minY+i*2),c=Math.min(1,et/Math.max(o,s,1));o=Math.max(1,Math.ceil(o*c)),s=Math.max(1,Math.ceil(s*c));let l=a.minX-i,u=a.minY-i,d=e=>({x:(e.x-l)*c,y:(e.y-u)*c}),f=document.createElement(`canvas`);f.width=o,f.height=s;let p=f.getContext(`2d`);if(!p)return null;p.lineCap=`round`,p.lineJoin=`round`,p.lineWidth=t*2*c,p.fillStyle=`#000`;for(let e of n){if(e.length<3)continue;p.beginPath();let t=d(e[0]);p.moveTo(t.x,t.y);for(let t=1;t<e.length;t++){let n=d(e[t]);p.lineTo(n.x,n.y)}p.closePath(),p.fill()}for(let t of e){if(!t.points.length)continue;p.globalCompositeOperation=t.mode===`erase`?`destination-out`:`source-over`,p.strokeStyle=t.mode===`erase`?`rgba(0,0,0,1)`:`#000`,p.beginPath();let e=d(t.points[0]);p.moveTo(e.x,e.y);for(let e=1;e<t.points.length;e++){let n=d(t.points[e]);p.lineTo(n.x,n.y)}t.points.length===1&&p.lineTo(e.x+.01,e.y),p.stroke()}return{canvas:f,ox:l,oy:u,scale:c}}function ut(e,t=1.5){let{canvas:n,ox:r,oy:i,scale:a}=e,o=at(n.getContext(`2d`).getImageData(0,0,n.width,n.height).data,n.width,n.height);if(!o.length)return[];let s=e=>({x:e.x/a+r,y:e.y/a+i}),c=[];for(let e of o){let n=e.map(s),r=q(n,t),i=r.length>=3?r:n;i.length>=3&&J(i)>=tt&&c.push(i)}return c}function dt(e,t){let{canvas:n}=e,r=document.createElement(`canvas`);r.width=n.width,r.height=n.height;let i=r.getContext(`2d`);return i?(i.drawImage(n,0,0),i.globalCompositeOperation=`source-in`,i.fillStyle=t,i.fillRect(0,0,r.width,r.height),r):n}function ft(e){return e.map(e=>({mode:e.mode,points:e.points.map(e=>({...e}))}))}function pt(e,t){return e.length===t.length&&e.every((e,n)=>e.mode===t[n].mode&&e.points.length===t[n].points.length&&e.points.every((e,r)=>e.x===t[n].points[r].x&&e.y===t[n].points[r].y))}function mt(e){return e.map(e=>({...e}))}function ht(e,t){return e.length===t.length&&e.every((e,n)=>e.x===t[n].x&&e.y===t[n].y)}var gt=10;function _t({toolRef:e,selRef:t,docRef:r,readOnlyRef:i,draftRef:a,brushSizeRef:s,simplifyEpsilonRef:c,draftMeta:l,engineRef:d,onDrawSessionChange:f,onDraftShapeChange:m,changeSelection:h,createShape:g}){let _=(0,n.useRef)(f);_.current=f;let v=(0,n.useRef)(m);v.current=m;let y=(0,n.useRef)(l);y.current=l;let b=(0,n.useRef)(g);b.current=g;let x=(0,n.useRef)([]),S=(0,n.useRef)(null),C=(0,n.useRef)(new Set),w=(0,n.useRef)([[]]),T=(0,n.useRef)(0),E=(0,n.useRef)(``),D=(0,n.useRef)([]),O=(0,n.useRef)([]),k=(0,n.useRef)([]),A=(0,n.useRef)([[]]),j=(0,n.useRef)(0),M=(0,n.useRef)(`draw`),N=()=>M.current===`erase`?`erase`:`add`,P=()=>k.current.length>0||D.current.length>0||e.current===L.BRUSH&&x.current.length>0,F=()=>{let t=e.current;return t===L.BRUSH&&P()?`brush`:t===L.POLYGON&&x.current.length>0?`polygon`:t===L.PATH&&x.current.length>0?`path`:`none`},I=()=>x.current.length>0||j.current>0,R=()=>x.current.length===0&&j.current<A.current.length-1,ee=()=>T.current>0,te=()=>T.current<w.current.length-1,ne=()=>{let t=e.current;return t===L.BRUSH?I():t===L.POLYGON||t===L.PATH?ee():!1},re=()=>{let t=e.current;return t===L.BRUSH?R():t===L.POLYGON||t===L.PATH?te():!1},ie=()=>F()!==`none`,z=(0,n.useCallback)(()=>{let e=F();_.current?.({active:e!==`none`,kind:e,canUndo:ne(),canRedo:re(),brush:e===`brush`?{mode:M.current,editing:k.current.length>0,editTargetIds:[...k.current]}:void 0})},[]),B=(0,n.useCallback)(()=>{A.current=[[]],j.current=0},[]),V=(0,n.useCallback)(()=>{let t=d.current;if(!t)return;let n=e.current;if(n===L.BRUSH){let e=[...D.current];if(x.current.length&&e.push({points:x.current,mode:N()}),!e.length&&!O.current.length){t.clearPreview();return}let n=lt(e,s.current,O.current);if(!n){t.clearPreview();return}let r=a.current?.color??`#00e5ff`;t.previewScalarMask(n,r);return}let r=x.current;if(!r.length){t.clearPreview(),n===L.POLYGON&&E.current&&(E.current=``,v.current?.(null));return}let i={...a.current,color:a.current?.color??`#00e5ff`},c=Array.from(C.current),l=n!==L.PATH;if(t.previewPoly(r,S.current,i,!1,c,l),n===L.POLYGON){let e=r.map(e=>`${e.x},${e.y}`).join(`;`);e!==E.current&&(E.current=e,v.current?.({type:o.POLYGON,points:mt(r),meta:y.current}))}},[s,a,d,e]),ae=(0,n.useCallback)(e=>{let t=ft(e),n=A.current,r=j.current,i=n[r];i&&pt(i,t)||(A.current=[...n.slice(0,r+1),t],j.current+=1,z())},[z]),oe=(0,n.useCallback)(e=>{let t=w.current,n=T.current,r=t[n];r&&ht(r,e)||(w.current=[...t.slice(0,n+1),mt(e)],T.current+=1)},[]),H=(0,n.useCallback)(()=>{x.current=[],D.current=[],O.current=[],k.current=[],S.current=null,C.current=new Set,w.current=[[]],T.current=0,E.current=``,B(),d.current?.clearPreview(),v.current?.(null),z()},[d,z,B]),se=(0,n.useCallback)((e,t)=>{x.current=e,C.current=new Set(Array.from(C.current).filter(t=>t>=0&&t<e.length)),t&&oe(e),V(),z()},[z,oe,V]),ce=(0,n.useCallback)(()=>mt(x.current),[]),le=(0,n.useCallback)(()=>x.current.length>0,[]),ue=(0,n.useCallback)((t,n)=>{if(e.current!==L.POLYGON)return!1;let r=x.current;if(r.length<3)return!1;let i=r[0];return Math.hypot(t.x-i.x,t.y-i.y)>n?!1:(b.current(o.POLYGON,r),H(),!0)},[H,e]),de=(0,n.useCallback)(e=>{let t=x.current;return e<0||e>=t.length?!1:(se(t.filter((t,n)=>n!==e),!0),!0)},[se]),fe=(0,n.useCallback)((e,t)=>{let n=x.current;if(e<0||e>=n.length)return null;let r=new Set(C.current);return t?r.has(e)?r.delete(e):r.add(e):r.has(e)||(r.clear(),r.add(e)),C.current=r,S.current=null,V(),z(),{base:mt(n),indices:Array.from(r)}},[z,V]),pe=(0,n.useCallback)(e=>{C.current=new Set,S.current=e,se([...x.current,e],!0)},[se]),me=(0,n.useCallback)(e=>{S.current=null,C.current=new Set,x.current=[{...e}],V(),z()},[z,V]),he=(0,n.useCallback)((e,t)=>{let n=x.current[x.current.length-1];return n&&Math.hypot(e.x-n.x,e.y-n.y)<t?!1:(x.current=[...x.current,{...e}],S.current=null,V(),z(),!0)},[z,V]),U=(0,n.useCallback)((e,t,n,r)=>{let i=new Set(t);x.current=e.map((e,t)=>i.has(t)?{x:e.x+n,y:e.y+r}:{...e}),S.current=null,V(),z()},[z,V]),ge=(0,n.useCallback)(e=>{e&&(oe(x.current),V(),z())},[z,oe,V]),_e=(0,n.useCallback)(e=>{S.current=e?{...e}:null,V(),z()},[z,V]),ve=(0,n.useCallback)(()=>x.current.length>0?(x.current=[],V(),z(),!0):j.current<=0?!1:(--j.current,D.current=ft(A.current[j.current]),V(),z(),!0),[z,V]),ye=(0,n.useCallback)(()=>x.current.length>0||j.current>=A.current.length-1?!1:(j.current+=1,D.current=ft(A.current[j.current]),V(),z(),!0),[z,V]),be=(0,n.useCallback)(()=>T.current<=0?!1:(--T.current,x.current=mt(w.current[T.current]),C.current=new Set,V(),z(),!0),[z,V]),xe=(0,n.useCallback)(()=>T.current>=w.current.length-1?!1:(T.current+=1,x.current=mt(w.current[T.current]),C.current=new Set,V(),z(),!0),[z,V]),Se=(0,n.useCallback)(()=>{let t=e.current;return t===L.BRUSH?ve():t===L.POLYGON||t===L.PATH?be():!1},[e,ve,be]),Ce=(0,n.useCallback)(()=>{let t=e.current;return t===L.BRUSH?ye():t===L.POLYGON||t===L.PATH?xe():!1},[ye,xe,e]),we=(0,n.useCallback)(()=>{let e=t.current;if(!e.length)return k.current.length>0;let n=r.current.getShapes().filter(t=>e.includes(t.id)&&u(t)),i=ct(n);return i.length?(k.current=n.map(e=>e.id),O.current=i,!0):(k.current=[],O.current=[],!1)},[r,t]),Te=(0,n.useCallback)(()=>{if(i.current)return!1;let e=[...D.current];x.current.length&&e.push({points:mt(x.current),mode:N()});let t=O.current,n=[...k.current];if(!e.length&&!t.length)return!1;let u=lt(e,s.current,t);if(!u)return H(),!1;let d=ut(u,c.current);if(n.length){let e=r.current.getShapes().filter(e=>n.includes(e.id));if(!d.length)return r.current.remove(n),H(),h([]),!0;d.sort((e,t)=>J(t)-J(e));let t=[],i=[],a=[];for(let n=0;n<d.length;n++){let r=d[n];if(n<e.length){let i=e[n];t.push({...i,type:o.POLYGON,points:r}),a.push(i.id)}else{let t=e[0],n=p();i.push({...t,id:n,type:o.POLYGON,points:r}),a.push(n)}}let s=e.slice(d.length).map(e=>e.id);return t.length&&r.current.update(t),i.length&&r.current.create(i),s.length&&r.current.remove(s),H(),h(a),!0}if(!d.length)return H(),!1;let f=a.current;if(!f)return!1;let m=d.map(e=>({id:p(),type:o.POLYGON,points:e,style:f,meta:l}));return r.current.create(m),h(m.map(e=>e.id)),H(),!0},[s,h,r,l,a,i,H]),Ee=(0,n.useCallback)(()=>{let t=e.current;if(t===L.BRUSH)return Te();let n=x.current;return t===L.POLYGON&&n.length>=3?(b.current(o.POLYGON,n),H(),!0):!1},[Te,H,e]),De=(0,n.useCallback)(()=>{let t=x.current;if(e.current===L.PATH&&t.length>=3){let e=q(t,c.current);e.length>=3&&b.current(o.POLYGON,e)}H()},[H,e]),Oe=(0,n.useCallback)(e=>{M.current=e,z(),V()},[z,V]),ke=(0,n.useCallback)(()=>{if(i.current||e.current!==L.BRUSH)return!1;D.current=[],x.current=[],B();let t=we();return z(),V(),t},[z,i,V,B,we,e]),Ae=(0,n.useCallback)(()=>{let e=C.current;if(!e.size)return!1;let t=x.current.filter((t,n)=>!e.has(n));return C.current=new Set,se(t,!0),!0},[se]),W=(0,n.useCallback)(e=>{let t=d.current,n=x.current;if(!t||!n.length)return-1;let r=gt/(t.viewport.scale||1);for(let t=n.length-1;t>=0;t--){let i=n[t];if(Math.hypot(e.x-i.x,e.y-i.y)<=r)return t}return-1},[d]),je=(0,n.useCallback)(()=>{x.current.length>=1&&(D.current.push({points:mt(x.current),mode:N()}),x.current=[],ae(D.current)),V(),z()},[z,ae,V]);return{reset:H,undoSession:Se,redoSession:Ce,canUndoSession:ne,canRedoSession:re,hasDraftSession:ie,hasDraftPoints:le,commitDraftSession:Ee,completeFreehandStroke:De,setBrushScalarMode:Oe,getBrushScalarMode:()=>M.current,hasBrushSession:P,commitBrush:Te,cancelBrush:(0,n.useCallback)(()=>{e.current===L.BRUSH&&H()},[H,e]),beginBrushEditFromSelection:ke,deleteDraftSelectedPoints:Ae,hitDraftPoint:W,getDraftPointsSnapshot:ce,tryClosePolygon:ue,removeDraftPoint:de,selectDraftPointForDrag:fe,appendPolygonPoint:pe,beginStroke:me,appendStrokePoint:he,moveDraftPoints:U,commitDraftPointDrag:ge,setDraftCursor:_e,finishScalarStroke:je,handleToolChange:(0,n.useCallback)((e,t)=>{if(t){H(),M.current=`draw`;return}if(e!==L.BRUSH){H(),M.current=`draw`;return}M.current=`draw`,D.current=[],x.current=[],B(),we(),z(),V()},[z,V,H,B,we]),handleBrushSelectionChange:(0,n.useCallback)((t,n)=>{if(!(e.current!==L.BRUSH||n)){if(!t.length){z();return}[...t].sort().join(`,`)!==[...k.current].sort().join(`,`)&&(D.current.length||x.current.length||(D.current=[],x.current=[],B(),we(),z(),V()))}},[z,V,B,we,e])}}function vt(e,t){return{shapes:t,past:[...e.past,e.shapes],future:[]}}function yt(e,t){switch(t.type){case`CREATE`:return vt(e,[...e.shapes,...t.shapes]);case`UPDATE`:{let n=new Map(t.shapes.map(e=>[e.id,e]));return vt(e,e.shapes.map(e=>n.get(e.id)??e))}case`DELETE`:{let n=new Set(t.ids);return vt(e,e.shapes.filter(e=>!n.has(e.id)))}case`REPLACE`:{let n=new Set(t.removeIds);return vt(e,[...e.shapes.filter(e=>!n.has(e.id)),...t.shapes])}case`REORDER`:{let n=new Set(t.ids),r=e.shapes.filter(e=>n.has(e.id)),i=e.shapes.filter(e=>!n.has(e.id));return r.length===0?e:vt(e,t.edge===`front`?[...i,...r]:[...r,...i])}case`RESET`:return{shapes:t.shapes,past:[],future:[]};case`UNDO`:return e.past.length===0?e:{shapes:e.past[e.past.length-1],past:e.past.slice(0,-1),future:[e.shapes,...e.future]};case`REDO`:return e.future.length===0?e:{shapes:e.future[0],past:[...e.past,e.shapes],future:e.future.slice(1)};default:return e}}function bt(e){let{onShapesCreated:t,onShapesUpdated:r,onShapesDeleted:i}=e,[a,o]=(0,n.useReducer)(yt,{shapes:[],past:[],future:[]}),s=(0,n.useRef)(a);s.current=a;let c=(0,n.useCallback)(e=>{s.current=yt(s.current,e),o(e)},[]),l=(0,n.useCallback)((e,n)=>{let a=new Map(e.map(e=>[e.id,e])),o=new Map(n.map(e=>[e.id,e])),s=n.filter(e=>!a.has(e.id));s.length&&t?.(s);let c=e.filter(e=>!o.has(e.id)).map(e=>e.id);c.length&&i?.(c);let l=n.filter(e=>a.has(e.id)&&a.get(e.id)!==e);l.length&&r?.(l)},[t,r,i]),u=(0,n.useCallback)(e=>{let n=Array.isArray(e)?e:[e];n.length&&(c({type:`CREATE`,shapes:n}),t?.(n))},[t]),d=(0,n.useCallback)(e=>{c({type:`UPDATE`,shapes:e}),r?.(e)},[r]),f=(0,n.useCallback)(e=>{e.length!==0&&(c({type:`DELETE`,ids:e}),i?.(e))},[i]),p=(0,n.useCallback)((e,n)=>{!e.length&&!n.length||(c({type:`REPLACE`,removeIds:e,shapes:n}),e.length&&i?.(e),n.length&&t?.(n))},[t,i]),m=(0,n.useCallback)((e,t)=>{e.length!==0&&c({type:`REORDER`,ids:e,edge:t})},[]),h=(0,n.useCallback)(e=>{c({type:`RESET`,shapes:e})},[]),g=(0,n.useCallback)(()=>{let e=s.current;e.past.length!==0&&(l(e.shapes,e.past[e.past.length-1]),c({type:`UNDO`}))},[l]),_=(0,n.useCallback)(()=>{let e=s.current;e.future.length!==0&&(l(e.shapes,e.future[0]),c({type:`REDO`}))},[l]),v=(0,n.useCallback)(()=>s.current.past.length>0,[]),y=(0,n.useCallback)(()=>s.current.future.length>0,[]),b=(0,n.useCallback)(()=>s.current.shapes,[]);return{shapes:a.shapes,create:u,update:d,remove:f,replace:p,reorder:m,reset:h,undo:g,redo:_,canUndo:v,canRedo:y,getShapes:b}}var xt={undo:[`mod+z`],redo:[`mod+shift+z`],selectAll:[`mod+a`],copy:[`mod+c`],cut:[`mod+x`],paste:[`mod+v`],duplicate:[`mod+d`],delete:[`delete`,`backspace`],cancel:[`escape`],commitDraft:[`enter`],bringToFront:[`mod+]`],sendToBack:[`mod+[`],zoomIn:[`mod+=`,`mod+shift+=`],zoomOut:[`mod+-`],zoom100:[`shift+1`],zoomFit:[`shift+2`],toggleMinimap:[`m`],toggleCursorGuide:[`;`],togglePixelation:[`.`],selectTool:[`s`],rectangleTool:[`r`],rotatedRectangleTool:[`shift+r`],circleTool:[`o`],polygonTool:[`p`],pathTool:[`g`],brushTool:[`b`],pointTool:[`i`]},St={Equal:`=`,Minus:`-`,BracketLeft:`[`,BracketRight:`]`,Semicolon:`;`,Period:`.`,Comma:`,`,Slash:`/`,Backquote:"`"},Ct={Escape:`escape`,Enter:`enter`,Backspace:`backspace`,Delete:`delete`,Tab:`tab`,ArrowUp:`arrowup`,ArrowDown:`arrowdown`,ArrowLeft:`arrowleft`,ArrowRight:`arrowright`};function wt(e){let t=e.code,n=/^Key([A-Z])$/.exec(t);if(n)return n[1].toLowerCase();let r=/^Digit([0-9])$/.exec(t);return r?r[1]:St[t]?St[t]:Ct[e.key]?Ct[e.key]:null}function Tt(e){let t=wt(e);if(!t)return null;let n=[];return(e.metaKey||e.ctrlKey)&&n.push(`mod`),e.shiftKey&&n.push(`shift`),e.altKey&&n.push(`alt`),n.push(t),n.join(`+`)}function Et(e){let t=new Map;for(let n of Object.keys(xt)){let r=e?.[n],i=r===void 0?xt[n]:r===null?[]:Array.isArray(r)?r:[r];for(let e of i)t.set(e.toLowerCase(),n)}return t}var Z={ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0]};function Dt(){let e=document.activeElement;return!!e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable)}function Ot(e,t){if(!t||!(e instanceof Element))return!1;let n=e.closest(`[role="dialog"],[aria-modal="true"]`);return!!n&&!n.contains(t)}function kt(e){let{spaceRef:t,shiftRef:r}=e,i=(0,n.useMemo)(()=>Et(e.keymap),[e.keymap]),a=(0,n.useRef)(e);a.current=e;let o=(0,n.useRef)(i);o.current=i,(0,n.useEffect)(()=>{let e=e=>{if(e.code===`Space`&&(t.current=!0,a.current.onSpaceDown()),e.key===`Shift`&&(r.current=!0),Dt()||Ot(e.target,a.current.hostRef.current))return;let n=Z[e.key];if(n){e.preventDefault();let t=e.shiftKey?10:1;a.current.nudge(n[0]*t,n[1]*t);return}let i=Tt(e);if(!i)return;let s=o.current.get(i);s&&a.current.actions[s]?.()!==!1&&e.preventDefault()},n=e=>{e.code===`Space`&&(t.current=!1,a.current.onSpaceUp()),e.key===`Shift`&&(r.current=!1)};return window.addEventListener(`keydown`,e,{capture:!0}),window.addEventListener(`keyup`,n,{capture:!0}),()=>{window.removeEventListener(`keydown`,e,{capture:!0}),window.removeEventListener(`keyup`,n,{capture:!0})}},[t,r])}async function At(e){for(let t of[`default`,`reload`])try{let n=await fetch(e,{mode:`cors`,credentials:`omit`,cache:t});if(n.ok)return URL.createObjectURL(await n.blob())}catch{}return null}var jt=4e3;function Mt(e,t,n=jt){if(e<=0||t<=0)return[];let r=Math.ceil(e/n),i=Math.ceil(t/n);return Array.from({length:i},(a,o)=>Array.from({length:r},(a,s)=>{let c=s*n,l=o*n,u=s===r-1,d=o===i-1;return{x:c,y:l,width:u?e-c:n+1,height:d?t-l:n+1,srcX:c,srcY:l}})).flat()}function Nt(e,t){let n=document.createElement(`canvas`);n.width=t.width,n.height=t.height;let r=n.getContext(`2d`);return r&&r.drawImage(e,t.srcX,t.srcY,t.width,t.height,0,0,t.width,t.height),n}function Pt(e,t,n){if(t===o.POINT){e.setAttrs({x:n[0].x,y:n[0].y});return}if(t===o.RECTANGLE){let[t,r]=n;e.setAttrs({x:Math.min(t.x,r.x),y:Math.min(t.y,r.y),width:Math.abs(r.x-t.x),height:Math.abs(r.y-t.y)});return}if(t===o.ELLIPSE){let t=h(n);e.setAttrs({x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2,radiusX:(t.maxX-t.minX)/2,radiusY:(t.maxY-t.minY)/2});return}e.setAttrs({x:0,y:0,points:n.flatMap(e=>[e.x,e.y])})}var Ft=`M8 0C12.4183 0 16 3.58172 16 8C16 11.5323 13.71 14.5277 10.5342 15.5879L10.166 20.0068C10.0721 21.1334 9.13046 22 8 22C6.86954 22 5.92786 21.1334 5.83398 20.0068L5.46484 15.5879C2.28949 14.5275 0 11.532 0 8C0 3.58172 3.58172 0 8 0Z`,It=`#ffffff`,Lt=1.5;function Rt(e){return`<svg width="16" height="22" viewBox="0 0 16 22" xmlns="http://www.w3.org/2000/svg"><path d="${Ft}" fill="${e}" stroke="${It}" stroke-width="${Lt}"/></svg>`}var zt=Math.PI/12;function Bt(e,t){return t.kind!==`resize`&&t.kind!==`move`||t.shapes.length!==1?!1:e.find(e=>e.id===t.shapes[0].id)?.type===o.ROTATED_RECTANGLE}function Vt(e,t,n){if(e.kind===`resize`){let r=n?e.box:_(e.anchor,e.box,t.x,t.y);return{updates:e.shapes.map(i=>({id:i.id,points:n?N(i.points,e.anchor,t):P(i.points,e.box,r)})),box:r}}if(e.kind===`move`){let n=t.x-e.start.x,r=t.y-e.start.y;return{updates:e.shapes.map(e=>({id:e.id,points:e.points.map(e=>({x:e.x+n,y:e.y+r}))})),box:{minX:e.box.minX+n,minY:e.box.minY+r,maxX:e.box.maxX+n,maxY:e.box.maxY+r}}}if(e.kind===`rotate`){let n=Math.atan2(t.y-e.center.y,t.x-e.center.x)-e.startAngle;return e.shiftKey&&(n=Math.round(n/zt)*zt),{updates:[{id:e.id,points:e.points.map(t=>y(t,e.center,n))}],box:null}}let r=t.x-e.start.x,i=t.y-e.start.y,a=e.base.map((t,n)=>e.indices.includes(n)?{x:t.x+r,y:t.y+i}:t);return{updates:[{id:e.id,points:a}],box:h(a)}}function Ht(e,t){return t.kind===`move`||t.kind===`vertex`?t.start:t.kind===`rotate`?{x:t.center.x+Math.cos(t.startAngle),y:t.center.y+Math.sin(t.startAngle)}:Bt(e,t)?A(t.shapes[0].points)[m.indexOf(t.anchor)]:g(t.anchor,t.box)}function Ut(e,t,n){let r=e.filter(e=>t.includes(e.id)&&d(e)).map(e=>({id:e.id,points:e.points}));return r.length?{kind:`move`,start:n,box:h(r.flatMap(e=>e.points)),shapes:r}:null}function Wt(e){return e.map(e=>({...e,points:e.points.map(e=>({...e}))}))}function Gt(e,t){let n=new Set(t);return e.filter(e=>n.has(e.id)&&u(e))}function Kt(e,t){return e.filter(e=>{if(!l(e))return!1;let n=h(e.points);return n.minX<=t.maxX&&n.maxX>=t.minX&&n.minY<=t.maxY&&n.maxY>=t.minY}).map(e=>e.id)}function qt(e,t,n){return(e?le(e,{strokeWidth:t}).pointRadius:5)/(n||1)}function Jt(e,t){return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}function Yt(e,t,n){if(e.type===o.ROTATED_RECTANGLE)return t;let r=e.type===o.POINT?Jt(t[0],n):h(t);return b([{x:r.minX,y:r.minY},{x:r.maxX,y:r.maxY}])}function Xt(e){return 24/(e||1)}function Zt(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}var Qt=2,$t=`#1e88e5`,en=`#669def`,tn=class{constructor(e,t){this.layer=new i.default.Layer,this.world=new i.default.Group,this.bgGroup=new i.default.Group,this.overlayGroup=new i.default.Group({listening:!1}),this.shapeGroup=new i.default.Group,this.selGroup=new i.default.Group,this.previewGroup=new i.default.Group,this.handleGroup=new i.default.Group,this.baseCursor=`default`,this.strokeSize=Qt,this.imageSmoothing=!0,this.imageWidth=0,this.imageHeight=0,this.shapes=[],this.selected=[],this.nodes=new Map,this.altNodes=new Map,this.lastAppliedScale=-1,this.imageLoadToken=0,this.transformEnabled=!1,this.handleNodes=[],this.vertexNodes=[],this.lastImg={x:0,y:0},this.lastDragImg=null,this.ro=null,this.activeDrag=null,this.midNodes=[],this.selectedVertices=new Set,this.vertexPolygonId=null,this.editingId=null,this.rotNode=null,this.rotLineNode=null,this.transformerOutline=null,this.selectionBorders=[],this.upCleanup=null,this.lastPreviewPoly=null,this.preview=null,this.marquee=null,this.host=e,this.cb=t,this.stage=new i.default.Stage({container:e,width:e.clientWidth||1,height:e.clientHeight||1}),this.world.add(this.bgGroup,this.overlayGroup,this.shapeGroup,this.selGroup,this.previewGroup),this.layer.add(this.world,this.handleGroup),this.world.visible(!1),this.stage.add(this.layer)}async init(){let e=e=>({button:e.evt.button,shiftKey:e.evt.shiftKey,altKey:e.evt.altKey,ctrlKey:e.evt.ctrlKey,metaKey:e.evt.metaKey,global:this.stage.getPointerPosition()??{x:0,y:0}});this.stage.on(`mousedown`,t=>{let n=t.target===this.stage?null:t.target.id()||null;this.cb.onPointerDown(this.toImage(),n,e(t))}),this.stage.on(`mousemove`,()=>{if(this.lastImg=this.toImage(),this.activeDrag){this.lastDragImg=this.lastImg,this.dragTransform(this.lastImg);return}this.cb.onPointerMove(this.lastImg,{global:this.stage.getPointerPosition()??{x:0,y:0}})});let t=()=>{if(this.activeDrag){this.endTransform();return}this.cb.onPointerUp(this.lastImg)};this.stage.on(`mouseup`,t),window.addEventListener(`mouseup`,t),this.upCleanup=()=>window.removeEventListener(`mouseup`,t),this.ro=new ResizeObserver(()=>{this.stage.size({width:this.host.clientWidth||1,height:this.host.clientHeight||1}),this.layer.batchDraw()}),this.ro.observe(this.host)}destroy(){this.ro?.disconnect(),this.upCleanup?.(),this.stage.destroy()}get dom(){return this.stage.container()}get screenSize(){return{w:this.stage.width(),h:this.stage.height()}}setCursor(e){this.baseCursor=e,this.applyCursor()}emitCursorHint(e){this.cb.onCursorHint?.(e)}emitInteractionMode(e){this.cb.onInteractionModeChange?.(e)}applyCursor(){this.stage.container().style.cursor=this.baseCursor;for(let e of this.stage.container().querySelectorAll(`canvas`))e.style.cursor=this.baseCursor}bindCursor(e,t){let n=()=>{this.activeDrag||t===`pointer`&&!this.transformEnabled||this.emitCursorHint(t)},r=()=>{this.activeDrag||this.emitCursorHint(null)};e.on(`mouseenter`,n),e.on(`mouseover`,n),e.on(`mouseleave`,r),e.on(`mouseout`,r)}toImage(){let e=this.world.getRelativePointerPosition();return e?{x:e.x,y:e.y}:this.lastImg}imgToScreen(e){return this.world.getAbsoluteTransform().point(e)}async setImage(e,t,n){let r=++this.imageLoadToken,a=await At(e);await new Promise(o=>{let s=new Image;a||(s.crossOrigin=`anonymous`),s.onload=()=>{if(a&&URL.revokeObjectURL(a),r!==this.imageLoadToken)return o();this.imageWidth=t?.width??s.naturalWidth,this.imageHeight=t?.height??s.naturalHeight;let e=n?.width??this.imageWidth,c=n?.height??this.imageHeight;this.bgGroup.scale({x:e/s.naturalWidth,y:c/s.naturalHeight}),this.bgGroup.destroyChildren();for(let e of Mt(s.naturalWidth,s.naturalHeight))this.bgGroup.add(new i.default.Image({image:s,x:e.x,y:e.y,width:e.width,height:e.height,crop:{x:e.srcX,y:e.srcY,width:e.width,height:e.height},listening:!1}));this.layer.batchDraw(),o()},s.onerror=()=>{a&&URL.revokeObjectURL(a),this.imageWidth||=800,this.imageHeight||=600,o()},s.src=a??e})}clearImage(){this.imageLoadToken++,this.bgGroup.destroyChildren(),this.layer.batchDraw()}setFilter(e,t){let n=e!==1||t!==1?`brightness(${e}) contrast(${t})`:``,r=this.stage.container().querySelector(`canvas`);r&&(r.style.filter=n)}setStrokeSize(e){this.strokeSize!==e&&(this.strokeSize=e,this.setShapes(this.shapes,this.selected))}setImageSmoothing(e){this.imageSmoothing!==e&&(this.imageSmoothing=e,this.layer.imageSmoothingEnabled(e),this.layer.batchDraw())}setOverlays(e,t,n){if(this.overlayGroup.destroyChildren(),e&&this.overlayGroup.add(new i.default.Image({image:e,opacity:.55,imageSmoothingEnabled:!1,listening:!1})),t){let{imageWidth:e,imageHeight:n}=this;if(this.overlayGroup.add(new i.default.Shape({listening:!1,sceneFunc:r=>{Le(r._context,t,e,n)}})),t.outlineStyles){let e=(e,t)=>{let n={strokeWidth:t.width,strokeScaleEnabled:!1,listening:!1};for(let[r,a]of e)t.underlayColor&&this.overlayGroup.add(new i.default.Line({points:[r.x,r.y,a.x,a.y],stroke:t.underlayColor,...n})),this.overlayGroup.add(new i.default.Line({points:[r.x,r.y,a.x,a.y],stroke:t.color,opacity:t.opacity,dash:t.dash,...n}))};e(t.visibleOutline,t.outlineStyles.visible),e(t.occludedOutline,t.outlineStyles.occluded)}}n&&this.imageWidth&&this.overlayGroup.add(new i.default.Rect({x:0,y:0,width:this.imageWidth,height:this.imageHeight,fill:`#0d0d12`,opacity:.3,listening:!1})),this.layer.batchDraw()}get viewport(){return{scale:this.world.scaleX(),x:this.world.x(),y:this.world.y()}}applyViewport(e){let t=e.scale!==this.lastAppliedScale;if(this.lastAppliedScale=e.scale,this.world.scale({x:e.scale,y:e.scale}),this.world.position({x:e.x,y:e.y}),this.world.visible(!0),t){this.syncScreenFixedShapes(),this.updateSelectionBordersLive(e=>e.points);let e=this.lastPreviewPoly;e&&this.previewPoly(e.points,e.cursor,e.style,e.closed,e.selectedPointIndices,e.showVertices)}this.activeDrag?this.dragTransform(this.lastDragImg??Ht(this.shapes,this.activeDrag)):this.drawTransformer(),this.layer.batchDraw(),this.cb.onViewportChange?.()}fit(){if(!this.imageWidth||!this.imageHeight)return;let{w:e,h:t}=this.screenSize,n=Math.min(e/this.imageWidth,t/this.imageHeight);this.applyViewport({scale:n,x:(e-this.imageWidth*n)/2,y:(t-this.imageHeight*n)/2})}zoom100(){if(!this.imageWidth||!this.imageHeight)return;let{w:e,h:t}=this.screenSize;this.applyViewport({scale:1,x:(e-this.imageWidth)/2,y:(t-this.imageHeight)/2})}zoomAt(e,t,n){let r=this.world.scaleX(),i=Math.min(20,Math.max(.05,r*n)),a=(e-this.world.x())/r,o=(t-this.world.y())/r;this.applyViewport({scale:i,x:e-a*i,y:t-o*i})}setShapes(e,t){if(this.shapes=Wt(e),this.selected=t,!this.activeDrag){this.shapeGroup.destroyChildren(),this.nodes.clear(),this.altNodes.clear();for(let t of f(e).filter(s)){let e=this.makeNode(t),n=le(t,{strokeWidth:this.strokeSize});if(t.style?.alternateColor&&n.dash?.length&&t.type!==o.POINT){let n=e.clone({id:`${t.id}__alt`,stroke:t.style.alternateColor,dash:[],fillEnabled:!1,listening:!1});this.altNodes.set(t.id,n),this.shapeGroup.add(n)}this.nodes.set(t.id,e),this.shapeGroup.add(e)}this.drawSelectionBorders(),this.drawTransformer(),this.layer.batchDraw()}}setSelection(e){this.selected=e,(e.length!==1||e[0]!==this.vertexPolygonId)&&(this.vertexPolygonId=null,this.selectedVertices.clear()),this.editingId&&(e.length!==1||e[0]!==this.editingId)&&(this.editingId=null),!this.activeDrag&&(this.drawSelectionBorders(),this.drawTransformer(),this.layer.batchDraw())}setEditing(e){this.editingId!==e&&(this.editingId=e,this.selectedVertices.clear(),this.activeDrag||(this.drawTransformer(),this.layer.batchDraw()))}makeNode(e){let{type:t,points:n}=e,r=le(e,{strokeWidth:this.strokeSize}),a=l(e),s={id:e.id,stroke:r.color,strokeWidth:r.strokeWidth,dash:this.scaledDash(r.dash),opacity:r.opacity,strokeScaleEnabled:!1,listening:a},c=r.fillVisible?ue(r.color,r.fillAlpha):void 0;if(t===o.POINT){let t=1/(this.world.scaleX()||1),o=new i.default.Path({id:e.id,data:Ft,x:n[0].x,y:n[0].y,offsetX:16/2,offsetY:22,scaleX:t,scaleY:t,fill:r.color,stroke:It,strokeWidth:Lt,strokeScaleEnabled:!1,shadowColor:`#000`,shadowBlur:2,shadowOpacity:.3,shadowForStrokeEnabled:!1,opacity:r.opacity,listening:a});return this.bindCursor(o,d(e)?`grab`:`default`),o}if(t===o.RECTANGLE){let t=h(n),r=new i.default.Rect({x:t.minX,y:t.minY,width:t.maxX-t.minX,height:t.maxY-t.minY,fill:c,...s});return this.bindCursor(r,d(e)?`grab`:`default`),r}if(t===o.ELLIPSE){let t=h(n),r=new i.default.Ellipse({x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2,radiusX:(t.maxX-t.minX)/2,radiusY:(t.maxY-t.minY)/2,fill:c,...s});return this.bindCursor(r,d(e)?`grab`:`default`),r}let u=n.flatMap(e=>[e.x,e.y]),f=t!==o.LINE,p=new i.default.Line({points:u,closed:f,fill:f?c:void 0,lineJoin:`round`,...s});return this.bindCursor(p,d(e)?`grab`:`default`),p}liveUpdateShape(e,t){let n=this.nodes.get(e),r=this.shapes.find(t=>t.id===e);if(n&&r){Pt(n,r.type,t);let a=this.altNodes.get(e);a&&Pt(a,r.type,t),r.type===o.POINT&&n instanceof i.default.Circle&&n.radius(this.pointRadius(r)),this.layer.batchDraw()}}pointRadius(e){return qt(e,this.strokeSize,this.world.scaleX()||1)}scaledDash(e){return e}syncScreenFixedShapes(){let e=1/(this.world.scaleX()||1);for(let t of this.shapes){let n=this.nodes.get(t.id);if(t.type===o.POINT){n?.scale({x:e,y:e});continue}n?.dash(this.scaledDash(le(t,{strokeWidth:this.strokeSize}).dash))}}shapesIntersecting(e){return Kt(this.shapes,e)}drawSelectionBorders(){let e=new Set(this.selected),t=this.selected.length?this.shapes.filter(t=>e.has(t.id)&&l(t)):[];if(this.selectionBorders.length!==t.length){for(let e of this.selectionBorders)e.destroy();this.selectionBorders=t.map(()=>{let e=new i.default.Line({closed:!0,stroke:en,strokeWidth:1.5,strokeScaleEnabled:!1,listening:!1});return this.selGroup.add(e),e})}t.forEach((e,t)=>{this.selectionBorders[t].points(this.selectionOutlinePoints(e,e.points).flatMap(e=>[e.x,e.y]))})}updateSelectionBordersLive(e){let t=new Set(this.selected),n=0;for(let r of this.shapes){if(!t.has(r.id)||!l(r))continue;let i=this.selectionOutlinePoints(r,e(r)),a=this.selectionBorders[n++];a&&a.points(i.flatMap(e=>[e.x,e.y]))}}selectionOutlinePoints(e,t){return Yt(e,t,this.pointRadius(e))}clearPreview(){this.lastPreviewPoly=null,this.previewGroup.destroyChildren(),this.layer.batchDraw()}clearMarquee(){this.marquee?.destroy(),this.marquee=null,this.layer.batchDraw()}previewBox(e,t,n,r){this.lastPreviewPoly=null,this.previewGroup.destroyChildren();let a=Math.min(t.x,n.x),o=Math.min(t.y,n.y),s=Math.abs(n.x-t.x),c=Math.abs(n.y-t.y),l=(t,n)=>e===`ellipse`?new i.default.Ellipse({x:a+s/2,y:o+c/2,radiusX:s/2,radiusY:c/2,stroke:t,strokeWidth:r.strokeWidth??this.strokeSize,dash:this.scaledDash(n),strokeScaleEnabled:!1}):new i.default.Rect({x:a,y:o,width:s,height:c,stroke:t,strokeWidth:r.strokeWidth??this.strokeSize,dash:this.scaledDash(n),strokeScaleEnabled:!1});r.alternateColor&&this.previewGroup.add(l(r.alternateColor)),this.preview=l(r.color??`#00e5ff`,r.dash),this.previewGroup.add(this.preview),this.layer.batchDraw()}previewPoly(e,t,n,r,a=[],o=!0){if(this.lastPreviewPoly={points:e,cursor:t,style:n,closed:r,selectedPointIndices:a,showVertices:o},this.previewGroup.destroyChildren(),!e.length)return;let s=e.flatMap(e=>[e.x,e.y]);t&&s.push(t.x,t.y);let c=(e,t)=>new i.default.Line({points:s,closed:r,stroke:e,strokeWidth:n.strokeWidth??this.strokeSize,dash:this.scaledDash(t),strokeScaleEnabled:!1,lineCap:`round`,lineJoin:`round`});if(n.alternateColor&&this.previewGroup.add(c(n.alternateColor)),this.previewGroup.add(c(n.color??`#00e5ff`,n.dash)),!o){this.layer.batchDraw();return}let l=new Set(a),u=this.world.scaleX()||1;for(let t=0;t<e.length;t++){let n=e[t],r=l.has(t);this.previewGroup.add(new i.default.Circle({x:n.x,y:n.y,radius:(r?6:5)/u,fill:r?$t:`#ffffff`,stroke:r?`#ffffff`:$t,strokeWidth:1.5,strokeScaleEnabled:!1,listening:!1}))}this.layer.batchDraw()}previewScalarMask(e,t){this.previewGroup.destroyChildren();let n=dt(e,t.length===7?`${t}99`:t);this.previewGroup.add(new i.default.Image({image:n,x:e.ox,y:e.oy,scaleX:1/e.scale,scaleY:1/e.scale,listening:!1})),this.layer.batchDraw()}previewMarquee(e,t){this.marquee||(this.marquee=new i.default.Rect({fill:ue(oe,H),stroke:oe,strokeWidth:1,strokeScaleEnabled:!1,listening:!1,perfectDrawEnabled:!1}),this.previewGroup.add(this.marquee)),this.marquee.setAttrs({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(t.x-e.x),height:Math.abs(t.y-e.y)}),this.layer.batchDraw()}setTransformEnabled(e){this.transformEnabled=e,this.drawTransformer(),this.layer.batchDraw()}setPanMode(e){this.handleGroup.listening(!e),this.layer.batchDraw()}setTransformerOutline(e){let t=Math.max(0,e.maxX-e.minX),n=Math.max(0,e.maxY-e.minY);!t&&!n||this.setTransformerOutlinePoints(b([{x:e.minX,y:e.minY},{x:e.maxX,y:e.maxY}]))}setTransformerOutlinePoints(e){e.length<2||(this.transformerOutline||(this.transformerOutline=new i.default.Line({closed:!0,stroke:$t,strokeWidth:1,strokeScaleEnabled:!1,listening:!1}),this.selGroup.add(this.transformerOutline)),this.transformerOutline.points(e.flatMap(e=>[e.x,e.y])))}rotationHandleGap(){return Xt(this.viewport.scale)}rotationHandleScreenPoint(e){return this.imgToScreen(j(e,this.rotationHandleGap()))}setRotationConnector(e){let t=this.imgToScreen(O(e[0],e[1])),n=this.rotationHandleScreenPoint(e);this.rotLineNode?this.rotLineNode.points([t.x,t.y,n.x,n.y]):(this.rotLineNode=new i.default.Line({points:[t.x,t.y,n.x,n.y],stroke:$t,strokeWidth:1,listening:!1}),this.handleGroup.add(this.rotLineNode))}layoutResizeHandle(e,t,n){e.position({x:t.x,y:t.y}),e.offset({x:4,y:4}),e.rotation(n*180/Math.PI)}orientedHandleAngle(e){return Zt(this.imgToScreen(e[0]),this.imgToScreen(e[1]))}repositionOrientedHandles(e){let t=this.orientedHandleAngle(e);if(A(e).forEach((e,n)=>{let r=this.imgToScreen(e),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,t)}),this.setTransformerOutlinePoints(e),this.rotNode){let t=this.rotationHandleScreenPoint(e);this.rotNode.position({x:t.x,y:t.y})}this.rotLineNode&&this.setRotationConnector(e)}drawTransformer(){if(this.activeDrag)return;for(let e of this.handleNodes)e.destroy();for(let e of this.vertexNodes)e.destroy();for(let e of this.midNodes)e.destroy();if(this.rotNode?.destroy(),this.rotNode=null,this.rotLineNode?.destroy(),this.rotLineNode=null,this.transformerOutline?.destroy(),this.transformerOutline=null,this.handleNodes=[],this.vertexNodes=[],this.midNodes=[],!this.transformEnabled)return;let e=Gt(this.shapes,this.selected);if(!e.length||e.length===1&&e[0].type===o.POINT)return;let t=e.length===1&&(e[0].type===o.POLYGON||e[0].type===o.LINE)&&this.editingId===e[0].id?e[0]:null,n=h(e.flatMap(e=>e.points)),r=e.length===1&&e[0].type===o.ROTATED_RECTANGLE?e[0]:null,a=r?A(r.points):m.map(e=>g(e,n));r?this.setTransformerOutlinePoints(r.points):this.setTransformerOutline(n),r&&this.setRotationConnector(r.points);let s=r?this.orientedHandleAngle(r.points):0;for(let e of t?[]:m){let t=this.imgToScreen(a[m.indexOf(e)]),n=new i.default.Rect({x:t.x,y:t.y,width:8,height:8,offsetX:4,offsetY:4,rotation:s*180/Math.PI,fill:`#ffffff`,stroke:$t,strokeWidth:1}),r=De(e,s);this.bindCursor(n,r),n.on(`mousedown`,t=>{t.cancelBubble=!0,this.emitCursorHint(r),this.emitInteractionMode(`resizing`);let n=Gt(this.shapes,this.selected);this.activeDrag={kind:`resize`,anchor:e,box:h(n.flatMap(e=>e.points)),shapes:n.map(e=>({id:e.id,points:e.points}))},this.lastDragImg=null}),this.handleGroup.add(n),this.handleNodes.push(n)}if(t){let e=t,n=e.points,r=e.type===o.POLYGON?n.length:n.length-1;for(let t=0;t<r;t++){let r=n[t],a=n[(t+1)%n.length],o={x:(r.x+a.x)/2,y:(r.y+a.y)/2},s=this.imgToScreen(o),c=new i.default.Circle({x:s.x,y:s.y,radius:4,fill:`#ffffff`,opacity:.6,stroke:$t,strokeWidth:1});this.bindCursor(c,`copy`),c.on(`mousedown`,r=>{r.cancelBubble=!0;let i=[...n.slice(0,t+1),o,...n.slice(t+1)];this.cb.onTransformCommit?.([{id:e.id,points:i}])}),this.handleGroup.add(c),this.midNodes.push(c)}this.vertexPolygonId!==e.id&&(this.vertexPolygonId=e.id,this.selectedVertices.clear()),n.forEach((t,r)=>{let a=this.imgToScreen(t),o=this.selectedVertices.has(r),s=new i.default.Circle({x:a.x,y:a.y,radius:5,fill:o?$t:`#ffffff`,stroke:o?`#ffffff`:$t,strokeWidth:1.5});this.bindCursor(s,`pointer`),s.on(`mousedown`,t=>{if(t.cancelBubble=!0,t.evt.shiftKey||t.evt.ctrlKey||t.evt.metaKey){this.selectedVertices.has(r)?this.selectedVertices.delete(r):this.selectedVertices.add(r),this.drawTransformer();return}let i=this.selectedVertices.has(r)&&this.selectedVertices.size>1?[...this.selectedVertices]:[r];i.length===1&&(this.selectedVertices.clear(),this.selectedVertices.add(r)),this.activeDrag={kind:`vertex`,id:e.id,indices:i,base:n,start:this.toImage()},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`vertexDragging`)}),this.handleGroup.add(s),this.vertexNodes.push(s)})}if(e.length===1&&e[0].type===o.ROTATED_RECTANGLE){let t=e[0],n=k(t.points),r=this.rotationHandleScreenPoint(t.points),a=new i.default.Circle({x:r.x,y:r.y,radius:6,fill:`#ffffff`,stroke:$t,strokeWidth:1.5});this.bindCursor(a,`grab`),a.on(`mousedown`,e=>{e.cancelBubble=!0;let r=this.toImage();this.activeDrag={kind:`rotate`,id:t.id,center:n,startAngle:Math.atan2(r.y-n.y,r.x-n.x),points:t.points,shiftKey:e.evt.shiftKey},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`rotating`)}),this.handleGroup.add(a),this.rotNode=a}this.layer.batchDraw()}beginMove(e,t){let n=Ut(this.shapes,t,e);n&&(this.transformEnabled&&!this.handleNodes.length&&this.drawTransformer(),this.activeDrag=n,this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`moving`),(n.shapes.length===1?this.shapes.find(e=>e.id===n.shapes[0].id):null)?.type===o.ROTATED_RECTANGLE?this.setTransformerOutlinePoints(n.shapes[0].points):this.setTransformerOutline(n.box),this.updateSelectionBordersLive(e=>e.points))}repositionHandles(e){m.forEach((t,n)=>{let r=this.imgToScreen(g(t,e)),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,0)}),this.setTransformerOutline(e)}repositionPolygonHandles(e,t){if(!this.vertexNodes.length)return;e.forEach((e,t)=>{let n=this.imgToScreen(e);this.vertexNodes[t]?.position({x:n.x,y:n.y})});let n=t?e.length:e.length-1;for(let t=0;t<n;t++){let n=e[t],r=e[(t+1)%e.length],i=this.imgToScreen({x:(n.x+r.x)/2,y:(n.y+r.y)/2});this.midNodes[t]?.position({x:i.x,y:i.y})}}commitTransformUpdates(e){if(e.length){for(let t of e){let e=this.shapes.find(e=>e.id===t.id);e&&(e.points=t.points,this.liveUpdateShape(t.id,t.points))}this.cb.onTransformCommit?.(e),this.drawTransformer(),this.layer.batchDraw()}}dragTransform(e){let t=this.activeDrag;if(!t)return;this.applyCursor();let n=Bt(this.shapes,t),{updates:r,box:i}=Vt(t,e,n);for(let e of r)this.liveUpdateShape(e.id,e.points);if(this.cb.onTransformPreview?.(r),this.updateSelectionBordersLive(e=>r.find(t=>t.id===e.id)?.points??e.points),t.kind===`resize`||t.kind===`move`){n?this.repositionOrientedHandles(r[0].points):i&&this.repositionHandles(i);let e=t.shapes.length===1?this.shapes.find(e=>e.id===t.shapes[0].id):null,a=e?.type===o.POLYGON||e?.type===o.LINE;(t.kind===`resize`?a:this.vertexNodes.length>0&&t.shapes.length===1)&&this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}else if(t.kind===`rotate`){this.repositionOrientedHandles(r[0].points);let e=this.shapes.find(e=>e.id===t.id);e&&(e.type===o.POLYGON||e.type===o.LINE)&&this.repositionPolygonHandles(r[0].points,e.type===o.POLYGON)}else{i&&this.repositionHandles(i);let e=this.shapes.find(e=>e.id===t.id);this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}this.layer.batchDraw()}endTransform(){let e=this.activeDrag,t=this.lastDragImg;if(this.activeDrag=null,this.emitInteractionMode(`idle`),this.emitCursorHint(e?.kind===`move`?`grab`:null),!e||!t){this.cb.onTransformPreview?.([]),this.drawTransformer();return}if(e.kind===`move`&&t.x===e.start.x&&t.y===e.start.y){this.cb.onTransformPreview?.([]),this.drawTransformer();return}let{updates:n}=Vt(e,t,Bt(this.shapes,e));this.commitTransformUpdates(n)}},nn=2,rn=58879,an=6725103;function Q(e){if(!e)return rn;let t=e.replace(`#`,``);return Number.parseInt(t.length===3?t.replace(/./g,`$&$&`):t,16)}var on=class{constructor(e,t){this.app=new a.Application,this.world=new a.Container,this.bgLayer=new a.Container,this.overlayLayer=new a.Container,this.shapeLayer=new a.Container,this.selLayer=new a.Container,this.previewLayer=new a.Container,this.handleLayer=new a.Container,this.filter=new a.ColorMatrixFilter,this.imageWidth=0,this.imageHeight=0,this.imageTileTextures=[],this.imageLoadToken=0,this.overlayTextures=[],this.region=null,this.regionOutlineG=null,this.baseCursor=`default`,this.strokeSize=nn,this.shapes=[],this.selected=[],this.nodes=new Map,this.lastAppliedScale=-1,this.brightness=1,this.contrast=1,this.imageSmoothing=!0,this.destroyed=!1,this.transformEnabled=!1,this.handleNodes=[],this.vertexNodes=[],this.lastDragImg=null,this.activeDrag=null,this.midNodes=[],this.selectedVertices=new Set,this.vertexPolygonId=null,this.editingId=null,this.rotNode=null,this.rotLineNode=null,this.transformerOutline=null,this.selectionBorderGfx=[],this.previewG=new a.Graphics,this.marqueeG=new a.Graphics,this.previewMaskSprite=null,this.previewMaskTexture=null,this.previewReady=!1,this.lastPreview=null,this.host=e,this.cb=t}ev(e){return{button:e.button,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,global:{x:e.global.x,y:e.global.y}}}async init(){if(await this.app.init({resizeTo:this.host,background:`#111111`,antialias:!0,autoDensity:!0,resolution:window.devicePixelRatio||1,preference:`webgl`}),this.destroyed){this.app.destroy(!0);return}this.host.appendChild(this.app.canvas),this.applyCursor(),this.world.addChild(this.bgLayer,this.overlayLayer,this.shapeLayer,this.selLayer,this.previewLayer),this.app.stage.addChild(this.world,this.handleLayer),this.world.visible=!1,this.app.stage.eventMode=`static`,this.syncHitArea(),this.app.stage.on(`pointerdown`,e=>{this.cb.onPointerDown(this.toImage(e),null,this.ev(e))}),this.app.stage.on(`pointermove`,e=>{if(this.activeDrag){this.lastDragImg=this.toImage(e),this.dragTransform(this.lastDragImg);return}this.cb.onPointerMove(this.toImage(e),this.ev(e))});let e=e=>{if(this.activeDrag){this.endTransform();return}this.cb.onPointerUp(this.toImage(e))};this.app.stage.on(`pointerup`,e),this.app.stage.on(`pointerupoutside`,e),this.app.renderer.on(`resize`,()=>this.syncHitArea())}syncHitArea(){let{w:e,h:t}=this.screenSize;this.app.stage.hitArea=new a.Rectangle(0,0,e,t)}destroy(){this.destroyed=!0,this.clearImageTiles();for(let e of this.overlayTextures)e.destroy(!0);this.overlayTextures=[],this.app.renderer&&this.app.destroy(!0,{children:!0})}get screenSize(){return{w:this.app.renderer.screen.width,h:this.app.renderer.screen.height}}setCursor(e){this.baseCursor=e,this.syncShapeCursors(),this.applyCursor()}emitCursorHint(e){this.cb.onCursorHint?.(e)}emitInteractionMode(e){this.cb.onInteractionModeChange?.(e)}applyCursor(){if(this.destroyed||!this.app.renderer)return;let e=this.app.canvas;e&&(e.style.cursor=this.baseCursor)}syncShapeCursors(){for(let e of this.nodes.values())e.cursor=void 0}bindCursor(e,t){e.cursor=void 0,e.on(`pointerover`,()=>{this.activeDrag||this.emitCursorHint(t)}),e.on(`pointerout`,()=>{this.activeDrag||this.emitCursorHint(null)})}get dom(){return this.app.canvas}toImage(e){let t=this.world.toLocal(e.global);return{x:t.x,y:t.y}}async setImage(e,t,n){let r=++this.imageLoadToken,i=await At(e);if(this.destroyed){i&&URL.revokeObjectURL(i);return}await new Promise(o=>{let s=new Image;i||(s.crossOrigin=`anonymous`),s.onload=()=>{if(i&&URL.revokeObjectURL(i),this.destroyed||r!==this.imageLoadToken)return o();this.imageWidth=t?.width??s.naturalWidth,this.imageHeight=t?.height??s.naturalHeight;let e=n?.width??this.imageWidth,c=n?.height??this.imageHeight;this.bgLayer.scale.set(e/s.naturalWidth,c/s.naturalHeight),this.clearImageTiles();for(let e of Mt(s.naturalWidth,s.naturalHeight)){let t=a.Texture.from(Nt(s,e));t.source.scaleMode=this.imageSmoothing?`linear`:`nearest`,this.imageTileTextures.push(t);let n=new a.Sprite(t);n.x=e.x,n.y=e.y,n.width=e.width,n.height=e.height,this.bgLayer.addChild(n)}this.applySpriteFilter(),o()},s.onerror=()=>{i&&URL.revokeObjectURL(i),this.imageWidth||=t?.width??800,this.imageHeight||=t?.height??600,o()},s.src=i??e})}setFilter(e,t){this.brightness=e,this.contrast=t,this.applySpriteFilter()}setStrokeSize(e){this.strokeSize!==e&&(this.strokeSize=e,this.setShapes(this.shapes,this.selected))}applySpriteFilter(){if(!(this.destroyed||!this.app.renderer)){if(!(this.brightness!==1||this.contrast!==1)){this.filter.reset(),this.bgLayer.filters=void 0;return}this.filter.brightness(this.brightness,!1),this.filter.contrast(this.contrast-1,!0),this.bgLayer.filters=[this.filter]}}clearImage(){this.destroyed||(this.imageLoadToken++,this.clearImageTiles())}clearImageTiles(){for(let e of this.bgLayer.removeChildren())e.destroy();for(let e of this.imageTileTextures)e.destroy(!0);this.imageTileTextures=[]}setImageSmoothing(e){if(this.imageSmoothing===e)return;this.imageSmoothing=e;let t=e?`linear`:`nearest`;for(let e of this.imageTileTextures)e.source.scaleMode=t,e.source.style.update();!this.destroyed&&this.app.renderer&&this.app.render()}setOverlays(e,t,n){for(let e of this.overlayLayer.removeChildren())e.destroy();this.regionOutlineG=null,this.region=t;for(let e of this.overlayTextures)e.destroy(!0);if(this.overlayTextures=[],e){let t=a.Texture.from(e);t.source.scaleMode=`nearest`,this.overlayTextures.push(t);let n=new a.Sprite(t);n.alpha=.55,this.overlayLayer.addChild(n)}if(t){let e=Q(t.dim.color),n=()=>{let e=new a.Graphics;for(let n of t.rects)e.rect(n.x,n.y,n.w,n.h).fill(16777215);return e},r=new a.Graphics().rect(0,0,this.imageWidth,this.imageHeight).fill({color:e,alpha:t.dim.opacity}),i=n();if(this.overlayLayer.addChild(i,r),r.setMask({mask:i,inverse:!0}),t.zones.length){let r=new a.Graphics;for(let n of t.zones)r.poly(n.points.flatMap(e=>[e.x,e.y]),!0).fill({color:e,alpha:t.dim.opacity});let i=n();this.overlayLayer.addChild(i,r),r.setMask({mask:i})}t.outlineStyles&&(this.regionOutlineG=this.overlayLayer.addChild(new a.Graphics),this.redrawRegionOutline())}n&&this.imageWidth&&this.overlayLayer.addChild(new a.Graphics().rect(0,0,this.imageWidth,this.imageHeight).fill({color:855314,alpha:.3})),!this.destroyed&&this.app.renderer&&this.app.render()}get viewport(){return{scale:this.world.scale.x,x:this.world.x,y:this.world.y}}applyViewport(e){let t=e.scale!==this.lastAppliedScale;this.lastAppliedScale=e.scale,this.world.scale.set(e.scale),this.world.position.set(e.x,e.y),this.world.visible=!0,t&&this.restrokeShapes(),this.activeDrag?this.dragTransform(this.lastDragImg??Ht(this.shapes,this.activeDrag)):this.drawTransformer(),this.cb.onViewportChange?.()}fit(){if(!this.imageWidth||!this.imageHeight)return;let{w:e,h:t}=this.screenSize,n=Math.min(e/this.imageWidth,t/this.imageHeight);this.applyViewport({scale:n,x:(e-this.imageWidth*n)/2,y:(t-this.imageHeight*n)/2})}zoom100(){if(!this.imageWidth||!this.imageHeight)return;let{w:e,h:t}=this.screenSize;this.applyViewport({scale:1,x:(e-this.imageWidth)/2,y:(t-this.imageHeight)/2})}zoomAt(e,t,n,r=.05,i=20){let a=this.world.scale.x,o=Math.min(i,Math.max(r,a*n)),s=(e-this.world.x)/a,c=(t-this.world.y)/a;this.applyViewport({scale:o,x:e-s*o,y:t-c*o})}panBy(e,t){this.applyViewport({scale:this.world.scale.x,x:this.world.x+e,y:this.world.y+t})}setShapes(e,t){this.shapes=Wt(e),this.selected=t,!this.activeDrag&&(this.drawShapes(),this.drawSelectionBorders(),this.drawTransformer())}setSelection(e){this.selected=e,(e.length!==1||e[0]!==this.vertexPolygonId)&&(this.vertexPolygonId=null,this.selectedVertices.clear()),this.editingId&&(e.length!==1||e[0]!==this.editingId)&&(this.editingId=null),!this.activeDrag&&(this.drawSelectionBorders(),this.drawTransformer())}setEditing(e){this.editingId!==e&&(this.editingId=e,this.selectedVertices.clear(),this.activeDrag||this.drawTransformer())}setTransformEnabled(e){this.transformEnabled=e,this.syncShapeCursors(),this.drawTransformer()}setPanMode(e){this.handleLayer.interactiveChildren=!e}strokeW(e){return(e?le(e,{strokeWidth:this.strokeSize}).strokeWidth:nn)/this.world.scale.x}pointRadius(e){return qt(e,this.strokeSize,this.world.scale.x)}dashForShape(e){let t=le(e,{strokeWidth:this.strokeSize}).dash;if(!t?.length)return null;let n=this.world.scale.x||1;return[t[0]/n,(t[1]??t[0])/n]}drawShapes(){this.shapeLayer.removeChildren();for(let e of this.nodes.values())e.destroy();this.nodes.clear();for(let e of f(this.shapes).filter(s)){let t=new a.Graphics;this.paintShape(t,e),t.eventMode=l(e)?`static`:`none`,t.cursor=void 0,l(e)&&d(e)&&(t.on(`pointerover`,()=>{!this.activeDrag&&this.transformEnabled&&this.emitCursorHint(`grab`)}),t.on(`pointerout`,()=>{this.activeDrag||this.emitCursorHint(null)})),t.on(`pointerdown`,t=>{t.stopPropagation(),this.cb.onPointerDown(this.toImage(t),e.id,this.ev(t))}),this.shapeLayer.addChild(t),this.nodes.set(e.id,t)}}paintShape(e,t){e.clear();let n=le(t,{strokeWidth:this.strokeSize}),r=Q(n.color),i=this.strokeW(t),a=n.opacity,s=this.dashForShape(t);if(t.type===o.POINT){e.svg(Rt(n.color)),e.position.set(t.points[0].x,t.points[0].y),e.pivot.set(16/2,22);let r=1/(this.world.scale.x||1);e.scale.set(r,r),e.alpha=a;return}if(n.fillVisible&&t.type!==o.LINE?(this.path(e,t),e.fill({color:r,alpha:n.fillAlpha*a})):t.type!==o.LINE&&(this.path(e,t),e.fill({color:r,alpha:0})),s){t.style?.alternateColor&&(this.path(e,t),e.stroke({width:i,color:Q(t.style.alternateColor),alpha:a})),this.dashedStrokeShape(e,t,i,r,a,s);return}this.path(e,t),e.stroke({width:i,color:r,alpha:a})}liveUpdateShape(e,t){let n=this.nodes.get(e),r=this.shapes.find(t=>t.id===e);n&&r&&this.paintShape(n,{...r,points:t})}shapesIntersecting(e){return Kt(this.shapes,e)}shapesAt(e){return this.shapes.filter(t=>{let n=h(t.points);return e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY}).map(e=>e.id)}repaintPreview(){let e=this.lastPreview;e&&(e.kind===`poly`?this.previewPoly(e.points,e.cursor,e.style,e.closed,e.selectedPointIndices,e.showVertices):this.previewBox(e.boxKind,e.a,e.b,e.style))}ensurePreview(){this.previewReady||=(this.previewLayer.addChild(this.previewG,this.marqueeG),!0)}clearPreview(){this.lastPreview=null,this.previewG.clear(),this.previewMaskSprite&&(this.previewMaskSprite.visible=!1)}clearMarquee(){this.marqueeG.clear()}previewBox(e,t,n,r){this.lastPreview={kind:`box`,boxKind:e,a:t,b:n,style:r},this.ensurePreview(),this.previewG.clear();let i={id:`__preview__`,type:e===`ellipse`?o.ELLIPSE:o.RECTANGLE,points:[t,n],style:r},a=this.strokeW(i);r.alternateColor&&(this.path(this.previewG,i),this.previewG.stroke({width:a,color:Q(r.alternateColor)}));let s=this.dashForShape(i);if(s){this.dashedStrokeShape(this.previewG,i,a,Q(r.color??`#00e5ff`),r.opacity??1,s);return}this.path(this.previewG,i),this.previewG.stroke({width:a,color:Q(r.color??`#00e5ff`),alpha:r.opacity??1})}previewPoly(e,t,n,r,i=[],a=!0){if(this.lastPreview={kind:`poly`,points:e,cursor:t,style:n,closed:r,selectedPointIndices:i,showVertices:a},this.ensurePreview(),this.previewG.clear(),!e.length)return;let s=t?[...e,t]:e,c={id:`__preview__`,type:r?o.POLYGON:o.LINE,points:s,style:n},l=this.strokeW(c);n.alternateColor&&(this.path(this.previewG,c),this.previewG.stroke({width:l,color:Q(n.alternateColor)}));let u=this.dashForShape(c);if(u?this.dashedStrokeShape(this.previewG,c,l,Q(n.color??`#00e5ff`),n.opacity??1,u):(this.path(this.previewG,c),this.previewG.stroke({width:l,color:Q(n.color??`#00e5ff`),alpha:n.opacity??1})),!a)return;let d=new Set(i),f=5/this.world.scale.x,p=6/this.world.scale.x;for(let t=0;t<e.length;t++){let n=e[t],r=d.has(t);this.previewG.circle(n.x,n.y,r?p:f).fill({color:r?2001125:16777215}).stroke({width:1.5/this.world.scale.x,color:r?16777215:2001125})}}previewScalarMask(e,t){this.lastPreview=null,this.ensurePreview(),this.previewG.clear();let n=dt(e,t.length===7?`${t}99`:t);this.previewMaskTexture&&this.previewMaskTexture.destroy(!0),this.previewMaskTexture=a.Texture.from(n),this.previewMaskSprite?(this.previewMaskSprite.texture=this.previewMaskTexture,this.previewMaskSprite.visible=!0):(this.previewMaskSprite=new a.Sprite(this.previewMaskTexture),this.previewLayer.addChildAt(this.previewMaskSprite,0)),this.previewMaskSprite.x=e.ox,this.previewMaskSprite.y=e.oy,this.previewMaskSprite.width=n.width/e.scale,this.previewMaskSprite.height=n.height/e.scale}previewMarquee(e,t){this.ensurePreview(),this.marqueeG.clear();let n=Math.min(e.x,t.x),r=Math.min(e.y,t.y),i=Math.abs(t.x-e.x),a=Math.abs(t.y-e.y),o=Q(oe);this.marqueeG.rect(n,r,i,a).fill({color:o,alpha:H}).stroke({width:1/this.world.scale.x,color:o})}restrokeShapes(){if(!this.nodes.size)this.shapes.length&&this.drawShapes();else{let e=new Map(this.shapes.map(e=>[e.id,e]));for(let[t,n]of this.nodes){let r=e.get(t);r&&this.paintShape(n,r)}}this.drawSelectionBorders(),this.redrawRegionOutline(),this.repaintPreview()}redrawRegionOutline(){let e=this.regionOutlineG;if(!e)return;e.clear();let t=this.region?.outlineStyles;if(!this.region||!t)return;let n=this.world.scale.x||1,r=(t,r)=>{let i=r.width/n,a=[r.dash[0]/n,r.dash[1]/n];for(let[n,o]of t)r.underlayColor&&e.poly([n.x,n.y,o.x,o.y],!1).stroke({width:i,color:Q(r.underlayColor)}),this.strokeDashedPolyline(e,[n,o],!1,i,Q(r.color),r.opacity,a)};r(this.region.visibleOutline,t.visible),r(this.region.occludedOutline,t.occluded)}path(e,t){let{type:n,points:r}=t;if(n===o.POINT){e.circle(r[0].x,r[0].y,this.pointRadius(t));return}if(n===o.RECTANGLE){let t=h(r);e.rect(t.minX,t.minY,t.maxX-t.minX,t.maxY-t.minY);return}if(n===o.ELLIPSE){let t=h(r);e.ellipse((t.minX+t.maxX)/2,(t.minY+t.maxY)/2,(t.maxX-t.minX)/2,(t.maxY-t.minY)/2);return}let i=r.flatMap(e=>[e.x,e.y]);e.poly(i,n!==o.LINE)}dashedStrokeShape(e,t,n,r,i,a){let{type:s,points:c}=t;if(s===o.RECTANGLE){let t=h(c);this.strokeDashedPolyline(e,[{x:t.minX,y:t.minY},{x:t.maxX,y:t.minY},{x:t.maxX,y:t.maxY},{x:t.minX,y:t.maxY}],!0,n,r,i,a);return}if(s===o.ELLIPSE){let t=h(c),o=(t.minX+t.maxX)/2,s=(t.minY+t.maxY)/2,l=(t.maxX-t.minX)/2,u=(t.maxY-t.minY)/2,d=Array.from({length:96},(e,t)=>{let n=t/96*Math.PI*2;return{x:o+Math.cos(n)*l,y:s+Math.sin(n)*u}});this.strokeDashedPolyline(e,d,!0,n,r,i,a);return}this.strokeDashedPolyline(e,c,s!==o.LINE,n,r,i,a)}strokeDashedPolyline(e,t,n,r,i,a,o){if(t.length<2)return;let[s,c]=o,l=!0,u=0,d=n?t.length:t.length-1;for(let n=0;n<d;n++){let o=t[n],d=t[(n+1)%t.length],f=d.x-o.x,p=d.y-o.y,m=Math.hypot(f,p);if(!m)continue;let h=0;for(;h<m;){let t=l?s:c,n=Math.min(t-u,m-h);if(l){let t=h/m,s=(h+n)/m;e.moveTo(o.x+f*t,o.y+p*t).lineTo(o.x+f*s,o.y+p*s).stroke({width:r,color:i,alpha:a})}h+=n,u+=n,u>=t-1e-4&&(u=0,l=!l)}}}drawSelectionBorders(){this.selLayer.position.set(0,0);let e=new Set(this.selected),t=this.selected.length?this.shapes.filter(t=>e.has(t.id)&&l(t)):[];if(this.selectionBorderGfx.length!==t.length){for(let e of this.selectionBorderGfx)e.destroy();this.selectionBorderGfx=t.map(()=>{let e=new a.Graphics;return this.selLayer.addChild(e),e})}let n=1.5/this.world.scale.x;t.forEach((e,t)=>{let r=this.selectionBorderGfx[t];r.clear(),r.poly(this.selectionOutlinePoints(e,e.points).flatMap(e=>[e.x,e.y]),!0).stroke({width:n,color:an})})}updateSelectionBordersLive(e){let t=new Set(this.selected),n=1.5/this.world.scale.x,r=0;for(let i of this.shapes){if(!t.has(i.id)||!l(i))continue;let a=this.selectionBorderGfx[r++];a&&(a.clear(),a.poly(this.selectionOutlinePoints(i,e(i)).flatMap(e=>[e.x,e.y]),!0).stroke({width:n,color:an}))}}selectionOutlinePoints(e,t){return Yt(e,t,this.pointRadius(e))}imgToScreen(e){let t=this.world.toGlobal({x:e.x,y:e.y});return{x:t.x,y:t.y}}setTransformerOutline(e){let t=e.maxX-e.minX,n=e.maxY-e.minY;t<=0&&n<=0||this.setTransformerOutlinePoints(b([{x:e.minX,y:e.minY},{x:e.maxX,y:e.maxY}]))}setTransformerOutlinePoints(e){e.length<2||(this.transformerOutline||(this.transformerOutline=new a.Graphics,this.selLayer.addChild(this.transformerOutline)),this.transformerOutline.clear(),this.transformerOutline.poly(e.flatMap(e=>[e.x,e.y]),!0).stroke({width:1/this.world.scale.x,color:2001125}))}rotationHandleGap(){return Xt(this.viewport.scale)}rotationHandleScreenPoint(e){return this.imgToScreen(j(e,this.rotationHandleGap()))}setRotationConnector(e){let t=this.imgToScreen(O(e[0],e[1])),n=this.rotationHandleScreenPoint(e);this.rotLineNode||(this.rotLineNode=new a.Graphics,this.rotLineNode.eventMode=`none`,this.handleLayer.addChild(this.rotLineNode)),this.rotLineNode.clear(),this.rotLineNode.moveTo(t.x,t.y).lineTo(n.x,n.y).stroke({width:1,color:2001125})}layoutResizeHandle(e,t,n){e.position.set(t.x,t.y),e.rotation=n}orientedHandleAngle(e){return Zt(this.imgToScreen(e[0]),this.imgToScreen(e[1]))}drawTransformer(){if(this.activeDrag)return;for(let e of this.handleNodes)e.destroy();for(let e of this.vertexNodes)e.destroy();for(let e of this.midNodes)e.destroy();if(this.rotNode?.destroy(),this.rotNode=null,this.rotLineNode?.destroy(),this.rotLineNode=null,this.transformerOutline?.destroy(),this.transformerOutline=null,this.handleNodes=[],this.vertexNodes=[],this.midNodes=[],!this.transformEnabled)return;let e=Gt(this.shapes,this.selected);if(e.length===0||e.length===1&&e[0].type===o.POINT)return;let t=e.length===1&&(e[0].type===o.POLYGON||e[0].type===o.LINE)&&this.editingId===e[0].id?e[0]:null,n=h(e.flatMap(e=>e.points)),r=e.length===1&&e[0].type===o.ROTATED_RECTANGLE?e[0]:null,i=r?A(r.points):m.map(e=>g(e,n));r?this.setTransformerOutlinePoints(r.points):this.setTransformerOutline(n),r&&this.setRotationConnector(r.points);let s=r?this.orientedHandleAngle(r.points):0;for(let e of t?[]:m){let t=this.imgToScreen(i[m.indexOf(e)]),n=new a.Graphics;n.rect(-4,-4,8,8).fill({color:16777215}).stroke({width:1,color:2001125}),this.layoutResizeHandle(n,t,s),n.eventMode=`static`;let r=De(e,s);this.bindCursor(n,r),n.on(`pointerdown`,t=>{t.stopPropagation(),this.emitCursorHint(r),this.emitInteractionMode(`resizing`);let n=Gt(this.shapes,this.selected);this.activeDrag={kind:`resize`,anchor:e,box:h(n.flatMap(e=>e.points)),shapes:n.map(e=>({id:e.id,points:e.points}))},this.lastDragImg=null}),this.handleLayer.addChild(n),this.handleNodes.push(n)}if(t){let e=t,n=e.points,r=e.type===o.POLYGON?n.length:n.length-1;for(let t=0;t<r;t++){let r=n[t],i=n[(t+1)%n.length],o={x:(r.x+i.x)/2,y:(r.y+i.y)/2},s=this.imgToScreen(o),c=new a.Graphics;c.circle(0,0,4).fill({color:16777215,alpha:.6}).stroke({width:1,color:2001125}),c.position.set(s.x,s.y),c.eventMode=`static`,this.bindCursor(c,`copy`),c.on(`pointerdown`,r=>{r.stopPropagation();let i=[...n.slice(0,t+1),o,...n.slice(t+1)];this.cb.onTransformCommit?.([{id:e.id,points:i}])}),this.handleLayer.addChild(c),this.midNodes.push(c)}this.vertexPolygonId!==e.id&&(this.vertexPolygonId=e.id,this.selectedVertices.clear()),n.forEach((t,r)=>{let i=this.imgToScreen(t),o=this.selectedVertices.has(r),s=new a.Graphics;s.circle(0,0,5).fill({color:o?2001125:16777215}).stroke({width:1.5,color:o?16777215:2001125}),s.position.set(i.x,i.y),s.eventMode=`static`,this.bindCursor(s,`pointer`),s.on(`pointerdown`,t=>{if(t.stopPropagation(),t.shiftKey||t.ctrlKey||t.metaKey){this.selectedVertices.has(r)?this.selectedVertices.delete(r):this.selectedVertices.add(r),this.drawTransformer();return}let i=this.selectedVertices.has(r)&&this.selectedVertices.size>1?[...this.selectedVertices]:[r];i.length===1&&(this.selectedVertices.clear(),this.selectedVertices.add(r)),this.activeDrag={kind:`vertex`,id:e.id,indices:i,base:n,start:this.toImage(t)},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`vertexDragging`)}),this.handleLayer.addChild(s),this.vertexNodes.push(s)})}if(e.length===1&&e[0].type===o.ROTATED_RECTANGLE){let t=e[0],n=k(t.points),r=this.rotationHandleScreenPoint(t.points),i=new a.Graphics;i.circle(0,0,6).fill({color:16777215}).stroke({width:1.5,color:2001125}),i.position.set(r.x,r.y),i.eventMode=`static`,this.bindCursor(i,`grab`),i.on(`pointerdown`,e=>{e.stopPropagation();let r=this.toImage(e);this.activeDrag={kind:`rotate`,id:t.id,center:n,startAngle:Math.atan2(r.y-n.y,r.x-n.x),points:t.points,shiftKey:e.shiftKey},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`rotating`)}),this.handleLayer.addChild(i),this.rotNode=i}}beginMove(e,t){let n=Ut(this.shapes,t,e);n&&(this.transformEnabled&&!this.handleNodes.length&&this.drawTransformer(),this.activeDrag=n,this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`moving`),(n.shapes.length===1?this.shapes.find(e=>e.id===n.shapes[0].id):null)?.type===o.ROTATED_RECTANGLE?this.setTransformerOutlinePoints(n.shapes[0].points):this.setTransformerOutline(n.box),this.updateSelectionBordersLive(e=>e.points))}repositionHandlesForBox(e){m.forEach((t,n)=>{let r=this.imgToScreen(g(t,e)),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,0)}),this.setTransformerOutline(e)}repositionOrientedHandles(e){let t=this.orientedHandleAngle(e);if(A(e).forEach((e,n)=>{let r=this.imgToScreen(e),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,t)}),this.setTransformerOutlinePoints(e),this.rotNode){let t=this.rotationHandleScreenPoint(e);this.rotNode.position.set(t.x,t.y)}this.rotLineNode&&this.setRotationConnector(e)}repositionPolygonHandles(e,t){if(!this.vertexNodes.length)return;e.forEach((e,t)=>{let n=this.imgToScreen(e);this.vertexNodes[t]?.position.set(n.x,n.y)});let n=t?e.length:e.length-1;for(let t=0;t<n;t++){let n=e[t],r=e[(t+1)%e.length],i=this.imgToScreen({x:(n.x+r.x)/2,y:(n.y+r.y)/2});this.midNodes[t]?.position.set(i.x,i.y)}}resetMoveOffsets(){for(let[e,t]of this.nodes)this.shapes.find(t=>t.id===e)?.type!==o.POINT&&t.position.set(0,0);this.selLayer.position.set(0,0)}commitTransformUpdates(e){if(e.length){for(let t of e){let e=this.shapes.find(e=>e.id===t.id);if(!e)continue;e.points=t.points;let n=this.nodes.get(t.id);n&&this.paintShape(n,{...e,points:t.points})}this.cb.onTransformCommit?.(e),this.drawTransformer()}}dragTransform(e){let t=this.activeDrag;if(!t)return;this.applyCursor();let n=Bt(this.shapes,t),{updates:r,box:i}=Vt(t,e,n);if(t.kind===`move`){let n=e.x-t.start.x,r=e.y-t.start.y;for(let e of t.shapes){let t=this.nodes.get(e.id);t&&(this.shapes.find(t=>t.id===e.id)?.type===o.POINT?t.position.set(e.points[0].x+n,e.points[0].y+r):t.position.set(n,r))}}else for(let e of r)this.liveUpdateShape(e.id,e.points);if(this.cb.onTransformPreview?.(r),this.updateSelectionBordersLive(e=>r.find(t=>t.id===e.id)?.points??e.points),t.kind===`resize`||t.kind===`move`){n?this.repositionOrientedHandles(r[0].points):i&&this.repositionHandlesForBox(i);let e=t.shapes.length===1?this.shapes.find(e=>e.id===t.shapes[0].id):null,a=e?.type===o.POLYGON||e?.type===o.LINE;(t.kind===`resize`?a:this.vertexNodes.length>0&&t.shapes.length===1)&&this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}else if(t.kind===`rotate`){this.repositionOrientedHandles(r[0].points);let e=this.shapes.find(e=>e.id===t.id);e&&(e.type===o.POLYGON||e.type===o.LINE)&&this.repositionPolygonHandles(r[0].points,e.type===o.POLYGON)}else{i&&this.repositionHandlesForBox(i);let e=this.shapes.find(e=>e.id===t.id);this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}}endTransform(){let e=this.activeDrag,t=this.lastDragImg;if(this.activeDrag=null,this.emitInteractionMode(`idle`),this.emitCursorHint(e?.kind===`move`?`grab`:null),!e||!t){this.cb.onTransformPreview?.([]),this.drawTransformer();return}if(e.kind===`move`&&t.x===e.start.x&&t.y===e.start.y){this.cb.onTransformPreview?.([]),this.drawTransformer();return}let{updates:n}=Vt(e,t,Bt(this.shapes,e));e.kind===`move`&&this.resetMoveOffsets(),this.commitTransformUpdates(n)}};function sn({backend:e,hostRef:t,engineRef:r,imageUrl:i,renderedImageUrl:a,makeCallbacks:o,viewRef:s,readOnlyRef:c,toolRef:l,renderShapesRef:u,coordinateSizeRef:d,imageSizeRef:f,selRef:p,maskCanvasRef:m,regionOverlayRef:h,dimmedRef:g,syncMinimap:_,setImage:v,setImageVisible:y,setReady:b,setImageStatus:x,onContextMenuRequest:S}){let C=(0,n.useRef)(a);C.current=a;let w=(0,n.useRef)(i);w.current=i;let T=(0,n.useRef)(null),E=(0,n.useRef)(null),D=(0,n.useRef)(!1),O=(0,n.useRef)(null),k=(0,n.useRef)(o);k.current=o;let A=(0,n.useRef)(S);A.current=S,(0,n.useEffect)(()=>{let n=t.current;if(!n)return;let i=!1,a=null,o=null,x=k.current(),S=e===`konva`?new tn(n,x):new on(n,x);return r.current=S,(async()=>{if(await S.init(),!i){if(S.setFilter(s.current.brightness,s.current.contrast),S.setStrokeSize(s.current.strokeSize),S.setImageSmoothing(s.current.imageSmoothing),S.setTransformEnabled(!c.current),D.current=!0,C.current){if(await S.setImage(C.current,d.current,f.current),i)return;T.current=C.current,E.current=w.current,v({w:S.imageWidth,h:S.imageHeight}),y(!0),S.setShapes(u.current,p.current),S.setOverlays(s.current.showGuide?m.current:null,s.current.showRegionMask?h.current:null,g.current);let e=O.current;e?.viewport&&(e.imageUrl===T.current||s.current.keepZoomOnImageChange)?S.applyViewport(e.viewport):S.fit(),_(),b(!0)}a=e=>{e.preventDefault();let t=S.dom.getBoundingClientRect();if(e.ctrlKey||e.metaKey){S.zoomAt(e.clientX-t.left,e.clientY-t.top,Math.exp(-e.deltaY*.01));return}if(!s.current.wheelZoom){let t=S.viewport;S.applyViewport({scale:t.scale,x:t.x-e.deltaX,y:t.y-e.deltaY});return}S.zoomAt(e.clientX-t.left,e.clientY-t.top,e.deltaY<0?1.1:1/1.1)},S.dom.addEventListener(`wheel`,a,{passive:!1}),o=e=>{if(e.preventDefault(),l.current===L.ASSISTANT_POINT&&e.altKey)return;let t=n.getBoundingClientRect(),r=e.clientX-t.left,i=e.clientY-t.top,a=S.viewport;A.current({x:r,y:i,img:{x:(r-a.x)/a.scale,y:(i-a.y)/a.scale}})},S.dom.addEventListener(`contextmenu`,o)}})(),()=>{i=!0,D.current=!1,O.current={imageUrl:T.current??``,viewport:S.viewport},r.current=null,a&&S.dom&&S.dom.removeEventListener(`wheel`,a),o&&S.dom&&S.dom.removeEventListener(`contextmenu`,o),S.destroy()}},[e]),(0,n.useEffect)(()=>{let e=r.current;if(!e||!D.current||!a||T.current===a)return;let t=a,n=E.current!==i;n&&(e.clearImage(),e.setShapes([],[]),e.setOverlays(null,null,!1),y(!1));let o=!1;return(async()=>{await e.setImage(t,d.current,f.current),!(o||r.current!==e)&&(T.current=t,n&&(E.current=i,v({w:e.imageWidth,h:e.imageHeight}),y(!0),e.setShapes(u.current,p.current),e.setOverlays(s.current.showGuide?m.current:null,s.current.showRegionMask?h.current:null,g.current),s.current.keepZoomOnImageChange||e.fit(),_(),b(!0)))})(),()=>{o=!0}},[a]),(0,n.useEffect)(()=>{let e=!1;if(!a){x(`loading`);return}x(`loading`);let t=new Image;return t.onload=()=>{e||x(`ready`)},t.onerror=()=>{e||x(`error`)},t.src=a,()=>{e=!0}},[a])}var cn=.05,ln=20;function un(e){let{deltaY:t,deltaX:n,deltaMode:r}=e;return r===0?Math.abs(t)<10||Math.abs(n)<10||!Number.isInteger(t)||!Number.isInteger(n):r===1?!1:!Number.isInteger(t)||!Number.isInteger(n)}function dn({engineRef:e,image:t,wheelZoom:r,minimapSize:i}){let a=(0,n.useRef)(null),o=!!t&&t.w>0&&t.h>0,s=o?Math.min(i/t.w,i/t.h):1,c=o?t.w*s:0,l=o?t.h*s:0,u=o?(i-c)/2:0,d=o?(i-l)/2:0,f=e=>{let t=e.currentTarget.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}},p=()=>{let t=e.current;if(!t)return null;let n=t.viewport;return{x:-n.x/n.scale*s+u,y:-n.y/n.scale*s+d,width:t.screenSize.w/n.scale*s,height:t.screenSize.h/n.scale*s}},m=(n,r,i)=>{let a=e.current;if(!a||!t)return;let o=p();if(!o)return;let c=i?.offsetX??o.width/2,l=i?.offsetY??o.height/2,f=n.x-c+o.width/2,m=n.y-l+o.height/2,h=(f-u)/s,g=(m-d)/s;a.applyViewport({scale:r,x:a.screenSize.w/2-h*r,y:a.screenSize.h/2-g*r})};return{mm:s,offX:u,offY:d,dispW:c,dispH:l,handleMinimapPointerDown:t=>{let n=e.current,r=p();if(!n||!r)return;t.preventDefault(),t.stopPropagation();let i=f(t),o=i.x>=r.x&&i.x<=r.x+r.width&&i.y>=r.y&&i.y<=r.y+r.height?{offsetX:i.x-r.x,offsetY:i.y-r.y}:{offsetX:r.width/2,offsetY:r.height/2};a.current={pointerId:t.pointerId,...o},t.currentTarget.setPointerCapture(t.pointerId),m(i,n.viewport.scale,o)},handleMinimapPointerMove:t=>{let n=a.current,r=e.current;!n||!r||n.pointerId!==t.pointerId||(t.preventDefault(),t.stopPropagation(),m(f(t),r.viewport.scale,n))},endMinimapDrag:e=>{let t=a.current;!t||t.pointerId!==e.pointerId||(a.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))},handleMinimapWheel:t=>{let n=e.current;if(!n||!r)return;t.preventDefault(),t.stopPropagation();let i=un(t.nativeEvent)?2.5:1,a=t.deltaY*i,o=1.05,s=a>0?n.viewport.scale/o:n.viewport.scale*o,c=Math.max(cn,Math.min(ln,s));m(f(t),c)},zoomCentered:t=>{let n=e.current;if(!n)return;let{w:r,h:i}=n.screenSize;n.zoomAt(r/2,i/2,t)}}}function fn(e,t,n){if(!(!e||!n.length)){if(t.type===o.POINT){e.setAttribute(`cx`,String(n[0].x)),e.setAttribute(`cy`,String(n[0].y));return}if(t.type===o.RECTANGLE||t.type===o.ELLIPSE){let r=h(n);if(t.type===o.ELLIPSE){e.setAttribute(`cx`,String((r.minX+r.maxX)/2)),e.setAttribute(`cy`,String((r.minY+r.maxY)/2)),e.setAttribute(`rx`,String((r.maxX-r.minX)/2)),e.setAttribute(`ry`,String((r.maxY-r.minY)/2));return}e.setAttribute(`x`,String(r.minX)),e.setAttribute(`y`,String(r.minY)),e.setAttribute(`width`,String(r.maxX-r.minX)),e.setAttribute(`height`,String(r.maxY-r.minY));return}e.setAttribute(`points`,n.map(e=>`${e.x},${e.y}`).join(` `))}}function pn({engineRef:e,docRef:t,overlayRef:r,zoomLabelRef:i,minimapRectRef:a,minimapSize:o,onViewportChangeRef:s}){let c=(0,n.useRef)(new Map);return{registerMinimapShape:(0,n.useCallback)((e,t)=>{t?c.current.set(e,t):c.current.delete(e)},[]),applyMinimapPreview:(0,n.useCallback)(e=>{let n=t.current.getShapes();if(!e.length){for(let e of n)fn(c.current.get(e.id),e,e.points);return}let r=new Map(n.map(e=>[e.id,e]));for(let t of e){let e=r.get(t.id);e&&fn(c.current.get(e.id),e,t.points)}},[t]),syncMinimap:(0,n.useCallback)(()=>{let t=e.current;if(!t?.imageWidth)return;let n=t.viewport;if(s.current?.(n),r.current){r.current.style.transform=`translate(${n.x}px, ${n.y}px) scale(${n.scale})`;let e=1/(n.scale||1);r.current.style.setProperty(`--editor-overlay-stroke`,`${e}`),r.current.style.setProperty(`--editor-overlay-dash`,`${4*e}`),r.current.style.setProperty(`--editor-overlay-inverse-scale`,`${e}`)}i.current&&(i.current.textContent=`${Math.round(n.scale*100)}%`);let c=a.current;if(!c)return;let l=Math.min(o/t.imageWidth,o/t.imageHeight),u=(o-t.imageWidth*l)/2,d=(o-t.imageHeight*l)/2,{w:f,h:p}=t.screenSize;c.style.left=`${-n.x/n.scale*l+u}px`,c.style.top=`${-n.y/n.scale*l+d}px`,c.style.width=`${f/n.scale*l}px`,c.style.height=`${p/n.scale*l}px`},[e,r,i,a,o,s])}}var mn=12;function hn({doc:e,selRef:t,effectiveReadOnly:r,changeSelection:i,canMergeSelection:a}){let s=(0,n.useRef)([]),c=(0,n.useRef)(0),d=(0,n.useCallback)(()=>i(e.getShapes().filter(e=>l(e)).map(e=>e.id)),[e,i]),f=(0,n.useCallback)(()=>i([]),[i]),m=(0,n.useCallback)(()=>e.getShapes().filter(e=>t.current.includes(e.id)&&u(e)),[e,t]),h=(0,n.useCallback)(()=>{if(r||!t.current.length)return;let n=m().map(e=>e.id);n.length&&(e.remove(n),i([]))},[e,r,i,m,t]),g=(0,n.useCallback)(()=>{s.current=m(),c.current=0},[m]),_=(0,n.useCallback)(()=>s.current.length>0,[]),v=(0,n.useCallback)(()=>{if(r||!s.current.length)return;c.current+=1;let t=mn*c.current,n=s.current.map(e=>({...e,id:p(),points:e.points.map(e=>({x:e.x+t,y:e.y+t}))}));e.create(n),i(n.map(e=>e.id))},[e,r,i]),y=(0,n.useCallback)(()=>{if(r||!t.current.length)return;let n=m().map(e=>({...e,id:p(),points:e.points.map(e=>({x:e.x+mn,y:e.y+mn}))}));n.length&&(e.create(n),i(n.map(e=>e.id)))},[e,r,i,m,t]),b=(0,n.useCallback)(()=>{if(r)return;let t=m().map(e=>e.id);t.length&&e.reorder(t,`front`)},[e,r,m]),x=(0,n.useCallback)(()=>{if(r)return;let t=m().map(e=>e.id);t.length&&e.reorder(t,`back`)},[e,r,m]),S=(0,n.useCallback)((n,i)=>{if(r||!t.current.length)return;let a=e.getShapes().filter(e=>t.current.includes(e.id)&&u(e));a.length&&e.update(a.map(e=>({...e,points:e.points.map(e=>({x:e.x+n,y:e.y+i}))})))},[e,r,t]),C=(0,n.useCallback)(()=>m().filter(e=>e.type===o.POLYGON||e.type===o.RECTANGLE||e.type===o.ROTATED_RECTANGLE||e.type===o.ELLIPSE),[m]);return{selectAll:d,clearSelection:f,getEditableSelection:m,deleteSelection:h,copySelection:g,canPaste:_,paste:v,duplicate:y,bringToFront:b,sendToBack:x,nudgeSelection:S,getMergeTargets:C,mergeSelection:(0,n.useCallback)(()=>{if(r)return;let t=C();if(t.length<2||a&&!a(t))return;let n=lt([],1,ct(t));if(!n)return;let s=ut(n,1);if(!s.length)return;let c=t[0],l=s.map(e=>({id:p(),type:o.POLYGON,points:e,style:c.style,meta:c.meta}));e.replace(t.map(e=>e.id),l),i(l.map(e=>e.id))},[e,r,C,a,i])}}function gn({engineRef:e,doc:t,selRef:r,zoomAnimationDuration:i,zoomBound:a,ready:o}){let s=(0,n.useRef)(null),c=(0,n.useRef)(null),l=(0,n.useCallback)(()=>{s.current?.(),s.current=null},[]),u=(0,n.useCallback)((t,n=i)=>{let r=e.current;r&&(l(),s.current=Xe(r.viewport,t,e=>r.applyViewport(e),n))},[l,i,e]),d=(0,n.useCallback)((t,n=i)=>{let r=e.current;if(!r)return;let a=Je(t,r.screenSize.w,r.screenSize.h);a&&u(a,n)},[u,i,e]),f=(0,n.useCallback)((e,n=i)=>{let r=qe(t.getShapes().filter(t=>e.includes(t.id)));r&&d(r,n)},[t,d,i]),p=(0,n.useCallback)(()=>{let n=t.getShapes().filter(e=>r.current.includes(e.id));if(!n.length)return;let i=e.current;if(!i)return;let a=Ye(h(n.flatMap(e=>e.points)),i.screenSize.w,i.screenSize.h,80);a&&u(a)},[t,u,e,r]),m=(0,n.useCallback)(t=>{let n=e.current;if(!n)return;let{w:r,h:i}=n.screenSize;n.zoomAt(r/2,i/2,t)},[e]);return(0,n.useEffect)(()=>()=>l(),[l]),(0,n.useEffect)(()=>{if(!a){c.current=null;return}if(!o)return;let t=e.current;if(!t?.imageWidth)return;let{w:n,h:r}=t.screenSize;if(!n||!r)return;let i=JSON.stringify(a);c.current!==i&&(d(a),c.current=i)},[a,o,d,e]),{cancelZoomAnimation:l,runViewportAnimation:u,zoomToBounds:d,zoomToShapes:f,zoomToSelection:p,zoomAtCenter:m}}var _n=180,vn=`__draft_preview__`;function yn(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function bn({imageUrl:t,displayImageUrl:i,coordinateSize:a,renderImageState:c,dimmed:d=!1,initialShapes:f,selectedIds:m,activeTool:g,draftStyle:_,draftMeta:v,readOnly:y,disableMarquee:b,locked:x,onLockedInteraction:S,onIdleEscape:C,overrideShapeInteraction:w,defaultViewSettings:T,viewSettings:E,onViewSettingsChange:D,showMinimap:O=!0,showViewSettings:k=!0,getContextMenuItems:A,strings:j,canMergeSelection:M,brushSize:N=20,zoomBound:P,zoomAnimationDuration:F=300,decorationShapes:ee,regionMask:te,guideMask:ne,maskPalette:re,overlayMarkers:z,renderOverlayMarker:oe,onOverlayMarkerClick:H,renderImageOverlay:se,getSelectionLabel:ce,hideSelectionLabelDot:le,formatSelectionInfo:ue,externalTools:de,assistant:fe,keymap:pe,handleRef:me,backend:he=`pixi`,onActiveToolChange:U,onSelectionChange:_e,onEditingChange:ve,onShapesCreated:ye,onShapesUpdated:Se,onShapesDeleted:we,onDrawSessionChange:Te,onDraftShapeChange:Ee,onViewportChange:De,onShapesTransformPreview:Oe}){let Ae=(0,n.useRef)(null),W=(0,n.useRef)(null),Me=(0,n.useRef)(null),Ne=(0,n.useRef)(null),Pe=(0,n.useRef)(null),Fe=`${(0,n.useId)()}-minimap`,[G,Ie]=(0,n.useState)(null),[Le,Re]=(0,n.useState)(!1),[K,ze]=(0,n.useState)(!1),[Be,He]=(0,n.useState)(null),[Ue,We]=(0,n.useState)({active:!1,kind:`none`,canUndo:!1,canRedo:!1}),[Ge,Ke]=(0,n.useState)(!0),[qe,Je]=(0,n.useState)(!1),Ye=i??t,[Xe,$e]=(0,n.useState)(`loading`),q=bt({onShapesCreated:ye,onShapesUpdated:Se,onShapesDeleted:we}),[et,tt]=(0,n.useState)([]),J=m??et,nt=m!==void 0,rt=(0,n.useMemo)(()=>new Map((de??[]).map(e=>[e.id,e])),[de]),it=(0,n.useRef)(rt);it.current=rt;let at=(0,n.useRef)(Ue);at.current=Ue;let[Y,ot]=(0,n.useState)(()=>{let e=Object.fromEntries(Object.entries(T??{}).filter(([,e])=>e!==void 0));return{...R,...e}}),st=(0,n.useCallback)(e=>ot(t=>({...t,...e})),[]),X=(0,n.useMemo)(()=>I(j),[j]);(0,n.useEffect)(()=>{E&&ot(e=>{let t=Object.entries(E).filter(([t,n])=>n!==void 0&&e[t]!==n);return t.length?{...e,...Object.fromEntries(t)}:e})},[E]);let ct=(0,n.useRef)(D);ct.current=D;let lt=(0,n.useRef)(!1);(0,n.useEffect)(()=>{if(!lt.current){lt.current=!0;return}ct.current?.(Y)},[Y]);let ut=(0,n.useMemo)(()=>!ne||!re?null:je(ne,re),[ne,re]),dt=(0,n.useMemo)(()=>ut?.toDataURL()??null,[ut]),ft=(0,n.useMemo)(()=>!G||!te?null:Ve(te,G.w,G.h),[G,te]),pt=(0,n.useRef)(ut);pt.current=ut;let mt=(0,n.useRef)(ft);mt.current=ft;let ht=(0,n.useRef)(d);ht.current=d;let gt=(0,n.useRef)(G);gt.current=G;let vt=(0,n.useRef)(a);vt.current=a;let yt=(0,n.useRef)(a?.imageSize);yt.current=a?.imageSize;let xt=(0,n.useRef)([]);xt.current=J;let St=(0,n.useRef)(g);St.current=g;let Ct=(0,n.useRef)(_);Ct.current=_;let wt=(0,n.useRef)(v);wt.current=v;let Tt=(0,n.useRef)(N);Tt.current=N;let Et=(0,n.useRef)(Y.simplifyStrength);Et.current=Y.simplifyStrength;let Z=!!y||!!x,Dt=(0,n.useRef)(Z);Dt.current=Z;let Ot=(0,n.useRef)(b);Ot.current=b;let At=(0,n.useRef)(x);At.current=x;let jt=(0,n.useRef)(S);jt.current=S;let Mt=(0,n.useRef)(w);Mt.current=w;let Nt=(0,n.useRef)(q);Nt.current=q;let Pt=(0,n.useRef)(!1),Ft=(0,n.useRef)(!1),It=(0,n.useRef)(`idle`),Lt=(0,n.useRef)(null),Rt=(0,n.useCallback)(()=>{let e=W.current;if(!e)return;let t=St.current,n=it.current.get(t),r=at.current;e.setCursor(ke({tool:t,externalToolCursor:n?.cursor,isSpacePressed:Pt.current,interactionMode:It.current,rendererCursorHint:Lt.current,isPolygonDrawing:r.kind===`polygon`&&r.active}))},[]),zt=(0,n.useCallback)(e=>{It.current!==e&&(It.current=e,Rt())},[Rt]),Bt=(0,n.useCallback)(e=>{Lt.current!==e&&(Lt.current=e,Rt())},[Rt]),Vt=(0,n.useCallback)(e=>{let t=new Set,n=new Map(Nt.current.getShapes().map(e=>[e.id,e]));return e.filter(e=>{if(t.has(e))return!1;t.add(e);let r=n.get(e);if(!r)return!1;let i=Mt.current?.(r);return l(i?{...r,interaction:{...r.interaction,...i}}:r)})},[]),Ht=(0,n.useCallback)(e=>{let t=Vt(e);yn(xt.current,t)||(nt||tt(t),W.current?.setSelection(t),_e?.(t))},[Vt,_e,nt]),Ut=(0,n.useRef)(Ht);Ut.current=Ht;let[Wt,Gt]=(0,n.useState)(null),Kt=(0,n.useCallback)(e=>Gt(e),[]),qt=(0,n.useRef)(Kt);qt.current=Kt,(0,n.useEffect)(()=>{if(!nt)return;let e=Vt(m);yn(m,e)||_e?.(e)},[m,q.shapes,Vt,_e,nt]);let Jt=(0,n.useRef)(De);Jt.current=De;let{registerMinimapShape:Yt,applyMinimapPreview:Xt,syncMinimap:Zt}=pn({engineRef:W,docRef:Nt,overlayRef:Ne,zoomLabelRef:Pe,minimapRectRef:Me,minimapSize:_n,onViewportChangeRef:Jt}),Qt=(0,n.useRef)(new Map),$t=(0,n.useRef)(ue);$t.current=ue;let en=(0,n.useCallback)((e,t)=>{t?Qt.current.set(e,t):Qt.current.delete(e)},[]),tn=(0,n.useRef)(null),[nn,rn]=(0,n.useState)(null),an=(0,n.useCallback)(e=>{if(!e.length)return;let t=new Map(Nt.current.getShapes().map(e=>[e.id,e]));tn.current&&t.set(tn.current.id,tn.current);for(let{id:n,points:r}of e){let e=Qt.current.get(n),i=t.get(n);if(!e||!i)continue;let a=h(r);e.style.left=`${a.minX}px`,e.style.top=`${a.minY}px`,e.style.width=`${a.maxX-a.minX}px`,e.style.height=`${a.maxY-a.minY}px`;let o=e.querySelector(`[data-selinfo-dim]`);if(o){let e=be(i,r);o.textContent=$t.current?.(e)??xe(e)}}},[]),Q=(0,n.useCallback)(e=>{Xt(e),an(e),Oe?.(e)},[Xt,an,Oe]),on=(0,n.useCallback)(e=>{if(Ee?.(e?{...e,meta:wt.current}:null),!e||!Ct.current){tn.current&&(tn.current=null,rn(null));return}let t={id:vn,type:e.type,points:e.points,style:Ct.current,meta:wt.current},n=tn.current!==null;tn.current=t,n?an([{id:vn,points:e.points}]):rn(t)},[an,Ee]),cn=(0,n.useCallback)((e,t)=>{let n=Ct.current;if(!n||Dt.current)return;let r=p();Nt.current.create({id:r,type:e,points:t,style:n,meta:v}),Ut.current([r])},[v]),ln=(0,n.useRef)(cn);ln.current=cn;let un=_t({toolRef:St,selRef:xt,docRef:Nt,readOnlyRef:Dt,draftRef:Ct,brushSizeRef:Tt,simplifyEpsilonRef:Et,draftMeta:v,engineRef:W,onDrawSessionChange:(0,n.useCallback)(e=>{We(e),Te?.(e)},[Te]),onDraftShapeChange:Ee,changeSelection:Ht,createShape:cn}),fn=(0,n.useRef)(un);fn.current=un;let{reset:mn,undoSession:bn,redoSession:xn,canUndoSession:Sn,canRedoSession:Cn,hasDraftSession:wn,hasDraftPoints:Tn,commitDraftSession:En,setBrushScalarMode:Dn,getBrushScalarMode:On,hasBrushSession:kn,commitBrush:An,cancelBrush:jn,beginBrushEditFromSelection:Mn,deleteDraftSelectedPoints:Nn,handleToolChange:Pn,handleBrushSelectionChange:Fn}=un,In=(0,n.useRef)(fe);In.current=fe;let $=Qe({docRef:Nt,draftRef:Ct,draftMeta:v,changeSelection:Ht,assistantRef:In}),Ln=(0,n.useRef)($);Ln.current=$;let{selectAll:Rn,clearSelection:zn,deleteSelection:Bn,copySelection:Vn,canPaste:Hn,paste:Un,duplicate:Wn,bringToFront:Gn,sendToBack:Kn,nudgeSelection:qn,getMergeTargets:Jn,mergeSelection:Yn}=hn({doc:q,selRef:xt,effectiveReadOnly:Z,changeSelection:Ht,canMergeSelection:M}),{zoomToBounds:Xn,zoomToShapes:Zn,zoomToSelection:Qn,zoomAtCenter:$n}=gn({engineRef:W,doc:q,selRef:xt,zoomAnimationDuration:F,zoomBound:P,ready:K});(0,n.useImperativeHandle)(me,()=>({previewRegionMask:e=>{let t=gt.current;if(!t)return;let n=e?Ve(e,t.w,t.h):mt.current;W.current?.setOverlays(er.current.showGuide?pt.current:null,er.current.showRegionMask?n:null,ht.current)},undo:()=>{bn()||q.undo()},redo:()=>{xn()||q.redo()},canUndo:()=>Sn()||q.canUndo(),canRedo:()=>Cn()||q.canRedo(),undoSession:bn,redoSession:xn,canUndoSession:Sn,canRedoSession:Cn,hasDraftSession:wn,cancelDraftSession:mn,commitDraftSession:En,setSelection:Ht,createShapes:e=>{e.length&&(q.create(e),Ht(e.map(e=>e.id)))},updateShapes:q.update,deleteShapes:q.remove,getShapes:q.getShapes,selectAll:Rn,clearSelection:zn,deleteSelection:Bn,copySelection:Vn,paste:Un,duplicate:Wn,bringToFront:Gn,sendToBack:Kn,zoomFit:()=>W.current?.fit(),zoom100:()=>W.current?.zoom100(),zoomIn:()=>{let e=W.current;if(!e)return;let{w:t,h:n}=e.screenSize;e.zoomAt(t/2,n/2,1.2)},zoomOut:()=>{let e=W.current;if(!e)return;let{w:t,h:n}=e.screenSize;e.zoomAt(t/2,n/2,1/1.2)},zoomToSelection:Qn,zoomToShapes:Zn,zoomToBounds:Xn,brush:{setScalarMode:Dn,getScalarMode:On,hasSession:kn,commit:An,cancel:jn,beginEditFromSelection:Mn}}),[q,Ht,bn,xn,En,mn,An,jn,Rn,zn,Bn,Vn,Un,Wn,Gn,Kn,Qn,Zn,Xn,Dn,On,kn,Mn]);let er=(0,n.useRef)(Y);er.current=Y;let tr=(0,n.useCallback)(()=>Ze({engineRef:W,toolRef:St,externalToolMapRef:it,spaceRef:Pt,shiftRef:Ft,docRef:Nt,selRef:xt,draftRef:Ct,readOnlyRef:Dt,disableMarqueeRef:Ot,lockedRef:At,onLockedInteraction:()=>jt.current?.(),createRef:ln,selectRef:Ut,enterEditRef:qt,drawSessionRef:fn,assistantRef:Ln,setCursorHint:Bt,setInteractionMode:zt,syncMinimap:Zt,onTransformPreview:Q,onDrawPreview:on}),[Bt,zt,Zt,Q,on]),nr=(0,n.useRef)([]);sn({backend:he,hostRef:Ae,engineRef:W,imageUrl:t,renderedImageUrl:Ye,makeCallbacks:tr,viewRef:er,readOnlyRef:Dt,toolRef:St,renderShapesRef:nr,coordinateSizeRef:vt,imageSizeRef:yt,selRef:xt,maskCanvasRef:pt,regionOverlayRef:mt,dimmedRef:ht,syncMinimap:Zt,setImage:Ie,setImageVisible:Re,setReady:ze,setImageStatus:$e,onContextMenuRequest:He});let rr=(0,n.useMemo)(()=>{let e=w?q.shapes.map(e=>{let t=w(e);return t?{...e,interaction:{...e.interaction,...t}}:e}):q.shapes;return ee?.length?[...ee.map(e=>({...e,interaction:{...e.interaction,selectable:!1,draggable:!1,editable:!1,hitTestDisabled:!0}})),...e]:e},[q.shapes,w,ee]);nr.current=rr,(0,n.useEffect)(()=>{W.current?.setShapes(rr,J),Zt()},[rr,J,Zt]),(0,n.useEffect)(()=>{W.current?.setEditing(Wt)},[Wt,K]);let ir=(0,n.useRef)(ve);ir.current=ve,(0,n.useEffect)(()=>{ir.current?.(Wt)},[Wt]),(0,n.useEffect)(()=>{Gt(null)},[g]),(0,n.useEffect)(()=>{Wt&&(J.length!==1||J[0]!==Wt)&&Gt(null)},[J,Wt]),(0,n.useEffect)(()=>{let e=W.current;e&&(e.setFilter(Y.brightness,Y.contrast),e.setStrokeSize(Y.strokeSize),e.setImageSmoothing(Y.imageSmoothing),Zt())},[Y.brightness,Y.contrast,Y.strokeSize,Y.imageSmoothing,Zt]),(0,n.useLayoutEffect)(()=>{K&&W.current?.setOverlays(Y.showGuide?ut:null,Y.showRegionMask?ft:null,d)},[K,ut,ft,Y.showGuide,Y.showRegionMask,d]),(0,n.useEffect)(()=>{!K||!G||Zt()},[K,G,dt,Y.showGuide,Y.showRegionMask,te,Zt]),(0,n.useEffect)(()=>{K&&W.current?.setTransformEnabled(!Z&&g!==L.BRUSH)},[Z,K,g]),(0,n.useEffect)(()=>{Pn(g,rt.has(g))},[g,rt,Pn]);let ar=$.finalize;(0,n.useEffect)(()=>{ar()},[g,ar]),(0,n.useEffect)(()=>{It.current=`idle`,Lt.current=null,Rt()},[g,he,Rt]),(0,n.useEffect)(()=>{Fn(J,Z)},[J,g,Z,Fn]),(0,n.useEffect)(()=>{K&&Rt()},[g,Ue,rt,K,Rt]);let or=(0,n.useRef)(null);(0,n.useEffect)(()=>{or.current!==t&&(or.current=t,q.reset(f??[]),Ht([]),mn(),ar())},[t,f,q.reset,Ht,mn,ar]),kt({keymap:pe,hostRef:Ae,actions:{undo:()=>{Z||bn()||q.undo()},redo:()=>{Z||xn()||q.redo()},selectAll:Rn,copy:Vn,cut:()=>{Vn(),Bn()},paste:Un,duplicate:Wn,delete:()=>{Tn()&&Nn()||Bn()},cancel:()=>{let e=it.current.get(St.current);if(!(e?.onCancel&&e.onCancel()!==!1)){if($.isActive()){$.cancel();return}if(wn()){mn();return}if(Wt){Gt(null);return}if(xt.current.length){zn();return}C?.()}},commitDraft:()=>{if($.isActive()){$.finalize();return}if(wn()){En();return}if(Z)return;if(Wt){Gt(null);return}let e=xt.current;if(e.length!==1)return;let t=Nt.current.getShapes().find(t=>t.id===e[0]);t&&(t.type===o.POLYGON||t.type===o.LINE)&&t.interaction?.editable!==!1&&!t.readOnly&&Gt(e[0])},bringToFront:Gn,sendToBack:Kn,zoomIn:()=>$n(1.2),zoomOut:()=>$n(1/1.2),zoom100:()=>W.current?.zoom100(),zoomFit:()=>W.current?.fit(),toggleMinimap:()=>Ke(e=>!e),toggleCursorGuide:()=>ot(e=>({...e,showCursorGuide:!e.showCursorGuide})),togglePixelation:()=>ot(e=>({...e,imageSmoothing:!e.imageSmoothing})),selectTool:()=>U?.(L.SELECT),rectangleTool:()=>U?.(L.RECTANGLE),rotatedRectangleTool:()=>U?.(L.ROTATED_RECTANGLE),circleTool:()=>U?.(L.CIRCLE),polygonTool:()=>U?.(L.POLYGON),pathTool:()=>U?.(L.PATH),brushTool:()=>U?.(L.BRUSH),pointTool:()=>U?.(L.POINT)},spaceRef:Pt,shiftRef:Ft,onSpaceDown:()=>{W.current?.setPanMode(!0),Rt()},onSpaceUp:()=>{W.current?.setPanMode(!1),It.current===`panning`?zt(`idle`):Rt()},nudge:qn});let sr=(0,n.useMemo)(()=>rr.filter(e=>J.includes(e.id)&&s(e)),[rr,J]),cr=(0,n.useMemo)(()=>nn?[...sr,nn]:sr,[sr,nn]),lr=J.length>0,ur=q.shapes.some(e=>J.includes(e.id)&&u(e)),dr=!Z&&J.length===1&&(()=>{let e=q.shapes.find(e=>e.id===J[0]);return!!e&&(e.type===o.POLYGON||e.type===o.LINE)&&e.interaction?.editable!==!1&&!e.readOnly})(),fr=Jn(),pr=Z||fr.length<2||(M?!M(fr):!1),mr=fe&&!Z&&J.length===1?(()=>{let e=q.shapes.find(e=>e.id===J[0]);return e&&e.type===o.POLYGON&&e.interaction?.editable!==!1&&!e.readOnly?e:null})():null,hr=[{id:`copy`,label:X.contextMenu.copy,shortcut:`⌘C`,disabled:!lr,onClick:Vn},{id:`paste`,label:X.contextMenu.paste,shortcut:`⌘V`,disabled:Z||!Hn(),onClick:Un},{id:`duplicate`,label:X.contextMenu.duplicate,shortcut:`⌘D`,disabled:!ur||Z,onClick:Wn},{id:`delete`,label:X.contextMenu.delete,shortcut:`Del`,danger:!0,disabled:!ur||Z,onClick:Bn},{separator:!0},{id:`editVertices`,label:X.contextMenu.editVertices,shortcut:`Enter`,disabled:!dr,onClick:()=>Gt(J[0])},{id:`merge`,label:X.contextMenu.merge,disabled:pr,onClick:Yn},{id:`assistExpand`,label:X.contextMenu.assistExpand,icon:(0,r.jsx)(e.$n,{size:14}),disabled:!mr,onClick:()=>{Be&&mr&&$.refineShape(mr,Be.img,!0)}},{id:`assistExclude`,label:X.contextMenu.assistExclude,icon:(0,r.jsx)(e.$n,{size:14}),disabled:!mr,onClick:()=>{Be&&mr&&$.refineShape(mr,Be.img,!1)}},{id:`bringToFront`,label:X.contextMenu.bringToFront,disabled:!ur||Z,onClick:Gn},{id:`sendToBack`,label:X.contextMenu.sendToBack,disabled:!ur||Z,onClick:Kn},{separator:!0},{id:`undo`,label:X.contextMenu.undo,shortcut:`⌘Z`,disabled:Z||!Sn()&&!q.canUndo(),onClick:()=>{bn()||q.undo()}},{id:`redo`,label:X.contextMenu.redo,shortcut:`⇧⌘Z`,disabled:Z||!Cn()&&!q.canRedo(),onClick:()=>{xn()||q.redo()}},{separator:!0},{id:`selectAll`,label:X.contextMenu.selectAll,shortcut:`⌘A`,onClick:Rn},{id:`clearSelection`,label:X.contextMenu.clearSelection,disabled:!lr,onClick:zn},{id:`zoomToSelection`,label:X.contextMenu.zoomToSelection,disabled:!lr,onClick:Qn}],gr=A?A(hr,{selectedIds:J,readOnly:Z}):hr,_r=dn({engineRef:W,image:G,wheelZoom:Y.wheelZoom,minimapSize:_n});return(0,r.jsxs)(`div`,{className:`aivex:relative aivex:h-full aivex:w-full aivex:overflow-hidden aivex:bg-black`,children:[(0,r.jsx)(`div`,{ref:Ae,className:`aivex:h-full aivex:w-full`,style:{opacity:+!!Le,transition:Le?`opacity 0.3s ease`:`none`}}),Xe!==`ready`&&(0,r.jsx)(ae,{status:Xe,render:c,loadingLabel:X.imageLoading,errorLabel:X.imageLoadError}),K&&G&&(0,r.jsx)(`div`,{className:`aivex:pointer-events-none aivex:absolute aivex:inset-0 aivex:overflow-hidden`,children:(0,r.jsxs)(`div`,{ref:Ne,style:{position:`absolute`,top:0,left:0,width:G.w,height:G.h,transformOrigin:`0 0`},children:[!!z?.length&&oe&&(0,r.jsx)(`div`,{style:{position:`absolute`,left:0,top:0,width:G.w,height:G.h,pointerEvents:`none`},children:z.map(e=>(0,r.jsx)(`div`,{role:e.disabled?void 0:`button`,tabIndex:e.disabled?void 0:0,"aria-pressed":e.selected||void 0,onPointerDown:e=>e.stopPropagation(),onClick:t=>{t.stopPropagation(),e.disabled||H?.(e)},onKeyDown:t=>{e.disabled||t.key!==`Enter`&&t.key!==` `||(t.preventDefault(),t.stopPropagation(),H?.(e))},style:{position:`absolute`,left:e.point.x,top:e.point.y,transform:e.anchor===`topLeft`?`scale(var(--editor-overlay-inverse-scale, 1))`:`translate(-50%, -50%) scale(var(--editor-overlay-inverse-scale, 1))`,transformOrigin:e.anchor===`topLeft`?`0 0`:`center`,zIndex:e.selected?1:void 0,pointerEvents:e.disabled?`none`:`auto`,cursor:e.disabled?`default`:`pointer`},children:oe(e)},e.id))}),se?.({image:G,viewport:W.current?.viewport??{scale:1,x:0,y:0}}),cr.length>0&&(0,r.jsx)(Ce,{shapes:cr,getLabel:ce,hideDot:le,formatInfo:ue,register:en}),fe&&($.status===`loading`||$.boxes.length>0)&&(0,r.jsx)(ie,{image:G,points:$.points,boxes:$.boxes,status:$.status})]})}),K&&Y.showCursorGuide&&(0,r.jsx)(V,{color:`#1e88e5`}),K&&G&&O&&(0,r.jsx)(ge,{image:G,imageUrl:Ye,imageVisible:Le,maskDataUrl:dt,region:ft,roiMaskId:Fe,shapes:rr,view:Y,onChangeView:st,nav:_r,registerShape:Yt,rectRef:Me,zoomLabelRef:Pe,onZoom100:()=>W.current?.zoom100(),open:Ge,onToggleOpen:()=>Ke(e=>!e),labels:X.minimap,settingsLabels:X.viewSettings,showSettings:k,settingsOpen:qe,onToggleSettings:()=>Je(e=>!e),onCloseSettings:()=>Je(!1)}),Be&&(0,r.jsx)(B,{x:Be.x,y:Be.y,items:gr,onClose:()=>He(null)})]})}async function xn(e){let t=await At(e);return await new Promise((n,r)=>{let i=new Image;t||(i.crossOrigin=`anonymous`),i.onload=()=>n({image:i,revoke:t?()=>URL.revokeObjectURL(t):null}),i.onerror=()=>{t&&URL.revokeObjectURL(t),r(Error(`Failed to load image`))},i.src=t??e})}function Sn(e,t,n){if(t.length!==0){e.beginPath(),e.moveTo(t[0].x,t[0].y);for(let n=1;n<t.length;n+=1)e.lineTo(t[n].x,t[n].y);n&&e.closePath()}}function Cn(e,t,n,r){if(t.interaction?.visible===!1)return;let i=le(t,{strokeWidth:r,pointRadius:2});if(e.save(),e.globalAlpha=i.opacity,e.lineWidth=i.strokeWidth/n,e.lineJoin=`round`,e.lineCap=`round`,t.type===o.POINT){let r=t.points[0];r&&(e.fillStyle=i.color,e.beginPath(),e.arc(r.x,r.y,i.pointRadius/n,0,Math.PI*2),e.fill()),e.restore();return}if(t.type===o.RECTANGLE||t.type===o.ELLIPSE){let[n,r]=t.points;if(n&&r){let i=Math.min(n.x,r.x),a=Math.min(n.y,r.y),s=Math.abs(r.x-n.x),c=Math.abs(r.y-n.y);e.beginPath(),t.type===o.ELLIPSE?e.ellipse(i+s/2,a+c/2,s/2,c/2,0,0,Math.PI*2):e.rect(i,a,s,c)}}else Sn(e,t.points,t.type!==o.LINE);i.fillVisible&&(e.save(),e.fillStyle=i.color,e.globalAlpha*=i.fillAlpha,e.fill(),e.restore()),t.style?.alternateColor&&i.dash?.length&&(e.setLineDash([]),e.strokeStyle=t.style.alternateColor,e.stroke()),e.setLineDash((i.dash??[]).map(e=>e/n)),e.strokeStyle=i.color,e.stroke(),e.restore()}function wn({imageUrl:e,alt:t=`Shape preview`,coordinateSize:i,shapes:a=[],regionMask:o,guideMask:s,maskPalette:c,focusedShapeId:l,focusFit:u=`contain`,zoomPadding:d=.3,strokeSize:p=1,brightness:m=1,contrast:g=1,imageSmoothing:_=!0,lazy:v=!0,className:y,style:b,renderImageState:x}){let S=(0,n.useRef)(null),C=(0,n.useRef)(null),w=(0,n.useRef)(null),[T,E]=(0,n.useState)(!v),[D,O]=(0,n.useState)(`loading`),[k,A]=(0,n.useState)(0);(0,n.useEffect)(()=>{if(!v||T)return;let e=S.current;if(!e)return;let t=new IntersectionObserver(([e])=>{e.isIntersecting&&(E(!0),t.disconnect())});return t.observe(e),()=>t.disconnect()},[v,T]),(0,n.useEffect)(()=>{let e=S.current;if(!e)return;let t=new ResizeObserver(()=>A(e=>e+1));return t.observe(e),()=>t.disconnect()},[]),(0,n.useEffect)(()=>{if(!T||!e){O(e?`loading`:`error`);return}let t=!0;return O(`loading`),xn(e).then(e=>{if(!t){e.revoke?.();return}w.current?.revoke?.(),w.current=e,O(`ready`)}).catch(()=>{t&&(w.current?.revoke?.(),w.current=null,O(`error`))}),()=>{t=!1}},[e,T]),(0,n.useEffect)(()=>()=>{w.current?.revoke?.(),w.current=null},[]);let j=(0,n.useMemo)(()=>a.find(e=>e.id===l),[l,a]),M=(0,n.useMemo)(()=>s&&c?je(s,c):null,[s,c]);return(0,n.useEffect)(()=>{if(D===`error`){let e=C.current;e?.getContext(`2d`)?.clearRect(0,0,e.width,e.height)}if(D!==`ready`)return;let e=S.current,t=C.current,n=w.current;if(!e||!t||!n)return;let{width:r,height:s}=e.getBoundingClientRect();if(!r||!s)return;let c=window.devicePixelRatio||1;t.width=Math.max(1,Math.round(r*c)),t.height=Math.max(1,Math.round(s*c)),t.style.width=`${r}px`,t.style.height=`${s}px`;let l=t.getContext(`2d`);if(!l)return;let v=i?.width??n.image.naturalWidth,y=i?.height??n.image.naturalHeight;if(!v||!y)return;let b=Math.min(r/v,s/y),x=(r-v*b)/2,T=(s-y*b)/2;if(j&&j.points.length>0){let e=h(j.points),t=Math.max(e.maxX-e.minX,50),n=Math.max(e.maxY-e.minY,50),i=Math.min(t,n)*d;b=Math.min(r/(t+i*2),s/(n+i*2)),u===`cover`&&(b=Math.max(b,Math.max(r/v,s/y))),x=r/2-(e.minX+e.maxX)/2*b,T=s/2-(e.minY+e.maxY)/2*b,u===`cover`&&(x=Math.min(0,Math.max(x,r-v*b)),T=Math.min(0,Math.max(T,s-y*b)))}l.setTransform(c,0,0,c,0,0),l.clearRect(0,0,r,s),l.save(),l.translate(x,T),l.scale(b,b),l.imageSmoothingEnabled=_,l.filter=`brightness(${m}) contrast(${g})`,l.drawImage(n.image,0,0,v,y),l.filter=`none`,M&&(l.save(),l.globalAlpha=.55,l.drawImage(M,0,0,v,y),l.restore());let E=o?Ve(o,v,y):null;if(E&&(Le(l,E,v,y),E.outlineStyles)){let e=(e,t)=>{if(l.lineWidth=t.width/b,t.underlayColor){l.setLineDash([]),l.strokeStyle=t.underlayColor;for(let[t,n]of e)Sn(l,[t,n],!1),l.stroke()}l.save(),l.globalAlpha*=t.opacity,l.setLineDash(t.dash.map(e=>e/b)),l.strokeStyle=t.color;for(let[t,n]of e)Sn(l,[t,n],!1),l.stroke();l.restore()};e(E.visibleOutline,E.outlineStyles.visible),e(E.occludedOutline,E.outlineStyles.occluded)}for(let e of f(a))Cn(l,e,b,p);l.restore()},[m,g,i,j,u,_,M,o,a,k,D,p,d]),(0,r.jsxs)(`div`,{ref:S,className:y,style:{position:`relative`,width:`100%`,height:`100%`,...b},children:[(0,r.jsx)(`canvas`,{ref:C,role:`img`,"aria-label":t,style:{display:`block`}}),D!==`ready`&&x&&(0,r.jsx)(`div`,{style:{position:`absolute`,inset:0},children:x(D===`error`?`error`:`loading`)})]})}exports.DEFAULT_EDITOR_STRINGS=F,exports.DEFAULT_VIEW_SETTINGS=R,exports.SHAPE_TYPE=o,exports.ShapeEditor=bn,exports.default=bn,exports.ShapeViewer=wn,exports.TOOL=L,exports.generateId=p;
1
+ "use client";require(`./styles.css`),Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require(`./Button-BDMw8Le7.cjs`),t=require(`./Switch-BaZLB-fT.cjs`);let n=require(`react`),r=require(`react/jsx-runtime`),i=require(`konva`);i=e.Ia(i,1);let a=require(`pixi.js`);var o={POINT:`POINT`,RECTANGLE:`RECTANGLE`,ROTATED_RECTANGLE:`ROTATED_RECTANGLE`,POLYGON:`POLYGON`,ELLIPSE:`ELLIPSE`,LINE:`LINE`};function s(e){return e.interaction?.visible!==!1}function c(e){return s(e)&&e.interaction?.hitTestDisabled!==!0}function l(e){return c(e)&&e.interaction?.selectable!==!1}function u(e){return l(e)&&!e.readOnly&&e.interaction?.editable!==!1}function d(e){return u(e)&&e.interaction?.draggable!==!1}function f(e){return e.map((e,t)=>({shape:e,index:t})).sort((e,t)=>{let n=e.shape.style?.zIndex??0,r=t.shape.style?.zIndex??0;return n===r?e.index-t.index:n-r}).map(e=>e.shape)}function p(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`id_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}var m=[`tl`,`t`,`tr`,`r`,`br`,`b`,`bl`,`l`];function h(e){let t=e.map(e=>e.x),n=e.map(e=>e.y);return{minX:Math.min(...t),minY:Math.min(...n),maxX:Math.max(...t),maxY:Math.max(...n)}}function g(e,t){let n=(t.minX+t.maxX)/2,r=(t.minY+t.maxY)/2;return{x:e.includes(`l`)?t.minX:e.includes(`r`)?t.maxX:n,y:e.includes(`t`)?t.minY:e.includes(`b`)?t.maxY:r}}function _(e,t,n,r){let i={...t};return e.includes(`l`)&&(i.minX=n),e.includes(`r`)&&(i.maxX=n),e.includes(`t`)&&(i.minY=r),e.includes(`b`)&&(i.maxY=r),i}function v(e,t){let n=t.x-e.x,r=t.y-e.y,i=Math.max(Math.abs(n),Math.abs(r));return{x:e.x+(n<0?-i:i),y:e.y+(r<0?-i:i)}}function y(e,t,n){let r=Math.cos(n),i=Math.sin(n),a=e.x-t.x,o=e.y-t.y;return{x:t.x+a*r-o*i,y:t.y+a*i+o*r}}function b(e){let t=h(e);return[{x:t.minX,y:t.minY},{x:t.maxX,y:t.minY},{x:t.maxX,y:t.maxY},{x:t.minX,y:t.maxY}]}function x(e,t,n=32){let r=(e.x+t.x)/2,i=(e.y+t.y)/2,a=Math.abs(t.x-e.x)/2,o=Math.abs(t.y-e.y)/2;return Array.from({length:n},(e,t)=>{let s=t/n*2*Math.PI;return{x:r+a*Math.cos(s),y:i+o*Math.sin(s)}})}function S(e){let t=[...e].sort((e,t)=>e.x-t.x||e.y-t.y);if(t.length<=2)return t;let n=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x),r=[];for(let e of t){for(;r.length>=2&&n(r[r.length-2],r[r.length-1],e)<=0;)r.pop();r.push(e)}let i=[];for(let e=t.length-1;e>=0;e--){let r=t[e];for(;i.length>=2&&n(i[i.length-2],i[i.length-1],r)<=0;)i.pop();i.push(r)}return r.pop(),i.pop(),r.concat(i)}function C(e){let t=S(e);if(t.length<3)return b(e);let n=1/0,r=b(e);for(let e=0;e<t.length;e++){let i=t[e],a=t[(e+1)%t.length],o=Math.hypot(a.x-i.x,a.y-i.y)||1,s=(a.x-i.x)/o,c=(a.y-i.y)/o,l=1/0,u=-1/0,d=1/0,f=-1/0;for(let e of t){let t=e.x*s+e.y*c,n=-e.x*c+e.y*s;t<l&&(l=t),t>u&&(u=t),n<d&&(d=n),n>f&&(f=n)}let p=(u-l)*(f-d);if(p<n){n=p;let e=(e,t)=>({x:e*s-t*c,y:e*c+t*s});r=[e(l,d),e(u,d),e(u,f),e(l,f)]}}return r}var w=(e,t)=>({x:e.x-t.x,y:e.y-t.y}),T=(e,t)=>e.x*t.x+e.y*t.y,E=e=>Math.hypot(e.x,e.y),D=e=>{let t=E(e)||1;return{x:e.x/t,y:e.y/t}},O=(e,t)=>({x:(e.x+t.x)/2,y:(e.y+t.y)/2}),k=e=>{let t=e.reduce((e,t)=>({x:e.x+t.x,y:e.y+t.y}),{x:0,y:0});return{x:t.x/e.length,y:t.y/e.length}};function A(e){return[e[0],O(e[0],e[1]),e[1],O(e[1],e[2]),e[2],O(e[2],e[3]),e[3],O(e[3],e[0])]}function j(e,t){let n=O(e[0],e[1]),r=D(w(e[0],e[3]));return{x:n.x+r.x*t,y:n.y+r.y*t}}function M(e,t,n,r){let i=(e,i)=>({x:t.x+e*n.x+i*r.x,y:t.y+e*n.y+i*r.y});return[i(e.minX,e.minY),i(e.maxX,e.minY),i(e.maxX,e.maxY),i(e.minX,e.maxY)]}function N(e,t,n){if(e.length<4)return e;let r=e[0],i=D(w(e[1],e[0])),a=D(w(e[3],e[0])),o=T(w(e[1],r),i),s=T(w(e[3],r),a),c=w(n,r);return M(_(t,{minX:0,minY:0,maxX:o,maxY:s},T(c,i),T(c,a)),r,i,a)}function P(e,t,n){let r=t.maxX-t.minX||1,i=t.maxY-t.minY||1,a=n.maxX-n.minX,o=n.maxY-n.minY;return e.map(e=>({x:n.minX+(e.x-t.minX)/r*a,y:n.minY+(e.y-t.minY)/i*o}))}var F={contextMenu:{copy:`복사`,paste:`붙여넣기`,duplicate:`복제`,delete:`삭제`,bringToFront:`맨 앞으로`,sendToBack:`맨 뒤로`,editVertices:`정점 편집`,merge:`레이블 합치기`,assistExpand:`이 지점 포함하기`,assistExclude:`이 지점 제외하기`,undo:`실행 취소`,redo:`다시 실행`,zoomToSelection:`선택 영역으로 확대`,selectAll:`전체 선택`,clearSelection:`선택 해제`},viewSettings:{title:`보기 설정`,reset:`보기설정 초기화`,brightness:`밝기`,contrast:`대비`,strokeSize:`선 두께`,simplifyStrength:`단순화 강도`,pixelation:`이미지 픽셀화`,cursorGuide:`커서 가이드라인`,guideMask:`가이드 마스크`,regionMask:`ROI 표시`,keepZoomOnImageChange:`이미지 변경 시 줌 유지`,wheelZoom:`스크롤로 확대·축소`},minimap:{zoomIn:`확대`,zoomOut:`축소`,zoom100:`100%로 초기화`,viewSettings:`보기 설정`,toggleMinimap:`미니맵 접기/펼치기`},imageLoading:`이미지를 불러오는 중…`,imageLoadError:`이미지를 불러올 수 없습니다`};function I(e){return e?{contextMenu:{...F.contextMenu,...e.contextMenu},viewSettings:{...F.viewSettings,...e.viewSettings},minimap:{...F.minimap,...e.minimap},imageLoading:e.imageLoading??F.imageLoading,imageLoadError:e.imageLoadError??F.imageLoadError}:F}var L={SELECT:`SELECT`,POLYGON:`POLYGON`,PATH:`PATH`,BRUSH:`BRUSH`,RECTANGLE:`RECTANGLE`,ROTATED_RECTANGLE:`ROTATED_RECTANGLE`,CIRCLE:`CIRCLE`,POINT:`POINT`,ASSISTANT_POLYGON:`ASSISTANT_POLYGON`,ASSISTANT_RECT:`ASSISTANT_RECT`,ASSISTANT_POINT:`ASSISTANT_POINT`},R={brightness:1,contrast:1,showCursorGuide:!1,imageSmoothing:!0,strokeSize:2,simplifyStrength:1.5,showGuide:!0,showRegionMask:!0,keepZoomOnImageChange:!1,wheelZoom:!0},ee=`var(--editor-overlay-inverse-scale, 1)`,te=`#377be2`,ne=`#e23c3c`;function re({point:e}){let t=e.positive?te:ne;return(0,r.jsx)(`div`,{style:{position:`absolute`,left:e.x,top:e.y,width:18,height:18,marginLeft:-9,marginTop:-9,borderRadius:`50%`,background:t,border:`2px solid #fff`,boxShadow:`0 0 3px rgba(0,0,0,0.5)`,color:`#fff`,fontSize:13,fontWeight:700,lineHeight:`14px`,display:`flex`,alignItems:`center`,justifyContent:`center`,transform:`scale(${ee})`,transformOrigin:`center`},children:e.positive?`+`:`−`})}function ie({image:e,points:t,boxes:n,status:i}){return(0,r.jsxs)(`div`,{style:{position:`absolute`,left:0,top:0,width:e.w,height:e.h,pointerEvents:`none`},children:[(0,r.jsx)(`style`,{children:`@keyframes editorv2-assistant-shimmer{from{background-position:200% 0}to{background-position:-200% 0}}`}),n.map((e,t)=>(0,r.jsx)(`div`,{style:{position:`absolute`,left:e.x,top:e.y,width:e.width,height:e.height,boxSizing:`border-box`,border:`calc(2px * var(--editor-overlay-inverse-scale, 1)) solid rgba(255,255,255,0.9)`,backgroundImage:`linear-gradient(90deg, rgba(255,255,255,0.10) 0%, rgba(255,255,255,0.30) 50%, rgba(255,255,255,0.10) 100%)`,backgroundSize:`200% 100%`,animation:`editorv2-assistant-shimmer 1.4s linear infinite`}},`box-${t}-${e.x}-${e.y}-${e.width}-${e.height}`)),i===`loading`&&t.map((e,t)=>(0,r.jsx)(re,{point:e},`pt-${t}-${e.x}-${e.y}`))]})}function z(e){let t=[];for(let n of e)if(`separator`in n){if(!t.length||`separator`in t[t.length-1])continue;t.push(n)}else t.push(n);for(;t.length&&`separator`in t[t.length-1];)t.pop();return t}function B({x:e,y:n,items:i,onClose:a}){let o=z(i);return(0,r.jsxs)(t.c,{open:!0,modal:!1,onOpenChange:e=>{e||a()},children:[(0,r.jsx)(t.c.Trigger,{asChild:!0,children:(0,r.jsx)(`span`,{"aria-hidden":!0,style:{position:`absolute`,left:e,top:n,width:0,height:0}})}),(0,r.jsx)(t.c.Content,{side:`bottom`,align:`start`,sideOffset:2,collisionPadding:8,style:{maxHeight:`var(--radix-dropdown-menu-content-available-height)`,overflowY:`auto`},onContextMenu:e=>e.preventDefault(),onCloseAutoFocus:e=>e.preventDefault(),children:o.map((e,n)=>`separator`in e?(0,r.jsx)(t.c.Separator,{className:`aivex:shrink-0`},`sep-${n}`):(0,r.jsx)(t.c.Item,{danger:e.danger,disabled:e.disabled,className:`aivex:shrink-0`,onSelect:()=>e.onClick(),children:(0,r.jsxs)(`span`,{className:`aivex:flex aivex:w-full aivex:items-center aivex:justify-between aivex:gap-6`,children:[(0,r.jsxs)(`span`,{className:`aivex:flex aivex:min-w-0 aivex:items-center aivex:gap-1.5`,children:[e.icon,(0,r.jsx)(`span`,{className:`aivex:truncate`,children:e.label})]}),e.shortcut&&(0,r.jsx)(t.c.Shortcut,{children:e.shortcut})]})},e.label))})]})}function V({color:e=`#1e88e5`}){let t=(0,n.useRef)(null),i=(0,n.useRef)(null),a=(0,n.useRef)(null);return(0,n.useEffect)(()=>{let e=t.current,n=i.current,r=a.current;if(!e||!n||!r)return;let o=t=>{let i=e.getBoundingClientRect(),a=t.clientX-i.left,o=t.clientY-i.top;if(a<0||o<0||a>i.width||o>i.height){n.style.display=`none`,r.style.display=`none`;return}n.style.display=`block`,r.style.display=`block`,n.style.transform=`translateX(${a}px)`,r.style.transform=`translateY(${o}px)`},s=()=>{n.style.display=`none`,r.style.display=`none`};return window.addEventListener(`mousemove`,o),e.parentElement?.addEventListener(`mouseleave`,s),()=>{window.removeEventListener(`mousemove`,o),e.parentElement?.removeEventListener(`mouseleave`,s)}},[]),(0,r.jsxs)(`div`,{ref:t,className:`aivex:pointer-events-none aivex:absolute aivex:inset-0 aivex:overflow-hidden`,children:[(0,r.jsx)(`div`,{ref:i,style:{position:`absolute`,top:0,left:0,width:1,height:`100%`,background:e,opacity:.6,display:`none`}}),(0,r.jsx)(`div`,{ref:a,style:{position:`absolute`,top:0,left:0,width:`100%`,height:1,background:e,opacity:.6,display:`none`}})]})}function ae({status:e,render:t,loadingLabel:n=F.imageLoading,errorLabel:i=F.imageLoadError}){return(0,r.jsx)(`div`,{"data-track-id":e===`loading`?`editor-image-loading-wrap`:`editor-image-error-wrap`,style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,background:e===`error`?`rgba(13,13,18,1)`:`rgba(13,13,18,0.6)`,backdropFilter:e===`loading`?`blur(2px)`:void 0,color:`#fff`,fontFamily:`Pretendard, sans-serif`,pointerEvents:e===`error`?`auto`:`none`},children:t?t(e):e===`loading`?(0,r.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10,fontSize:13},children:[(0,r.jsx)(`span`,{style:{width:18,height:18,borderRadius:`50%`,border:`2px solid rgba(255,255,255,0.3)`,borderTopColor:`#fff`,animation:`editorv2-image-spin 0.7s linear infinite`}}),n,(0,r.jsx)(`style`,{children:`@keyframes editorv2-image-spin{to{transform:rotate(360deg)}}`})]}):(0,r.jsxs)(`div`,{style:{textAlign:`center`,opacity:.85},children:[(0,r.jsx)(`div`,{style:{fontSize:28,marginBottom:6},children:`⚠`}),(0,r.jsx)(`div`,{style:{fontSize:13},children:i})]})})}Math.PI/12;var oe=`#669DEF`,H=.1,se=.7,ce=2.5;function le(e,t={}){let n=e.style?.color??`#00e5ff`,r=!!e.readOnly,i=e.style?.strokeWidth??t.strokeWidth??2,a=r?i*ce:i,o=r?se:e.style?.opacity??1,s=e.style?.fillOpacity??.12549019607843137,c=e.style?.dash??(r?[a,a*2]:void 0);return{color:n,strokeWidth:a,opacity:o,fillAlpha:s,fillVisible:!!e.style?.filled,dash:c,pointRadius:e.style?.pointRadius??t.pointRadius??5}}function ue(e,t){let n=Math.max(0,Math.min(1,t)),r=e.trim().replace(`#`,``);if(r.length===3||r.length===6){let e=r.length===3?r.replace(/./g,e=>e+e):r,t=Number.parseInt(e,16);if(!Number.isNaN(t))return`rgba(${t>>16&255}, ${t>>8&255}, ${t&255}, ${n})`}return e}function de({shape:e,strokeSize:t,register:n}){let{type:i,points:a}=e,s=le(e,{strokeWidth:t}),c=t=>n?.(e.id,t),l={ref:c,stroke:s.color,strokeWidth:s.strokeWidth,strokeDasharray:s.dash?.join(` `),opacity:s.opacity,fill:s.fillVisible&&i!==o.LINE?s.color:`none`,fillOpacity:s.fillAlpha,vectorEffect:`non-scaling-stroke`};if(i===o.POINT)return(0,r.jsx)(`circle`,{ref:c,cx:a[0].x,cy:a[0].y,r:s.pointRadius,fill:s.color,opacity:s.opacity});if(i===o.RECTANGLE||i===o.ELLIPSE){let e=h(a);return i===o.ELLIPSE?(0,r.jsx)(`ellipse`,{cx:(e.minX+e.maxX)/2,cy:(e.minY+e.maxY)/2,rx:(e.maxX-e.minX)/2,ry:(e.maxY-e.minY)/2,...l}):(0,r.jsx)(`rect`,{x:e.minX,y:e.minY,width:e.maxX-e.minX,height:e.maxY-e.minY,...l})}let u=a.map(e=>`${e.x},${e.y}`).join(` `);return i===o.LINE?(0,r.jsx)(`polyline`,{points:u,...l}):(0,r.jsx)(`polygon`,{points:u,...l})}function fe({image:e,region:t,maskId:n,width:i,height:a,strokeWidth:o,strokeDasharray:s,style:c}){let l=[...t.visibleOutline,...t.occludedOutline];return(0,r.jsxs)(`svg`,{width:i,height:a,viewBox:`0 0 ${e.w} ${e.h}`,style:c,"aria-hidden":!0,children:[(0,r.jsx)(`defs`,{children:(0,r.jsxs)(`mask`,{id:n,children:[(0,r.jsx)(`rect`,{x:0,y:0,width:e.w,height:e.h,fill:`white`}),t.rects.map((e,t)=>(0,r.jsx)(`rect`,{x:e.x,y:e.y,width:e.w,height:e.h,fill:`black`},e.id??`area-${t}`)),t.zones.map((e,t)=>(0,r.jsx)(`polygon`,{points:e.points.map(e=>`${e.x},${e.y}`).join(` `),fill:`white`},`occ-${t}`))]})}),(0,r.jsx)(`rect`,{x:0,y:0,width:e.w,height:e.h,fill:t.dim.color,fillOpacity:t.dim.opacity,mask:`url(#${n})`}),l.length>0&&(0,r.jsx)(`path`,{d:l.map(([e,t])=>`M${e.x} ${e.y}L${t.x} ${t.y}`).join(``),fill:`none`,stroke:`#fff`,strokeWidth:o,strokeDasharray:s,vectorEffect:`non-scaling-stroke`})]})}var pe={trackRootClassName:`aivex:h-1.5`,thumbClassName:`aivex:h-4 aivex:w-4 aivex:border`};function me({value:i,onChange:a,onClose:o,labels:s=F.viewSettings}){return(0,n.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()},t=()=>o();return window.addEventListener(`keydown`,e),window.addEventListener(`pointerdown`,t),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`pointerdown`,t)}},[o]),(0,r.jsxs)(`div`,{className:`aivex:absolute aivex:bottom-full aivex:left-0 aivex:mb-1 aivex:w-[220px] aivex:rounded-[8px] aivex:border aivex:border-border-default aivex:bg-bg-primary aivex:p-3 aivex:text-text-primary aivex:text-xs aivex:shadow-lg`,onPointerDown:e=>e.stopPropagation(),children:[(0,r.jsxs)(`div`,{className:`aivex:mb-2 aivex:flex aivex:items-center aivex:justify-between`,children:[(0,r.jsx)(`span`,{className:`aivex:font-semibold aivex:text-text-secondary`,children:s.title}),(0,r.jsx)(e.t,{variant:`ghost`,size:`sm`,onClick:()=>a({...R}),children:s.reset})]}),(0,r.jsx)(he,{label:`${s.brightness} ${i.brightness.toFixed(2)}`,children:(0,r.jsx)(t.n,{min:0,max:3,step:.05,value:[i.brightness],onValueChange:([e])=>a({brightness:e}),...pe})}),(0,r.jsx)(he,{label:`${s.contrast} ${i.contrast.toFixed(2)}`,children:(0,r.jsx)(t.n,{min:0,max:3,step:.05,value:[i.contrast],onValueChange:([e])=>a({contrast:e}),...pe})}),(0,r.jsx)(he,{label:`${s.strokeSize} ${i.strokeSize}`,children:(0,r.jsx)(t.n,{min:1,max:10,step:.5,value:[i.strokeSize],onValueChange:([e])=>a({strokeSize:e}),...pe})}),(0,r.jsx)(he,{label:`${s.simplifyStrength} ${i.simplifyStrength}`,children:(0,r.jsx)(t.n,{min:.5,max:5,step:.5,value:[i.simplifyStrength],onValueChange:([e])=>a({simplifyStrength:e}),...pe})}),(0,r.jsx)(`div`,{className:`aivex:my-2`,children:(0,r.jsx)(t.a,{})}),(0,r.jsx)(U,{label:s.pixelation,checked:!i.imageSmoothing,onChange:e=>a({imageSmoothing:!e})}),(0,r.jsx)(U,{label:s.cursorGuide,checked:i.showCursorGuide,onChange:e=>a({showCursorGuide:e})}),(0,r.jsx)(U,{label:s.guideMask,checked:i.showGuide,onChange:e=>a({showGuide:e})}),(0,r.jsx)(U,{label:s.regionMask,checked:i.showRegionMask,onChange:e=>a({showRegionMask:e})}),(0,r.jsx)(U,{label:s.keepZoomOnImageChange,checked:i.keepZoomOnImageChange,onChange:e=>a({keepZoomOnImageChange:e})}),(0,r.jsx)(U,{label:s.wheelZoom,checked:i.wheelZoom,onChange:e=>a({wheelZoom:e})})]})}function he({label:e,children:t}){return(0,r.jsxs)(`div`,{className:`aivex:mb-2 aivex:block`,children:[(0,r.jsx)(`span`,{className:`aivex:mb-1 aivex:block aivex:text-text-secondary`,children:e}),t]})}function U({label:e,checked:n,onChange:i}){return(0,r.jsxs)(`div`,{className:`aivex:flex aivex:items-center aivex:justify-between aivex:py-1`,children:[(0,r.jsx)(`span`,{children:e}),(0,r.jsx)(t.t,{size:`sm`,checked:n,onCheckedChange:i})]})}function ge({image:t,imageUrl:n,imageVisible:i=!0,maskDataUrl:a,region:o,roiMaskId:c,shapes:l,view:u,onChangeView:d,nav:p,registerShape:m,rectRef:h,zoomLabelRef:g,onZoom100:_,open:v,onToggleOpen:y,showSettings:b=!0,settingsOpen:x,onToggleSettings:S,onCloseSettings:C,labels:w=F.minimap,settingsLabels:T}){let{offX:E,offY:D,dispW:O,dispH:k,zoomCentered:A}=p,j={position:`absolute`,left:E,top:D,width:O,height:k};return(0,r.jsxs)(`div`,{className:`aivex:absolute aivex:bottom-2 aivex:left-2 aivex:w-[188px] aivex:rounded-[8px] aivex:border aivex:border-border-default aivex:bg-bg-primary aivex:p-[4px] aivex:shadow-lg`,children:[(0,r.jsx)(`div`,{className:`aivex:overflow-hidden aivex:rounded-[4px] aivex:transition-all aivex:duration-200 aivex:ease-in-out ${v?`aivex:mb-1 aivex:max-h-[180px] aivex:opacity-100`:`aivex:max-h-0 aivex:opacity-0`}`,children:(0,r.jsx)(`div`,{className:`aivex:relative aivex:h-[180px] aivex:w-[180px] aivex:cursor-grab aivex:touch-none aivex:overflow-hidden aivex:rounded-[4px] aivex:bg-black aivex:active:cursor-grabbing`,onPointerDown:p.handleMinimapPointerDown,onPointerMove:p.handleMinimapPointerMove,onPointerUp:p.endMinimapDrag,onPointerCancel:p.endMinimapDrag,onWheel:p.handleMinimapWheel,children:(0,r.jsxs)(`div`,{style:{position:`absolute`,inset:0,opacity:+!!i,transition:i?`opacity 0.3s ease`:`none`},children:[n&&(0,r.jsx)(`img`,{src:n,alt:``,draggable:!1,style:j}),a&&u.showGuide&&(0,r.jsx)(`img`,{src:a,alt:``,draggable:!1,style:{...j,opacity:.55,imageRendering:`pixelated`,pointerEvents:`none`}}),u.showRegionMask&&o&&o.rects.length>0&&(0,r.jsx)(fe,{image:t,region:o,maskId:c,width:O,height:k,strokeWidth:1,strokeDasharray:`4 4`,style:{position:`absolute`,left:E,top:D,pointerEvents:`none`}}),(0,r.jsx)(`svg`,{viewBox:`0 0 ${t.w} ${t.h}`,width:O,height:k,style:{position:`absolute`,left:E,top:D,pointerEvents:`none`},"aria-hidden":!0,children:f(l).filter(s).map(e=>(0,r.jsx)(de,{shape:e,strokeSize:u.strokeSize,register:m},e.id))}),(0,r.jsx)(`div`,{ref:h,style:{position:`absolute`,border:`1px solid #00ff00`,background:`rgba(0,255,0,0.1)`,boxSizing:`border-box`,pointerEvents:`none`}})]})})}),(0,r.jsxs)(`div`,{className:`aivex:flex aivex:items-center aivex:justify-between`,children:[(0,r.jsxs)(`div`,{className:`aivex:flex aivex:items-center aivex:gap-0.5`,children:[(0,r.jsx)(e.t,{variant:`ghost`,size:`icon-sm`,"aria-label":w.zoomOut,onClick:()=>A(1/1.2),children:(0,r.jsx)(e.cr,{size:16})}),(0,r.jsx)(e.t,{variant:`ghost`,size:`sm`,"aria-label":w.zoom100,onClick:_,className:`aivex:min-w-[44px] aivex:px-1 aivex:tabular-nums`,children:(0,r.jsx)(`span`,{ref:g,children:`100%`})}),(0,r.jsx)(e.t,{variant:`ghost`,size:`icon-sm`,"aria-label":w.zoomIn,onClick:()=>A(1.2),children:(0,r.jsx)(e.zr,{size:16})})]}),(0,r.jsxs)(`div`,{className:`aivex:relative aivex:flex aivex:items-center aivex:gap-0.5`,children:[b&&(0,r.jsx)(e.t,{variant:`ghost`,size:`icon-sm`,"aria-label":w.viewSettings,onClick:S,onPointerDown:e=>e.stopPropagation(),className:x?`aivex:text-text-brand`:void 0,children:(0,r.jsx)(e.ci,{size:16})}),(0,r.jsx)(e.t,{variant:`ghost`,size:`icon-sm`,"aria-label":w.toggleMinimap,title:`(M)`,onClick:y,children:v?(0,r.jsx)(e.nt,{size:16}):(0,r.jsx)(e.at,{size:16})}),b&&x&&(0,r.jsx)(me,{value:u,onChange:d,onClose:C,labels:T})]})]})]})}var _e=`var(--editor-overlay-inverse-scale, 1)`,ve=6,ye={fontFamily:`Pretendard, sans-serif`,fontSize:12,fontWeight:500,lineHeight:`16px`,color:`#fff`,textShadow:`0 0 4px #000, 0 0 4px #000`,whiteSpace:`nowrap`};function be(e,t){let n=h(t);return{shape:e,x:n.minX,y:n.minY,width:n.maxX-n.minX,height:n.maxY-n.minY}}function xe(e){return`${Math.round(e.width)} x ${Math.round(e.height)} px`}function Se({color:e,striped:t}){return(0,r.jsx)(`span`,{style:{display:`inline-block`,width:12,height:12,borderRadius:`50%`,...t?{border:`2px dashed ${e}`,background:`transparent`}:{background:e}}})}function Ce({shapes:e,getLabel:t,hideDot:n,formatInfo:i,register:a}){return(0,r.jsx)(r.Fragment,{children:e.map(e=>{let s=h(e.points),c=e.type===o.POINT,l=t?.(e),u=e.style?.color??`#00e5ff`,d=!!e.readOnly||!!e.style?.dash,f=be(e,e.points),p=i?i(f):xe(f);return(0,r.jsxs)(`div`,{ref:t=>a(e.id,t),style:{position:`absolute`,left:s.minX,top:s.minY,width:s.maxX-s.minX,height:s.maxY-s.minY,pointerEvents:`none`},children:[!!l&&(0,r.jsxs)(`div`,{style:{position:`absolute`,left:0,top:0,display:`flex`,alignItems:`center`,gap:4,transform:`scale(${_e}) translateY(calc(-100% - ${ve}px))`,transformOrigin:`left top`,...ye},children:[!n&&(0,r.jsx)(Se,{color:u,striped:d}),(0,r.jsx)(`span`,{children:l})]}),!c&&!!p&&(0,r.jsx)(`div`,{"data-selinfo-dim":!0,style:{position:`absolute`,right:0,top:`100%`,transform:`scale(${_e}) translateY(${ve}px)`,transformOrigin:`right top`,...ye},children:p})]},e.id)})})}var we=new Set([L.RECTANGLE,L.ROTATED_RECTANGLE,L.CIRCLE,L.POLYGON,L.PATH,L.BRUSH,L.POINT,L.ASSISTANT_POLYGON,L.ASSISTANT_RECT,L.ASSISTANT_POINT]),Te={tl:-135,t:-90,tr:-45,r:0,br:45,b:90,bl:135,l:180},Ee=[`ew-resize`,`nwse-resize`,`ns-resize`,`nesw-resize`];function De(e,t=0){let n=((Te[e]+t*180/Math.PI)%180+180)%180;return Ee[Math.round(n/45)%4]}function Oe({tool:e,externalToolCursor:t,isSpacePressed:n,isPolygonDrawing:r}){return n?`grab`:t||(e===L.SELECT?`default`:we.has(e)?r?`default`:`crosshair`:`default`)}function ke({tool:e,externalToolCursor:t,isSpacePressed:n,interactionMode:r,rendererCursorHint:i,isPolygonDrawing:a}){return r===`marquee`?`default`:r===`moving`||r===`panning`||r===`vertexDragging`?`grabbing`:r===`resizing`||r===`rotating`?i??`grabbing`:r===`drawing`?`crosshair`:n?`grab`:t||(e===L.SELECT&&i?i:Oe({tool:e,externalToolCursor:t,isSpacePressed:n,isPolygonDrawing:a}))}var Ae=e=>Math.min(255,Math.max(0,e)),W=e=>{let t=e.replace(`#`,``).trim();if(![3,4,6,8].includes(t.length))return null;let n=e=>e.length===1?`${e}${e}`:e,r=t.length<=4,i=n(t.slice(0,r?1:2)),a=n(t.slice(r?1:2,r?2:4)),o=n(t.slice(r?2:4,r?3:6)),s=t.length===4?n(t.slice(3,4)):t.length===8?n(t.slice(6,8)):`ff`,c=e=>Number.parseInt(e,16),l=[c(i),c(a),c(o),c(s)];return l.some(e=>Number.isNaN(e))?null:l.map(Ae)},je=(e,t)=>{let{width:n,height:r,indices:i,transparent:a}=e;if(!n||!r||i.length<n*r)return null;let o={};for(let[e,n]of Object.entries(t)){let t=W(n);t&&(o[Number(e)]=t)}if(!Object.keys(o).length)return null;let s=document.createElement(`canvas`);s.width=n,s.height=r;let c=s.getContext(`2d`);if(!c)return null;let l=new Uint8ClampedArray(n*r*4),u=n*r;for(let e=0;e<u;e+=1){let t=i[e];if(t===a)continue;let n=o[t];if(!n)continue;let r=e*4;l[r]=n[0],l[r+1]=n[1],l[r+2]=n[2],l[r+3]=n[3]}return c.putImageData(new ImageData(l,n,r),0,0),s};function Me(e,t){e.beginPath(),e.moveTo(t[0].x,t[0].y);for(let n=1;n<t.length;n+=1)e.lineTo(t[n].x,t[n].y);e.closePath()}var Ne=e=>[{x:e.x,y:e.y},{x:e.x+e.w,y:e.y},{x:e.x+e.w,y:e.y+e.h},{x:e.x,y:e.y+e.h}];function Pe(e,t){let n=!1;for(let r=0,i=t.length-1;r<t.length;i=r,r+=1){let a=t[r],o=t[i];if(a.y>e.y!=o.y>e.y){let t=(e.y-a.y)/(o.y-a.y);e.x<a.x+t*(o.x-a.x)&&(n=!n)}}return n}function Fe(e,t,n){let r=[],i=t.x-e.x,a=t.y-e.y;for(let t=0;t<n.length;t+=1){let o=n[t],s=n[(t+1)%n.length],c=s.x-o.x,l=s.y-o.y,u=i*l-a*c;if(!u)continue;let d=((o.x-e.x)*l-(o.y-e.y)*c)/u,f=((o.x-e.x)*a-(o.y-e.y)*i)/u;d>0&&d<1&&f>=0&&f<=1&&r.push(d)}return r}function G(e,t,n){let r=.001,i=[],a=(e,t,n)=>({x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n});for(let o of e)if(!(o.length<2))for(let e=0;e<o.length;e+=1){let s=o[e],c=o[(e+1)%o.length],l=[0,1];for(let e of t)e!==o&&l.push(...Fe(s,c,e));if(n)for(let e of n)l.push(...Fe(s,c,e));let u=Math.hypot(c.x-s.x,c.y-s.y);if(!u)continue;let d=-(c.y-s.y)/u*r,f=(c.x-s.x)/u*r;l.sort((e,t)=>e-t);for(let e=0;e+1<l.length;e+=1){let r=l[e],u=l[e+1];if(u-r<1e-9)continue;let p=a(s,c,(r+u)/2),m={x:p.x+d,y:p.y+f},h={x:p.x-d,y:p.y-f},g=Pe(m,o)?m:h,_=g===m?h:m;t.some(e=>e!==o&&Pe(_,e))||n&&!n.some(e=>Pe(g,e))||i.push([a(s,c,r),a(s,c,u)])}}return i}function Ie(e){let t=[...new Set(e.flatMap(e=>[e.x,e.x+e.w]))].sort((e,t)=>e-t),n=[];for(let r=0;r+1<t.length;r+=1){let i=t[r],a=t[r+1];if(a<=i)continue;let o=e.filter(e=>e.x<=i&&e.x+e.w>=a).map(e=>[e.y,e.y+e.h]).sort((e,t)=>e[0]-t[0]),s=null;for(let[e,t]of o)!s||e>s[1]?(s&&n.push({x:i,y:s[0],w:a-i,h:s[1]-s[0]}),s=[e,t]):s[1]=Math.max(s[1],t);s&&n.push({x:i,y:s[0],w:a-i,h:s[1]-s[0]})}return n}function Le(e,t,n,r){e.save(),e.globalAlpha*=t.dim.opacity,e.fillStyle=t.dim.color,e.beginPath(),e.rect(0,0,n,r);for(let n of t.dimHoles)e.moveTo(n.x,n.y),e.lineTo(n.x,n.y+n.h),e.lineTo(n.x+n.w,n.y+n.h),e.lineTo(n.x+n.w,n.y),e.closePath();if(e.fill(),t.zones.length){e.beginPath();for(let n of t.rects)e.rect(n.x,n.y,n.w,n.h);e.clip();for(let n of t.zones)Me(e,n.points),e.fill()}e.restore()}function Re(e){let t=[];for(let n of e)if(!(n.length<2))for(let e=0;e<n.length;e+=1)t.push([n[e],n[(e+1)%n.length]]);return t}var K={color:`#000000`,opacity:.5},ze={color:`#ffffff`,opacity:1,width:2,dash:[6,6],underlayColor:`#000000`},Be={color:`#dc2626`,opacity:.8,width:2,dash:[6,6],underlayColor:`#000000`},Ve=(e,t,n)=>{let r=e.occludedAreas?.filter(e=>e.points.length>=3)??[];if(!t||!n||!e.visibleAreas.length&&!r.length)return null;let i=e.visibleAreas,a=i.length?i:[{x:0,y:0,w:t,h:n}],o=Ie(a),s={...K,...e.dim},c=e.outline;if(c===!1)return{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:[],occludedOutline:[],outlineStyles:null};let l={visible:{...ze,...c?.visibleStyle},occluded:{...Be,...c?.occludedStyle}},u=i.map(Ne),d=a.map(Ne),f=r.map(e=>e.points);return c?.mode===`separate`?{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:Re(u),occludedOutline:Re(f),outlineStyles:l}:{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:[...G(u,[...u,...f],null),...G(f,f,d)],occludedOutline:[],outlineStyles:l}},He=.3,Ue=.05;function We(e){return 1-(1-e)**3}function Ge(e){return{x:e.minX,y:e.minY,width:Math.max(0,e.maxX-e.minX),height:Math.max(0,e.maxY-e.minY)}}function Ke(e,t){if(!t.length)return null;if(e===o.POINT){let e=t[0];return{x:e.x-8,y:e.y-8,width:16,height:16}}let n=h(t),r=Math.max(1,n.maxX-n.minX),i=Math.max(1,n.maxY-n.minY);return{x:n.minX,y:n.minY,width:r,height:i}}function qe(e){if(!e.length)return null;let t=e.map(e=>Ke(e.type,e.points)).filter(e=>e!==null);return t.length?Ge(h(t.flatMap(e=>[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y+e.height}]))):null}function Je(e,t,n,r={}){let{containerRatio:i=He,minScale:a=Ue,maxScale:o=20}=r;if(!t||!n||e.width<=0||e.height<=0)return null;let s=Math.min(t*i/e.width,n*i/e.height),c=Math.max(a,Math.min(o,s)),l=e.x+e.width/2,u=e.y+e.height/2;return{scale:c,x:t/2-l*c,y:n/2-u*c}}function Ye(e,t,n,r=80){if(!t||!n)return null;let i=Math.max(1,e.maxX-e.minX),a=Math.max(1,e.maxY-e.minY),o=Math.max(Ue,Math.min(20,Math.min((t-r)/i,(n-r)/a))),s=(e.minX+e.maxX)/2,c=(e.minY+e.maxY)/2;return{scale:o,x:t/2-s*o,y:n/2-c*o}}function Xe(e,t,n,r=300){let i=Date.now(),a=0,o=()=>{let s=Date.now()-i,c=Math.min(s/r,1),l=We(c);n({scale:e.scale+(t.scale-e.scale)*l,x:e.x+(t.x-e.x)*l,y:e.y+(t.y-e.y)*l}),c<1&&(a=requestAnimationFrame(o))};return a=requestAnimationFrame(o),()=>cancelAnimationFrame(a)}function Ze(e){let{engineRef:t,toolRef:n,externalToolMapRef:r,spaceRef:i,shiftRef:a,docRef:s,selRef:c,draftRef:u,readOnlyRef:p,disableMarqueeRef:m,lockedRef:g,onLockedInteraction:_,createRef:y,selectRef:S,enterEditRef:C,drawSessionRef:w,assistantRef:T,setCursorHint:E,setInteractionMode:D,syncMinimap:O,onTransformPreview:k,onDrawPreview:A}=e,j=()=>w.current,M=()=>T.current,N=null,P=null,F=null,I=null,R=null,ee=``,te=null,ne=e=>e===L.RECTANGLE||e===L.ROTATED_RECTANGLE||e===L.CIRCLE,re=e=>e===L.ASSISTANT_POLYGON||e===L.ASSISTANT_RECT,ie=e=>e===L.POLYGON,z=()=>r.current.get(n.current),B=(e,t,n,r)=>({point:t,targetId:r,event:n,readOnly:p.current,viewport:e.viewport});return{onCursorHint:E,onInteractionModeChange:D,onPointerDown:(e,r,m)=>{let v=t.current;if(!v)return;let y=n.current;if(m.button===1||i.current){D(`panning`),E(null),N={x:v.viewport.x,y:v.viewport.y,px:m.global.x,py:m.global.y};return}if(m.button===2&&!(y===L.ASSISTANT_POINT&&m.altKey))return;let b=z();if(b){j().reset(),S.current([]),b.onPointerDown?.(B(v,e,m,r));return}if(g.current){_();return}if(y===L.ASSISTANT_POINT){m.altKey?M().addPoint(e,m.button!==2):M().newPolygon(e);return}if(re(y)&&u.current){P=e,D(`drawing`);return}if(y===L.SELECT&&m.altKey){let t=f(s.current.getShapes()).filter(t=>{if(!l(t))return!1;let n=h(t.points);return e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY});if(t.length){let e=[...t].reverse(),n=[e[(e.findIndex(e=>c.current.includes(e.id))+1)%e.length].id];S.current(n);return}}if(r&&y===L.SELECT){let t=s.current.getShapes().find(e=>e.id===r);if(!t||!l(t))return;let n=typeof performance<`u`?performance.now():0,i=!!te&&te.id===r&&n-te.t<300;te={id:r,t:n};let u=(t.type===o.POLYGON||t.type===o.LINE)&&!p.current&&t.interaction?.editable!==!1&&!t.readOnly;if(i&&u){S.current([r]),C.current(r);return}let f=c.current;if(a.current){let e=new Set(f);e.has(r)?e.delete(r):e.add(r),f=[...e]}else f.includes(r)||(f=[r]);S.current(f),!p.current&&d(t)&&v.beginMove(e,f);return}if(ne(y)&&u.current){P=e,D(`drawing`);return}if(ie(y)&&u.current){if(!j().getDraftPointsSnapshot().length&&c.current.length&&S.current([]),j().tryClosePolygon(e,12/v.viewport.scale))return;let t=j().hitDraftPoint(e);if(t>=0){if(m.altKey){j().removeDraftPoint(t);return}let n=j().selectDraftPointForDrag(t,m.shiftKey||m.ctrlKey||m.metaKey);if(!n)return;I={start:e,base:n.base,indices:n.indices,moved:!1},D(`vertexDragging`);return}j().appendPolygonPoint(e);return}if(y===L.PATH&&u.current){c.current.length&&S.current([]),F=`path`,D(`drawing`),j().beginStroke(e);return}if(y===L.BRUSH&&u.current&&!p.current){F=`scalar`,D(`drawing`),j().beginStroke(e);return}if(y===L.SELECT){if(!a.current&&!p.current&&c.current.length>=2){let t=s.current.getShapes().filter(e=>c.current.includes(e.id)&&d(e));if(t.length){let n=h(t.flatMap(e=>e.points));if(e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY){v.beginMove(e,c.current);return}}}R=e,ee=``,D(`marquee`),E(null)}},onPointerMove:(e,r)=>{let i=t.current;if(!i)return;if(N){i.applyViewport({scale:i.viewport.scale,x:N.x+(r.global.x-N.px),y:N.y+(r.global.y-N.py)});return}let s=n.current,c=z();if(c){c.onPointerMove?.(B(i,e,r));return}if(I){let t=e.x-I.start.x,n=e.y-I.start.y;I.moved=I.moved||Math.hypot(t,n)>.5,j().moveDraftPoints(I.base,I.indices,t,n);return}if(P&&(ne(s)||re(s))){let t=a.current?v(P,e):e;i.previewBox(s===L.CIRCLE?`ellipse`:`rect`,P,t,{...u.current,color:u.current?.color??`#00e5ff`}),ne(s)&&A({type:s===L.CIRCLE?o.ELLIPSE:o.RECTANGLE,points:[P,t]});return}if(F){j().appendStrokePoint(e,2/i.viewport.scale);return}if(ie(s)&&j().hasDraftPoints()){j().setDraftCursor(e);return}if(R){if(m?.current)return;let t={minX:Math.min(R.x,e.x),minY:Math.min(R.y,e.y),maxX:Math.max(R.x,e.x),maxY:Math.max(R.y,e.y)};i.previewMarquee(R,e);let n=i.shapesIntersecting(t),r=n.join(`,`);r!==ee&&(ee=r,S.current(n))}},onPointerUp:e=>{let r=t.current;if(!r)return;if(N){N=null,D(`idle`);return}if(I){j().commitDraftPointDrag(I.moved),I=null,D(`idle`);return}let i=n.current,s=z();if(s){s.onPointerUp?.(B(r,e,{}));return}if(i===L.POINT&&u.current){y.current(o.POINT,[e]);return}if(F){let e=F;F=null,D(`idle`),e===`path`?j().completeFreehandStroke():j().finishScalarStroke();return}if(P&&re(i)){let t=P;P=null,D(`idle`),r.clearPreview();let n={x:Math.min(t.x,e.x),y:Math.min(t.y,e.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)};n.width>2&&n.height>2&&M().beginBox(n,i===L.ASSISTANT_RECT?`rect`:`polygon`);return}if(P&&ne(i)){let t=a.current?v(P,e):e,n=P;P=null,D(`idle`),r.clearPreview(),A(null),Math.abs(t.x-n.x)>2&&Math.abs(t.y-n.y)>2&&(i===L.ROTATED_RECTANGLE?y.current(o.ROTATED_RECTANGLE,b([n,t])):i===L.CIRCLE?y.current(o.POLYGON,x(n,t)):y.current(o.RECTANGLE,[n,t]));return}if(R){let t=Math.abs(e.x-R.x)>3||Math.abs(e.y-R.y)>3;R=null,r.clearMarquee(),D(`idle`),!t&&c.current.length&&S.current([])}},onViewportChange:O,onTransformPreview:k,onTransformCommit:e=>{let t=s.current.getShapes(),n=e.map(e=>{let n=t.find(t=>t.id===e.id);return n?{...n,points:e.points}:null}).filter(e=>!!e);n.length&&s.current.update(n)}}}function Qe({docRef:e,draftRef:t,draftMeta:r,changeSelection:i,assistantRef:a}){let[s,c]=(0,n.useState)(`idle`),[l,u]=(0,n.useState)([]),[d,f]=(0,n.useState)([]),m=(0,n.useRef)([]),g=(0,n.useRef)([]),_=(0,n.useRef)([]),v=(0,n.useRef)(`idle`),y=(0,n.useRef)(0),b=(0,n.useRef)(null),x=(0,n.useRef)(null),S=(0,n.useRef)(0),w=(0,n.useCallback)(e=>{m.current=e(m.current),f(m.current)},[]),T=(0,n.useCallback)(e=>{v.current=e,c(e)},[]),E=(0,n.useCallback)((e,t,n)=>{let i=a.current?.rectResult===`rotatedRect`;return e.map(e=>{if(t===`rect`&&i)return{id:p(),type:o.ROTATED_RECTANGLE,points:C(e),style:n,meta:r};if(t===`rect`){let t=h(e);return{id:p(),type:o.RECTANGLE,points:[{x:t.minX,y:t.minY},{x:t.maxX,y:t.maxY}],style:n,meta:r}}return{id:p(),type:o.POLYGON,points:e,style:n,meta:r}})},[r,a]),D=(0,n.useCallback)(()=>{y.current++,g.current=[],_.current=[],b.current=null,x.current=null,u([]),T(`idle`)},[T]),O=(0,n.useCallback)(()=>{S.current++,w(()=>[]);let t=x.current;t?e.current.update([t]):_.current.length&&e.current.remove(_.current),D()},[e,D,w]),k=(0,n.useCallback)(n=>{let r=_.current;if(!n.length){r.length&&(e.current.remove(r),_.current=[]);return}if(r.length===n.length){let t=e.current.getShapes(),i=n.map((e,n)=>{let i=t.find(e=>e.id===r[n]);return i?{...i,points:e}:null}).filter(e=>!!e);i.length&&e.current.update(i);return}b.current=null,x.current=null,r.length&&e.current.remove(r);let a=t.current;if(!a)return;let o=E(n,`polygon`,a);o?.length&&(e.current.create(o),_.current=o.map(e=>e.id),i(_.current))},[e,t,i,E]),A=(0,n.useCallback)(async()=>{let e=a.current?.infer;if(!e)return;let t={kind:`points`,points:g.current,base:b.current??void 0},n=++y.current;T(`loading`);let r=[];try{r=(await e(t)??[]).filter(e=>e.length>=3)}catch{r=[]}n===y.current&&(k(r),T(`ready`))},[a,k,T]),j=(0,n.useCallback)((e,t)=>{g.current=[...g.current,{x:e.x,y:e.y,positive:t}],u([{x:e.x,y:e.y,positive:t}]),A()},[A]),M=(0,n.useCallback)(e=>{D();let t=[{x:e.x,y:e.y,positive:!0}];g.current=t,u(t),A()},[D,A]),N=(0,n.useCallback)((e,t,n)=>{(_.current.length!==1||_.current[0]!==e.id)&&(D(),_.current=[e.id],b.current=e.points,x.current=e),g.current=[...g.current,{x:t.x,y:t.y,positive:n}],u([{x:t.x,y:t.y,positive:n}]),A()},[D,A]);return{status:s,points:l,boxes:d,beginBox:(0,n.useCallback)((n,r=`polygon`)=>{let o=a.current?.infer,s=t.current;if(!o||!s)return;let c=S.current;w(e=>[...e,n]),(async()=>{let t=[];try{t=(await o({kind:`box`,box:n})??[]).filter(e=>e.length>=3)}catch{t=[]}if(w(e=>e.filter(e=>e!==n)),c!==S.current)return;let a=E(t,r,s);a?.length&&(e.current.create(a),i(a.map(e=>e.id)))})()},[a,t,E,i,e,w]),addPoint:j,newPolygon:M,refineShape:N,finalize:D,cancel:O,isActive:(0,n.useCallback)(()=>v.current===`loading`||g.current.length>0||m.current.length>0||_.current.length>0,[])}}function $e(e,t,n){let r=Math.abs(.5*(t.x*n.y+n.x*e.y+e.x*t.y-n.x*t.y-e.x*n.y-t.x*e.y)),i=Math.hypot(t.x-n.x,t.y-n.y);return i===0?0:r*2/i}function q(e,t=1.5){if(e.length<=2)return e;let n=(e,t)=>{if(e.length<3)return e;let r=0,i=0,a=e.length-1;for(let t=1;t<a;t++){let n=$e(e[t],e[0],e[a]);n>r&&(i=t,r=n)}if(r>t){let r=n(e.slice(0,i+1),t),a=n(e.slice(i),t);return r.slice(0,-1).concat(a)}return[e[0],e[a]]},r=n(e,t),i=e[e.length-1],a=r[r.length-1];return(i.x!==a.x||i.y!==a.y)&&r.push(i),r}var et=4096,tt=4;function J(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n],i=e[(n+1)%e.length];t+=r.x*i.y-i.x*r.y}return Math.abs(t/2)}function nt(e,t,n){let r=new Uint8Array(t*n);for(let i=0;i<t*n;i++)r[i]=e[i*4+3]>128?255:0;return r}function rt(e){let t=new Uint8ClampedArray(e.length*4);for(let n=0;n<e.length;n++)e[n]>128&&(t[n*4+3]=255);return t}function it(e,t,n,r,i){let a=new Uint8Array(t*n),o=[[r,i]];for(;o.length;){let[r,i]=o.pop(),s=i*t+r;r<0||i<0||r>=t||i>=n||e[s]<=128||(e[s]=0,a[s]=255,o.push([r+1,i],[r-1,i],[r,i+1],[r,i-1]))}return a}function at(e,t,n){let r=nt(e,t,n),i=[];for(;;){let e=-1,a=-1;outer:for(let i=0;i<n;i++)for(let n=0;n<t;n++)if(r[i*t+n]>128){e=n,a=i;break outer}if(e<0)break;let o=ot(rt(it(r,t,n,e,a)),t,n);o.length>=3&&i.push(o)}return i}function Y(e,t,n,r,i){return r<0||i<0||r>=t||i>=n?!1:e[(i*t+r)*4+3]>128}function ot(e,t,n){let r=-1,i=-1;outer:for(let a=0;a<n;a++)for(let o=0;o<t;o++)if(Y(e,t,n,o,a)){r=o,i=a;break outer}if(r<0)return[];let a=[1,1,0,-1,-1,-1,0,1],o=[0,1,1,1,0,-1,-1,-1],s=[],c=r,l=i,u=7,d={x:c,y:l},f=0;do{s.push({x:c,y:l});let r=!1;for(let i=0;i<8;i++){let s=(u+i)%8,d=c+a[s],f=l+o[s];if(Y(e,t,n,d,f)){c=d,l=f,u=(s+6)%8,r=!0;break}}if(!r||(f+=1,f>t*n*4))break}while(c!==d.x||l!==d.y||s.length===1);return s}function st(e,t){let n=[];for(let t of e)for(let e of t.points)n.push(e);for(let e of t)for(let t of e)n.push(t);return n}function X(e){switch(e.type){case o.RECTANGLE:return e.points.length<2?null:b(e.points);case o.POLYGON:case o.ROTATED_RECTANGLE:case o.ELLIPSE:return e.points.length>=3?e.points:null;case o.POINT:{let t=e.points[0];return t?x({x:t.x-6,y:t.y-6},{x:t.x+6,y:t.y+6}):null}default:return null}}function ct(e){return e.map(X).filter(e=>!!e&&e.length>=3)}function lt(e,t,n=[]){if(t<=0||!e.length&&!n.length)return null;let r=st(e,n);if(!r.length)return null;let i=t+4,a=h(r),o=Math.ceil(a.maxX-a.minX+i*2),s=Math.ceil(a.maxY-a.minY+i*2),c=Math.min(1,et/Math.max(o,s,1));o=Math.max(1,Math.ceil(o*c)),s=Math.max(1,Math.ceil(s*c));let l=a.minX-i,u=a.minY-i,d=e=>({x:(e.x-l)*c,y:(e.y-u)*c}),f=document.createElement(`canvas`);f.width=o,f.height=s;let p=f.getContext(`2d`);if(!p)return null;p.lineCap=`round`,p.lineJoin=`round`,p.lineWidth=t*2*c,p.fillStyle=`#000`;for(let e of n){if(e.length<3)continue;p.beginPath();let t=d(e[0]);p.moveTo(t.x,t.y);for(let t=1;t<e.length;t++){let n=d(e[t]);p.lineTo(n.x,n.y)}p.closePath(),p.fill()}for(let t of e){if(!t.points.length)continue;p.globalCompositeOperation=t.mode===`erase`?`destination-out`:`source-over`,p.strokeStyle=t.mode===`erase`?`rgba(0,0,0,1)`:`#000`,p.beginPath();let e=d(t.points[0]);p.moveTo(e.x,e.y);for(let e=1;e<t.points.length;e++){let n=d(t.points[e]);p.lineTo(n.x,n.y)}t.points.length===1&&p.lineTo(e.x+.01,e.y),p.stroke()}return{canvas:f,ox:l,oy:u,scale:c}}function ut(e,t=1.5){let{canvas:n,ox:r,oy:i,scale:a}=e,o=at(n.getContext(`2d`).getImageData(0,0,n.width,n.height).data,n.width,n.height);if(!o.length)return[];let s=e=>({x:e.x/a+r,y:e.y/a+i}),c=[];for(let e of o){let n=e.map(s),r=q(n,t),i=r.length>=3?r:n;i.length>=3&&J(i)>=tt&&c.push(i)}return c}function dt(e,t){let{canvas:n}=e,r=document.createElement(`canvas`);r.width=n.width,r.height=n.height;let i=r.getContext(`2d`);return i?(i.drawImage(n,0,0),i.globalCompositeOperation=`source-in`,i.fillStyle=t,i.fillRect(0,0,r.width,r.height),r):n}function ft(e){return e.map(e=>({mode:e.mode,points:e.points.map(e=>({...e}))}))}function pt(e,t){return e.length===t.length&&e.every((e,n)=>e.mode===t[n].mode&&e.points.length===t[n].points.length&&e.points.every((e,r)=>e.x===t[n].points[r].x&&e.y===t[n].points[r].y))}function mt(e){return e.map(e=>({...e}))}function ht(e,t){return e.length===t.length&&e.every((e,n)=>e.x===t[n].x&&e.y===t[n].y)}var gt=10;function _t({toolRef:e,selRef:t,docRef:r,readOnlyRef:i,draftRef:a,brushSizeRef:s,simplifyEpsilonRef:c,draftMeta:l,engineRef:d,onDrawSessionChange:f,onDraftShapeChange:m,changeSelection:h,createShape:g}){let _=(0,n.useRef)(f);_.current=f;let v=(0,n.useRef)(m);v.current=m;let y=(0,n.useRef)(l);y.current=l;let b=(0,n.useRef)(g);b.current=g;let x=(0,n.useRef)([]),S=(0,n.useRef)(null),C=(0,n.useRef)(new Set),w=(0,n.useRef)([[]]),T=(0,n.useRef)(0),E=(0,n.useRef)(``),D=(0,n.useRef)([]),O=(0,n.useRef)([]),k=(0,n.useRef)([]),A=(0,n.useRef)([[]]),j=(0,n.useRef)(0),M=(0,n.useRef)(`draw`),N=()=>M.current===`erase`?`erase`:`add`,P=()=>k.current.length>0||D.current.length>0||e.current===L.BRUSH&&x.current.length>0,F=()=>{let t=e.current;return t===L.BRUSH&&P()?`brush`:t===L.POLYGON&&x.current.length>0?`polygon`:t===L.PATH&&x.current.length>0?`path`:`none`},I=()=>x.current.length>0||j.current>0,R=()=>x.current.length===0&&j.current<A.current.length-1,ee=()=>T.current>0,te=()=>T.current<w.current.length-1,ne=()=>{let t=e.current;return t===L.BRUSH?I():t===L.POLYGON||t===L.PATH?ee():!1},re=()=>{let t=e.current;return t===L.BRUSH?R():t===L.POLYGON||t===L.PATH?te():!1},ie=()=>F()!==`none`,z=(0,n.useCallback)(()=>{let e=F();_.current?.({active:e!==`none`,kind:e,canUndo:ne(),canRedo:re(),brush:e===`brush`?{mode:M.current,editing:k.current.length>0,editTargetIds:[...k.current]}:void 0})},[]),B=(0,n.useCallback)(()=>{A.current=[[]],j.current=0},[]),V=(0,n.useCallback)(()=>{let t=d.current;if(!t)return;let n=e.current;if(n===L.BRUSH){let e=[...D.current];if(x.current.length&&e.push({points:x.current,mode:N()}),!e.length&&!O.current.length){t.clearPreview();return}let n=lt(e,s.current,O.current);if(!n){t.clearPreview();return}let r=a.current?.color??`#00e5ff`;t.previewScalarMask(n,r);return}let r=x.current;if(!r.length){t.clearPreview(),n===L.POLYGON&&E.current&&(E.current=``,v.current?.(null));return}let i={...a.current,color:a.current?.color??`#00e5ff`},c=Array.from(C.current),l=n!==L.PATH;if(t.previewPoly(r,S.current,i,!1,c,l),n===L.POLYGON){let e=r.map(e=>`${e.x},${e.y}`).join(`;`);e!==E.current&&(E.current=e,v.current?.({type:o.POLYGON,points:mt(r),meta:y.current}))}},[s,a,d,e]),ae=(0,n.useCallback)(e=>{let t=ft(e),n=A.current,r=j.current,i=n[r];i&&pt(i,t)||(A.current=[...n.slice(0,r+1),t],j.current+=1,z())},[z]),oe=(0,n.useCallback)(e=>{let t=w.current,n=T.current,r=t[n];r&&ht(r,e)||(w.current=[...t.slice(0,n+1),mt(e)],T.current+=1)},[]),H=(0,n.useCallback)(()=>{x.current=[],D.current=[],O.current=[],k.current=[],S.current=null,C.current=new Set,w.current=[[]],T.current=0,E.current=``,B(),d.current?.clearPreview(),v.current?.(null),z()},[d,z,B]),se=(0,n.useCallback)((e,t)=>{x.current=e,C.current=new Set(Array.from(C.current).filter(t=>t>=0&&t<e.length)),t&&oe(e),V(),z()},[z,oe,V]),ce=(0,n.useCallback)(()=>mt(x.current),[]),le=(0,n.useCallback)(()=>x.current.length>0,[]),ue=(0,n.useCallback)((t,n)=>{if(e.current!==L.POLYGON)return!1;let r=x.current;if(r.length<3)return!1;let i=r[0];return Math.hypot(t.x-i.x,t.y-i.y)>n?!1:(b.current(o.POLYGON,r),H(),!0)},[H,e]),de=(0,n.useCallback)(e=>{let t=x.current;return e<0||e>=t.length?!1:(se(t.filter((t,n)=>n!==e),!0),!0)},[se]),fe=(0,n.useCallback)((e,t)=>{let n=x.current;if(e<0||e>=n.length)return null;let r=new Set(C.current);return t?r.has(e)?r.delete(e):r.add(e):r.has(e)||(r.clear(),r.add(e)),C.current=r,S.current=null,V(),z(),{base:mt(n),indices:Array.from(r)}},[z,V]),pe=(0,n.useCallback)(e=>{C.current=new Set,S.current=e,se([...x.current,e],!0)},[se]),me=(0,n.useCallback)(e=>{S.current=null,C.current=new Set,x.current=[{...e}],V(),z()},[z,V]),he=(0,n.useCallback)((e,t)=>{let n=x.current[x.current.length-1];return n&&Math.hypot(e.x-n.x,e.y-n.y)<t?!1:(x.current=[...x.current,{...e}],S.current=null,V(),z(),!0)},[z,V]),U=(0,n.useCallback)((e,t,n,r)=>{let i=new Set(t);x.current=e.map((e,t)=>i.has(t)?{x:e.x+n,y:e.y+r}:{...e}),S.current=null,V(),z()},[z,V]),ge=(0,n.useCallback)(e=>{e&&(oe(x.current),V(),z())},[z,oe,V]),_e=(0,n.useCallback)(e=>{S.current=e?{...e}:null,V(),z()},[z,V]),ve=(0,n.useCallback)(()=>x.current.length>0?(x.current=[],V(),z(),!0):j.current<=0?!1:(--j.current,D.current=ft(A.current[j.current]),V(),z(),!0),[z,V]),ye=(0,n.useCallback)(()=>x.current.length>0||j.current>=A.current.length-1?!1:(j.current+=1,D.current=ft(A.current[j.current]),V(),z(),!0),[z,V]),be=(0,n.useCallback)(()=>T.current<=0?!1:(--T.current,x.current=mt(w.current[T.current]),C.current=new Set,V(),z(),!0),[z,V]),xe=(0,n.useCallback)(()=>T.current>=w.current.length-1?!1:(T.current+=1,x.current=mt(w.current[T.current]),C.current=new Set,V(),z(),!0),[z,V]),Se=(0,n.useCallback)(()=>{let t=e.current;return t===L.BRUSH?ve():t===L.POLYGON||t===L.PATH?be():!1},[e,ve,be]),Ce=(0,n.useCallback)(()=>{let t=e.current;return t===L.BRUSH?ye():t===L.POLYGON||t===L.PATH?xe():!1},[ye,xe,e]),we=(0,n.useCallback)(()=>{let e=t.current;if(!e.length)return k.current.length>0;let n=r.current.getShapes().filter(t=>e.includes(t.id)&&u(t)),i=ct(n);return i.length?(k.current=n.map(e=>e.id),O.current=i,!0):(k.current=[],O.current=[],!1)},[r,t]),Te=(0,n.useCallback)(()=>{if(i.current)return!1;let e=[...D.current];x.current.length&&e.push({points:mt(x.current),mode:N()});let t=O.current,n=[...k.current];if(!e.length&&!t.length)return!1;let u=lt(e,s.current,t);if(!u)return H(),!1;let d=ut(u,c.current);if(n.length){let e=r.current.getShapes().filter(e=>n.includes(e.id));if(!d.length)return r.current.remove(n),H(),h([]),!0;d.sort((e,t)=>J(t)-J(e));let t=[],i=[],a=[];for(let n=0;n<d.length;n++){let r=d[n];if(n<e.length){let i=e[n];t.push({...i,type:o.POLYGON,points:r}),a.push(i.id)}else{let t=e[0],n=p();i.push({...t,id:n,type:o.POLYGON,points:r}),a.push(n)}}let s=e.slice(d.length).map(e=>e.id);return t.length&&r.current.update(t),i.length&&r.current.create(i),s.length&&r.current.remove(s),H(),h(a),!0}if(!d.length)return H(),!1;let f=a.current;if(!f)return!1;let m=d.map(e=>({id:p(),type:o.POLYGON,points:e,style:f,meta:l}));return r.current.create(m),h(m.map(e=>e.id)),H(),!0},[s,h,r,l,a,i,H]),Ee=(0,n.useCallback)(()=>{let t=e.current;if(t===L.BRUSH)return Te();let n=x.current;return t===L.POLYGON&&n.length>=3?(b.current(o.POLYGON,n),H(),!0):!1},[Te,H,e]),De=(0,n.useCallback)(()=>{let t=x.current;if(e.current===L.PATH&&t.length>=3){let e=q(t,c.current);e.length>=3&&b.current(o.POLYGON,e)}H()},[H,e]),Oe=(0,n.useCallback)(e=>{M.current=e,z(),V()},[z,V]),ke=(0,n.useCallback)(()=>{if(i.current||e.current!==L.BRUSH)return!1;D.current=[],x.current=[],B();let t=we();return z(),V(),t},[z,i,V,B,we,e]),Ae=(0,n.useCallback)(()=>{let e=C.current;if(!e.size)return!1;let t=x.current.filter((t,n)=>!e.has(n));return C.current=new Set,se(t,!0),!0},[se]),W=(0,n.useCallback)(e=>{let t=d.current,n=x.current;if(!t||!n.length)return-1;let r=gt/(t.viewport.scale||1);for(let t=n.length-1;t>=0;t--){let i=n[t];if(Math.hypot(e.x-i.x,e.y-i.y)<=r)return t}return-1},[d]),je=(0,n.useCallback)(()=>{x.current.length>=1&&(D.current.push({points:mt(x.current),mode:N()}),x.current=[],ae(D.current)),V(),z()},[z,ae,V]);return{reset:H,undoSession:Se,redoSession:Ce,canUndoSession:ne,canRedoSession:re,hasDraftSession:ie,hasDraftPoints:le,commitDraftSession:Ee,completeFreehandStroke:De,setBrushScalarMode:Oe,getBrushScalarMode:()=>M.current,hasBrushSession:P,commitBrush:Te,cancelBrush:(0,n.useCallback)(()=>{e.current===L.BRUSH&&H()},[H,e]),beginBrushEditFromSelection:ke,deleteDraftSelectedPoints:Ae,hitDraftPoint:W,getDraftPointsSnapshot:ce,tryClosePolygon:ue,removeDraftPoint:de,selectDraftPointForDrag:fe,appendPolygonPoint:pe,beginStroke:me,appendStrokePoint:he,moveDraftPoints:U,commitDraftPointDrag:ge,setDraftCursor:_e,finishScalarStroke:je,handleToolChange:(0,n.useCallback)((e,t)=>{if(t){H(),M.current=`draw`;return}if(e!==L.BRUSH){H(),M.current=`draw`;return}M.current=`draw`,D.current=[],x.current=[],B(),we(),z(),V()},[z,V,H,B,we]),handleBrushSelectionChange:(0,n.useCallback)((t,n)=>{if(!(e.current!==L.BRUSH||n)){if(!t.length){z();return}[...t].sort().join(`,`)!==[...k.current].sort().join(`,`)&&(D.current.length||x.current.length||(D.current=[],x.current=[],B(),we(),z(),V()))}},[z,V,B,we,e])}}function vt(e,t){return{shapes:t,past:[...e.past,e.shapes],future:[]}}function yt(e,t){switch(t.type){case`CREATE`:return vt(e,[...e.shapes,...t.shapes]);case`UPDATE`:{let n=new Map(t.shapes.map(e=>[e.id,e]));return vt(e,e.shapes.map(e=>n.get(e.id)??e))}case`DELETE`:{let n=new Set(t.ids);return vt(e,e.shapes.filter(e=>!n.has(e.id)))}case`REPLACE`:{let n=new Set(t.removeIds);return vt(e,[...e.shapes.filter(e=>!n.has(e.id)),...t.shapes])}case`REORDER`:{let n=new Set(t.ids),r=e.shapes.filter(e=>n.has(e.id)),i=e.shapes.filter(e=>!n.has(e.id));return r.length===0?e:vt(e,t.edge===`front`?[...i,...r]:[...r,...i])}case`RESET`:return{shapes:t.shapes,past:[],future:[]};case`UNDO`:return e.past.length===0?e:{shapes:e.past[e.past.length-1],past:e.past.slice(0,-1),future:[e.shapes,...e.future]};case`REDO`:return e.future.length===0?e:{shapes:e.future[0],past:[...e.past,e.shapes],future:e.future.slice(1)};default:return e}}function bt(e){let{onShapesCreated:t,onShapesUpdated:r,onShapesDeleted:i}=e,[a,o]=(0,n.useReducer)(yt,{shapes:[],past:[],future:[]}),s=(0,n.useRef)(a);s.current=a;let c=(0,n.useCallback)(e=>{s.current=yt(s.current,e),o(e)},[]),l=(0,n.useCallback)((e,n)=>{let a=new Map(e.map(e=>[e.id,e])),o=new Map(n.map(e=>[e.id,e])),s=n.filter(e=>!a.has(e.id));s.length&&t?.(s);let c=e.filter(e=>!o.has(e.id)).map(e=>e.id);c.length&&i?.(c);let l=n.filter(e=>a.has(e.id)&&a.get(e.id)!==e);l.length&&r?.(l)},[t,r,i]),u=(0,n.useCallback)(e=>{let n=Array.isArray(e)?e:[e];n.length&&(c({type:`CREATE`,shapes:n}),t?.(n))},[t]),d=(0,n.useCallback)(e=>{c({type:`UPDATE`,shapes:e}),r?.(e)},[r]),f=(0,n.useCallback)(e=>{e.length!==0&&(c({type:`DELETE`,ids:e}),i?.(e))},[i]),p=(0,n.useCallback)((e,n)=>{!e.length&&!n.length||(c({type:`REPLACE`,removeIds:e,shapes:n}),e.length&&i?.(e),n.length&&t?.(n))},[t,i]),m=(0,n.useCallback)((e,t)=>{e.length!==0&&c({type:`REORDER`,ids:e,edge:t})},[]),h=(0,n.useCallback)(e=>{c({type:`RESET`,shapes:e})},[]),g=(0,n.useCallback)(()=>{let e=s.current;e.past.length!==0&&(l(e.shapes,e.past[e.past.length-1]),c({type:`UNDO`}))},[l]),_=(0,n.useCallback)(()=>{let e=s.current;e.future.length!==0&&(l(e.shapes,e.future[0]),c({type:`REDO`}))},[l]),v=(0,n.useCallback)(()=>s.current.past.length>0,[]),y=(0,n.useCallback)(()=>s.current.future.length>0,[]),b=(0,n.useCallback)(()=>s.current.shapes,[]);return{shapes:a.shapes,create:u,update:d,remove:f,replace:p,reorder:m,reset:h,undo:g,redo:_,canUndo:v,canRedo:y,getShapes:b}}var xt={undo:[`mod+z`],redo:[`mod+shift+z`],selectAll:[`mod+a`],copy:[`mod+c`],cut:[`mod+x`],paste:[`mod+v`],duplicate:[`mod+d`],delete:[`delete`,`backspace`],cancel:[`escape`],commitDraft:[`enter`],bringToFront:[`mod+]`],sendToBack:[`mod+[`],zoomIn:[`mod+=`,`mod+shift+=`],zoomOut:[`mod+-`],zoom100:[`shift+1`],zoomFit:[`shift+2`],toggleMinimap:[`m`],toggleCursorGuide:[`;`],togglePixelation:[`.`],selectTool:[`s`],rectangleTool:[`r`],rotatedRectangleTool:[`shift+r`],circleTool:[`o`],polygonTool:[`p`],pathTool:[`g`],brushTool:[`b`],pointTool:[`i`]},St={Equal:`=`,Minus:`-`,BracketLeft:`[`,BracketRight:`]`,Semicolon:`;`,Period:`.`,Comma:`,`,Slash:`/`,Backquote:"`"},Ct={Escape:`escape`,Enter:`enter`,Backspace:`backspace`,Delete:`delete`,Tab:`tab`,ArrowUp:`arrowup`,ArrowDown:`arrowdown`,ArrowLeft:`arrowleft`,ArrowRight:`arrowright`};function wt(e){let t=e.code,n=/^Key([A-Z])$/.exec(t);if(n)return n[1].toLowerCase();let r=/^Digit([0-9])$/.exec(t);return r?r[1]:St[t]?St[t]:Ct[e.key]?Ct[e.key]:null}function Tt(e){let t=wt(e);if(!t)return null;let n=[];return(e.metaKey||e.ctrlKey)&&n.push(`mod`),e.shiftKey&&n.push(`shift`),e.altKey&&n.push(`alt`),n.push(t),n.join(`+`)}function Et(e){let t=new Map;for(let n of Object.keys(xt)){let r=e?.[n],i=r===void 0?xt[n]:r===null?[]:Array.isArray(r)?r:[r];for(let e of i)t.set(e.toLowerCase(),n)}return t}var Z={ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0]};function Dt(){let e=document.activeElement;return!!e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable)}function Ot(e,t){if(!t||!(e instanceof Element))return!1;let n=e.closest(`[role="dialog"],[aria-modal="true"]`);return!!n&&!n.contains(t)}function kt(e){let{spaceRef:t,shiftRef:r}=e,i=(0,n.useMemo)(()=>Et(e.keymap),[e.keymap]),a=(0,n.useRef)(e);a.current=e;let o=(0,n.useRef)(i);o.current=i,(0,n.useEffect)(()=>{let e=e=>{if(e.code===`Space`&&(t.current=!0,a.current.onSpaceDown()),e.key===`Shift`&&(r.current=!0),Dt()||Ot(e.target,a.current.hostRef.current))return;let n=Z[e.key];if(n){e.preventDefault();let t=e.shiftKey?10:1;a.current.nudge(n[0]*t,n[1]*t);return}let i=Tt(e);if(!i)return;let s=o.current.get(i);s&&a.current.actions[s]?.()!==!1&&e.preventDefault()},n=e=>{e.code===`Space`&&(t.current=!1,a.current.onSpaceUp()),e.key===`Shift`&&(r.current=!1)};return window.addEventListener(`keydown`,e,{capture:!0}),window.addEventListener(`keyup`,n,{capture:!0}),()=>{window.removeEventListener(`keydown`,e,{capture:!0}),window.removeEventListener(`keyup`,n,{capture:!0})}},[t,r])}async function At(e){for(let t of[`default`,`reload`])try{let n=await fetch(e,{mode:`cors`,credentials:`omit`,cache:t});if(n.ok)return URL.createObjectURL(await n.blob())}catch{}return null}var jt=4e3;function Mt(e,t,n=jt){if(e<=0||t<=0)return[];let r=Math.ceil(e/n),i=Math.ceil(t/n);return Array.from({length:i},(a,o)=>Array.from({length:r},(a,s)=>{let c=s*n,l=o*n,u=s===r-1,d=o===i-1;return{x:c,y:l,width:u?e-c:n+1,height:d?t-l:n+1,srcX:c,srcY:l}})).flat()}function Nt(e,t){let n=document.createElement(`canvas`);n.width=t.width,n.height=t.height;let r=n.getContext(`2d`);return r&&r.drawImage(e,t.srcX,t.srcY,t.width,t.height,0,0,t.width,t.height),n}function Pt(e,t,n){if(t===o.POINT){e.setAttrs({x:n[0].x,y:n[0].y});return}if(t===o.RECTANGLE){let[t,r]=n;e.setAttrs({x:Math.min(t.x,r.x),y:Math.min(t.y,r.y),width:Math.abs(r.x-t.x),height:Math.abs(r.y-t.y)});return}if(t===o.ELLIPSE){let t=h(n);e.setAttrs({x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2,radiusX:(t.maxX-t.minX)/2,radiusY:(t.maxY-t.minY)/2});return}e.setAttrs({x:0,y:0,points:n.flatMap(e=>[e.x,e.y])})}var Ft=`M8 0C12.4183 0 16 3.58172 16 8C16 11.5323 13.71 14.5277 10.5342 15.5879L10.166 20.0068C10.0721 21.1334 9.13046 22 8 22C6.86954 22 5.92786 21.1334 5.83398 20.0068L5.46484 15.5879C2.28949 14.5275 0 11.532 0 8C0 3.58172 3.58172 0 8 0Z`,It=`#ffffff`,Lt=1.5;function Rt(e){return`<svg width="16" height="22" viewBox="0 0 16 22" xmlns="http://www.w3.org/2000/svg"><path d="${Ft}" fill="${e}" stroke="${It}" stroke-width="${Lt}"/></svg>`}var zt=Math.PI/12;function Bt(e,t){return t.kind!==`resize`&&t.kind!==`move`||t.shapes.length!==1?!1:e.find(e=>e.id===t.shapes[0].id)?.type===o.ROTATED_RECTANGLE}function Vt(e,t,n){if(e.kind===`resize`){let r=n?e.box:_(e.anchor,e.box,t.x,t.y);return{updates:e.shapes.map(i=>({id:i.id,points:n?N(i.points,e.anchor,t):P(i.points,e.box,r)})),box:r}}if(e.kind===`move`){let n=t.x-e.start.x,r=t.y-e.start.y;return{updates:e.shapes.map(e=>({id:e.id,points:e.points.map(e=>({x:e.x+n,y:e.y+r}))})),box:{minX:e.box.minX+n,minY:e.box.minY+r,maxX:e.box.maxX+n,maxY:e.box.maxY+r}}}if(e.kind===`rotate`){let n=Math.atan2(t.y-e.center.y,t.x-e.center.x)-e.startAngle;return e.shiftKey&&(n=Math.round(n/zt)*zt),{updates:[{id:e.id,points:e.points.map(t=>y(t,e.center,n))}],box:null}}let r=t.x-e.start.x,i=t.y-e.start.y,a=e.base.map((t,n)=>e.indices.includes(n)?{x:t.x+r,y:t.y+i}:t);return{updates:[{id:e.id,points:a}],box:h(a)}}function Ht(e,t){return t.kind===`move`||t.kind===`vertex`?t.start:t.kind===`rotate`?{x:t.center.x+Math.cos(t.startAngle),y:t.center.y+Math.sin(t.startAngle)}:Bt(e,t)?A(t.shapes[0].points)[m.indexOf(t.anchor)]:g(t.anchor,t.box)}function Ut(e,t,n){let r=e.filter(e=>t.includes(e.id)&&d(e)).map(e=>({id:e.id,points:e.points}));return r.length?{kind:`move`,start:n,box:h(r.flatMap(e=>e.points)),shapes:r}:null}function Wt(e){return e.map(e=>({...e,points:e.points.map(e=>({...e}))}))}function Gt(e,t){let n=new Set(t);return e.filter(e=>n.has(e.id)&&u(e))}function Kt(e,t){return e.filter(e=>{if(!l(e))return!1;let n=h(e.points);return n.minX<=t.maxX&&n.maxX>=t.minX&&n.minY<=t.maxY&&n.maxY>=t.minY}).map(e=>e.id)}function qt(e,t,n){return(e?le(e,{strokeWidth:t}).pointRadius:5)/(n||1)}function Jt(e,t){return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}function Yt(e,t,n){if(e.type===o.ROTATED_RECTANGLE)return t;let r=e.type===o.POINT?Jt(t[0],n):h(t);return b([{x:r.minX,y:r.minY},{x:r.maxX,y:r.maxY}])}function Xt(e){return 24/(e||1)}function Zt(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}var Qt=2,$t=`#1e88e5`,en=`#669def`,tn=class{constructor(e,t){this.layer=new i.default.Layer,this.world=new i.default.Group,this.bgGroup=new i.default.Group,this.overlayGroup=new i.default.Group({listening:!1}),this.shapeGroup=new i.default.Group,this.selGroup=new i.default.Group,this.previewGroup=new i.default.Group,this.handleGroup=new i.default.Group,this.baseCursor=`default`,this.strokeSize=Qt,this.imageSmoothing=!0,this.imageWidth=0,this.imageHeight=0,this.shapes=[],this.selected=[],this.nodes=new Map,this.altNodes=new Map,this.lastAppliedScale=-1,this.imageLoadToken=0,this.transformEnabled=!1,this.handleNodes=[],this.vertexNodes=[],this.lastImg={x:0,y:0},this.lastDragImg=null,this.ro=null,this.activeDrag=null,this.midNodes=[],this.selectedVertices=new Set,this.vertexPolygonId=null,this.editingId=null,this.rotNode=null,this.rotLineNode=null,this.transformerOutline=null,this.selectionBorders=[],this.upCleanup=null,this.lastPreviewPoly=null,this.preview=null,this.marquee=null,this.host=e,this.cb=t,this.stage=new i.default.Stage({container:e,width:e.clientWidth||1,height:e.clientHeight||1}),this.world.add(this.bgGroup,this.overlayGroup,this.shapeGroup,this.selGroup,this.previewGroup),this.layer.add(this.world,this.handleGroup),this.world.visible(!1),this.stage.add(this.layer)}async init(){let e=e=>({button:e.evt.button,shiftKey:e.evt.shiftKey,altKey:e.evt.altKey,ctrlKey:e.evt.ctrlKey,metaKey:e.evt.metaKey,global:this.stage.getPointerPosition()??{x:0,y:0}});this.stage.on(`mousedown`,t=>{let n=t.target===this.stage?null:t.target.id()||null;this.cb.onPointerDown(this.toImage(),n,e(t))}),this.stage.on(`mousemove`,()=>{if(this.lastImg=this.toImage(),this.activeDrag){this.lastDragImg=this.lastImg,this.dragTransform(this.lastImg);return}this.cb.onPointerMove(this.lastImg,{global:this.stage.getPointerPosition()??{x:0,y:0}})});let t=()=>{if(this.activeDrag){this.endTransform();return}this.cb.onPointerUp(this.lastImg)};this.stage.on(`mouseup`,t),window.addEventListener(`mouseup`,t),this.upCleanup=()=>window.removeEventListener(`mouseup`,t),this.ro=new ResizeObserver(()=>{this.stage.size({width:this.host.clientWidth||1,height:this.host.clientHeight||1}),this.layer.batchDraw()}),this.ro.observe(this.host)}destroy(){this.ro?.disconnect(),this.upCleanup?.(),this.stage.destroy()}get dom(){return this.stage.container()}get screenSize(){return{w:this.stage.width(),h:this.stage.height()}}setCursor(e){this.baseCursor=e,this.applyCursor()}emitCursorHint(e){this.cb.onCursorHint?.(e)}emitInteractionMode(e){this.cb.onInteractionModeChange?.(e)}applyCursor(){this.stage.container().style.cursor=this.baseCursor;for(let e of this.stage.container().querySelectorAll(`canvas`))e.style.cursor=this.baseCursor}bindCursor(e,t){let n=()=>{this.activeDrag||t===`pointer`&&!this.transformEnabled||this.emitCursorHint(t)},r=()=>{this.activeDrag||this.emitCursorHint(null)};e.on(`mouseenter`,n),e.on(`mouseover`,n),e.on(`mouseleave`,r),e.on(`mouseout`,r)}toImage(){let e=this.world.getRelativePointerPosition();return e?{x:e.x,y:e.y}:this.lastImg}imgToScreen(e){return this.world.getAbsoluteTransform().point(e)}async setImage(e,t,n){let r=++this.imageLoadToken,a=await At(e);await new Promise(o=>{let s=new Image;a||(s.crossOrigin=`anonymous`),s.onload=()=>{if(a&&URL.revokeObjectURL(a),r!==this.imageLoadToken)return o();this.imageWidth=t?.width??s.naturalWidth,this.imageHeight=t?.height??s.naturalHeight;let e=n?.width??this.imageWidth,c=n?.height??this.imageHeight;this.bgGroup.scale({x:e/s.naturalWidth,y:c/s.naturalHeight}),this.bgGroup.destroyChildren();for(let e of Mt(s.naturalWidth,s.naturalHeight))this.bgGroup.add(new i.default.Image({image:s,x:e.x,y:e.y,width:e.width,height:e.height,crop:{x:e.srcX,y:e.srcY,width:e.width,height:e.height},listening:!1}));this.layer.batchDraw(),o()},s.onerror=()=>{a&&URL.revokeObjectURL(a),this.imageWidth||=800,this.imageHeight||=600,o()},s.src=a??e})}clearImage(){this.imageLoadToken++,this.bgGroup.destroyChildren(),this.layer.batchDraw()}setFilter(e,t){let n=e!==1||t!==1?`brightness(${e}) contrast(${t})`:``,r=this.stage.container().querySelector(`canvas`);r&&(r.style.filter=n)}setStrokeSize(e){this.strokeSize!==e&&(this.strokeSize=e,this.setShapes(this.shapes,this.selected))}setImageSmoothing(e){this.imageSmoothing!==e&&(this.imageSmoothing=e,this.layer.imageSmoothingEnabled(e),this.layer.batchDraw())}setOverlays(e,t,n){if(this.overlayGroup.destroyChildren(),e&&this.overlayGroup.add(new i.default.Image({image:e,opacity:.55,imageSmoothingEnabled:!1,listening:!1})),t){let{imageWidth:e,imageHeight:n}=this;if(this.overlayGroup.add(new i.default.Shape({listening:!1,sceneFunc:r=>{Le(r._context,t,e,n)}})),t.outlineStyles){let e=(e,t)=>{let n={strokeWidth:t.width,strokeScaleEnabled:!1,listening:!1};for(let[r,a]of e)t.underlayColor&&this.overlayGroup.add(new i.default.Line({points:[r.x,r.y,a.x,a.y],stroke:t.underlayColor,...n})),this.overlayGroup.add(new i.default.Line({points:[r.x,r.y,a.x,a.y],stroke:t.color,opacity:t.opacity,dash:t.dash,...n}))};e(t.visibleOutline,t.outlineStyles.visible),e(t.occludedOutline,t.outlineStyles.occluded)}}n&&this.imageWidth&&this.overlayGroup.add(new i.default.Rect({x:0,y:0,width:this.imageWidth,height:this.imageHeight,fill:`#0d0d12`,opacity:.3,listening:!1})),this.layer.batchDraw()}get viewport(){return{scale:this.world.scaleX(),x:this.world.x(),y:this.world.y()}}applyViewport(e){let t=e.scale!==this.lastAppliedScale;if(this.lastAppliedScale=e.scale,this.world.scale({x:e.scale,y:e.scale}),this.world.position({x:e.x,y:e.y}),this.world.visible(!0),t){this.syncScreenFixedShapes(),this.updateSelectionBordersLive(e=>e.points);let e=this.lastPreviewPoly;e&&this.previewPoly(e.points,e.cursor,e.style,e.closed,e.selectedPointIndices,e.showVertices)}this.activeDrag?this.dragTransform(this.lastDragImg??Ht(this.shapes,this.activeDrag)):this.drawTransformer(),this.layer.batchDraw(),this.cb.onViewportChange?.()}fit(){if(!this.imageWidth||!this.imageHeight)return;let{w:e,h:t}=this.screenSize,n=Math.min(e/this.imageWidth,t/this.imageHeight);this.applyViewport({scale:n,x:(e-this.imageWidth*n)/2,y:(t-this.imageHeight*n)/2})}zoom100(){if(!this.imageWidth||!this.imageHeight)return;let{w:e,h:t}=this.screenSize;this.applyViewport({scale:1,x:(e-this.imageWidth)/2,y:(t-this.imageHeight)/2})}zoomAt(e,t,n){let r=this.world.scaleX(),i=Math.min(20,Math.max(.05,r*n)),a=(e-this.world.x())/r,o=(t-this.world.y())/r;this.applyViewport({scale:i,x:e-a*i,y:t-o*i})}setShapes(e,t){if(this.shapes=Wt(e),this.selected=t,!this.activeDrag){this.shapeGroup.destroyChildren(),this.nodes.clear(),this.altNodes.clear();for(let t of f(e).filter(s)){let e=this.makeNode(t),n=le(t,{strokeWidth:this.strokeSize});if(t.style?.alternateColor&&n.dash?.length&&t.type!==o.POINT){let n=e.clone({id:`${t.id}__alt`,stroke:t.style.alternateColor,dash:[],fillEnabled:!1,listening:!1});this.altNodes.set(t.id,n),this.shapeGroup.add(n)}this.nodes.set(t.id,e),this.shapeGroup.add(e)}this.drawSelectionBorders(),this.drawTransformer(),this.layer.batchDraw()}}setSelection(e){this.selected=e,(e.length!==1||e[0]!==this.vertexPolygonId)&&(this.vertexPolygonId=null,this.selectedVertices.clear()),this.editingId&&(e.length!==1||e[0]!==this.editingId)&&(this.editingId=null),!this.activeDrag&&(this.drawSelectionBorders(),this.drawTransformer(),this.layer.batchDraw())}setEditing(e){this.editingId!==e&&(this.editingId=e,this.selectedVertices.clear(),this.activeDrag||(this.drawTransformer(),this.layer.batchDraw()))}makeNode(e){let{type:t,points:n}=e,r=le(e,{strokeWidth:this.strokeSize}),a=l(e),s={id:e.id,stroke:r.color,strokeWidth:r.strokeWidth,dash:this.scaledDash(r.dash),opacity:r.opacity,strokeScaleEnabled:!1,listening:a},c=r.fillVisible?ue(r.color,r.fillAlpha):void 0;if(t===o.POINT){let t=1/(this.world.scaleX()||1),o=new i.default.Path({id:e.id,data:Ft,x:n[0].x,y:n[0].y,offsetX:16/2,offsetY:22,scaleX:t,scaleY:t,fill:r.color,stroke:It,strokeWidth:Lt,strokeScaleEnabled:!1,shadowColor:`#000`,shadowBlur:2,shadowOpacity:.3,shadowForStrokeEnabled:!1,opacity:r.opacity,listening:a});return this.bindCursor(o,d(e)?`grab`:`default`),o}if(t===o.RECTANGLE){let t=h(n),r=new i.default.Rect({x:t.minX,y:t.minY,width:t.maxX-t.minX,height:t.maxY-t.minY,fill:c,...s});return this.bindCursor(r,d(e)?`grab`:`default`),r}if(t===o.ELLIPSE){let t=h(n),r=new i.default.Ellipse({x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2,radiusX:(t.maxX-t.minX)/2,radiusY:(t.maxY-t.minY)/2,fill:c,...s});return this.bindCursor(r,d(e)?`grab`:`default`),r}let u=n.flatMap(e=>[e.x,e.y]),f=t!==o.LINE,p=new i.default.Line({points:u,closed:f,fill:f?c:void 0,lineJoin:`round`,...s});return this.bindCursor(p,d(e)?`grab`:`default`),p}liveUpdateShape(e,t){let n=this.nodes.get(e),r=this.shapes.find(t=>t.id===e);if(n&&r){Pt(n,r.type,t);let a=this.altNodes.get(e);a&&Pt(a,r.type,t),r.type===o.POINT&&n instanceof i.default.Circle&&n.radius(this.pointRadius(r)),this.layer.batchDraw()}}pointRadius(e){return qt(e,this.strokeSize,this.world.scaleX()||1)}scaledDash(e){return e}syncScreenFixedShapes(){let e=1/(this.world.scaleX()||1);for(let t of this.shapes){let n=this.nodes.get(t.id);if(t.type===o.POINT){n?.scale({x:e,y:e});continue}n?.dash(this.scaledDash(le(t,{strokeWidth:this.strokeSize}).dash))}}shapesIntersecting(e){return Kt(this.shapes,e)}drawSelectionBorders(){let e=new Set(this.selected),t=this.selected.length?this.shapes.filter(t=>e.has(t.id)&&l(t)):[];if(this.selectionBorders.length!==t.length){for(let e of this.selectionBorders)e.destroy();this.selectionBorders=t.map(()=>{let e=new i.default.Line({closed:!0,stroke:en,strokeWidth:1.5,strokeScaleEnabled:!1,listening:!1});return this.selGroup.add(e),e})}t.forEach((e,t)=>{this.selectionBorders[t].points(this.selectionOutlinePoints(e,e.points).flatMap(e=>[e.x,e.y]))})}updateSelectionBordersLive(e){let t=new Set(this.selected),n=0;for(let r of this.shapes){if(!t.has(r.id)||!l(r))continue;let i=this.selectionOutlinePoints(r,e(r)),a=this.selectionBorders[n++];a&&a.points(i.flatMap(e=>[e.x,e.y]))}}selectionOutlinePoints(e,t){return Yt(e,t,this.pointRadius(e))}clearPreview(){this.lastPreviewPoly=null,this.previewGroup.destroyChildren(),this.layer.batchDraw()}clearMarquee(){this.marquee?.destroy(),this.marquee=null,this.layer.batchDraw()}previewBox(e,t,n,r){this.lastPreviewPoly=null,this.previewGroup.destroyChildren();let a=Math.min(t.x,n.x),o=Math.min(t.y,n.y),s=Math.abs(n.x-t.x),c=Math.abs(n.y-t.y),l=(t,n)=>e===`ellipse`?new i.default.Ellipse({x:a+s/2,y:o+c/2,radiusX:s/2,radiusY:c/2,stroke:t,strokeWidth:r.strokeWidth??this.strokeSize,dash:this.scaledDash(n),strokeScaleEnabled:!1}):new i.default.Rect({x:a,y:o,width:s,height:c,stroke:t,strokeWidth:r.strokeWidth??this.strokeSize,dash:this.scaledDash(n),strokeScaleEnabled:!1});r.alternateColor&&this.previewGroup.add(l(r.alternateColor)),this.preview=l(r.color??`#00e5ff`,r.dash),this.previewGroup.add(this.preview),this.layer.batchDraw()}previewPoly(e,t,n,r,a=[],o=!0){if(this.lastPreviewPoly={points:e,cursor:t,style:n,closed:r,selectedPointIndices:a,showVertices:o},this.previewGroup.destroyChildren(),!e.length)return;let s=e.flatMap(e=>[e.x,e.y]);t&&s.push(t.x,t.y);let c=(e,t)=>new i.default.Line({points:s,closed:r,stroke:e,strokeWidth:n.strokeWidth??this.strokeSize,dash:this.scaledDash(t),strokeScaleEnabled:!1,lineCap:`round`,lineJoin:`round`});if(n.alternateColor&&this.previewGroup.add(c(n.alternateColor)),this.previewGroup.add(c(n.color??`#00e5ff`,n.dash)),!o){this.layer.batchDraw();return}let l=new Set(a),u=this.world.scaleX()||1;for(let t=0;t<e.length;t++){let n=e[t],r=l.has(t);this.previewGroup.add(new i.default.Circle({x:n.x,y:n.y,radius:(r?6:5)/u,fill:r?$t:`#ffffff`,stroke:r?`#ffffff`:$t,strokeWidth:1.5,strokeScaleEnabled:!1,listening:!1}))}this.layer.batchDraw()}previewScalarMask(e,t){this.previewGroup.destroyChildren();let n=dt(e,t.length===7?`${t}99`:t);this.previewGroup.add(new i.default.Image({image:n,x:e.ox,y:e.oy,scaleX:1/e.scale,scaleY:1/e.scale,listening:!1})),this.layer.batchDraw()}previewMarquee(e,t){this.marquee||(this.marquee=new i.default.Rect({fill:ue(oe,H),stroke:oe,strokeWidth:1,strokeScaleEnabled:!1,listening:!1,perfectDrawEnabled:!1}),this.previewGroup.add(this.marquee)),this.marquee.setAttrs({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(t.x-e.x),height:Math.abs(t.y-e.y)}),this.layer.batchDraw()}setTransformEnabled(e){this.transformEnabled=e,this.drawTransformer(),this.layer.batchDraw()}setPanMode(e){this.handleGroup.listening(!e),this.layer.batchDraw()}setTransformerOutline(e){let t=Math.max(0,e.maxX-e.minX),n=Math.max(0,e.maxY-e.minY);!t&&!n||this.setTransformerOutlinePoints(b([{x:e.minX,y:e.minY},{x:e.maxX,y:e.maxY}]))}setTransformerOutlinePoints(e){e.length<2||(this.transformerOutline||(this.transformerOutline=new i.default.Line({closed:!0,stroke:$t,strokeWidth:1,strokeScaleEnabled:!1,listening:!1}),this.selGroup.add(this.transformerOutline)),this.transformerOutline.points(e.flatMap(e=>[e.x,e.y])))}rotationHandleGap(){return Xt(this.viewport.scale)}rotationHandleScreenPoint(e){return this.imgToScreen(j(e,this.rotationHandleGap()))}setRotationConnector(e){let t=this.imgToScreen(O(e[0],e[1])),n=this.rotationHandleScreenPoint(e);this.rotLineNode?this.rotLineNode.points([t.x,t.y,n.x,n.y]):(this.rotLineNode=new i.default.Line({points:[t.x,t.y,n.x,n.y],stroke:$t,strokeWidth:1,listening:!1}),this.handleGroup.add(this.rotLineNode))}layoutResizeHandle(e,t,n){e.position({x:t.x,y:t.y}),e.offset({x:4,y:4}),e.rotation(n*180/Math.PI)}orientedHandleAngle(e){return Zt(this.imgToScreen(e[0]),this.imgToScreen(e[1]))}repositionOrientedHandles(e){let t=this.orientedHandleAngle(e);if(A(e).forEach((e,n)=>{let r=this.imgToScreen(e),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,t)}),this.setTransformerOutlinePoints(e),this.rotNode){let t=this.rotationHandleScreenPoint(e);this.rotNode.position({x:t.x,y:t.y})}this.rotLineNode&&this.setRotationConnector(e)}drawTransformer(){if(this.activeDrag)return;for(let e of this.handleNodes)e.destroy();for(let e of this.vertexNodes)e.destroy();for(let e of this.midNodes)e.destroy();if(this.rotNode?.destroy(),this.rotNode=null,this.rotLineNode?.destroy(),this.rotLineNode=null,this.transformerOutline?.destroy(),this.transformerOutline=null,this.handleNodes=[],this.vertexNodes=[],this.midNodes=[],!this.transformEnabled)return;let e=Gt(this.shapes,this.selected);if(!e.length||e.length===1&&e[0].type===o.POINT)return;let t=e.length===1&&(e[0].type===o.POLYGON||e[0].type===o.LINE)&&this.editingId===e[0].id?e[0]:null,n=h(e.flatMap(e=>e.points)),r=e.length===1&&e[0].type===o.ROTATED_RECTANGLE?e[0]:null,a=r?A(r.points):m.map(e=>g(e,n));r?this.setTransformerOutlinePoints(r.points):this.setTransformerOutline(n),r&&this.setRotationConnector(r.points);let s=r?this.orientedHandleAngle(r.points):0;for(let e of t?[]:m){let t=this.imgToScreen(a[m.indexOf(e)]),n=new i.default.Rect({x:t.x,y:t.y,width:8,height:8,offsetX:4,offsetY:4,rotation:s*180/Math.PI,fill:`#ffffff`,stroke:$t,strokeWidth:1}),r=De(e,s);this.bindCursor(n,r),n.on(`mousedown`,t=>{t.cancelBubble=!0,this.emitCursorHint(r),this.emitInteractionMode(`resizing`);let n=Gt(this.shapes,this.selected);this.activeDrag={kind:`resize`,anchor:e,box:h(n.flatMap(e=>e.points)),shapes:n.map(e=>({id:e.id,points:e.points}))},this.lastDragImg=null}),this.handleGroup.add(n),this.handleNodes.push(n)}if(t){let e=t,n=e.points,r=e.type===o.POLYGON?n.length:n.length-1;for(let t=0;t<r;t++){let r=n[t],a=n[(t+1)%n.length],o={x:(r.x+a.x)/2,y:(r.y+a.y)/2},s=this.imgToScreen(o),c=new i.default.Circle({x:s.x,y:s.y,radius:4,fill:`#ffffff`,opacity:.6,stroke:$t,strokeWidth:1});this.bindCursor(c,`copy`),c.on(`mousedown`,r=>{r.cancelBubble=!0;let i=[...n.slice(0,t+1),o,...n.slice(t+1)];this.cb.onTransformCommit?.([{id:e.id,points:i}])}),this.handleGroup.add(c),this.midNodes.push(c)}this.vertexPolygonId!==e.id&&(this.vertexPolygonId=e.id,this.selectedVertices.clear()),n.forEach((t,r)=>{let a=this.imgToScreen(t),o=this.selectedVertices.has(r),s=new i.default.Circle({x:a.x,y:a.y,radius:5,fill:o?$t:`#ffffff`,stroke:o?`#ffffff`:$t,strokeWidth:1.5});this.bindCursor(s,`pointer`),s.on(`mousedown`,t=>{if(t.cancelBubble=!0,t.evt.shiftKey||t.evt.ctrlKey||t.evt.metaKey){this.selectedVertices.has(r)?this.selectedVertices.delete(r):this.selectedVertices.add(r),this.drawTransformer();return}let i=this.selectedVertices.has(r)&&this.selectedVertices.size>1?[...this.selectedVertices]:[r];i.length===1&&(this.selectedVertices.clear(),this.selectedVertices.add(r)),this.activeDrag={kind:`vertex`,id:e.id,indices:i,base:n,start:this.toImage()},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`vertexDragging`)}),this.handleGroup.add(s),this.vertexNodes.push(s)})}if(e.length===1&&e[0].type===o.ROTATED_RECTANGLE){let t=e[0],n=k(t.points),r=this.rotationHandleScreenPoint(t.points),a=new i.default.Circle({x:r.x,y:r.y,radius:6,fill:`#ffffff`,stroke:$t,strokeWidth:1.5});this.bindCursor(a,`grab`),a.on(`mousedown`,e=>{e.cancelBubble=!0;let r=this.toImage();this.activeDrag={kind:`rotate`,id:t.id,center:n,startAngle:Math.atan2(r.y-n.y,r.x-n.x),points:t.points,shiftKey:e.evt.shiftKey},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`rotating`)}),this.handleGroup.add(a),this.rotNode=a}this.layer.batchDraw()}beginMove(e,t){let n=Ut(this.shapes,t,e);n&&(this.transformEnabled&&!this.handleNodes.length&&this.drawTransformer(),this.activeDrag=n,this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`moving`),(n.shapes.length===1?this.shapes.find(e=>e.id===n.shapes[0].id):null)?.type===o.ROTATED_RECTANGLE?this.setTransformerOutlinePoints(n.shapes[0].points):this.setTransformerOutline(n.box),this.updateSelectionBordersLive(e=>e.points))}repositionHandles(e){m.forEach((t,n)=>{let r=this.imgToScreen(g(t,e)),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,0)}),this.setTransformerOutline(e)}repositionPolygonHandles(e,t){if(!this.vertexNodes.length)return;e.forEach((e,t)=>{let n=this.imgToScreen(e);this.vertexNodes[t]?.position({x:n.x,y:n.y})});let n=t?e.length:e.length-1;for(let t=0;t<n;t++){let n=e[t],r=e[(t+1)%e.length],i=this.imgToScreen({x:(n.x+r.x)/2,y:(n.y+r.y)/2});this.midNodes[t]?.position({x:i.x,y:i.y})}}commitTransformUpdates(e){if(e.length){for(let t of e){let e=this.shapes.find(e=>e.id===t.id);e&&(e.points=t.points,this.liveUpdateShape(t.id,t.points))}this.cb.onTransformCommit?.(e),this.drawTransformer(),this.layer.batchDraw()}}dragTransform(e){let t=this.activeDrag;if(!t)return;this.applyCursor();let n=Bt(this.shapes,t),{updates:r,box:i}=Vt(t,e,n);for(let e of r)this.liveUpdateShape(e.id,e.points);if(this.cb.onTransformPreview?.(r),this.updateSelectionBordersLive(e=>r.find(t=>t.id===e.id)?.points??e.points),t.kind===`resize`||t.kind===`move`){n?this.repositionOrientedHandles(r[0].points):i&&this.repositionHandles(i);let e=t.shapes.length===1?this.shapes.find(e=>e.id===t.shapes[0].id):null,a=e?.type===o.POLYGON||e?.type===o.LINE;(t.kind===`resize`?a:this.vertexNodes.length>0&&t.shapes.length===1)&&this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}else if(t.kind===`rotate`){this.repositionOrientedHandles(r[0].points);let e=this.shapes.find(e=>e.id===t.id);e&&(e.type===o.POLYGON||e.type===o.LINE)&&this.repositionPolygonHandles(r[0].points,e.type===o.POLYGON)}else{i&&this.repositionHandles(i);let e=this.shapes.find(e=>e.id===t.id);this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}this.layer.batchDraw()}endTransform(){let e=this.activeDrag,t=this.lastDragImg;if(this.activeDrag=null,this.emitInteractionMode(`idle`),this.emitCursorHint(e?.kind===`move`?`grab`:null),!e||!t){this.cb.onTransformPreview?.([]),this.drawTransformer();return}if(e.kind===`move`&&t.x===e.start.x&&t.y===e.start.y){this.cb.onTransformPreview?.([]),this.drawTransformer();return}let{updates:n}=Vt(e,t,Bt(this.shapes,e));this.commitTransformUpdates(n)}},nn=2,rn=58879,an=6725103;function Q(e){if(!e)return rn;let t=e.replace(`#`,``);return Number.parseInt(t.length===3?t.replace(/./g,`$&$&`):t,16)}var on=class{constructor(e,t){this.app=new a.Application,this.world=new a.Container,this.bgLayer=new a.Container,this.overlayLayer=new a.Container,this.shapeLayer=new a.Container,this.selLayer=new a.Container,this.previewLayer=new a.Container,this.handleLayer=new a.Container,this.filter=new a.ColorMatrixFilter,this.imageWidth=0,this.imageHeight=0,this.imageTileTextures=[],this.imageLoadToken=0,this.overlayTextures=[],this.region=null,this.regionOutlineG=null,this.baseCursor=`default`,this.strokeSize=nn,this.shapes=[],this.selected=[],this.nodes=new Map,this.lastAppliedScale=-1,this.brightness=1,this.contrast=1,this.imageSmoothing=!0,this.destroyed=!1,this.transformEnabled=!1,this.handleNodes=[],this.vertexNodes=[],this.lastDragImg=null,this.activeDrag=null,this.midNodes=[],this.selectedVertices=new Set,this.vertexPolygonId=null,this.editingId=null,this.rotNode=null,this.rotLineNode=null,this.transformerOutline=null,this.selectionBorderGfx=[],this.previewG=new a.Graphics,this.marqueeG=new a.Graphics,this.previewMaskSprite=null,this.previewMaskTexture=null,this.previewReady=!1,this.lastPreview=null,this.host=e,this.cb=t}ev(e){return{button:e.button,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,global:{x:e.global.x,y:e.global.y}}}async init(){if(await this.app.init({resizeTo:this.host,background:`#111111`,antialias:!0,autoDensity:!0,resolution:window.devicePixelRatio||1,preference:`webgl`}),this.destroyed){this.app.destroy(!0);return}this.host.appendChild(this.app.canvas),this.applyCursor(),this.world.addChild(this.bgLayer,this.overlayLayer,this.shapeLayer,this.selLayer,this.previewLayer),this.app.stage.addChild(this.world,this.handleLayer),this.world.visible=!1,this.app.stage.eventMode=`static`,this.syncHitArea(),this.app.stage.on(`pointerdown`,e=>{this.cb.onPointerDown(this.toImage(e),null,this.ev(e))}),this.app.stage.on(`pointermove`,e=>{if(this.activeDrag){this.lastDragImg=this.toImage(e),this.dragTransform(this.lastDragImg);return}this.cb.onPointerMove(this.toImage(e),this.ev(e))});let e=e=>{if(this.activeDrag){this.endTransform();return}this.cb.onPointerUp(this.toImage(e))};this.app.stage.on(`pointerup`,e),this.app.stage.on(`pointerupoutside`,e),this.app.renderer.on(`resize`,()=>this.syncHitArea())}syncHitArea(){let{w:e,h:t}=this.screenSize;this.app.stage.hitArea=new a.Rectangle(0,0,e,t)}destroy(){this.destroyed=!0,this.clearImageTiles();for(let e of this.overlayTextures)e.destroy(!0);this.overlayTextures=[],this.app.renderer&&this.app.destroy(!0,{children:!0})}get screenSize(){return{w:this.app.renderer.screen.width,h:this.app.renderer.screen.height}}setCursor(e){this.baseCursor=e,this.syncShapeCursors(),this.applyCursor()}emitCursorHint(e){this.cb.onCursorHint?.(e)}emitInteractionMode(e){this.cb.onInteractionModeChange?.(e)}applyCursor(){if(this.destroyed||!this.app.renderer)return;let e=this.app.canvas;e&&(e.style.cursor=this.baseCursor)}syncShapeCursors(){for(let e of this.nodes.values())e.cursor=void 0}bindCursor(e,t){e.cursor=void 0,e.on(`pointerover`,()=>{this.activeDrag||this.emitCursorHint(t)}),e.on(`pointerout`,()=>{this.activeDrag||this.emitCursorHint(null)})}get dom(){return this.app.canvas}toImage(e){let t=this.world.toLocal(e.global);return{x:t.x,y:t.y}}async setImage(e,t,n){let r=++this.imageLoadToken,i=await At(e);if(this.destroyed){i&&URL.revokeObjectURL(i);return}await new Promise(o=>{let s=new Image;i||(s.crossOrigin=`anonymous`),s.onload=()=>{if(i&&URL.revokeObjectURL(i),this.destroyed||r!==this.imageLoadToken)return o();this.imageWidth=t?.width??s.naturalWidth,this.imageHeight=t?.height??s.naturalHeight;let e=n?.width??this.imageWidth,c=n?.height??this.imageHeight;this.bgLayer.scale.set(e/s.naturalWidth,c/s.naturalHeight),this.clearImageTiles();for(let e of Mt(s.naturalWidth,s.naturalHeight)){let t=a.Texture.from(Nt(s,e));t.source.scaleMode=this.imageSmoothing?`linear`:`nearest`,this.imageTileTextures.push(t);let n=new a.Sprite(t);n.x=e.x,n.y=e.y,n.width=e.width,n.height=e.height,this.bgLayer.addChild(n)}this.applySpriteFilter(),o()},s.onerror=()=>{i&&URL.revokeObjectURL(i),this.imageWidth||=t?.width??800,this.imageHeight||=t?.height??600,o()},s.src=i??e})}setFilter(e,t){this.brightness=e,this.contrast=t,this.applySpriteFilter()}setStrokeSize(e){this.strokeSize!==e&&(this.strokeSize=e,this.setShapes(this.shapes,this.selected))}applySpriteFilter(){if(!(this.destroyed||!this.app.renderer)){if(!(this.brightness!==1||this.contrast!==1)){this.filter.reset(),this.bgLayer.filters=void 0;return}this.filter.brightness(this.brightness,!1),this.filter.contrast(this.contrast-1,!0),this.bgLayer.filters=[this.filter]}}clearImage(){this.destroyed||(this.imageLoadToken++,this.clearImageTiles())}clearImageTiles(){for(let e of this.bgLayer.removeChildren())e.destroy();for(let e of this.imageTileTextures)e.destroy(!0);this.imageTileTextures=[]}setImageSmoothing(e){if(this.imageSmoothing===e)return;this.imageSmoothing=e;let t=e?`linear`:`nearest`;for(let e of this.imageTileTextures)e.source.scaleMode=t,e.source.style.update();!this.destroyed&&this.app.renderer&&this.app.render()}setOverlays(e,t,n){for(let e of this.overlayLayer.removeChildren())e.destroy();this.regionOutlineG=null,this.region=t;for(let e of this.overlayTextures)e.destroy(!0);if(this.overlayTextures=[],e){let t=a.Texture.from(e);t.source.scaleMode=`nearest`,this.overlayTextures.push(t);let n=new a.Sprite(t);n.alpha=.55,this.overlayLayer.addChild(n)}if(t){let e=Q(t.dim.color),n=()=>{let e=new a.Graphics;for(let n of t.rects)e.rect(n.x,n.y,n.w,n.h).fill(16777215);return e},r=new a.Graphics().rect(0,0,this.imageWidth,this.imageHeight).fill({color:e,alpha:t.dim.opacity}),i=n();if(this.overlayLayer.addChild(i,r),r.setMask({mask:i,inverse:!0}),t.zones.length){let r=new a.Graphics;for(let n of t.zones)r.poly(n.points.flatMap(e=>[e.x,e.y]),!0).fill({color:e,alpha:t.dim.opacity});let i=n();this.overlayLayer.addChild(i,r),r.setMask({mask:i})}t.outlineStyles&&(this.regionOutlineG=this.overlayLayer.addChild(new a.Graphics),this.redrawRegionOutline())}n&&this.imageWidth&&this.overlayLayer.addChild(new a.Graphics().rect(0,0,this.imageWidth,this.imageHeight).fill({color:855314,alpha:.3})),!this.destroyed&&this.app.renderer&&this.app.render()}get viewport(){return{scale:this.world.scale.x,x:this.world.x,y:this.world.y}}applyViewport(e){let t=e.scale!==this.lastAppliedScale;this.lastAppliedScale=e.scale,this.world.scale.set(e.scale),this.world.position.set(e.x,e.y),this.world.visible=!0,t&&this.restrokeShapes(),this.activeDrag?this.dragTransform(this.lastDragImg??Ht(this.shapes,this.activeDrag)):this.drawTransformer(),this.cb.onViewportChange?.()}fit(){if(!this.imageWidth||!this.imageHeight)return;let{w:e,h:t}=this.screenSize,n=Math.min(e/this.imageWidth,t/this.imageHeight);this.applyViewport({scale:n,x:(e-this.imageWidth*n)/2,y:(t-this.imageHeight*n)/2})}zoom100(){if(!this.imageWidth||!this.imageHeight)return;let{w:e,h:t}=this.screenSize;this.applyViewport({scale:1,x:(e-this.imageWidth)/2,y:(t-this.imageHeight)/2})}zoomAt(e,t,n,r=.05,i=20){let a=this.world.scale.x,o=Math.min(i,Math.max(r,a*n)),s=(e-this.world.x)/a,c=(t-this.world.y)/a;this.applyViewport({scale:o,x:e-s*o,y:t-c*o})}panBy(e,t){this.applyViewport({scale:this.world.scale.x,x:this.world.x+e,y:this.world.y+t})}setShapes(e,t){this.shapes=Wt(e),this.selected=t,!this.activeDrag&&(this.drawShapes(),this.drawSelectionBorders(),this.drawTransformer())}setSelection(e){this.selected=e,(e.length!==1||e[0]!==this.vertexPolygonId)&&(this.vertexPolygonId=null,this.selectedVertices.clear()),this.editingId&&(e.length!==1||e[0]!==this.editingId)&&(this.editingId=null),!this.activeDrag&&(this.drawSelectionBorders(),this.drawTransformer())}setEditing(e){this.editingId!==e&&(this.editingId=e,this.selectedVertices.clear(),this.activeDrag||this.drawTransformer())}setTransformEnabled(e){this.transformEnabled=e,this.syncShapeCursors(),this.drawTransformer()}setPanMode(e){this.handleLayer.interactiveChildren=!e}strokeW(e){return(e?le(e,{strokeWidth:this.strokeSize}).strokeWidth:nn)/this.world.scale.x}pointRadius(e){return qt(e,this.strokeSize,this.world.scale.x)}dashForShape(e){let t=le(e,{strokeWidth:this.strokeSize}).dash;if(!t?.length)return null;let n=this.world.scale.x||1;return[t[0]/n,(t[1]??t[0])/n]}drawShapes(){this.shapeLayer.removeChildren();for(let e of this.nodes.values())e.destroy();this.nodes.clear();for(let e of f(this.shapes).filter(s)){let t=new a.Graphics;this.paintShape(t,e),t.eventMode=l(e)?`static`:`none`,t.cursor=void 0,l(e)&&d(e)&&(t.on(`pointerover`,()=>{!this.activeDrag&&this.transformEnabled&&this.emitCursorHint(`grab`)}),t.on(`pointerout`,()=>{this.activeDrag||this.emitCursorHint(null)})),t.on(`pointerdown`,t=>{t.stopPropagation(),this.cb.onPointerDown(this.toImage(t),e.id,this.ev(t))}),this.shapeLayer.addChild(t),this.nodes.set(e.id,t)}}paintShape(e,t){e.clear();let n=le(t,{strokeWidth:this.strokeSize}),r=Q(n.color),i=this.strokeW(t),a=n.opacity,s=this.dashForShape(t);if(t.type===o.POINT){e.svg(Rt(n.color)),e.position.set(t.points[0].x,t.points[0].y),e.pivot.set(16/2,22);let r=1/(this.world.scale.x||1);e.scale.set(r,r),e.alpha=a;return}if(n.fillVisible&&t.type!==o.LINE?(this.path(e,t),e.fill({color:r,alpha:n.fillAlpha*a})):t.type!==o.LINE&&(this.path(e,t),e.fill({color:r,alpha:0})),s){t.style?.alternateColor&&(this.path(e,t),e.stroke({width:i,color:Q(t.style.alternateColor),alpha:a})),this.dashedStrokeShape(e,t,i,r,a,s);return}this.path(e,t),e.stroke({width:i,color:r,alpha:a})}liveUpdateShape(e,t){let n=this.nodes.get(e),r=this.shapes.find(t=>t.id===e);n&&r&&this.paintShape(n,{...r,points:t})}shapesIntersecting(e){return Kt(this.shapes,e)}shapesAt(e){return this.shapes.filter(t=>{let n=h(t.points);return e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY}).map(e=>e.id)}repaintPreview(){let e=this.lastPreview;e&&(e.kind===`poly`?this.previewPoly(e.points,e.cursor,e.style,e.closed,e.selectedPointIndices,e.showVertices):this.previewBox(e.boxKind,e.a,e.b,e.style))}ensurePreview(){this.previewReady||=(this.previewLayer.addChild(this.previewG,this.marqueeG),!0)}clearPreview(){this.lastPreview=null,this.previewG.clear(),this.previewMaskSprite&&(this.previewMaskSprite.visible=!1)}clearMarquee(){this.marqueeG.clear()}previewBox(e,t,n,r){this.lastPreview={kind:`box`,boxKind:e,a:t,b:n,style:r},this.ensurePreview(),this.previewG.clear();let i={id:`__preview__`,type:e===`ellipse`?o.ELLIPSE:o.RECTANGLE,points:[t,n],style:r},a=this.strokeW(i);r.alternateColor&&(this.path(this.previewG,i),this.previewG.stroke({width:a,color:Q(r.alternateColor)}));let s=this.dashForShape(i);if(s){this.dashedStrokeShape(this.previewG,i,a,Q(r.color??`#00e5ff`),r.opacity??1,s);return}this.path(this.previewG,i),this.previewG.stroke({width:a,color:Q(r.color??`#00e5ff`),alpha:r.opacity??1})}previewPoly(e,t,n,r,i=[],a=!0){if(this.lastPreview={kind:`poly`,points:e,cursor:t,style:n,closed:r,selectedPointIndices:i,showVertices:a},this.ensurePreview(),this.previewG.clear(),!e.length)return;let s=t?[...e,t]:e,c={id:`__preview__`,type:r?o.POLYGON:o.LINE,points:s,style:n},l=this.strokeW(c);n.alternateColor&&(this.path(this.previewG,c),this.previewG.stroke({width:l,color:Q(n.alternateColor)}));let u=this.dashForShape(c);if(u?this.dashedStrokeShape(this.previewG,c,l,Q(n.color??`#00e5ff`),n.opacity??1,u):(this.path(this.previewG,c),this.previewG.stroke({width:l,color:Q(n.color??`#00e5ff`),alpha:n.opacity??1})),!a)return;let d=new Set(i),f=5/this.world.scale.x,p=6/this.world.scale.x;for(let t=0;t<e.length;t++){let n=e[t],r=d.has(t);this.previewG.circle(n.x,n.y,r?p:f).fill({color:r?2001125:16777215}).stroke({width:1.5/this.world.scale.x,color:r?16777215:2001125})}}previewScalarMask(e,t){this.lastPreview=null,this.ensurePreview(),this.previewG.clear();let n=dt(e,t.length===7?`${t}99`:t);this.previewMaskTexture&&this.previewMaskTexture.destroy(!0),this.previewMaskTexture=a.Texture.from(n),this.previewMaskSprite?(this.previewMaskSprite.texture=this.previewMaskTexture,this.previewMaskSprite.visible=!0):(this.previewMaskSprite=new a.Sprite(this.previewMaskTexture),this.previewLayer.addChildAt(this.previewMaskSprite,0)),this.previewMaskSprite.x=e.ox,this.previewMaskSprite.y=e.oy,this.previewMaskSprite.width=n.width/e.scale,this.previewMaskSprite.height=n.height/e.scale}previewMarquee(e,t){this.ensurePreview(),this.marqueeG.clear();let n=Math.min(e.x,t.x),r=Math.min(e.y,t.y),i=Math.abs(t.x-e.x),a=Math.abs(t.y-e.y),o=Q(oe);this.marqueeG.rect(n,r,i,a).fill({color:o,alpha:H}).stroke({width:1/this.world.scale.x,color:o})}restrokeShapes(){if(!this.nodes.size)this.shapes.length&&this.drawShapes();else{let e=new Map(this.shapes.map(e=>[e.id,e]));for(let[t,n]of this.nodes){let r=e.get(t);r&&this.paintShape(n,r)}}this.drawSelectionBorders(),this.redrawRegionOutline(),this.repaintPreview()}redrawRegionOutline(){let e=this.regionOutlineG;if(!e)return;e.clear();let t=this.region?.outlineStyles;if(!this.region||!t)return;let n=this.world.scale.x||1,r=(t,r)=>{let i=r.width/n,a=[r.dash[0]/n,r.dash[1]/n];for(let[n,o]of t)r.underlayColor&&e.poly([n.x,n.y,o.x,o.y],!1).stroke({width:i,color:Q(r.underlayColor)}),this.strokeDashedPolyline(e,[n,o],!1,i,Q(r.color),r.opacity,a)};r(this.region.visibleOutline,t.visible),r(this.region.occludedOutline,t.occluded)}path(e,t){let{type:n,points:r}=t;if(n===o.POINT){e.circle(r[0].x,r[0].y,this.pointRadius(t));return}if(n===o.RECTANGLE){let t=h(r);e.rect(t.minX,t.minY,t.maxX-t.minX,t.maxY-t.minY);return}if(n===o.ELLIPSE){let t=h(r);e.ellipse((t.minX+t.maxX)/2,(t.minY+t.maxY)/2,(t.maxX-t.minX)/2,(t.maxY-t.minY)/2);return}let i=r.flatMap(e=>[e.x,e.y]);e.poly(i,n!==o.LINE)}dashedStrokeShape(e,t,n,r,i,a){let{type:s,points:c}=t;if(s===o.RECTANGLE){let t=h(c);this.strokeDashedPolyline(e,[{x:t.minX,y:t.minY},{x:t.maxX,y:t.minY},{x:t.maxX,y:t.maxY},{x:t.minX,y:t.maxY}],!0,n,r,i,a);return}if(s===o.ELLIPSE){let t=h(c),o=(t.minX+t.maxX)/2,s=(t.minY+t.maxY)/2,l=(t.maxX-t.minX)/2,u=(t.maxY-t.minY)/2,d=Array.from({length:96},(e,t)=>{let n=t/96*Math.PI*2;return{x:o+Math.cos(n)*l,y:s+Math.sin(n)*u}});this.strokeDashedPolyline(e,d,!0,n,r,i,a);return}this.strokeDashedPolyline(e,c,s!==o.LINE,n,r,i,a)}strokeDashedPolyline(e,t,n,r,i,a,o){if(t.length<2)return;let[s,c]=o,l=!0,u=0,d=n?t.length:t.length-1;for(let n=0;n<d;n++){let o=t[n],d=t[(n+1)%t.length],f=d.x-o.x,p=d.y-o.y,m=Math.hypot(f,p);if(!m)continue;let h=0;for(;h<m;){let t=l?s:c,n=Math.min(t-u,m-h);if(l){let t=h/m,s=(h+n)/m;e.moveTo(o.x+f*t,o.y+p*t).lineTo(o.x+f*s,o.y+p*s).stroke({width:r,color:i,alpha:a})}h+=n,u+=n,u>=t-1e-4&&(u=0,l=!l)}}}drawSelectionBorders(){this.selLayer.position.set(0,0);let e=new Set(this.selected),t=this.selected.length?this.shapes.filter(t=>e.has(t.id)&&l(t)):[];if(this.selectionBorderGfx.length!==t.length){for(let e of this.selectionBorderGfx)e.destroy();this.selectionBorderGfx=t.map(()=>{let e=new a.Graphics;return this.selLayer.addChild(e),e})}let n=1.5/this.world.scale.x;t.forEach((e,t)=>{let r=this.selectionBorderGfx[t];r.clear(),r.poly(this.selectionOutlinePoints(e,e.points).flatMap(e=>[e.x,e.y]),!0).stroke({width:n,color:an})})}updateSelectionBordersLive(e){let t=new Set(this.selected),n=1.5/this.world.scale.x,r=0;for(let i of this.shapes){if(!t.has(i.id)||!l(i))continue;let a=this.selectionBorderGfx[r++];a&&(a.clear(),a.poly(this.selectionOutlinePoints(i,e(i)).flatMap(e=>[e.x,e.y]),!0).stroke({width:n,color:an}))}}selectionOutlinePoints(e,t){return Yt(e,t,this.pointRadius(e))}imgToScreen(e){let t=this.world.toGlobal({x:e.x,y:e.y});return{x:t.x,y:t.y}}setTransformerOutline(e){let t=e.maxX-e.minX,n=e.maxY-e.minY;t<=0&&n<=0||this.setTransformerOutlinePoints(b([{x:e.minX,y:e.minY},{x:e.maxX,y:e.maxY}]))}setTransformerOutlinePoints(e){e.length<2||(this.transformerOutline||(this.transformerOutline=new a.Graphics,this.selLayer.addChild(this.transformerOutline)),this.transformerOutline.clear(),this.transformerOutline.poly(e.flatMap(e=>[e.x,e.y]),!0).stroke({width:1/this.world.scale.x,color:2001125}))}rotationHandleGap(){return Xt(this.viewport.scale)}rotationHandleScreenPoint(e){return this.imgToScreen(j(e,this.rotationHandleGap()))}setRotationConnector(e){let t=this.imgToScreen(O(e[0],e[1])),n=this.rotationHandleScreenPoint(e);this.rotLineNode||(this.rotLineNode=new a.Graphics,this.rotLineNode.eventMode=`none`,this.handleLayer.addChild(this.rotLineNode)),this.rotLineNode.clear(),this.rotLineNode.moveTo(t.x,t.y).lineTo(n.x,n.y).stroke({width:1,color:2001125})}layoutResizeHandle(e,t,n){e.position.set(t.x,t.y),e.rotation=n}orientedHandleAngle(e){return Zt(this.imgToScreen(e[0]),this.imgToScreen(e[1]))}drawTransformer(){if(this.activeDrag)return;for(let e of this.handleNodes)e.destroy();for(let e of this.vertexNodes)e.destroy();for(let e of this.midNodes)e.destroy();if(this.rotNode?.destroy(),this.rotNode=null,this.rotLineNode?.destroy(),this.rotLineNode=null,this.transformerOutline?.destroy(),this.transformerOutline=null,this.handleNodes=[],this.vertexNodes=[],this.midNodes=[],!this.transformEnabled)return;let e=Gt(this.shapes,this.selected);if(e.length===0||e.length===1&&e[0].type===o.POINT)return;let t=e.length===1&&(e[0].type===o.POLYGON||e[0].type===o.LINE)&&this.editingId===e[0].id?e[0]:null,n=h(e.flatMap(e=>e.points)),r=e.length===1&&e[0].type===o.ROTATED_RECTANGLE?e[0]:null,i=r?A(r.points):m.map(e=>g(e,n));r?this.setTransformerOutlinePoints(r.points):this.setTransformerOutline(n),r&&this.setRotationConnector(r.points);let s=r?this.orientedHandleAngle(r.points):0;for(let e of t?[]:m){let t=this.imgToScreen(i[m.indexOf(e)]),n=new a.Graphics;n.rect(-4,-4,8,8).fill({color:16777215}).stroke({width:1,color:2001125}),this.layoutResizeHandle(n,t,s),n.eventMode=`static`;let r=De(e,s);this.bindCursor(n,r),n.on(`pointerdown`,t=>{t.stopPropagation(),this.emitCursorHint(r),this.emitInteractionMode(`resizing`);let n=Gt(this.shapes,this.selected);this.activeDrag={kind:`resize`,anchor:e,box:h(n.flatMap(e=>e.points)),shapes:n.map(e=>({id:e.id,points:e.points}))},this.lastDragImg=null}),this.handleLayer.addChild(n),this.handleNodes.push(n)}if(t){let e=t,n=e.points,r=e.type===o.POLYGON?n.length:n.length-1;for(let t=0;t<r;t++){let r=n[t],i=n[(t+1)%n.length],o={x:(r.x+i.x)/2,y:(r.y+i.y)/2},s=this.imgToScreen(o),c=new a.Graphics;c.circle(0,0,4).fill({color:16777215,alpha:.6}).stroke({width:1,color:2001125}),c.position.set(s.x,s.y),c.eventMode=`static`,this.bindCursor(c,`copy`),c.on(`pointerdown`,r=>{r.stopPropagation();let i=[...n.slice(0,t+1),o,...n.slice(t+1)];this.cb.onTransformCommit?.([{id:e.id,points:i}])}),this.handleLayer.addChild(c),this.midNodes.push(c)}this.vertexPolygonId!==e.id&&(this.vertexPolygonId=e.id,this.selectedVertices.clear()),n.forEach((t,r)=>{let i=this.imgToScreen(t),o=this.selectedVertices.has(r),s=new a.Graphics;s.circle(0,0,5).fill({color:o?2001125:16777215}).stroke({width:1.5,color:o?16777215:2001125}),s.position.set(i.x,i.y),s.eventMode=`static`,this.bindCursor(s,`pointer`),s.on(`pointerdown`,t=>{if(t.stopPropagation(),t.shiftKey||t.ctrlKey||t.metaKey){this.selectedVertices.has(r)?this.selectedVertices.delete(r):this.selectedVertices.add(r),this.drawTransformer();return}let i=this.selectedVertices.has(r)&&this.selectedVertices.size>1?[...this.selectedVertices]:[r];i.length===1&&(this.selectedVertices.clear(),this.selectedVertices.add(r)),this.activeDrag={kind:`vertex`,id:e.id,indices:i,base:n,start:this.toImage(t)},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`vertexDragging`)}),this.handleLayer.addChild(s),this.vertexNodes.push(s)})}if(e.length===1&&e[0].type===o.ROTATED_RECTANGLE){let t=e[0],n=k(t.points),r=this.rotationHandleScreenPoint(t.points),i=new a.Graphics;i.circle(0,0,6).fill({color:16777215}).stroke({width:1.5,color:2001125}),i.position.set(r.x,r.y),i.eventMode=`static`,this.bindCursor(i,`grab`),i.on(`pointerdown`,e=>{e.stopPropagation();let r=this.toImage(e);this.activeDrag={kind:`rotate`,id:t.id,center:n,startAngle:Math.atan2(r.y-n.y,r.x-n.x),points:t.points,shiftKey:e.shiftKey},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`rotating`)}),this.handleLayer.addChild(i),this.rotNode=i}}beginMove(e,t){let n=Ut(this.shapes,t,e);n&&(this.transformEnabled&&!this.handleNodes.length&&this.drawTransformer(),this.activeDrag=n,this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`moving`),(n.shapes.length===1?this.shapes.find(e=>e.id===n.shapes[0].id):null)?.type===o.ROTATED_RECTANGLE?this.setTransformerOutlinePoints(n.shapes[0].points):this.setTransformerOutline(n.box),this.updateSelectionBordersLive(e=>e.points))}repositionHandlesForBox(e){m.forEach((t,n)=>{let r=this.imgToScreen(g(t,e)),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,0)}),this.setTransformerOutline(e)}repositionOrientedHandles(e){let t=this.orientedHandleAngle(e);if(A(e).forEach((e,n)=>{let r=this.imgToScreen(e),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,t)}),this.setTransformerOutlinePoints(e),this.rotNode){let t=this.rotationHandleScreenPoint(e);this.rotNode.position.set(t.x,t.y)}this.rotLineNode&&this.setRotationConnector(e)}repositionPolygonHandles(e,t){if(!this.vertexNodes.length)return;e.forEach((e,t)=>{let n=this.imgToScreen(e);this.vertexNodes[t]?.position.set(n.x,n.y)});let n=t?e.length:e.length-1;for(let t=0;t<n;t++){let n=e[t],r=e[(t+1)%e.length],i=this.imgToScreen({x:(n.x+r.x)/2,y:(n.y+r.y)/2});this.midNodes[t]?.position.set(i.x,i.y)}}resetMoveOffsets(){for(let[e,t]of this.nodes)this.shapes.find(t=>t.id===e)?.type!==o.POINT&&t.position.set(0,0);this.selLayer.position.set(0,0)}commitTransformUpdates(e){if(e.length){for(let t of e){let e=this.shapes.find(e=>e.id===t.id);if(!e)continue;e.points=t.points;let n=this.nodes.get(t.id);n&&this.paintShape(n,{...e,points:t.points})}this.cb.onTransformCommit?.(e),this.drawTransformer()}}dragTransform(e){let t=this.activeDrag;if(!t)return;this.applyCursor();let n=Bt(this.shapes,t),{updates:r,box:i}=Vt(t,e,n);if(t.kind===`move`){let n=e.x-t.start.x,r=e.y-t.start.y;for(let e of t.shapes){let t=this.nodes.get(e.id);t&&(this.shapes.find(t=>t.id===e.id)?.type===o.POINT?t.position.set(e.points[0].x+n,e.points[0].y+r):t.position.set(n,r))}}else for(let e of r)this.liveUpdateShape(e.id,e.points);if(this.cb.onTransformPreview?.(r),this.updateSelectionBordersLive(e=>r.find(t=>t.id===e.id)?.points??e.points),t.kind===`resize`||t.kind===`move`){n?this.repositionOrientedHandles(r[0].points):i&&this.repositionHandlesForBox(i);let e=t.shapes.length===1?this.shapes.find(e=>e.id===t.shapes[0].id):null,a=e?.type===o.POLYGON||e?.type===o.LINE;(t.kind===`resize`?a:this.vertexNodes.length>0&&t.shapes.length===1)&&this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}else if(t.kind===`rotate`){this.repositionOrientedHandles(r[0].points);let e=this.shapes.find(e=>e.id===t.id);e&&(e.type===o.POLYGON||e.type===o.LINE)&&this.repositionPolygonHandles(r[0].points,e.type===o.POLYGON)}else{i&&this.repositionHandlesForBox(i);let e=this.shapes.find(e=>e.id===t.id);this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}}endTransform(){let e=this.activeDrag,t=this.lastDragImg;if(this.activeDrag=null,this.emitInteractionMode(`idle`),this.emitCursorHint(e?.kind===`move`?`grab`:null),!e||!t){this.cb.onTransformPreview?.([]),this.drawTransformer();return}if(e.kind===`move`&&t.x===e.start.x&&t.y===e.start.y){this.cb.onTransformPreview?.([]),this.drawTransformer();return}let{updates:n}=Vt(e,t,Bt(this.shapes,e));e.kind===`move`&&this.resetMoveOffsets(),this.commitTransformUpdates(n)}};function sn({backend:e,hostRef:t,engineRef:r,imageUrl:i,renderedImageUrl:a,makeCallbacks:o,viewRef:s,readOnlyRef:c,toolRef:l,renderShapesRef:u,coordinateSizeRef:d,imageSizeRef:f,selRef:p,maskCanvasRef:m,regionOverlayRef:h,dimmedRef:g,syncMinimap:_,setImage:v,setImageVisible:y,setReady:b,setImageStatus:x,onContextMenuRequest:S}){let C=(0,n.useRef)(a);C.current=a;let w=(0,n.useRef)(i);w.current=i;let T=(0,n.useRef)(null),E=(0,n.useRef)(null),D=(0,n.useRef)(!1),O=(0,n.useRef)(null),k=(0,n.useRef)(o);k.current=o;let A=(0,n.useRef)(S);A.current=S,(0,n.useEffect)(()=>{let n=t.current;if(!n)return;let i=!1,a=null,o=null,x=k.current(),S=e===`konva`?new tn(n,x):new on(n,x);return r.current=S,(async()=>{if(await S.init(),!i){if(S.setFilter(s.current.brightness,s.current.contrast),S.setStrokeSize(s.current.strokeSize),S.setImageSmoothing(s.current.imageSmoothing),S.setTransformEnabled(!c.current),D.current=!0,C.current){if(await S.setImage(C.current,d.current,f.current),i)return;T.current=C.current,E.current=w.current,v({w:S.imageWidth,h:S.imageHeight}),y(!0),S.setShapes(u.current,p.current),S.setOverlays(s.current.showGuide?m.current:null,s.current.showRegionMask?h.current:null,g.current);let e=O.current;e?.viewport&&(e.imageUrl===T.current||s.current.keepZoomOnImageChange)?S.applyViewport(e.viewport):S.fit(),_(),b(!0)}a=e=>{e.preventDefault();let t=S.dom.getBoundingClientRect();if(e.ctrlKey||e.metaKey){S.zoomAt(e.clientX-t.left,e.clientY-t.top,Math.exp(-e.deltaY*.01));return}if(!s.current.wheelZoom){let t=S.viewport;S.applyViewport({scale:t.scale,x:t.x-e.deltaX,y:t.y-e.deltaY});return}S.zoomAt(e.clientX-t.left,e.clientY-t.top,e.deltaY<0?1.1:1/1.1)},S.dom.addEventListener(`wheel`,a,{passive:!1}),o=e=>{if(e.preventDefault(),l.current===L.ASSISTANT_POINT&&e.altKey)return;let t=n.getBoundingClientRect(),r=e.clientX-t.left,i=e.clientY-t.top,a=S.viewport;A.current({x:r,y:i,img:{x:(r-a.x)/a.scale,y:(i-a.y)/a.scale}})},S.dom.addEventListener(`contextmenu`,o)}})(),()=>{i=!0,D.current=!1,O.current={imageUrl:T.current??``,viewport:S.viewport},r.current=null,a&&S.dom&&S.dom.removeEventListener(`wheel`,a),o&&S.dom&&S.dom.removeEventListener(`contextmenu`,o),S.destroy()}},[e]),(0,n.useEffect)(()=>{let e=r.current;if(!e||!D.current||!a||T.current===a)return;let t=a,n=E.current!==i;n&&(e.clearImage(),e.setShapes([],[]),e.setOverlays(null,null,!1),y(!1));let o=!1;return(async()=>{await e.setImage(t,d.current,f.current),!(o||r.current!==e)&&(T.current=t,n&&(E.current=i,v({w:e.imageWidth,h:e.imageHeight}),y(!0),e.setShapes(u.current,p.current),e.setOverlays(s.current.showGuide?m.current:null,s.current.showRegionMask?h.current:null,g.current),s.current.keepZoomOnImageChange||e.fit(),_(),b(!0)))})(),()=>{o=!0}},[a]),(0,n.useEffect)(()=>{let e=!1;if(!a){x(`loading`);return}x(`loading`);let t=new Image;return t.onload=()=>{e||x(`ready`)},t.onerror=()=>{e||x(`error`)},t.src=a,()=>{e=!0}},[a])}var cn=.05,ln=20;function un(e){let{deltaY:t,deltaX:n,deltaMode:r}=e;return r===0?Math.abs(t)<10||Math.abs(n)<10||!Number.isInteger(t)||!Number.isInteger(n):r===1?!1:!Number.isInteger(t)||!Number.isInteger(n)}function dn({engineRef:e,image:t,wheelZoom:r,minimapSize:i}){let a=(0,n.useRef)(null),o=!!t&&t.w>0&&t.h>0,s=o?Math.min(i/t.w,i/t.h):1,c=o?t.w*s:0,l=o?t.h*s:0,u=o?(i-c)/2:0,d=o?(i-l)/2:0,f=e=>{let t=e.currentTarget.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}},p=()=>{let t=e.current;if(!t)return null;let n=t.viewport;return{x:-n.x/n.scale*s+u,y:-n.y/n.scale*s+d,width:t.screenSize.w/n.scale*s,height:t.screenSize.h/n.scale*s}},m=(n,r,i)=>{let a=e.current;if(!a||!t)return;let o=p();if(!o)return;let c=i?.offsetX??o.width/2,l=i?.offsetY??o.height/2,f=n.x-c+o.width/2,m=n.y-l+o.height/2,h=(f-u)/s,g=(m-d)/s;a.applyViewport({scale:r,x:a.screenSize.w/2-h*r,y:a.screenSize.h/2-g*r})};return{mm:s,offX:u,offY:d,dispW:c,dispH:l,handleMinimapPointerDown:t=>{let n=e.current,r=p();if(!n||!r)return;t.preventDefault(),t.stopPropagation();let i=f(t),o=i.x>=r.x&&i.x<=r.x+r.width&&i.y>=r.y&&i.y<=r.y+r.height?{offsetX:i.x-r.x,offsetY:i.y-r.y}:{offsetX:r.width/2,offsetY:r.height/2};a.current={pointerId:t.pointerId,...o},t.currentTarget.setPointerCapture(t.pointerId),m(i,n.viewport.scale,o)},handleMinimapPointerMove:t=>{let n=a.current,r=e.current;!n||!r||n.pointerId!==t.pointerId||(t.preventDefault(),t.stopPropagation(),m(f(t),r.viewport.scale,n))},endMinimapDrag:e=>{let t=a.current;!t||t.pointerId!==e.pointerId||(a.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))},handleMinimapWheel:t=>{let n=e.current;if(!n||!r)return;t.preventDefault(),t.stopPropagation();let i=un(t.nativeEvent)?2.5:1,a=t.deltaY*i,o=1.05,s=a>0?n.viewport.scale/o:n.viewport.scale*o,c=Math.max(cn,Math.min(ln,s));m(f(t),c)},zoomCentered:t=>{let n=e.current;if(!n)return;let{w:r,h:i}=n.screenSize;n.zoomAt(r/2,i/2,t)}}}function fn(e,t,n){if(!(!e||!n.length)){if(t.type===o.POINT){e.setAttribute(`cx`,String(n[0].x)),e.setAttribute(`cy`,String(n[0].y));return}if(t.type===o.RECTANGLE||t.type===o.ELLIPSE){let r=h(n);if(t.type===o.ELLIPSE){e.setAttribute(`cx`,String((r.minX+r.maxX)/2)),e.setAttribute(`cy`,String((r.minY+r.maxY)/2)),e.setAttribute(`rx`,String((r.maxX-r.minX)/2)),e.setAttribute(`ry`,String((r.maxY-r.minY)/2));return}e.setAttribute(`x`,String(r.minX)),e.setAttribute(`y`,String(r.minY)),e.setAttribute(`width`,String(r.maxX-r.minX)),e.setAttribute(`height`,String(r.maxY-r.minY));return}e.setAttribute(`points`,n.map(e=>`${e.x},${e.y}`).join(` `))}}function pn({engineRef:e,docRef:t,overlayRef:r,zoomLabelRef:i,minimapRectRef:a,minimapSize:o,onViewportChangeRef:s}){let c=(0,n.useRef)(new Map);return{registerMinimapShape:(0,n.useCallback)((e,t)=>{t?c.current.set(e,t):c.current.delete(e)},[]),applyMinimapPreview:(0,n.useCallback)(e=>{let n=t.current.getShapes();if(!e.length){for(let e of n)fn(c.current.get(e.id),e,e.points);return}let r=new Map(n.map(e=>[e.id,e]));for(let t of e){let e=r.get(t.id);e&&fn(c.current.get(e.id),e,t.points)}},[t]),syncMinimap:(0,n.useCallback)(()=>{let t=e.current;if(!t?.imageWidth)return;let n=t.viewport;if(s.current?.(n),r.current){r.current.style.transform=`translate(${n.x}px, ${n.y}px) scale(${n.scale})`;let e=1/(n.scale||1);r.current.style.setProperty(`--editor-overlay-stroke`,`${e}`),r.current.style.setProperty(`--editor-overlay-dash`,`${4*e}`),r.current.style.setProperty(`--editor-overlay-inverse-scale`,`${e}`)}i.current&&(i.current.textContent=`${Math.round(n.scale*100)}%`);let c=a.current;if(!c)return;let l=Math.min(o/t.imageWidth,o/t.imageHeight),u=(o-t.imageWidth*l)/2,d=(o-t.imageHeight*l)/2,{w:f,h:p}=t.screenSize;c.style.left=`${-n.x/n.scale*l+u}px`,c.style.top=`${-n.y/n.scale*l+d}px`,c.style.width=`${f/n.scale*l}px`,c.style.height=`${p/n.scale*l}px`},[e,r,i,a,o,s])}}var mn=12;function hn({doc:e,selRef:t,effectiveReadOnly:r,changeSelection:i,canMergeSelection:a}){let s=(0,n.useRef)([]),c=(0,n.useRef)(0),d=(0,n.useCallback)(()=>i(e.getShapes().filter(e=>l(e)).map(e=>e.id)),[e,i]),f=(0,n.useCallback)(()=>i([]),[i]),m=(0,n.useCallback)(()=>e.getShapes().filter(e=>t.current.includes(e.id)&&u(e)),[e,t]),h=(0,n.useCallback)(()=>{if(r||!t.current.length)return;let n=m().map(e=>e.id);n.length&&(e.remove(n),i([]))},[e,r,i,m,t]),g=(0,n.useCallback)(()=>{s.current=m(),c.current=0},[m]),_=(0,n.useCallback)(()=>s.current.length>0,[]),v=(0,n.useCallback)(()=>{if(r||!s.current.length)return;c.current+=1;let t=mn*c.current,n=s.current.map(e=>({...e,id:p(),points:e.points.map(e=>({x:e.x+t,y:e.y+t}))}));e.create(n),i(n.map(e=>e.id))},[e,r,i]),y=(0,n.useCallback)(()=>{if(r||!t.current.length)return;let n=m().map(e=>({...e,id:p(),points:e.points.map(e=>({x:e.x+mn,y:e.y+mn}))}));n.length&&(e.create(n),i(n.map(e=>e.id)))},[e,r,i,m,t]),b=(0,n.useCallback)(()=>{if(r)return;let t=m().map(e=>e.id);t.length&&e.reorder(t,`front`)},[e,r,m]),x=(0,n.useCallback)(()=>{if(r)return;let t=m().map(e=>e.id);t.length&&e.reorder(t,`back`)},[e,r,m]),S=(0,n.useCallback)((n,i)=>{if(r||!t.current.length)return;let a=e.getShapes().filter(e=>t.current.includes(e.id)&&u(e));a.length&&e.update(a.map(e=>({...e,points:e.points.map(e=>({x:e.x+n,y:e.y+i}))})))},[e,r,t]),C=(0,n.useCallback)(()=>m().filter(e=>e.type===o.POLYGON||e.type===o.RECTANGLE||e.type===o.ROTATED_RECTANGLE||e.type===o.ELLIPSE),[m]);return{selectAll:d,clearSelection:f,getEditableSelection:m,deleteSelection:h,copySelection:g,canPaste:_,paste:v,duplicate:y,bringToFront:b,sendToBack:x,nudgeSelection:S,getMergeTargets:C,mergeSelection:(0,n.useCallback)(()=>{if(r)return;let t=C();if(t.length<2||a&&!a(t))return;let n=lt([],1,ct(t));if(!n)return;let s=ut(n,1);if(!s.length)return;let c=t[0],l=s.map(e=>({id:p(),type:o.POLYGON,points:e,style:c.style,meta:c.meta}));e.replace(t.map(e=>e.id),l),i(l.map(e=>e.id))},[e,r,C,a,i])}}function gn({engineRef:e,doc:t,selRef:r,zoomAnimationDuration:i,zoomBound:a,ready:o}){let s=(0,n.useRef)(null),c=(0,n.useRef)(null),l=(0,n.useCallback)(()=>{s.current?.(),s.current=null},[]),u=(0,n.useCallback)((t,n=i)=>{let r=e.current;r&&(l(),s.current=Xe(r.viewport,t,e=>r.applyViewport(e),n))},[l,i,e]),d=(0,n.useCallback)((t,n=i)=>{let r=e.current;if(!r)return;let a=Je(t,r.screenSize.w,r.screenSize.h);a&&u(a,n)},[u,i,e]),f=(0,n.useCallback)((e,n=i)=>{let r=qe(t.getShapes().filter(t=>e.includes(t.id)));r&&d(r,n)},[t,d,i]),p=(0,n.useCallback)(()=>{let n=t.getShapes().filter(e=>r.current.includes(e.id));if(!n.length)return;let i=e.current;if(!i)return;let a=Ye(h(n.flatMap(e=>e.points)),i.screenSize.w,i.screenSize.h,80);a&&u(a)},[t,u,e,r]),m=(0,n.useCallback)(t=>{let n=e.current;if(!n)return;let{w:r,h:i}=n.screenSize;n.zoomAt(r/2,i/2,t)},[e]);return(0,n.useEffect)(()=>()=>l(),[l]),(0,n.useEffect)(()=>{if(!a){c.current=null;return}if(!o)return;let t=e.current;if(!t?.imageWidth)return;let{w:n,h:r}=t.screenSize;if(!n||!r)return;let i=JSON.stringify(a);c.current!==i&&(d(a),c.current=i)},[a,o,d,e]),{cancelZoomAnimation:l,runViewportAnimation:u,zoomToBounds:d,zoomToShapes:f,zoomToSelection:p,zoomAtCenter:m}}var _n=180,vn=`__draft_preview__`;function yn(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function bn({imageUrl:t,displayImageUrl:i,coordinateSize:a,renderImageState:c,dimmed:d=!1,initialShapes:f,selectedIds:m,activeTool:g,draftStyle:_,draftMeta:v,readOnly:y,disableMarquee:b,locked:x,onLockedInteraction:S,onIdleEscape:C,overrideShapeInteraction:w,defaultViewSettings:T,viewSettings:E,onViewSettingsChange:D,showMinimap:O=!0,showViewSettings:k=!0,getContextMenuItems:A,strings:j,canMergeSelection:M,brushSize:N=20,zoomBound:P,zoomAnimationDuration:F=300,decorationShapes:ee,regionMask:te,guideMask:ne,maskPalette:re,overlayMarkers:z,renderOverlayMarker:oe,onOverlayMarkerClick:H,renderImageOverlay:se,getSelectionLabel:ce,hideSelectionLabelDot:le,formatSelectionInfo:ue,externalTools:de,assistant:fe,keymap:pe,handleRef:me,backend:he=`pixi`,onActiveToolChange:U,onSelectionChange:_e,onEditingChange:ve,onShapesCreated:ye,onShapesUpdated:Se,onShapesDeleted:we,onDrawSessionChange:Te,onDraftShapeChange:Ee,onViewportChange:De,onShapesTransformPreview:Oe}){let Ae=(0,n.useRef)(null),W=(0,n.useRef)(null),Me=(0,n.useRef)(null),Ne=(0,n.useRef)(null),Pe=(0,n.useRef)(null),Fe=`${(0,n.useId)()}-minimap`,[G,Ie]=(0,n.useState)(null),[Le,Re]=(0,n.useState)(!1),[K,ze]=(0,n.useState)(!1),[Be,He]=(0,n.useState)(null),[Ue,We]=(0,n.useState)({active:!1,kind:`none`,canUndo:!1,canRedo:!1}),[Ge,Ke]=(0,n.useState)(!0),[qe,Je]=(0,n.useState)(!1),Ye=i??t,[Xe,$e]=(0,n.useState)(`loading`),q=bt({onShapesCreated:ye,onShapesUpdated:Se,onShapesDeleted:we}),[et,tt]=(0,n.useState)([]),J=m??et,nt=m!==void 0,rt=(0,n.useMemo)(()=>new Map((de??[]).map(e=>[e.id,e])),[de]),it=(0,n.useRef)(rt);it.current=rt;let at=(0,n.useRef)(Ue);at.current=Ue;let[Y,ot]=(0,n.useState)(()=>{let e=Object.fromEntries(Object.entries(T??{}).filter(([,e])=>e!==void 0));return{...R,...e}}),st=(0,n.useCallback)(e=>ot(t=>({...t,...e})),[]),X=(0,n.useMemo)(()=>I(j),[j]);(0,n.useEffect)(()=>{E&&ot(e=>{let t=Object.entries(E).filter(([t,n])=>n!==void 0&&e[t]!==n);return t.length?{...e,...Object.fromEntries(t)}:e})},[E]);let ct=(0,n.useRef)(D);ct.current=D;let lt=(0,n.useRef)(!1);(0,n.useEffect)(()=>{if(!lt.current){lt.current=!0;return}ct.current?.(Y)},[Y]);let ut=(0,n.useMemo)(()=>!ne||!re?null:je(ne,re),[ne,re]),dt=(0,n.useMemo)(()=>ut?.toDataURL()??null,[ut]),ft=(0,n.useMemo)(()=>!G||!te?null:Ve(te,G.w,G.h),[G,te]),pt=(0,n.useRef)(ut);pt.current=ut;let mt=(0,n.useRef)(ft);mt.current=ft;let ht=(0,n.useRef)(d);ht.current=d;let gt=(0,n.useRef)(G);gt.current=G;let vt=(0,n.useRef)(a);vt.current=a;let yt=(0,n.useRef)(a?.imageSize);yt.current=a?.imageSize;let xt=(0,n.useRef)([]);xt.current=J;let St=(0,n.useRef)(g);St.current=g;let Ct=(0,n.useRef)(_);Ct.current=_;let wt=(0,n.useRef)(v);wt.current=v;let Tt=(0,n.useRef)(N);Tt.current=N;let Et=(0,n.useRef)(Y.simplifyStrength);Et.current=Y.simplifyStrength;let Z=!!y||!!x,Dt=(0,n.useRef)(Z);Dt.current=Z;let Ot=(0,n.useRef)(b);Ot.current=b;let At=(0,n.useRef)(x);At.current=x;let jt=(0,n.useRef)(S);jt.current=S;let Mt=(0,n.useRef)(w);Mt.current=w;let Nt=(0,n.useRef)(q);Nt.current=q;let Pt=(0,n.useRef)(!1),Ft=(0,n.useRef)(!1),It=(0,n.useRef)(`idle`),Lt=(0,n.useRef)(null),Rt=(0,n.useCallback)(()=>{let e=W.current;if(!e)return;let t=St.current,n=it.current.get(t),r=at.current;e.setCursor(ke({tool:t,externalToolCursor:n?.cursor,isSpacePressed:Pt.current,interactionMode:It.current,rendererCursorHint:Lt.current,isPolygonDrawing:r.kind===`polygon`&&r.active}))},[]),zt=(0,n.useCallback)(e=>{It.current!==e&&(It.current=e,Rt())},[Rt]),Bt=(0,n.useCallback)(e=>{Lt.current!==e&&(Lt.current=e,Rt())},[Rt]),Vt=(0,n.useCallback)(e=>{let t=new Set,n=new Map(Nt.current.getShapes().map(e=>[e.id,e]));return e.filter(e=>{if(t.has(e))return!1;t.add(e);let r=n.get(e);if(!r)return!1;let i=Mt.current?.(r);return l(i?{...r,interaction:{...r.interaction,...i}}:r)})},[]),Ht=(0,n.useCallback)(e=>{let t=Vt(e);yn(xt.current,t)||(nt||tt(t),W.current?.setSelection(t),_e?.(t))},[Vt,_e,nt]),Ut=(0,n.useRef)(Ht);Ut.current=Ht;let[Wt,Gt]=(0,n.useState)(null),Kt=(0,n.useCallback)(e=>Gt(e),[]),qt=(0,n.useRef)(Kt);qt.current=Kt,(0,n.useEffect)(()=>{if(!nt)return;let e=Vt(m);yn(m,e)||_e?.(e)},[m,q.shapes,Vt,_e,nt]);let Jt=(0,n.useRef)(De);Jt.current=De;let{registerMinimapShape:Yt,applyMinimapPreview:Xt,syncMinimap:Zt}=pn({engineRef:W,docRef:Nt,overlayRef:Ne,zoomLabelRef:Pe,minimapRectRef:Me,minimapSize:_n,onViewportChangeRef:Jt}),Qt=(0,n.useRef)(new Map),$t=(0,n.useRef)(ue);$t.current=ue;let en=(0,n.useCallback)((e,t)=>{t?Qt.current.set(e,t):Qt.current.delete(e)},[]),tn=(0,n.useRef)(null),[nn,rn]=(0,n.useState)(null),an=(0,n.useCallback)(e=>{if(!e.length)return;let t=new Map(Nt.current.getShapes().map(e=>[e.id,e]));tn.current&&t.set(tn.current.id,tn.current);for(let{id:n,points:r}of e){let e=Qt.current.get(n),i=t.get(n);if(!e||!i)continue;let a=h(r);e.style.left=`${a.minX}px`,e.style.top=`${a.minY}px`,e.style.width=`${a.maxX-a.minX}px`,e.style.height=`${a.maxY-a.minY}px`;let o=e.querySelector(`[data-selinfo-dim]`);if(o){let e=be(i,r);o.textContent=$t.current?.(e)??xe(e)}}},[]),Q=(0,n.useCallback)(e=>{Xt(e),an(e),Oe?.(e)},[Xt,an,Oe]),on=(0,n.useCallback)(e=>{if(Ee?.(e?{...e,meta:wt.current}:null),!e||!Ct.current){tn.current&&(tn.current=null,rn(null));return}let t={id:vn,type:e.type,points:e.points,style:Ct.current,meta:wt.current},n=tn.current!==null;tn.current=t,n?an([{id:vn,points:e.points}]):rn(t)},[an,Ee]),cn=(0,n.useCallback)((e,t)=>{let n=Ct.current;if(!n||Dt.current)return;let r=p();Nt.current.create({id:r,type:e,points:t,style:n,meta:v}),Ut.current([r])},[v]),ln=(0,n.useRef)(cn);ln.current=cn;let un=_t({toolRef:St,selRef:xt,docRef:Nt,readOnlyRef:Dt,draftRef:Ct,brushSizeRef:Tt,simplifyEpsilonRef:Et,draftMeta:v,engineRef:W,onDrawSessionChange:(0,n.useCallback)(e=>{We(e),Te?.(e)},[Te]),onDraftShapeChange:Ee,changeSelection:Ht,createShape:cn}),fn=(0,n.useRef)(un);fn.current=un;let{reset:mn,undoSession:bn,redoSession:xn,canUndoSession:Sn,canRedoSession:Cn,hasDraftSession:wn,hasDraftPoints:Tn,commitDraftSession:En,setBrushScalarMode:Dn,getBrushScalarMode:On,hasBrushSession:kn,commitBrush:An,cancelBrush:jn,beginBrushEditFromSelection:Mn,deleteDraftSelectedPoints:Nn,handleToolChange:Pn,handleBrushSelectionChange:Fn}=un,In=(0,n.useRef)(fe);In.current=fe;let $=Qe({docRef:Nt,draftRef:Ct,draftMeta:v,changeSelection:Ht,assistantRef:In}),Ln=(0,n.useRef)($);Ln.current=$;let{selectAll:Rn,clearSelection:zn,deleteSelection:Bn,copySelection:Vn,canPaste:Hn,paste:Un,duplicate:Wn,bringToFront:Gn,sendToBack:Kn,nudgeSelection:qn,getMergeTargets:Jn,mergeSelection:Yn}=hn({doc:q,selRef:xt,effectiveReadOnly:Z,changeSelection:Ht,canMergeSelection:M}),{zoomToBounds:Xn,zoomToShapes:Zn,zoomToSelection:Qn,zoomAtCenter:$n}=gn({engineRef:W,doc:q,selRef:xt,zoomAnimationDuration:F,zoomBound:P,ready:K});(0,n.useImperativeHandle)(me,()=>({previewRegionMask:e=>{let t=gt.current;if(!t)return;let n=e?Ve(e,t.w,t.h):mt.current;W.current?.setOverlays(er.current.showGuide?pt.current:null,er.current.showRegionMask?n:null,ht.current)},undo:()=>{bn()||q.undo()},redo:()=>{xn()||q.redo()},canUndo:()=>Sn()||q.canUndo(),canRedo:()=>Cn()||q.canRedo(),undoSession:bn,redoSession:xn,canUndoSession:Sn,canRedoSession:Cn,hasDraftSession:wn,cancelDraftSession:mn,commitDraftSession:En,setSelection:Ht,createShapes:e=>{e.length&&(q.create(e),Ht(e.map(e=>e.id)))},updateShapes:q.update,deleteShapes:q.remove,getShapes:q.getShapes,selectAll:Rn,clearSelection:zn,deleteSelection:Bn,copySelection:Vn,paste:Un,duplicate:Wn,bringToFront:Gn,sendToBack:Kn,zoomFit:()=>W.current?.fit(),zoom100:()=>W.current?.zoom100(),zoomIn:()=>{let e=W.current;if(!e)return;let{w:t,h:n}=e.screenSize;e.zoomAt(t/2,n/2,1.2)},zoomOut:()=>{let e=W.current;if(!e)return;let{w:t,h:n}=e.screenSize;e.zoomAt(t/2,n/2,1/1.2)},zoomToSelection:Qn,zoomToShapes:Zn,zoomToBounds:Xn,brush:{setScalarMode:Dn,getScalarMode:On,hasSession:kn,commit:An,cancel:jn,beginEditFromSelection:Mn}}),[q,Ht,bn,xn,En,mn,An,jn,Rn,zn,Bn,Vn,Un,Wn,Gn,Kn,Qn,Zn,Xn,Dn,On,kn,Mn]);let er=(0,n.useRef)(Y);er.current=Y;let tr=(0,n.useCallback)(()=>Ze({engineRef:W,toolRef:St,externalToolMapRef:it,spaceRef:Pt,shiftRef:Ft,docRef:Nt,selRef:xt,draftRef:Ct,readOnlyRef:Dt,disableMarqueeRef:Ot,lockedRef:At,onLockedInteraction:()=>jt.current?.(),createRef:ln,selectRef:Ut,enterEditRef:qt,drawSessionRef:fn,assistantRef:Ln,setCursorHint:Bt,setInteractionMode:zt,syncMinimap:Zt,onTransformPreview:Q,onDrawPreview:on}),[Bt,zt,Zt,Q,on]),nr=(0,n.useRef)([]);sn({backend:he,hostRef:Ae,engineRef:W,imageUrl:t,renderedImageUrl:Ye,makeCallbacks:tr,viewRef:er,readOnlyRef:Dt,toolRef:St,renderShapesRef:nr,coordinateSizeRef:vt,imageSizeRef:yt,selRef:xt,maskCanvasRef:pt,regionOverlayRef:mt,dimmedRef:ht,syncMinimap:Zt,setImage:Ie,setImageVisible:Re,setReady:ze,setImageStatus:$e,onContextMenuRequest:He});let rr=(0,n.useMemo)(()=>{let e=w?q.shapes.map(e=>{let t=w(e);return t?{...e,interaction:{...e.interaction,...t}}:e}):q.shapes;return ee?.length?[...ee.map(e=>({...e,interaction:{...e.interaction,selectable:!1,draggable:!1,editable:!1,hitTestDisabled:!0}})),...e]:e},[q.shapes,w,ee]);nr.current=rr,(0,n.useEffect)(()=>{W.current?.setShapes(rr,J),Zt()},[rr,J,Zt]),(0,n.useEffect)(()=>{W.current?.setEditing(Wt)},[Wt,K]);let ir=(0,n.useRef)(ve);ir.current=ve,(0,n.useEffect)(()=>{ir.current?.(Wt)},[Wt]),(0,n.useEffect)(()=>{Gt(null)},[g]),(0,n.useEffect)(()=>{Wt&&(J.length!==1||J[0]!==Wt)&&Gt(null)},[J,Wt]),(0,n.useEffect)(()=>{let e=W.current;e&&(e.setFilter(Y.brightness,Y.contrast),e.setStrokeSize(Y.strokeSize),e.setImageSmoothing(Y.imageSmoothing),Zt())},[Y.brightness,Y.contrast,Y.strokeSize,Y.imageSmoothing,Zt]),(0,n.useLayoutEffect)(()=>{K&&W.current?.setOverlays(Y.showGuide?ut:null,Y.showRegionMask?ft:null,d)},[K,ut,ft,Y.showGuide,Y.showRegionMask,d]),(0,n.useEffect)(()=>{!K||!G||Zt()},[K,G,dt,Y.showGuide,Y.showRegionMask,te,Zt]),(0,n.useEffect)(()=>{K&&W.current?.setTransformEnabled(!Z&&g!==L.BRUSH)},[Z,K,g]),(0,n.useEffect)(()=>{Pn(g,rt.has(g))},[g,rt,Pn]);let ar=$.finalize;(0,n.useEffect)(()=>{ar()},[g,ar]),(0,n.useEffect)(()=>{It.current=`idle`,Lt.current=null,Rt()},[g,he,Rt]),(0,n.useEffect)(()=>{Fn(J,Z)},[J,g,Z,Fn]),(0,n.useEffect)(()=>{K&&Rt()},[g,Ue,rt,K,Rt]);let or=(0,n.useRef)(null);(0,n.useEffect)(()=>{or.current!==t&&(or.current=t,q.reset(f??[]),Ht([]),mn(),ar())},[t,f,q.reset,Ht,mn,ar]),kt({keymap:pe,hostRef:Ae,actions:{undo:()=>{Z||bn()||q.undo()},redo:()=>{Z||xn()||q.redo()},selectAll:Rn,copy:Vn,cut:()=>{Vn(),Bn()},paste:Un,duplicate:Wn,delete:()=>{Tn()&&Nn()||Bn()},cancel:()=>{let e=it.current.get(St.current);if(!(e?.onCancel&&e.onCancel()!==!1)){if($.isActive()){$.cancel();return}if(wn()){mn();return}if(Wt){Gt(null);return}if(xt.current.length){zn();return}C?.()}},commitDraft:()=>{if($.isActive()){$.finalize();return}if(wn()){En();return}if(Z)return;if(Wt){Gt(null);return}let e=xt.current;if(e.length!==1)return;let t=Nt.current.getShapes().find(t=>t.id===e[0]);t&&(t.type===o.POLYGON||t.type===o.LINE)&&t.interaction?.editable!==!1&&!t.readOnly&&Gt(e[0])},bringToFront:Gn,sendToBack:Kn,zoomIn:()=>$n(1.2),zoomOut:()=>$n(1/1.2),zoom100:()=>W.current?.zoom100(),zoomFit:()=>W.current?.fit(),toggleMinimap:()=>Ke(e=>!e),toggleCursorGuide:()=>ot(e=>({...e,showCursorGuide:!e.showCursorGuide})),togglePixelation:()=>ot(e=>({...e,imageSmoothing:!e.imageSmoothing})),selectTool:()=>U?.(L.SELECT),rectangleTool:()=>U?.(L.RECTANGLE),rotatedRectangleTool:()=>U?.(L.ROTATED_RECTANGLE),circleTool:()=>U?.(L.CIRCLE),polygonTool:()=>U?.(L.POLYGON),pathTool:()=>U?.(L.PATH),brushTool:()=>U?.(L.BRUSH),pointTool:()=>U?.(L.POINT)},spaceRef:Pt,shiftRef:Ft,onSpaceDown:()=>{W.current?.setPanMode(!0),Rt()},onSpaceUp:()=>{W.current?.setPanMode(!1),It.current===`panning`?zt(`idle`):Rt()},nudge:qn});let sr=(0,n.useMemo)(()=>rr.filter(e=>J.includes(e.id)&&s(e)),[rr,J]),cr=(0,n.useMemo)(()=>nn?[...sr,nn]:sr,[sr,nn]),lr=J.length>0,ur=q.shapes.some(e=>J.includes(e.id)&&u(e)),dr=!Z&&J.length===1&&(()=>{let e=q.shapes.find(e=>e.id===J[0]);return!!e&&(e.type===o.POLYGON||e.type===o.LINE)&&e.interaction?.editable!==!1&&!e.readOnly})(),fr=Jn(),pr=Z||fr.length<2||(M?!M(fr):!1),mr=fe&&!Z&&J.length===1?(()=>{let e=q.shapes.find(e=>e.id===J[0]);return e&&e.type===o.POLYGON&&e.interaction?.editable!==!1&&!e.readOnly?e:null})():null,hr=[{id:`copy`,label:X.contextMenu.copy,shortcut:`⌘C`,disabled:!lr,onClick:Vn},{id:`paste`,label:X.contextMenu.paste,shortcut:`⌘V`,disabled:Z||!Hn(),onClick:Un},{id:`duplicate`,label:X.contextMenu.duplicate,shortcut:`⌘D`,disabled:!ur||Z,onClick:Wn},{id:`delete`,label:X.contextMenu.delete,shortcut:`Del`,danger:!0,disabled:!ur||Z,onClick:Bn},{separator:!0},{id:`editVertices`,label:X.contextMenu.editVertices,shortcut:`Enter`,disabled:!dr,onClick:()=>Gt(J[0])},{id:`merge`,label:X.contextMenu.merge,disabled:pr,onClick:Yn},{id:`assistExpand`,label:X.contextMenu.assistExpand,icon:(0,r.jsx)(e.$n,{size:14}),disabled:!mr,onClick:()=>{Be&&mr&&$.refineShape(mr,Be.img,!0)}},{id:`assistExclude`,label:X.contextMenu.assistExclude,icon:(0,r.jsx)(e.$n,{size:14}),disabled:!mr,onClick:()=>{Be&&mr&&$.refineShape(mr,Be.img,!1)}},{id:`bringToFront`,label:X.contextMenu.bringToFront,disabled:!ur||Z,onClick:Gn},{id:`sendToBack`,label:X.contextMenu.sendToBack,disabled:!ur||Z,onClick:Kn},{separator:!0},{id:`undo`,label:X.contextMenu.undo,shortcut:`⌘Z`,disabled:Z||!Sn()&&!q.canUndo(),onClick:()=>{bn()||q.undo()}},{id:`redo`,label:X.contextMenu.redo,shortcut:`⇧⌘Z`,disabled:Z||!Cn()&&!q.canRedo(),onClick:()=>{xn()||q.redo()}},{separator:!0},{id:`selectAll`,label:X.contextMenu.selectAll,shortcut:`⌘A`,onClick:Rn},{id:`clearSelection`,label:X.contextMenu.clearSelection,disabled:!lr,onClick:zn},{id:`zoomToSelection`,label:X.contextMenu.zoomToSelection,disabled:!lr,onClick:Qn}],gr=A?A(hr,{selectedIds:J,readOnly:Z}):hr,_r=dn({engineRef:W,image:G,wheelZoom:Y.wheelZoom,minimapSize:_n});return(0,r.jsxs)(`div`,{className:`aivex:relative aivex:h-full aivex:w-full aivex:overflow-hidden aivex:bg-black`,children:[(0,r.jsx)(`div`,{ref:Ae,className:`aivex:h-full aivex:w-full`,style:{opacity:+!!Le,transition:Le?`opacity 0.3s ease`:`none`}}),Xe!==`ready`&&(0,r.jsx)(ae,{status:Xe,render:c,loadingLabel:X.imageLoading,errorLabel:X.imageLoadError}),K&&G&&(0,r.jsx)(`div`,{className:`aivex:pointer-events-none aivex:absolute aivex:inset-0 aivex:overflow-hidden`,children:(0,r.jsxs)(`div`,{ref:Ne,style:{position:`absolute`,top:0,left:0,width:G.w,height:G.h,transformOrigin:`0 0`},children:[!!z?.length&&oe&&(0,r.jsx)(`div`,{style:{position:`absolute`,left:0,top:0,width:G.w,height:G.h,pointerEvents:`none`},children:z.map(e=>(0,r.jsx)(`div`,{role:e.disabled?void 0:`button`,tabIndex:e.disabled?void 0:0,"aria-pressed":e.selected||void 0,onPointerDown:e=>e.stopPropagation(),onClick:t=>{t.stopPropagation(),e.disabled||H?.(e)},onKeyDown:t=>{e.disabled||t.key!==`Enter`&&t.key!==` `||(t.preventDefault(),t.stopPropagation(),H?.(e))},style:{position:`absolute`,left:e.point.x,top:e.point.y,transform:e.anchor===`topLeft`?`scale(var(--editor-overlay-inverse-scale, 1))`:`translate(-50%, -50%) scale(var(--editor-overlay-inverse-scale, 1))`,transformOrigin:e.anchor===`topLeft`?`0 0`:`center`,zIndex:e.selected?1:void 0,pointerEvents:e.disabled?`none`:`auto`,cursor:e.disabled?`default`:`pointer`},children:oe(e)},e.id))}),se?.({image:G,viewport:W.current?.viewport??{scale:1,x:0,y:0}}),cr.length>0&&(0,r.jsx)(Ce,{shapes:cr,getLabel:ce,hideDot:le,formatInfo:ue,register:en}),fe&&($.status===`loading`||$.boxes.length>0)&&(0,r.jsx)(ie,{image:G,points:$.points,boxes:$.boxes,status:$.status})]})}),K&&Y.showCursorGuide&&(0,r.jsx)(V,{color:`#1e88e5`}),K&&G&&O&&(0,r.jsx)(ge,{image:G,imageUrl:Ye,imageVisible:Le,maskDataUrl:dt,region:ft,roiMaskId:Fe,shapes:rr,view:Y,onChangeView:st,nav:_r,registerShape:Yt,rectRef:Me,zoomLabelRef:Pe,onZoom100:()=>W.current?.zoom100(),open:Ge,onToggleOpen:()=>Ke(e=>!e),labels:X.minimap,settingsLabels:X.viewSettings,showSettings:k,settingsOpen:qe,onToggleSettings:()=>Je(e=>!e),onCloseSettings:()=>Je(!1)}),Be&&(0,r.jsx)(B,{x:Be.x,y:Be.y,items:gr,onClose:()=>He(null)})]})}async function xn(e){let t=await At(e);return await new Promise((n,r)=>{let i=new Image;t||(i.crossOrigin=`anonymous`),i.onload=()=>n({image:i,revoke:t?()=>URL.revokeObjectURL(t):null}),i.onerror=()=>{t&&URL.revokeObjectURL(t),r(Error(`Failed to load image`))},i.src=t??e})}function Sn(e,t,n){if(t.length!==0){e.beginPath(),e.moveTo(t[0].x,t[0].y);for(let n=1;n<t.length;n+=1)e.lineTo(t[n].x,t[n].y);n&&e.closePath()}}function Cn(e,t,n,r){if(t.interaction?.visible===!1)return;let i=le(t,{strokeWidth:r,pointRadius:2});if(e.save(),e.globalAlpha=i.opacity,e.lineWidth=i.strokeWidth/n,e.lineJoin=`round`,e.lineCap=`round`,t.type===o.POINT){let r=t.points[0];r&&(e.fillStyle=i.color,e.beginPath(),e.arc(r.x,r.y,i.pointRadius/n,0,Math.PI*2),e.fill()),e.restore();return}if(t.type===o.RECTANGLE||t.type===o.ELLIPSE){let[n,r]=t.points;if(n&&r){let i=Math.min(n.x,r.x),a=Math.min(n.y,r.y),s=Math.abs(r.x-n.x),c=Math.abs(r.y-n.y);e.beginPath(),t.type===o.ELLIPSE?e.ellipse(i+s/2,a+c/2,s/2,c/2,0,0,Math.PI*2):e.rect(i,a,s,c)}}else Sn(e,t.points,t.type!==o.LINE);i.fillVisible&&(e.save(),e.fillStyle=i.color,e.globalAlpha*=i.fillAlpha,e.fill(),e.restore()),t.style?.alternateColor&&i.dash?.length&&(e.setLineDash([]),e.strokeStyle=t.style.alternateColor,e.stroke()),e.setLineDash((i.dash??[]).map(e=>e/n)),e.strokeStyle=i.color,e.stroke(),e.restore()}function wn({imageUrl:e,alt:t=`Shape preview`,coordinateSize:i,shapes:a=[],regionMask:o,guideMask:s,maskPalette:c,focusedShapeId:l,focusFit:u=`contain`,zoomPadding:d=.3,strokeSize:p=1,brightness:m=1,contrast:g=1,imageSmoothing:_=!0,lazy:v=!0,className:y,style:b,renderImageState:x}){let S=(0,n.useRef)(null),C=(0,n.useRef)(null),w=(0,n.useRef)(null),[T,E]=(0,n.useState)(!v),[D,O]=(0,n.useState)(`loading`),[k,A]=(0,n.useState)(0);(0,n.useEffect)(()=>{if(!v||T)return;let e=S.current;if(!e)return;let t=new IntersectionObserver(([e])=>{e.isIntersecting&&(E(!0),t.disconnect())});return t.observe(e),()=>t.disconnect()},[v,T]),(0,n.useEffect)(()=>{let e=S.current;if(!e)return;let t=new ResizeObserver(()=>A(e=>e+1));return t.observe(e),()=>t.disconnect()},[]),(0,n.useEffect)(()=>{if(!T||!e){O(e?`loading`:`error`);return}let t=!0;return O(`loading`),xn(e).then(e=>{if(!t){e.revoke?.();return}w.current?.revoke?.(),w.current=e,O(`ready`)}).catch(()=>{t&&(w.current?.revoke?.(),w.current=null,O(`error`))}),()=>{t=!1}},[e,T]),(0,n.useEffect)(()=>()=>{w.current?.revoke?.(),w.current=null},[]);let j=(0,n.useMemo)(()=>a.find(e=>e.id===l),[l,a]),M=(0,n.useMemo)(()=>s&&c?je(s,c):null,[s,c]);return(0,n.useEffect)(()=>{if(D===`error`){let e=C.current;e?.getContext(`2d`)?.clearRect(0,0,e.width,e.height)}if(D!==`ready`)return;let e=S.current,t=C.current,n=w.current;if(!e||!t||!n)return;let{width:r,height:s}=e.getBoundingClientRect();if(!r||!s)return;let c=window.devicePixelRatio||1;t.width=Math.max(1,Math.round(r*c)),t.height=Math.max(1,Math.round(s*c)),t.style.width=`${r}px`,t.style.height=`${s}px`;let l=t.getContext(`2d`);if(!l)return;let v=i?.width??n.image.naturalWidth,y=i?.height??n.image.naturalHeight;if(!v||!y)return;let b=Math.min(r/v,s/y),x=(r-v*b)/2,T=(s-y*b)/2;if(j&&j.points.length>0){let e=h(j.points),t=Math.max(e.maxX-e.minX,50),n=Math.max(e.maxY-e.minY,50),i=Math.min(t,n)*d;b=Math.min(r/(t+i*2),s/(n+i*2)),u===`cover`&&(b=Math.max(b,Math.max(r/v,s/y))),x=r/2-(e.minX+e.maxX)/2*b,T=s/2-(e.minY+e.maxY)/2*b,u===`cover`&&(x=Math.min(0,Math.max(x,r-v*b)),T=Math.min(0,Math.max(T,s-y*b)))}l.setTransform(c,0,0,c,0,0),l.clearRect(0,0,r,s),l.save(),l.translate(x,T),l.scale(b,b),l.imageSmoothingEnabled=_,l.filter=`brightness(${m}) contrast(${g})`,l.drawImage(n.image,0,0,v,y),l.filter=`none`,M&&(l.save(),l.globalAlpha=.55,l.drawImage(M,0,0,v,y),l.restore());let E=o?Ve(o,v,y):null;if(E&&(Le(l,E,v,y),E.outlineStyles)){let e=(e,t)=>{if(l.lineWidth=t.width/b,t.underlayColor){l.setLineDash([]),l.strokeStyle=t.underlayColor;for(let[t,n]of e)Sn(l,[t,n],!1),l.stroke()}l.save(),l.globalAlpha*=t.opacity,l.setLineDash(t.dash.map(e=>e/b)),l.strokeStyle=t.color;for(let[t,n]of e)Sn(l,[t,n],!1),l.stroke();l.restore()};e(E.visibleOutline,E.outlineStyles.visible),e(E.occludedOutline,E.outlineStyles.occluded)}for(let e of f(a))Cn(l,e,b,p);l.restore()},[m,g,i,j,u,_,M,o,a,k,D,p,d]),(0,r.jsxs)(`div`,{ref:S,className:y,style:{position:`relative`,width:`100%`,height:`100%`,...b},children:[(0,r.jsx)(`canvas`,{ref:C,role:`img`,"aria-label":t,style:{display:`block`}}),D!==`ready`&&x&&(0,r.jsx)(`div`,{style:{position:`absolute`,inset:0},children:x(D===`error`?`error`:`loading`)})]})}exports.DEFAULT_EDITOR_STRINGS=F,exports.DEFAULT_VIEW_SETTINGS=R,exports.SHAPE_TYPE=o,exports.ShapeEditor=bn,exports.default=bn,exports.ShapeViewer=wn,exports.TOOL=L,exports.generateId=p;
2
2
  //# sourceMappingURL=shape-editor.cjs.map