@aivex/ui 1.2.0-dev.41 → 1.2.0-dev.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/comment.cjs +3 -2
- package/dist/comment.cjs.map +1 -1
- package/dist/comment.js +61 -30
- package/dist/comment.js.map +1 -1
- package/dist/components/Comment/mentionContent.d.ts +5 -0
- package/dist/components/Comment/mentionContent.test.d.ts +1 -0
- package/dist/components/DataGrid/DataGrid.d.ts +8 -3
- package/dist/components/DataGrid/DataGridPrimitives.d.ts +10 -2
- package/dist/components/DataGrid/index.d.ts +1 -1
- package/dist/components/ShapeEditor/_components/SelectionInfo.d.ts +7 -2
- package/dist/components/ShapeEditor/_state/useMinimapSync.d.ts +3 -1
- package/dist/components/Table/Table.d.ts +10 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1056 -1052
- package/dist/index.js.map +1 -1
- package/dist/shape-editor.cjs +1 -1
- package/dist/shape-editor.cjs.map +1 -1
- package/dist/shape-editor.js +680 -652
- package/dist/shape-editor.js.map +1 -1
- package/dist/styles.css +1 -1
- package/package.json +1 -1
package/dist/shape-editor.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";require(`./styles.css`),Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require(`./Button-EEErevS-.cjs`),t=require(`./keyboard-DCewgvMV.cjs`);let n=require(`react/jsx-runtime`),r=require(`react`),i=require(`konva`);i=e.ha(i,1),require(`pixi.js/unsafe-eval`);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(e,t,n){return Math.max(t,Math.min(n,e))}function m(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`id_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}var h=[`tl`,`t`,`tr`,`r`,`br`,`b`,`bl`,`l`];function g(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 _(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 v(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 y(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 b(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 x(e){let t=g(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 S(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 C(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 w(e){let t=C(e);if(t.length<3)return x(e);let n=1/0,r=x(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 T=(e,t)=>({x:e.x-t.x,y:e.y-t.y}),E=(e,t)=>e.x*t.x+e.y*t.y,D=e=>Math.hypot(e.x,e.y),O=e=>{let t=D(e)||1;return{x:e.x/t,y:e.y/t}},k=(e,t)=>({x:(e.x+t.x)/2,y:(e.y+t.y)/2}),A=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 j(e){return[e[0],k(e[0],e[1]),e[1],k(e[1],e[2]),e[2],k(e[2],e[3]),e[3],k(e[3],e[0])]}function M(e,t){let n=k(e[0],e[1]),r=O(T(e[0],e[3]));return{x:n.x+r.x*t,y:n.y+r.y*t}}function N(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 ee(e,t,n){if(e.length<4)return e;let r=e[0],i=O(T(e[1],e[0])),a=O(T(e[3],e[0])),o=E(T(e[1],r),i),s=E(T(e[3],r),a),c=T(n,r);return N(v(t,{minX:0,minY:0,maxX:o,maxY:s},E(c,i),E(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}))}function F(e){let t=e.length,n=Array.from({length:t},(n,r)=>{let i=e[r],a=e[(r+1)%t];return{i:r,minX:Math.min(i.x,a.x),maxX:Math.max(i.x,a.x),minY:Math.min(i.y,a.y),maxY:Math.max(i.y,a.y)}}).sort((e,t)=>e.minX-t.minX),r=[];for(let i=0;i<t;i++){let a=n[i];for(let o=i+1;o<t&&n[o].minX<=a.maxX;o++){let i=n[o];if(i.minY>a.maxY||i.maxY<a.minY)continue;let s=Math.min(a.i,i.i),c=Math.max(a.i,i.i);if(c===s+1||s===0&&c===t-1)continue;let l=I(e[s],e[(s+1)%t],e[c],e[(c+1)%t]);l&&r.push({i:s,j:c,ti:l.ti,tj:l.tj})}}return r}function I(e,t,n,r){let i=t.x-e.x,a=t.y-e.y,o=r.x-n.x,s=r.y-n.y,c=i*s-a*o;if(!c)return null;let l=((n.x-e.x)*s-(n.y-e.y)*o)/c,u=((n.x-e.x)*a-(n.y-e.y)*i)/c,d=1e-9;return l<=d||l>=1-d||u<=d||u>=1-d?null:{ti:l,tj:u}}var L=(e,t)=>e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY,te=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x),ne=(e,t,n)=>te(e,t,n)===0&&Math.min(e.x,t.x)<=n.x&&n.x<=Math.max(e.x,t.x)&&Math.min(e.y,t.y)<=n.y&&n.y<=Math.max(e.y,t.y);function re(e,t,n,r){let i=te(n,r,e),a=te(n,r,t),o=te(e,t,n),s=te(e,t,r);return(i>0&&a<0||i<0&&a>0)&&(o>0&&s<0||o<0&&s>0)?!0:ne(n,r,e)||ne(n,r,t)||ne(e,t,n)||ne(e,t,r)}function ie(e,t,n){if(L(e,n)||L(t,n))return!0;let r={x:n.minX,y:n.minY},i={x:n.maxX,y:n.minY},a={x:n.maxX,y:n.maxY},o={x:n.minX,y:n.maxY};return re(e,t,r,i)||re(e,t,i,a)||re(e,t,a,o)||re(e,t,o,r)}function ae(e,t){let n=!1;for(let r=0,i=t.length-1;r<t.length;i=r++){let a=t[r],o=t[i];a.y>e.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(n=!n)}return n}function R(e,t,n){if(e.some(e=>L(e,t)))return!0;let r=n?e.length:e.length-1;for(let n=0;n<r;n+=1)if(ie(e[n],e[(n+1)%e.length],t))return!0;return!1}function z(e,t){let n=e.points;if(!n.length)return!1;let r=g(n);if(r.minX>t.maxX||r.maxX<t.minX||r.minY>t.maxY||r.maxY<t.minY)return!1;switch(e.type){case o.POINT:return L(n[0],t);case o.RECTANGLE:return!0;case o.ELLIPSE:{let e=(r.maxX-r.minX)/2,n=(r.maxY-r.minY)/2;if(e<=0||n<=0)return!0;let i=(r.minX+r.maxX)/2,a=(r.minY+r.maxY)/2,o=p(i,t.minX,t.maxX),s=p(a,t.minY,t.maxY);return((o-i)/e)**2+((s-a)/n)**2<=1}case o.LINE:return R(n,t,!1);case o.POLYGON:case o.ROTATED_RECTANGLE:return R(n,t,!0)||n.length>=3&&ae({x:t.minX,y:t.minY},n);default:return!0}}var B=e=>{let t=0;for(let n=0,r=e.length-1;n<e.length;r=n++)t+=(e[r].x-e[n].x)*(e[r].y+e[n].y);return t/2};function oe(e,t,n,r){let i=0,a=n.length;for(let o=0,s=a-1;o<a;s=o++){let a=n[s],c=n[o],l=(a.x-e.x)*t.y-(a.y-e.y)*t.x,u=(c.x-e.x)*t.y-(c.y-e.y)*t.x;if(l>0==u>0)continue;let d=(a.x-e.x)*t.x+(a.y-e.y)*t.y;d+((c.x-e.x)*t.x+(c.y-e.y)*t.y-d)*l/(l-u)>r&&(i+=l>0?-1:1)}return i}function se(e){let t=e[0],n=e[1],r=-(n.y-t.y),i=n.x-t.x;B(e)<0&&(r=-r,i=-i);let a=Math.hypot(r,i);return a?{x:r/a,y:i/a}:null}function V(e,t=4096){let n=[{outline:e,holes:[],layers:1}],r=e.length;if(r<4||r>t)return n;let i=F(e);if(!i.length)return n;let a=Array.from({length:r},()=>[]);for(let t of i){let n=e[t.i],i=e[(t.i+1)%r],o={x:n.x+(i.x-n.x)*t.ti,y:n.y+(i.y-n.y)*t.ti};a[t.i].push({t:t.ti,p:o}),a[t.j].push({t:t.tj,p:o})}let o=[];for(let t=0;t<r;t++){o.push(e[t]);for(let e of a[t].sort((e,t)=>e.t-t.t))o.push(e.p)}let s=new Map,c=[],l=e=>{let t=s.get(e);return t===void 0&&(t=c.length,s.set(e,t),c.push(e)),t},u=o.length,d=[],f=[];for(let e=0;e<u;e++){let t=l(o[e]),n=l(o[(e+1)%u]);t!==n&&(d.push(t,n),f.push(n,t))}let p=d.length;if(!p)return n;let m=Array.from({length:c.length},()=>[]);for(let e=0;e<p;e++)m[d[e]].push(e);for(let e of m)e.sort((e,t)=>Math.atan2(c[f[e]].y-c[d[e]].y,c[f[e]].x-c[d[e]].x)-Math.atan2(c[f[t]].y-c[d[t]].y,c[f[t]].x-c[d[t]].x));let h=e=>e%2==0?e+1:e-1,g=e=>{let t=m[f[e]];return t[(t.indexOf(h(e))-1+t.length)%t.length]},_=Array(p).fill(!1),v=[];for(let e=0;e<p;e++){if(_[e])continue;let t=[],n=e,r=0;do _[n]=!0,t.push(c[d[n]]),n=g(n);while(n!==e&&!_[n]&&r++<=p);t.length>=3&&v.push(t)}let y=v.map(B),b=Math.sign(y.reduce((e,t)=>Math.abs(t)>Math.abs(e)?t:e,0)),x=v.map((e,t)=>t).filter(e=>Math.sign(y[e])===-b),S=new Set;for(let e of a)for(let t of e)S.add(t.p);let C=e=>{let t=0,n=new Set;for(let r of e)S.has(r)&&!n.has(r)&&(n.add(r),t++);return t},w=[];for(let t of x){let n=se(v[t]);if(!n)continue;let r=v[t][0],i=v[t][1],a=1e-9*(Math.abs(r.x-i.x)+Math.abs(r.y-i.y)+1),o=Math.abs(oe(k(r,i),n,e,a));o%2==0&&C(v[t])===1||w.push({outline:v[t],holes:[],layers:Math.max(1,o)})}return w.length?w:n}var H={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:`마우스 가이드라인 표시`,regionMask:`ROI 표시`,keepZoomOnImageChange:`이미지 변경시 확대 유지`,wheelZoom:`스크롤만 사용하여 확대 축소`,zoomSensitivity:`확대 축소 민감도`},minimap:{zoomIn:`확대`,zoomOut:`축소`,zoom100:`100%로 초기화`,viewSettings:`보기 설정`,toggleMinimap:`미니맵 접기/펼치기`},canvasLabel:`이미지 편집 영역`,imageLoading:`이미지를 불러오는 중…`,imageMissing:`표시할 이미지가 없습니다`,imageLoadError:`이미지를 불러올 수 없습니다`,imageErrorHints:{"mixed-content":`HTTPS 페이지에서 HTTP 이미지 요청은 혼합 콘텐츠 정책에 따라 차단됩니다. 이미지 스토리지의 HTTPS 전환이 필요합니다.`,cors:`이미지 스토리지 응답에 Access-Control-Allow-Origin 헤더가 없습니다. 스토리지 또는 프록시의 CORS 설정이 필요합니다.`,auth:`이미지 서버가 세션 인증(쿠키)을 요구합니다. 에디터의 이미지 요청은 자격 증명 없이 전송되므로 스토리지 인증 방식 검토가 필요합니다.`,forbidden:`이미지 접근이 거부되었습니다. 서명 URL(presigned) 만료 또는 접근 권한 설정 점검이 필요합니다.`,"not-found":`요청한 이미지가 서버에 존재하지 않습니다. 파일 삭제·이동 여부 확인이 필요합니다.`,"server-error":`이미지 서버가 내부 오류를 반환했습니다. 스토리지 서버 상태 점검이 필요합니다.`,http:`이미지 서버가 오류 상태 코드를 반환했습니다.`,offline:`네트워크 연결이 감지되지 않습니다. 클라이언트 네트워크 상태 확인이 필요합니다.`,network:`이미지 서버에 도달할 수 없습니다. 네트워크 경로·방화벽·DNS 구성 점검이 필요합니다.`,"unexpected-content":`이미지 대신 다른 형식의 응답이 수신되었습니다. 게이트웨이의 인증 리다이렉트 여부 확인이 필요합니다.`,decode:`전송은 정상이나 이미지 디코딩에 실패했습니다. 파일 손상 또는 미지원 형식일 수 있습니다.`,"csp-img":`콘텐츠 보안 정책(CSP)의 img-src 지시어가 이미지 표시를 차단하고 있습니다. 정책에 이미지 스토리지 출처 추가가 필요합니다.`,"csp-eval":`콘텐츠 보안 정책(CSP)이 동적 스크립트 실행(unsafe-eval)을 차단하여 렌더러 초기화에 실패했습니다.`,webgl:`WebGL 컨텍스트를 생성할 수 없습니다. 하드웨어 가속 설정 또는 브라우저 보안 정책(Edge 보안 강화 모드 등) 점검이 필요합니다.`,"renderer-init":`캔버스 렌더러 초기화 또는 렌더링 중 오류가 발생했습니다.`,unknown:`원인이 특정되지 않은 오류입니다. 아래 상세 정보와 함께 기술 지원에 문의하시기 바랍니다.`}};function ce(e){return e?{contextMenu:{...H.contextMenu,...e.contextMenu},viewSettings:{...H.viewSettings,...e.viewSettings},minimap:{...H.minimap,...e.minimap},canvasLabel:e.canvasLabel??H.canvasLabel,imageLoading:e.imageLoading??H.imageLoading,imageMissing:e.imageMissing??H.imageMissing,imageLoadError:e.imageLoadError??H.imageLoadError,imageErrorHints:{...H.imageErrorHints,...e.imageErrorHints}}:H}var U={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`},le={brightness:1,contrast:1,showCursorGuide:!1,imageSmoothing:!0,strokeSize:2,simplifyStrength:1.5,showRegionMask:!0,keepZoomOnImageChange:!1,wheelZoom:!0,zoomSensitivity:1},ue={brightness:{min:.5,max:1.5,step:.05},contrast:{min:.5,max:1.5,step:.05},strokeSize:{min:1,max:10,step:.5},simplifyStrength:{min:.5,max:5,step:.5},zoomSensitivity:{min:.2,max:3,step:.1}},de=Object.keys(ue);function fe(e){let t={};for(let n of de){let r=e[n];if(r===void 0)continue;let{min:i,max:a}=ue[n],o=Number.isFinite(r)?Math.min(a,Math.max(i,r)):le[n];o!==r&&(t[n]=o)}return Object.keys(t).length?{...e,...t}:e}var pe=`var(--editor-overlay-inverse-scale, 1)`,me=`#377be2`,he=`#e23c3c`;function ge({point:e}){let t=e.positive?me:he;return(0,n.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(${pe})`,transformOrigin:`center`},children:e.positive?`+`:`−`})}function _e({image:e,points:t,boxes:r,status:i}){return(0,n.jsxs)(`div`,{style:{position:`absolute`,left:0,top:0,width:e.w,height:e.h,pointerEvents:`none`},children:[(0,n.jsx)(`style`,{children:`@keyframes editorv2-assistant-shimmer{from{background-position:200% 0}to{background-position:-200% 0}}`}),r.map((e,t)=>(0,n.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,n.jsx)(ge,{point:e},`pt-${t}-${e.x}-${e.y}`))]})}function ve(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 ye({x:e,y:r,items:i,onClose:a}){let o=ve(i);return(0,n.jsxs)(t.c,{open:!0,modal:!1,onOpenChange:e=>{e||a()},children:[(0,n.jsx)(t.c.Trigger,{asChild:!0,children:(0,n.jsx)(`span`,{"aria-hidden":!0,style:{position:`absolute`,left:e,top:r,width:0,height:0}})}),(0,n.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,r)=>`separator`in e?(0,n.jsx)(t.c.Separator,{className:`aivex:shrink-0`},`sep-${r}`):(0,n.jsx)(t.c.Item,{danger:e.danger,disabled:e.disabled,className:`aivex:shrink-0`,onSelect:()=>e.onClick(),children:(0,n.jsxs)(`span`,{className:`aivex:flex aivex:w-full aivex:items-center aivex:justify-between aivex:gap-6`,children:[(0,n.jsxs)(`span`,{className:`aivex:flex aivex:min-w-0 aivex:items-center aivex:gap-1.5`,children:[e.icon,(0,n.jsx)(`span`,{className:`aivex:truncate`,children:e.label})]}),e.shortcut&&(0,n.jsx)(t.c.Shortcut,{children:e.shortcut})]})},e.label))})]})}function be({color:e=`#1e88e5`}){let t=(0,r.useRef)(null),i=(0,r.useRef)(null),a=(0,r.useRef)(null);return(0,r.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,n.jsxs)(`div`,{ref:t,className:`aivex:pointer-events-none aivex:absolute aivex:inset-0 aivex:overflow-hidden`,children:[(0,n.jsx)(`div`,{ref:i,style:{position:`absolute`,top:0,left:0,width:1,height:`100%`,background:e,opacity:.6,display:`none`}}),(0,n.jsx)(`div`,{ref:a,style:{position:`absolute`,top:0,left:0,width:`100%`,height:1,background:e,opacity:.6,display:`none`}})]})}function xe({status:e,error:t,render:r,loadingLabel:i=H.imageLoading,missingLabel:a=H.imageMissing,errorLabel:o=H.imageLoadError,errorHints:s=H.imageErrorHints}){let c=r?.(e,t)??null;return(0,n.jsx)(`div`,{"data-track-id":e===`loading`?`editor-image-loading-wrap`:e===`missing`?`editor-image-missing-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:c===null?e===`missing`?(0,n.jsx)(`div`,{style:{fontSize:13,opacity:.75},children:a}):e===`loading`?(0,n.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10,fontSize:13},children:[(0,n.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`}}),i,(0,n.jsx)(`style`,{children:`@keyframes editorv2-image-spin{to{transform:rotate(360deg)}}`})]}):(0,n.jsxs)(`div`,{style:{textAlign:`center`,opacity:.85,maxWidth:420,padding:`0 16px`},children:[(0,n.jsx)(`div`,{style:{fontSize:28,marginBottom:6},children:`⚠`}),(0,n.jsx)(`div`,{style:{fontSize:13},children:o}),t&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(`div`,{style:{fontSize:12,marginTop:8,opacity:.8,lineHeight:1.5},children:s[t.kind]}),(0,n.jsx)(`div`,{style:{fontSize:11,marginTop:6,opacity:.55,fontFamily:`ui-monospace, monospace`,wordBreak:`break-all`},children:t.detail})]})]}):c})}Math.PI/12;var Se=`#00ff00`,Ce=`rgba(0, 255, 0, 0.1)`,we=`#669DEF`,W=.1,Te=[3,3];function Ee(e,t={}){let n=e.style?.color??`#00e5ff`,r=e.style?.strokeWidth??t.strokeWidth??2,i=e.style?.opacity??1,a=e.style?.fillOpacity??.12549019607843137,o=e.style?.dash??(e.style?.dashed?[r*Te[0],r*Te[1]]:void 0);return{color:n,strokeWidth:r,opacity:i,fillAlpha:a,fillVisible:!!e.style?.filled,dash:o,pointRadius:e.style?.pointRadius??t.pointRadius??5}}function De(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}var Oe=(0,r.memo)(function({shape:e,strokeSize:t,register:r}){let{type:i,points:a}=e,s=Ee(e,{strokeWidth:t}),c=t=>r?.(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,n.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=g(a);return i===o.ELLIPSE?(0,n.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,n.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,n.jsx)(`polyline`,{points:u,...l}):(0,n.jsx)(`polygon`,{points:u,fillRule:`evenodd`,...l})});function G({image:e,region:t,maskId:r,width:i,height:a,strokeWidth:o,strokeDasharray:s,style:c}){let l=[...t.visibleOutline,...t.occludedOutline];return(0,n.jsxs)(`svg`,{width:i,height:a,viewBox:`0 0 ${e.w} ${e.h}`,style:c,"aria-hidden":!0,children:[(0,n.jsx)(`defs`,{children:(0,n.jsxs)(`mask`,{id:r,children:[(0,n.jsx)(`rect`,{x:0,y:0,width:e.w,height:e.h,fill:`white`}),t.rects.map((e,t)=>(0,n.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,n.jsx)(`polygon`,{points:e.points.map(e=>`${e.x},${e.y}`).join(` `),fill:`white`},`occ-${t}`))]})}),(0,n.jsx)(`rect`,{x:0,y:0,width:e.w,height:e.h,fill:t.dim.color,fillOpacity:t.dim.opacity,mask:`url(#${r})`}),l.length>0&&(0,n.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 ke=[`brightness`,`contrast`,`strokeSize`,`simplifyStrength`,`zoomSensitivity`,`pixelation`,`cursorGuide`,`regionMask`,`keepZoomOnImageChange`,`wheelZoom`],Ae=new Set([`brightness`,`contrast`,`strokeSize`,`simplifyStrength`,`zoomSensitivity`]);function je({value:r,defaults:i,onChange:a,labels:o=H.viewSettings,items:s=ke,openDown:c=!1,alignEnd:l=!1}){return(0,n.jsxs)(t.s.Content,{"aria-label":o.title,side:c?`bottom`:`top`,align:l?`end`:`start`,sideOffset:8,className:`aivex:max-h-none aivex:overflow-visible aivex:shadow-[var(--aivex-elevation-md)]`,children:[(0,n.jsx)(`div`,{className:`aivex:px-xs aivex:text-body-md`,children:o.title}),(0,n.jsxs)(`div`,{className:`aivex:flex aivex:flex-col aivex:gap-md`,children:[s.filter(e=>Ae.has(e)).map(e=>{let i=Me[e];return(0,n.jsx)(Pe,{icon:i.icon,label:o[e],value:i.format(r[e]),children:(0,n.jsx)(t.i,{...ue[e],value:[r[e]],onValueChange:([t])=>a({[e]:t})})},e)}),(0,n.jsx)(`div`,{className:`aivex:flex aivex:flex-col aivex:gap-xs`,children:s.filter(e=>!Ae.has(e)).map(e=>{let t=Ne[e];return(0,n.jsx)(Fe,{checked:t.checked(r),label:o[e],onChange:e=>a(t.patch(e))},e)})}),(0,n.jsx)(t.a,{})]}),(0,n.jsx)(`div`,{className:`aivex:flex aivex:justify-end`,children:(0,n.jsxs)(e.t,{variant:`solid`,color:`secondary`,size:`md`,onClick:()=>a({...i}),children:[(0,n.jsx)(e.$r,{size:20}),o.reset]})})]})}function K(e){return`${Math.round(e*100)}%`}var Me={brightness:{icon:(0,n.jsx)(e.Q,{size:16}),format:K},contrast:{icon:(0,n.jsx)(e.Dt,{size:16}),format:K},strokeSize:{icon:(0,n.jsx)(e.Ai,{size:16}),format:String},simplifyStrength:{icon:(0,n.jsx)(e.Nr,{size:16}),format:String},zoomSensitivity:{icon:(0,n.jsx)(e.la,{size:16}),format:e=>e.toFixed(1)}},Ne={pixelation:{checked:e=>!e.imageSmoothing,patch:e=>({imageSmoothing:!e})},cursorGuide:{checked:e=>e.showCursorGuide,patch:e=>({showCursorGuide:e})},regionMask:{checked:e=>e.showRegionMask,patch:e=>({showRegionMask:e})},keepZoomOnImageChange:{checked:e=>e.keepZoomOnImageChange,patch:e=>({keepZoomOnImageChange:e})},wheelZoom:{checked:e=>e.wheelZoom,patch:e=>({wheelZoom:e})}};function Pe({icon:e,label:t,value:r,children:i}){return(0,n.jsxs)(`div`,{className:`aivex:flex aivex:flex-col aivex:px-md aivex:py-2xs`,children:[(0,n.jsxs)(`div`,{className:`aivex:flex aivex:items-center aivex:gap-xs`,children:[(0,n.jsx)(`span`,{className:`aivex:flex aivex:h-4 aivex:items-center aivex:text-text-secondary`,children:e}),(0,n.jsx)(`span`,{className:`aivex:flex-1 aivex:truncate aivex:text-label-md`,children:t}),(0,n.jsx)(`span`,{className:`aivex:tabular-nums aivex:text-label-md aivex:text-text-secondary`,children:r})]}),(0,n.jsx)(`div`,{className:`aivex:flex aivex:h-5 aivex:items-center`,children:i})]})}function Fe({label:e,checked:r,onChange:i}){return(0,n.jsxs)(`div`,{className:`aivex:flex aivex:items-center aivex:gap-md aivex:rounded-md aivex:px-md aivex:py-sm`,children:[(0,n.jsx)(`span`,{className:`aivex:flex-1 aivex:truncate aivex:text-label-lg`,children:e}),(0,n.jsx)(t.r,{size:`md`,checked:r,onCheckedChange:i})]})}var Ie={"bottom-left":`aivex:bottom-2 aivex:left-2`,"bottom-right":`aivex:bottom-2 aivex:right-2`,"top-left":`aivex:top-2 aivex:left-2`,"top-right":`aivex:top-2 aivex:right-2`},Le=(0,r.memo)(function({image:r,imageUrl:i,imageVisible:a=!0,loading:o=!1,region:c,roiMaskId:l,shapes:u,view:d,viewDefaults:p,onChangeView:m,nav:h,registerShape:g,rectRef:_,zoomLabelRef:v,onZoom100:y,open:b,onToggleOpen:x,position:S=`bottom-left`,showSettings:C=!0,settingsOpen:w,onToggleSettings:T,onCloseSettings:E,labels:D=H.minimap,settingsLabels:O,settingsItems:k}){let{offX:A,offY:j,dispW:M,dispH:N,zoomCentered:ee}=h,P=S.startsWith(`top`),F={position:`absolute`,left:A,top:j,width:M,height:N},I=(0,n.jsx)(`div`,{className:`aivex:overflow-hidden aivex:rounded-sm aivex:transition-all aivex:duration-200 aivex:ease-in-out ${b?`${P?`aivex:mt-md`:`aivex:mb-md`} aivex:opacity-100`:`aivex:opacity-0`}`,style:{maxHeight:b?204:0},children:(0,n.jsx)(`div`,{style:{width:204,height:204},className:`aivex:relative aivex:touch-none aivex:overflow-hidden aivex:rounded-sm aivex:bg-static-gray ${o?`aivex:cursor-default`:`aivex:cursor-grab aivex:active:cursor-grabbing`}`,onPointerDown:o?void 0:h.handleMinimapPointerDown,onPointerMove:o?void 0:h.handleMinimapPointerMove,onPointerUp:o?void 0:h.endMinimapDrag,onPointerCancel:o?void 0:h.endMinimapDrag,onWheel:o?void 0:h.handleMinimapWheel,"aria-busy":o,children:(0,n.jsxs)(`div`,{style:{position:`absolute`,inset:0,opacity:+!!a,transition:a?`opacity 0.3s ease`:`none`},children:[i&&(0,n.jsx)(`img`,{src:i,alt:``,crossOrigin:`anonymous`,draggable:!1,style:F}),d.showRegionMask&&c&&c.rects.length>0&&(0,n.jsx)(G,{image:r,region:c,maskId:l,width:M,height:N,strokeWidth:1,strokeDasharray:`4 4`,style:{position:`absolute`,left:A,top:j,pointerEvents:`none`}}),(0,n.jsx)(`svg`,{viewBox:`0 0 ${r.w} ${r.h}`,width:M,height:N,style:{position:`absolute`,left:A,top:j,pointerEvents:`none`},"aria-hidden":!0,children:f(u).filter(s).map(e=>(0,n.jsx)(Oe,{shape:e,strokeSize:d.strokeSize,register:g},e.id))}),(0,n.jsx)(`div`,{ref:_,style:{position:`absolute`,border:`1px solid ${Se}`,background:Ce,boxSizing:`border-box`,pointerEvents:`none`}})]})})}),L=(0,n.jsxs)(`div`,{className:`aivex:relative aivex:flex aivex:items-center aivex:gap-xs`,children:[(0,n.jsx)(e.t,{variant:`ghost`,size:`icon-md`,"aria-label":D.zoomOut,onClick:()=>ee(1/1.2),disabled:o,children:(0,n.jsx)(e.pr,{size:20})}),(0,n.jsx)(e.t,{variant:`ghost`,size:`md`,"aria-label":D.zoom100,onClick:y,disabled:o,className:`aivex:w-[60px] aivex:tabular-nums`,children:(0,n.jsx)(`span`,{ref:v,children:`100%`})}),(0,n.jsx)(e.t,{variant:`ghost`,size:`icon-md`,"aria-label":D.zoomIn,onClick:()=>ee(1.2),disabled:o,children:(0,n.jsx)(e.Wr,{size:20})}),C&&(0,n.jsxs)(t.s,{open:w,onOpenChange:e=>e?T():E(),children:[(0,n.jsx)(t.s.Trigger,{asChild:!0,children:(0,n.jsx)(e.t,{variant:`ghost`,size:`icon-md`,"aria-label":D.viewSettings,className:w?`aivex:text-text-brand`:void 0,children:(0,n.jsx)(e.pi,{size:20})})}),(0,n.jsx)(je,{value:d,defaults:p,onChange:m,labels:O,items:k,openDown:P,alignEnd:S.endsWith(`right`)})]}),(0,n.jsx)(e.t,{variant:`ghost`,size:`icon-md`,"aria-label":D.toggleMinimap,title:`(M)`,onClick:x,children:b?(0,n.jsx)(e.nt,{size:20,className:P?`aivex:rotate-180`:void 0}):(0,n.jsx)(e.ar,{size:20})})]});return(0,n.jsxs)(`div`,{className:`aivex:absolute ${Ie[S]} aivex:w-[220px] aivex:rounded-[12px] aivex:border aivex:border-border-subtle aivex:bg-bg-primary aivex:p-md aivex:shadow-[0_4px_12px_rgba(13,13,18,0.24)]`,children:[P?L:I,P?I:L]})}),Re=`var(--editor-overlay-inverse-scale, 1)`,ze=6,Be={fontFamily:`Pretendard, sans-serif`,fontSize:12,fontWeight:500,lineHeight:`16px`,color:`#fff`,textShadow:`0 0 4px #000, 0 0 4px #000`,whiteSpace:`nowrap`};function Ve(e){let t=g(e);return{x:t.minX,y:t.minY,width:t.maxX-t.minX,height:t.maxY-t.minY}}function He(e){return`translate3d(${e.width}px, ${e.height}px, 0) scale(${Re}) translate(-100%, ${ze}px)`}function Ue(e,t){let n=Ve(t);e.style.transform=`translate3d(${n.x}px, ${n.y}px, 0)`;let r=e.querySelector(`[data-selinfo-dim]`);return r&&(r.style.transform=He(n)),r}function We(e,t){return{shape:e,...Ve(t)}}function Ge(e){return`${Math.round(e.width)} x ${Math.round(e.height)} px`}function Ke({color:e,striped:t}){return(0,n.jsx)(`span`,{style:{display:`inline-block`,width:12,height:12,borderRadius:`50%`,...t?{border:`2px dashed ${e}`,background:`transparent`}:{background:e}}})}function qe({shapes:e,getLabel:t,hideDot:r,formatInfo:i,register:a}){return(0,n.jsx)(n.Fragment,{children:e.map(e=>{let s=Ve(e.points),c=e.type===o.POINT,l=c?void 0:t?.(e),u=e.style?.color??`#00e5ff`,d=!!e.style?.dashed||!!e.style?.dash,f=We(e,e.points),p=i?i(f):Ge(f);return(0,n.jsxs)(`div`,{ref:t=>a(e.id,t),style:{position:`absolute`,left:0,top:0,transform:`translate3d(${s.x}px, ${s.y}px, 0)`,willChange:`transform`,pointerEvents:`none`},children:[!!l&&(0,n.jsxs)(`div`,{style:{position:`absolute`,left:0,top:0,display:`flex`,alignItems:`center`,gap:4,transform:`scale(${Re}) translateY(calc(-100% - ${ze}px))`,transformOrigin:`left top`,...Be},children:[!r&&(0,n.jsx)(Ke,{color:u,striped:d}),(0,n.jsx)(`span`,{children:l})]}),!c&&!!p&&(0,n.jsx)(`div`,{"data-selinfo-dim":!0,style:{position:`absolute`,left:0,top:0,transform:He(s),transformOrigin:`left top`,willChange:`transform`,...Be},children:p})]},e.id)})})}var Je=`AIVEX_SHAPE_EDITOR:`,Ye=1,Xe=new Set(Object.values(o)),Ze=null,Qe=`unavailable`,$e=0;function et(e){if(!e||typeof e!=`object`)return!1;let t=e;return Number.isFinite(t.x)&&Number.isFinite(t.y)}function tt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.type==`string`&&Xe.has(t.type)&&Array.isArray(t.points)&&t.points.length>0&&t.points.every(et)}function nt(e,t,n){return{kind:`aivex-shape-editor`,version:Ye,scope:n,documentId:t,shapes:e}}function rt(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a:${(t>>>0).toString(36)}`}function it(e){return`${Je}${JSON.stringify(e)}`}function at(e){if(!e.startsWith(Je))return null;try{let t=JSON.parse(e.slice(19));return t.kind!==`aivex-shape-editor`||t.version!==Ye||!Array.isArray(t.shapes)||t.shapes.length===0||!t.shapes.every(tt)||t.scope!==void 0&&typeof t.scope!=`string`||t.documentId!==void 0&&typeof t.documentId!=`string`?null:t}catch{return null}}function q(e){Ze=e;let t=++$e;if(typeof navigator>`u`||!navigator.clipboard?.writeText){Qe=`unavailable`;return}let n;try{n=it(e)}catch{Qe=`unavailable`;return}Qe=`pending`,navigator.clipboard.writeText(n).then(()=>{t===$e&&(Qe=`written`)},()=>{t===$e&&(Qe=`unavailable`)})}function ot(e,t){return!!e&&e.scope===t}function st(e){return ot(Ze,e)||typeof navigator<`u`&&typeof navigator.clipboard?.readText==`function`}async function J(e){let t=ot(Ze,e)?Ze:null;if(t&&Qe!==`written`)return t;if(typeof navigator<`u`&&navigator.clipboard?.readText)try{let t=at(await navigator.clipboard.readText());return t?.scope===e?(Ze=t,t):null}catch{}return t}function ct(e,t,n){return{offset:n*(t?e:e+1),nextPasteCount:e+1}}var lt=new Set([U.RECTANGLE,U.ROTATED_RECTANGLE,U.CIRCLE,U.POLYGON,U.PATH,U.BRUSH,U.POINT,U.ASSISTANT_POLYGON,U.ASSISTANT_RECT,U.ASSISTANT_POINT]),ut={tl:-135,t:-90,tr:-45,r:0,br:45,b:90,bl:135,l:180},dt=[`ew-resize`,`nwse-resize`,`ns-resize`,`nesw-resize`],ft=`grab-unselected`,pt=new Set([U.RECTANGLE,U.ROTATED_RECTANGLE,U.CIRCLE]);function Y(e,t=0){let n=((ut[e]+t*180/Math.PI)%180+180)%180;return dt[Math.round(n/45)%4]}function mt({tool:e,externalToolCursor:t,isSpacePressed:n,isPolygonDrawing:r}){return n?`grab`:t||(e===U.SELECT?`default`:lt.has(e)?r?`default`:`crosshair`:`default`)}function ht({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===U.SELECT&&i?i===`grab-unselected`?`grab`:i:pt.has(e)&&i&&i!==`grab-unselected`?i:mt({tool:e,externalToolCursor:t,isSpacePressed:n,isPolygonDrawing:a}))}function gt(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 X=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 _t(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 vt(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 yt(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(...vt(s,c,e));if(n)for(let e of n)l.push(...vt(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=_t(m,o)?m:h,_=g===m?h:m;t.some(e=>e!==o&&_t(_,e))||n&&!n.some(e=>_t(g,e))||i.push([a(s,c,r),a(s,c,u)])}}return i}function bt(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 xt(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)gt(e,n.points),e.fill()}e.restore()}function St(e){let t=getComputedStyle(e);return{color:t.getPropertyValue(`--aivex-static-black`).trim()||`#17171c`,opacity:Number.parseFloat(t.getPropertyValue(`--aivex-opacity-dim`))||.32}}function Ct(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 wt={color:`#000000`,opacity:.5},Tt={color:`#ffffff`,opacity:1,width:2,dash:[6,6],underlayColor:`#000000`},Et={color:`#dc2626`,opacity:.8,width:2,dash:[6,6],underlayColor:`#000000`},Dt=(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=bt(a),s={...wt,...e.dim},c=e.outline;if(c===!1)return{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:[],occludedOutline:[],outlineStyles:null};let l={visible:{...Tt,...c?.visibleStyle},occluded:{...Et,...c?.occludedStyle}},u=i.map(X),d=a.map(X),f=r.map(e=>e.points);return c?.mode===`separate`?{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:Ct(u),occludedOutline:Ct(f),outlineStyles:l}:{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:[...yt(u,[...u,...f],null),...yt(f,f,d)],occludedOutline:[],outlineStyles:l}},Ot=.3,kt=.05;function At(e){return 1-(1-e)**3}function jt(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 Z(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=g(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 Mt(e){if(!e.length)return null;let t=e.map(e=>Z(e.type,e.points)).filter(e=>e!==null);return t.length?jt(g(t.flatMap(e=>[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y+e.height}]))):null}function Nt(e,t,n,r={}){let{containerRatio:i=Ot,minScale:a=kt,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 Pt(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(kt,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 Ft(e,t,n,r=300){let i=Date.now(),a=0,o=()=>{let s=Date.now()-i,c=Math.min(s/r,1),l=At(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 It(e){let{engineRef:t,toolRef:n,externalToolMapRef:r,spaceRef:i,docRef:a,selRef:s,draftRef:c,readOnlyRef:u,disableMarqueeRef:p,lockedRef:m,onLockedInteraction:h,onDrawAttemptWithoutDraft:_,createRef:v,selectRef:b,enterEditRef:C,editingIdRef:w,drawSessionRef:T,assistantRef:E,setCursorHint:D,setInteractionMode:O,syncMinimap:k,onTransformPreview:A,onDrawPreview:j}=e,M=()=>T.current,N=()=>E.current,ee=null,P=null,F=null,I=null,L=null,te=null,ne=!1,re=``,ie=null,ae=null,R=null,z=e=>e===U.RECTANGLE||e===U.ROTATED_RECTANGLE||e===U.CIRCLE,B=e=>e===U.ASSISTANT_POLYGON||e===U.ASSISTANT_RECT,oe=e=>e===U.POLYGON,se=e=>z(e)||B(e)||oe(e)||e===U.PATH||e===U.BRUSH||e===U.POINT,V=(e,t)=>{let n=!1;P&&!z(t)&&!B(t)&&(P=null,e.clearPreview(),j(null),n=!0),(F===`path`&&t!==U.PATH||F===`scalar`&&t!==U.BRUSH)&&(F=null,n=!0),I&&!oe(t)&&(I=null,n=!0),L&&t!==U.SELECT&&(L=null,te=null,ne=!1,e.clearMarquee(),n=!0),ie&&t!==U.POINT&&(ie=null,n=!0),n&&O(`idle`)},H=()=>r.current.get(n.current),ce=(e,t,n,r)=>({point:t,targetId:r,event:n,readOnly:u.current,viewport:e.viewport});return{onCursorHint:D,onInteractionModeChange:O,onPointerDown:(e,r,p)=>{let v=t.current;if(!v)return;let y=n.current;if(ie=null,ae=null,V(v,y),p.button===1||i.current){O(`panning`),D(null),ee={px:p.global.x,py:p.global.y};return}if(p.button===2&&!(y===U.ASSISTANT_POINT&&p.altKey)){if(r&&!s.current.includes(r)){let e=a.current.getShapes().find(e=>e.id===r);e&&l(e)&&b.current([r])}return}let x=H();if(x){M().reset(),b.current([]),x.onPointerDown?.(ce(v,e,p,r));return}if(m.current&&y!==U.SELECT){h();return}if(z(y)&&r&&s.current.includes(r)&&!u.current){let t=a.current.getShapes().find(e=>e.id===r);if(t&&d(t)){v.beginMove(e,s.current);return}}if(se(y)&&!c.current){_();return}if(y===U.ASSISTANT_POINT){p.altKey?N().addPoint(e,p.button!==2):N().newPolygon(e);return}if(B(y)&&c.current){P=e,O(`drawing`);return}if(y===U.SELECT&&w.current){te=p.shiftKey?v.getVertexSelection():[],ne=r===w.current,L=e,re=``,O(`marquee`),D(null);return}if(y===U.SELECT&&p.altKey){let t=f(a.current.getShapes()).filter(t=>{if(!l(t))return!1;let n=g(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=>s.current.includes(e.id))+1)%e.length].id];b.current(n);return}}if(r&&y===U.SELECT){let t=a.current.getShapes().find(e=>e.id===r);if(!t||!l(t))return;let n=typeof performance<`u`?performance.now():0,i=!!R&&R.id===r&&n-R.t<300;R={id:r,t:n};let c=(t.type===o.POLYGON||t.type===o.LINE)&&t.interaction?.editable!==!1&&!t.readOnly;if(i&&c&&m.current){b.current([r]),h();return}if(i&&c&&!u.current){b.current([r]),C.current(r);return}let f=s.current;if(p.shiftKey){let e=new Set(f);e.has(r)?e.delete(r):e.add(r),f=[...e]}else f.includes(r)||(f=[r]);b.current(f),d(t)&&(m.current?ae=p.global:u.current||v.beginMove(e,f));return}if(z(y)&&c.current){P=e,O(`drawing`);return}if(oe(y)&&c.current){if(!M().getDraftPointsSnapshot().length&&s.current.length&&b.current([]),M().tryClosePolygon(e,12/v.viewport.scale))return;let t=M().hitDraftPoint(e);if(t>=0){if(p.altKey){M().removeDraftPoint(t);return}let n=M().selectDraftPointForDrag(t,p.shiftKey||p.ctrlKey||p.metaKey);if(!n)return;I={start:e,base:n.base,indices:n.indices,moved:!1},O(`vertexDragging`);return}M().appendPolygonPoint(e);return}if(y===U.PATH&&c.current){s.current.length&&b.current([]),F=`path`,O(`drawing`),M().beginStroke(e);return}if(y===U.BRUSH&&c.current&&!u.current){F=`scalar`,O(`drawing`),M().beginStroke(e);return}if(y===U.POINT&&c.current&&p.button===0){ie={pointerId:p.pointerId,global:p.global,cancelled:!1};return}if(y===U.SELECT){te=null,ne=!1;let t=!u.current||m.current;if(!p.shiftKey&&t&&s.current.length>=2){let t=a.current.getShapes().filter(e=>s.current.includes(e.id)&&d(e));if(t.length){let n=g(t.flatMap(e=>e.points));if(e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY){m.current?ae=p.global:v.beginMove(e,s.current);return}}}L=e,re=``,O(`marquee`),D(null)}},onPointerMove:(e,r)=>{let i=t.current;if(!i)return;if(ie&&ie.pointerId===r.pointerId&&Math.hypot(r.global.x-ie.global.x,r.global.y-ie.global.y)>4&&(ie.cancelled=!0),ae&&Math.hypot(r.global.x-ae.x,r.global.y-ae.y)>4){ae=null,h();return}if(ee){i.applyViewport({scale:i.viewport.scale,x:i.viewport.x+(r.global.x-ee.px),y:i.viewport.y+(r.global.y-ee.py)}),ee.px=r.global.x,ee.py=r.global.y;return}let s=n.current;V(i,s);let l=H();if(l){l.onPointerMove?.(ce(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,M().moveDraftPoints(I.base,I.indices,t,n);return}if(P&&(z(s)||B(s))){let t=r.shiftKey?y(P,e):e;i.previewBox(s===U.CIRCLE?`ellipse`:`rect`,P,t,{...c.current,color:c.current?.color??`#00e5ff`}),z(s)&&j({type:s===U.CIRCLE?o.ELLIPSE:o.RECTANGLE,points:[P,t]});return}if(F){M().appendStrokePoint(e,2/i.viewport.scale);return}if(oe(s)&&M().hasDraftPoints()){M().setDraftCursor(e);return}if(L){if(p?.current)return;let t={minX:Math.min(L.x,e.x),minY:Math.min(L.y,e.y),maxX:Math.max(L.x,e.x),maxY:Math.max(L.y,e.y)};if(i.previewMarquee(L,e),te){let e=(a.current.getShapes().find(e=>e.id===w.current)?.points??[]).flatMap((e,n)=>e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY?[n]:[]),n=[...new Set([...te,...e])].sort((e,t)=>e-t),r=n.join(`,`);r!==re&&(re=r,i.setVertexSelection(n));return}let n=i.shapesIntersecting(t),r=n.join(`,`);r!==re&&(re=r,b.current(n))}},onPointerUp:(e,r)=>{let i=t.current;if(!i)return;let a=ie;if(ie=null,ae=null,ee){ee=null,O(`idle`);return}let l=n.current;if(V(i,l),I){M().commitDraftPointDrag(I.moved),I=null,O(`idle`);return}let u=H();if(u){u.onPointerUp?.(ce(i,e,r));return}let d=a?Math.hypot(r.global.x-a.global.x,r.global.y-a.global.y):1/0;if(l===U.POINT&&c.current&&a&&!a.cancelled&&a.pointerId===r.pointerId&&r.insideCanvas&&d<=4){v.current(o.POINT,[e]);return}if(F){let e=F;F=null,O(`idle`),e===`path`?M().completeFreehandStroke():M().finishScalarStroke();return}if(P&&B(l)){let t=P;P=null,O(`idle`),i.clearPreview();let n=r.shiftKey?y(t,e):e,a={x:Math.min(t.x,n.x),y:Math.min(t.y,n.y),width:Math.abs(n.x-t.x),height:Math.abs(n.y-t.y)};a.width>2&&a.height>2&&N().beginBox(a,l===U.ASSISTANT_RECT?`rect`:`polygon`);return}if(P&&z(l)){let t=r.shiftKey?y(P,e):e,n=P;P=null,O(`idle`),i.clearPreview(),j(null),Math.abs(t.x-n.x)>2&&Math.abs(t.y-n.y)>2&&(l===U.ROTATED_RECTANGLE?v.current(o.ROTATED_RECTANGLE,x([n,t])):l===U.CIRCLE?v.current(o.POLYGON,S(n,t)):v.current(o.RECTANGLE,[n,t]));return}if(L){let t=Math.abs(e.x-L.x)>3||Math.abs(e.y-L.y)>3,n=te!==null,r=ne;if(L=null,te=null,ne=!1,i.clearMarquee(),O(`idle`),n&&t)return;if(n&&r){i.setVertexSelection([]);return}!t&&s.current.length&&b.current([])}},onViewportChange:k,onTransformPreview:A,onTransformCommit:e=>{let t=a.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&&a.current.update(n)}}}function Lt({docRef:e,draftRef:t,draftMeta:n,changeSelection:i,assistantRef:a}){let[s,c]=(0,r.useState)(`idle`),[l,u]=(0,r.useState)([]),[d,f]=(0,r.useState)([]),p=(0,r.useRef)([]),h=(0,r.useRef)([]),_=(0,r.useRef)([]),v=(0,r.useRef)(`idle`),y=(0,r.useRef)(0),b=(0,r.useRef)(null),x=(0,r.useRef)(null),S=(0,r.useRef)(0),C=(0,r.useCallback)(e=>{p.current=e(p.current),f(p.current)},[]),T=(0,r.useCallback)(e=>{v.current=e,c(e)},[]),E=(0,r.useCallback)((e,t,r)=>{let i=a.current?.rectResult===`rotatedRect`;return e.map(e=>{if(t===`rect`&&i)return{id:m(),type:o.ROTATED_RECTANGLE,points:w(e),style:r,meta:n};if(t===`rect`){let t=g(e);return{id:m(),type:o.RECTANGLE,points:[{x:t.minX,y:t.minY},{x:t.maxX,y:t.maxY}],style:r,meta:n}}return{id:m(),type:o.POLYGON,points:e,style:r,meta:n}})},[n,a]),D=(0,r.useCallback)(()=>{y.current++,h.current=[],_.current=[],b.current=null,x.current=null,u([]),T(`idle`)},[T]),O=(0,r.useCallback)(()=>{S.current++,C(()=>[]);let t=x.current;t?e.current.update([t]):_.current.length&&e.current.remove(_.current),D()},[e,D,C]),k=(0,r.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,r.useCallback)(async()=>{let e=a.current?.infer;if(!e)return;let t={kind:`points`,points:h.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,r.useCallback)((e,t)=>{h.current=[...h.current,{x:e.x,y:e.y,positive:t}],u([{x:e.x,y:e.y,positive:t}]),A()},[A]),M=(0,r.useCallback)(e=>{D();let t=[{x:e.x,y:e.y,positive:!0}];h.current=t,u(t),A()},[D,A]),N=(0,r.useCallback)((e,t,n)=>{(_.current.length!==1||_.current[0]!==e.id)&&(D(),_.current=[e.id],b.current=e.points,x.current=e),h.current=[...h.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,r.useCallback)((n,r=`polygon`)=>{let o=a.current?.infer,s=t.current;if(!o||!s)return;let c=S.current;C(e=>[...e,n]),(async()=>{let t=[];try{t=(await o({kind:`box`,box:n})??[]).filter(e=>e.length>=3)}catch{t=[]}if(C(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,C]),addPoint:j,newPolygon:M,refineShape:N,finalize:D,cancel:O,isActive:(0,r.useCallback)(()=>v.current===`loading`||h.current.length>0||p.current.length>0||_.current.length>0,[])}}function Rt(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 zt(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=Rt(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 Bt=4096,Vt=4;function Ht(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 Ut(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 Wt(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 Gt(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 Kt(e,t,n){let r=Ut(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=Jt(Wt(Gt(r,t,n,e,a)),t,n);o.length>=3&&i.push(o)}return i}function qt(e,t,n,r,i){return r<0||i<0||r>=t||i>=n?!1:e[(i*t+r)*4+3]>128}function Jt(e,t,n){let r=-1,i=-1;outer:for(let a=0;a<n;a++)for(let o=0;o<t;o++)if(qt(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(qt(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 Yt(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 Xt(e){switch(e.type){case o.RECTANGLE:return e.points.length<2?null:x(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?S({x:t.x-6,y:t.y-6},{x:t.x+6,y:t.y+6}):null}default:return null}}function Zt(e){return e.map(Xt).filter(e=>!!e&&e.length>=3)}function Qt(e,t,n=[]){if(t<=0||!e.length&&!n.length)return null;let r=Yt(e,n);if(!r.length)return null;let i=t+4,a=g(r),o=Math.ceil(a.maxX-a.minX+i*2),s=Math.ceil(a.maxY-a.minY+i*2),c=Math.min(1,Bt/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 $t(e,t=1.5){let{canvas:n,ox:r,oy:i,scale:a}=e,o=Kt(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=zt(n,t),i=r.length>=3?r:n;i.length>=3&&Ht(i)>=Vt&&c.push(i)}return c}function en(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 tn(e){return e.map(e=>({mode:e.mode,points:e.points.map(e=>({...e}))}))}function nn(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 rn(e){return e.map(e=>({...e}))}function an(e,t){return e.length===t.length&&e.every((e,n)=>e.x===t[n].x&&e.y===t[n].y)}var on=10;function sn(e,t){if(e.active!==t.active||e.kind!==t.kind||e.canUndo!==t.canUndo||e.canRedo!==t.canRedo)return!1;let n=e.brush,r=t.brush;return!n||!r?n===r:n.mode===r.mode&&n.editing===r.editing&&n.editTargetIds.length===r.editTargetIds.length&&n.editTargetIds.every((e,t)=>e===r.editTargetIds[t])}function cn({toolRef:e,selRef:t,docRef:n,readOnlyRef:i,draftRef:a,brushSizeRef:s,simplifyEpsilonRef:c,draftMeta:l,engineRef:d,onDrawSessionChange:f,onDraftShapeChange:p,changeSelection:h,createShape:g}){let _=(0,r.useRef)(f);_.current=f;let v=(0,r.useRef)(p);v.current=p;let y=(0,r.useRef)(l);y.current=l;let b=(0,r.useRef)(g);b.current=g;let x=(0,r.useRef)(null),S=(0,r.useRef)([]),C=(0,r.useRef)(null),w=(0,r.useRef)(new Set),T=(0,r.useRef)([[]]),E=(0,r.useRef)(0),D=(0,r.useRef)(null),O=(0,r.useRef)([]),k=(0,r.useRef)([]),A=(0,r.useRef)([]),j=(0,r.useRef)([[]]),M=(0,r.useRef)(0),N=(0,r.useRef)(`draw`),ee=()=>N.current===`erase`?`erase`:`add`,P=()=>A.current.length>0||O.current.length>0||e.current===U.BRUSH&&S.current.length>0,F=()=>{let t=e.current;return t===U.BRUSH&&P()?`brush`:t===U.POLYGON&&S.current.length>0?`polygon`:t===U.PATH&&S.current.length>0?`path`:`none`},I=()=>S.current.length>0||M.current>0,L=()=>S.current.length===0&&M.current<j.current.length-1,te=()=>E.current>0,ne=()=>E.current<T.current.length-1,re=()=>{let t=e.current;return t===U.BRUSH?I():t===U.POLYGON||t===U.PATH?te():!1},ie=()=>{let t=e.current;return t===U.BRUSH?L():t===U.POLYGON||t===U.PATH?ne():!1},ae=()=>F()!==`none`,R=(0,r.useCallback)(()=>{let e=F(),t={active:e!==`none`,kind:e,canUndo:re(),canRedo:ie(),brush:e===`brush`?{mode:N.current,editing:A.current.length>0,editTargetIds:[...A.current]}:void 0},n=x.current;n&&sn(n,t)||(x.current=t,_.current?.(t))},[]),z=(0,r.useCallback)(()=>{j.current=[[]],M.current=0},[]),B=(0,r.useCallback)(()=>{let t=d.current;if(!t)return;let n=e.current;if(n===U.BRUSH){let e=[...O.current];if(S.current.length&&e.push({points:S.current,mode:ee()}),!e.length&&!k.current.length){t.clearPreview();return}let n=Qt(e,s.current,k.current);if(!n){t.clearPreview();return}let r=a.current?.color??`#00e5ff`;t.previewScalarMask(n,r);return}let r=S.current;if(!r.length){t.clearPreview(),D.current&&(D.current=null,v.current?.(null));return}let i={...a.current,color:a.current?.color??`#00e5ff`},c=Array.from(w.current),l=n!==U.PATH;if(t.previewPoly(r,C.current,i,!1,c,l),n===U.POLYGON||n===U.PATH){let e=v.current;e&&r!==D.current&&(D.current=r,e({type:o.POLYGON,points:rn(r),meta:y.current}))}},[s,a,d,e]),oe=(0,r.useCallback)(e=>{let t=tn(e),n=j.current,r=M.current,i=n[r];i&&nn(i,t)||(j.current=[...n.slice(0,r+1),t],M.current+=1,R())},[R]),se=(0,r.useCallback)(e=>{let t=T.current,n=E.current,r=t[n];r&&an(r,e)||(T.current=[...t.slice(0,n+1),rn(e)],E.current+=1)},[]),V=(0,r.useCallback)(()=>{S.current=[],O.current=[],k.current=[],A.current=[],C.current=null,w.current=new Set,T.current=[[]],E.current=0,D.current=null,z(),d.current?.clearPreview(),v.current?.(null),R()},[d,R,z]),H=(0,r.useCallback)((e,t)=>{S.current=e,w.current=new Set(Array.from(w.current).filter(t=>t>=0&&t<e.length)),t&&se(e),B(),R()},[R,se,B]),ce=(0,r.useCallback)(()=>rn(S.current),[]),le=(0,r.useCallback)(()=>S.current.length>0,[]),ue=(0,r.useCallback)((t,n)=>{if(e.current!==U.POLYGON)return!1;let r=S.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),V(),!0)},[V,e]),de=(0,r.useCallback)(e=>{let t=S.current;return e<0||e>=t.length?!1:(H(t.filter((t,n)=>n!==e),!0),!0)},[H]),fe=(0,r.useCallback)((e,t)=>{let n=S.current;if(e<0||e>=n.length)return null;let r=new Set(w.current);return t?r.has(e)?r.delete(e):r.add(e):r.has(e)||(r.clear(),r.add(e)),w.current=r,C.current=null,B(),R(),{base:rn(n),indices:Array.from(r)}},[R,B]),pe=(0,r.useCallback)(e=>{w.current=new Set,C.current=e,H([...S.current,e],!0)},[H]),me=(0,r.useCallback)(e=>{C.current=null,w.current=new Set,S.current=[{...e}],B(),R()},[R,B]),he=(0,r.useCallback)((e,t)=>{let n=S.current[S.current.length-1];return n&&Math.hypot(e.x-n.x,e.y-n.y)<t?!1:(S.current=[...S.current,{...e}],C.current=null,B(),R(),!0)},[R,B]),ge=(0,r.useCallback)((e,t,n,r)=>{let i=new Set(t);S.current=e.map((e,t)=>i.has(t)?{x:e.x+n,y:e.y+r}:{...e}),C.current=null,B(),R()},[R,B]),_e=(0,r.useCallback)(e=>{e&&(se(S.current),B(),R())},[R,se,B]),ve=(0,r.useCallback)(e=>{C.current=e?{...e}:null,B()},[B]),ye=(0,r.useCallback)(()=>S.current.length>0?(S.current=[],B(),R(),!0):M.current<=0?!1:(--M.current,O.current=tn(j.current[M.current]),B(),R(),!0),[R,B]),be=(0,r.useCallback)(()=>S.current.length>0||M.current>=j.current.length-1?!1:(M.current+=1,O.current=tn(j.current[M.current]),B(),R(),!0),[R,B]),xe=(0,r.useCallback)(()=>E.current<=0?!1:(--E.current,S.current=rn(T.current[E.current]),w.current=new Set,B(),R(),!0),[R,B]),Se=(0,r.useCallback)(()=>E.current>=T.current.length-1?!1:(E.current+=1,S.current=rn(T.current[E.current]),w.current=new Set,B(),R(),!0),[R,B]),Ce=(0,r.useCallback)(()=>{let t=e.current;return t===U.BRUSH?ye():t===U.POLYGON||t===U.PATH?xe():!1},[e,ye,xe]),we=(0,r.useCallback)(()=>{let t=e.current;return t===U.BRUSH?be():t===U.POLYGON||t===U.PATH?Se():!1},[be,Se,e]),W=(0,r.useCallback)(()=>{let e=t.current;if(!e.length)return A.current.length>0;let r=n.current.getShapes().filter(t=>e.includes(t.id)&&u(t)),i=Zt(r);return i.length?(A.current=r.map(e=>e.id),k.current=i,!0):(A.current=[],k.current=[],!1)},[n,t]),Te=(0,r.useCallback)(()=>{if(i.current)return!1;let e=[...O.current];S.current.length&&e.push({points:rn(S.current),mode:ee()});let t=k.current,r=[...A.current];if(!e.length&&!t.length)return!1;let u=Qt(e,s.current,t);if(!u)return V(),!1;let d=$t(u,c.current);if(r.length){let e=n.current.getShapes().filter(e=>r.includes(e.id));if(!d.length)return n.current.remove(r),V(),h([]),!0;d.sort((e,t)=>Ht(t)-Ht(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=m();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&&n.current.update(t),i.length&&n.current.create(i),s.length&&n.current.remove(s),V(),h(a),!0}if(!d.length)return V(),!1;let f=a.current;if(!f)return!1;let p=d.map(e=>({id:m(),type:o.POLYGON,points:e,style:f,meta:l}));return n.current.create(p),h(p.map(e=>e.id)),V(),!0},[s,h,n,l,a,i,V]),Ee=(0,r.useCallback)(()=>{let t=e.current;if(t===U.BRUSH)return Te();let n=S.current;return t===U.POLYGON&&n.length>=3?(b.current(o.POLYGON,n),V(),!0):!1},[Te,V,e]),De=(0,r.useCallback)(()=>{let t=S.current;if(e.current===U.PATH&&t.length>=3){let e=zt(t,c.current);e.length>=3&&b.current(o.POLYGON,e)}V()},[V,e]),Oe=(0,r.useCallback)(e=>{N.current=e,R(),B()},[R,B]),G=(0,r.useCallback)(()=>{if(i.current||e.current!==U.BRUSH)return!1;O.current=[],S.current=[],z();let t=W();return R(),B(),t},[R,i,B,z,W,e]),ke=(0,r.useCallback)(()=>{let e=w.current;if(!e.size)return!1;let t=S.current.filter((t,n)=>!e.has(n));return w.current=new Set,H(t,!0),!0},[H]),Ae=(0,r.useCallback)(e=>{let t=d.current,n=S.current;if(!t||!n.length)return-1;let r=on/(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,r.useCallback)(()=>{S.current.length>=1&&(O.current.push({points:rn(S.current),mode:ee()}),S.current=[],oe(O.current)),B(),R()},[R,oe,B]);return{reset:V,undoSession:Ce,redoSession:we,canUndoSession:re,canRedoSession:ie,hasDraftSession:ae,hasDraftPoints:le,commitDraftSession:Ee,completeFreehandStroke:De,setBrushScalarMode:Oe,getBrushScalarMode:()=>N.current,hasBrushSession:P,commitBrush:Te,cancelBrush:(0,r.useCallback)(()=>{e.current===U.BRUSH&&V()},[V,e]),beginBrushEditFromSelection:G,deleteDraftSelectedPoints:ke,hitDraftPoint:Ae,getDraftPointsSnapshot:ce,tryClosePolygon:ue,removeDraftPoint:de,selectDraftPointForDrag:fe,appendPolygonPoint:pe,beginStroke:me,appendStrokePoint:he,moveDraftPoints:ge,commitDraftPointDrag:_e,setDraftCursor:ve,finishScalarStroke:je,handleToolChange:(0,r.useCallback)((e,t)=>{if(t){V(),N.current=`draw`;return}if(e!==U.BRUSH){V(),N.current=`draw`;return}N.current=`draw`,O.current=[],S.current=[],z(),W(),R(),B()},[R,B,V,z,W]),handleBrushSelectionChange:(0,r.useCallback)((t,n)=>{if(!(e.current!==U.BRUSH||n)){if(!t.length){R();return}[...t].sort().join(`,`)!==[...A.current].sort().join(`,`)&&(O.current.length||S.current.length||(O.current=[],S.current=[],z(),W(),R(),B()))}},[R,B,z,W,e])}}function ln(e,t){return{shapes:t,past:[...e.past,e.shapes],future:[]}}function un(e,t){switch(t.type){case`CREATE`:return ln(e,[...e.shapes,...t.shapes]);case`UPDATE`:{let n=new Map(t.shapes.map(e=>[e.id,e]));return ln(e,e.shapes.map(e=>n.get(e.id)??e))}case`DELETE`:{let n=new Set(t.ids);return ln(e,e.shapes.filter(e=>!n.has(e.id)))}case`REPLACE`:{let n=new Set(t.removeIds);return ln(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:ln(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 dn(e){let{onShapesCreated:t,onShapesUpdated:n,onShapesDeleted:i}=e,[a,o]=(0,r.useReducer)(un,{shapes:[],past:[],future:[]}),s=(0,r.useRef)(a);s.current=a;let c=(0,r.useCallback)(e=>{s.current=un(s.current,e),o(e)},[]),l=(0,r.useCallback)((e,r)=>{let a=new Map(e.map(e=>[e.id,e])),o=new Map(r.map(e=>[e.id,e])),s=r.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=r.filter(e=>a.has(e.id)&&a.get(e.id)!==e);l.length&&n?.(l)},[t,n,i]),u=(0,r.useCallback)(e=>{let n=Array.isArray(e)?e:[e];n.length&&(c({type:`CREATE`,shapes:n}),t?.(n))},[t]),d=(0,r.useCallback)(e=>{c({type:`UPDATE`,shapes:e}),n?.(e)},[n]),f=(0,r.useCallback)(e=>{e.length!==0&&(c({type:`DELETE`,ids:e}),i?.(e))},[i]),p=(0,r.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,r.useCallback)((e,t)=>{e.length!==0&&c({type:`REORDER`,ids:e,edge:t})},[]),h=(0,r.useCallback)(e=>{c({type:`RESET`,shapes:e})},[]),g=(0,r.useCallback)(()=>{let e=s.current;e.past.length!==0&&(l(e.shapes,e.past[e.past.length-1]),c({type:`UNDO`}))},[l]),_=(0,r.useCallback)(()=>{let e=s.current;e.future.length!==0&&(l(e.shapes,e.future[0]),c({type:`REDO`}))},[l]),v=(0,r.useCallback)(()=>s.current.past.length>0,[]),y=(0,r.useCallback)(()=>s.current.future.length>0,[]),b=(0,r.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 fn={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`]},pn={Equal:`=`,Minus:`-`,BracketLeft:`[`,BracketRight:`]`,Semicolon:`;`,Period:`.`,Comma:`,`,Slash:`/`,Backquote:"`"},mn={Escape:`escape`,Enter:`enter`,Backspace:`backspace`,Delete:`delete`,Tab:`tab`,ArrowUp:`arrowup`,ArrowDown:`arrowdown`,ArrowLeft:`arrowleft`,ArrowRight:`arrowright`};function hn(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]:pn[t]?pn[t]:mn[e.key]?mn[e.key]:null}function gn(e){let t=hn(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 _n(e){let t=new Map;for(let n of Object.keys(fn)){let r=e?.[n],i=r===void 0?fn[n]:r===null?[]:Array.isArray(r)?r:[r];for(let e of i)t.set(e.toLowerCase(),n)}return t}var vn={ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0]};function yn(e){let{spaceRef:n}=e,i=(0,r.useMemo)(()=>_n(e.keymap),[e.keymap]),a=(0,r.useRef)(e);a.current=e;let o=(0,r.useRef)(i);o.current=i,(0,r.useEffect)(()=>{let e=a.current.hostRef.current,r=e?.ownerDocument.defaultView;if(!e||!r)return;let i=r=>{if(r.defaultPrevented&&r.key!==`Escape`||t.t(r.target)||!t.n(e,r.target))return;r.code===`Space`&&(n.current=!0,a.current.onSpaceDown());let i=vn[r.key];if(i){let e=r.shiftKey?10:1;a.current.nudge(i[0]*e,i[1]*e)!==!1&&r.preventDefault();return}let s=gn(r);if(!s)return;let c=o.current.get(s);c&&a.current.actions[c]?.()!==!1&&r.preventDefault()},s=e=>{e.code===`Space`&&n.current&&(n.current=!1,a.current.onSpaceUp())},c=()=>{n.current&&(n.current=!1,a.current.onSpaceUp())};return e.addEventListener(`keydown`,i),r.addEventListener(`keyup`,s,!0),r.addEventListener(`blur`,c),()=>{e.removeEventListener(`keydown`,i),r.removeEventListener(`keyup`,s,!0),r.removeEventListener(`blur`,c),c()}},[n])}function bn(e,t){return new Promise(n=>{let r=new Image;t?.crossOrigin&&(r.crossOrigin=`anonymous`),r.onload=()=>n(r),r.onerror=()=>n(null),r.src=e})}async function xn(e){let t=await bn(e,{crossOrigin:!0});if(t)return t;try{let t=await fetch(e,{mode:`cors`,credentials:`omit`,cache:`reload`});if(!t.ok)return null;await t.blob()}catch{return null}return bn(e,{crossOrigin:!0})}async function Sn(e){for(let t of[`default`,`reload`])try{let n=await fetch(e,{mode:`cors`,credentials:`omit`,cache:t});return n.ok?await n.blob():null}catch{}return null}async function Cn(e){let t=await Sn(e);if(t)try{let e=await createImageBitmap(t);return{source:e,width:e.width,height:e.height,release:()=>e.close()}}catch{}let n=await xn(e);return n?{source:n,width:n.naturalWidth,height:n.naturalHeight,release:()=>{}}:null}var wn=2,Tn=0,En=[];async function Dn(e){Tn<wn?Tn+=1:await new Promise(e=>En.push(e));try{return await e()}finally{let e=En.shift();e?e():--Tn}}function On(e){return new Promise(t=>{let n=null,r=!1,i=()=>{r||(r=!0,clearTimeout(o),document.removeEventListener(`securitypolicyviolation`,a),t(n))},a=t=>{let r=t.effectiveDirective??t.violatedDirective??``;r.includes(`img-src`)&&(n=`CSP ${r} blocked ${t.blockedURI||e}`)},o=setTimeout(i,1e4);document.addEventListener(`securitypolicyviolation`,a),bn(e,{crossOrigin:!0}).then(()=>{setTimeout(i,0)})})}var kn=3e4,An=200,jn=new Map;function Mn(e){let t=jn.get(e),n=Date.now();if(t&&n-t.at<kn)return t.result;let r=Nn(e).catch(t=>(jn.delete(e),{kind:`unknown`,detail:t instanceof Error?t.message:String(t)}));if(jn.set(e,{at:n,result:r}),jn.size>An){let e=jn.keys().next().value;e!==void 0&&jn.delete(e)}return r}async function Nn(e){let t=e;try{t=new URL(e,location.href).origin}catch{}if(location.protocol===`https:`&&e.startsWith(`http:`))return{kind:`mixed-content`,detail:`http image on https page (${t})`};let n;try{n=await fetch(e,{mode:`cors`,credentials:`omit`,cache:`no-store`})}catch{if(!navigator.onLine)return{kind:`offline`,detail:`navigator.onLine=false`};try{return await fetch(e,{mode:`no-cors`,cache:`no-store`}),{kind:`cors`,detail:`no Access-Control-Allow-Origin from ${t}`}}catch{return{kind:`network`,detail:`fetch failed: ${t}`}}}let{status:r}=n;if(n.ok){let t=n.headers.get(`content-type`)??``;if(t&&!t.startsWith(`image/`))return{kind:`unexpected-content`,detail:`HTTP ${r} (${t})${n.redirected?` via redirect`:``}`};let i=await On(e);return i?{kind:`csp-img`,detail:i}:{kind:`decode`,detail:`HTTP ${r}${t?` (${t})`:``}`}}if(r===401||r===403){try{let t=await fetch(e,{mode:`cors`,credentials:`include`,cache:`no-store`});if(t.ok)return{kind:`auth`,detail:`HTTP ${r} without cookies, ${t.status} with cookies`}}catch{}return{kind:`forbidden`,detail:`HTTP ${r}`}}return r===404||r===410?{kind:`not-found`,detail:`HTTP ${r}`}:r>=500?{kind:`server-error`,detail:`HTTP ${r}`}:{kind:`http`,detail:`HTTP ${r}`}}function Pn(){try{let e=document.createElement(`canvas`);return!!(e.getContext(`webgl2`)??e.getContext(`webgl`))}catch{return!1}}function Fn(e){let t=e instanceof Error?e.message:String(e);return/unsafe-eval/i.test(t)?{kind:`csp-eval`,detail:t}:Pn()?{kind:`renderer-init`,detail:t||`renderer init failed`}:{kind:`webgl`,detail:t||`WebGL context unavailable`}}var In=4e3;function Ln(e,t,n=In){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 Rn(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 zn(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=g(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 Bn=`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`,Vn=`#ffffff`,Q=1.5;function Hn(e){return`<svg width="16" height="22" viewBox="0 0 16 22" xmlns="http://www.w3.org/2000/svg"><path d="${Bn}" fill="${e}" stroke="${Vn}" stroke-width="${Q}"/></svg>`}var Un=Math.PI/12;function Wn(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 Gn(e,t,n){if(e.kind===`resize`){let r=n?e.box:v(e.anchor,e.box,t.x,t.y);return{updates:e.shapes.map(i=>({id:i.id,points:n?ee(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/Un)*Un),{updates:[{id:e.id,points:e.points.map(t=>b(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:g(a)}}function Kn(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)}:Wn(e,t)?j(t.shapes[0].points)[h.indexOf(t.anchor)]:_(t.anchor,t.box)}function qn(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:g(r.flatMap(e=>e.points)),shapes:r}:null}function Jn(e){return e.map(e=>({...e,points:e.points.map(e=>({...e}))}))}function Yn(e,t){let n=new Set(t);return e.filter(e=>n.has(e.id)&&u(e))}function Xn(e,t){return e.filter(e=>l(e)&&z(e,t)).map(e=>e.id)}function Zn(e,t,n){return(e?Ee(e,{strokeWidth:t}).pointRadius:5)/(n||1)}function Qn(e,t){return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}function $n(e,t,n){if(e.type===o.ROTATED_RECTANGLE)return t;let r=e.type===o.POINT?Qn(t[0],n):g(t);return x([{x:r.minX,y:r.minY},{x:r.maxX,y:r.maxY}])}function er(e){return 24/(e||1)}function tr(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}var nr=2,rr=`#1e88e5`,ir=`#669def`,ar=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.regionOverlayGroup=new i.default.Group({listening:!1}),this.dimOverlayGroup=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=nr,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.ghostNode=null,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.overlayGroup.add(this.regionOverlayGroup,this.dimOverlayGroup),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=>({pointerId:1,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`,e=>{if(this.lastImg=this.toImage(),this.activeDrag){this.lastDragImg=this.lastImg,this.dragTransform(this.lastImg);return}this.cb.onPointerMove(this.lastImg,{pointerId:1,global:this.stage.getPointerPosition()??{x:0,y:0},shiftKey:e.evt.shiftKey})});let t=null,n=(e,n)=>{if(t!==e){if(t=e,this.activeDrag){this.endTransform();return}this.cb.onPointerUp(this.lastImg,{pointerId:1,global:this.stage.getPointerPosition()??{x:0,y:0},shiftKey:e.shiftKey,insideCanvas:n})}};this.stage.on(`mouseup`,e=>n(e.evt,!0));let r=e=>{let t=e.target;n(e,t instanceof Node&&this.host.contains(t))};window.addEventListener(`mouseup`,r),this.upCleanup=()=>window.removeEventListener(`mouseup`,r),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}bindShapeCursor(e,t){if(!d(t))return this.bindCursor(e,`default`);this.bindCursor(e,()=>this.selected.includes(t.id)?`grab`:ft)}bindCursor(e,t){let n=()=>{if(this.activeDrag)return;let e=typeof t==`function`?t():t;e===`pointer`&&!this.transformEnabled||this.emitCursorHint(e)},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 xn(e);if(r!==this.imageLoadToken)return!0;if(!a)return this.imageWidth||=800,this.imageHeight||=600,!1;this.imageWidth=t?.width??a.naturalWidth,this.imageHeight=t?.height??a.naturalHeight;let o=n?.width??this.imageWidth,s=n?.height??this.imageHeight;this.bgGroup.scale({x:o/a.naturalWidth,y:s/a.naturalHeight}),this.bgGroup.destroyChildren();for(let e of Ln(a.naturalWidth,a.naturalHeight))this.bgGroup.add(new i.default.Image({image:a,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}));return this.layer.batchDraw(),!0}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)}setRenderDefaults(e){let t=e.strokeWidth??this.strokeSize;this.strokeSize!==t&&(this.strokeSize=t,this.setShapes(this.shapes,this.selected))}vertexHandleRadius(){return Math.max(4,this.strokeSize*2.5)}setImageSmoothing(e){this.imageSmoothing!==e&&(this.imageSmoothing=e,this.layer.imageSmoothingEnabled(e),this.layer.batchDraw())}setOverlays(e,t){if(this.setRegionOverlay(e),this.dimOverlayGroup.destroyChildren(),t&&this.imageWidth){let e=St(this.host);this.dimOverlayGroup.add(new i.default.Rect({x:0,y:0,width:this.imageWidth,height:this.imageHeight,fill:e.color,opacity:e.opacity,listening:!1}))}this.layer.batchDraw()}setRegionOverlay(e){if(this.regionOverlayGroup.destroyChildren(),e){let{imageWidth:t,imageHeight:n}=this;if(this.regionOverlayGroup.add(new i.default.Shape({listening:!1,sceneFunc:r=>{xt(r._context,e,t,n)}})),e.outlineStyles){let t=(e,t)=>{let n={strokeWidth:t.width,strokeScaleEnabled:!1,listening:!1};for(let[r,a]of e)t.underlayColor&&this.regionOverlayGroup.add(new i.default.Line({points:[r.x,r.y,a.x,a.y],stroke:t.underlayColor,...n})),this.regionOverlayGroup.add(new i.default.Line({points:[r.x,r.y,a.x,a.y],stroke:t.color,opacity:t.opacity,dash:t.dash,...n}))};t(e.visibleOutline,e.outlineStyles.visible),t(e.occludedOutline,e.outlineStyles.occluded)}}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??Kn(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=Jn(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=Ee(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()))}getVertexSelection(){return[...this.selectedVertices]}setVertexSelection(e){if(!this.editingId)return;let t=new Set(e);t.size===this.selectedVertices.size&&[...t].every(e=>this.selectedVertices.has(e))||(this.selectedVertices=t,this.activeDrag||(this.drawTransformer(),this.layer.batchDraw()))}makeNode(e){let{type:t,points:n}=e,r=Ee(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?De(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:Bn,x:n[0].x,y:n[0].y,offsetX:16/2,offsetY:22,scaleX:t,scaleY:t,fill:r.color,stroke:Vn,strokeWidth:Q,strokeScaleEnabled:!1,shadowColor:`#000`,shadowBlur:2,shadowOpacity:.3,shadowForStrokeEnabled:!1,opacity:r.opacity,listening:a});return this.bindShapeCursor(o,e),o}if(t===o.RECTANGLE){let t=g(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.bindShapeCursor(r,e),r}if(t===o.ELLIPSE){let t=g(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.bindShapeCursor(r,e),r}let u=n.flatMap(e=>[e.x,e.y]),d=t!==o.LINE,f=new i.default.Line({points:u,closed:d,fill:d?c:void 0,fillRule:`evenodd`,lineJoin:`round`,...s});return this.bindShapeCursor(f,e),f}liveUpdateShape(e,t){let n=this.nodes.get(e),r=this.shapes.find(t=>t.id===e);if(n&&r){zn(n,r.type,t);let a=this.altNodes.get(e);a&&zn(a,r.type,t),r.type===o.POINT&&n instanceof i.default.Circle&&n.radius(this.pointRadius(r)),this.layer.batchDraw()}}pointRadius(e){return Zn(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(Ee(t,{strokeWidth:this.strokeSize}).dash))}}shapesIntersecting(e){return Xn(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:ir,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 $n(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?rr:`#ffffff`,stroke:r?`#ffffff`:rr,strokeWidth:1.5,strokeScaleEnabled:!1,listening:!1}))}this.layer.batchDraw()}previewScalarMask(e,t){this.previewGroup.destroyChildren();let n=en(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:De(we,W),stroke:we,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,e||this.cancelTransform(),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(x([{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:rr,strokeWidth:1,strokeScaleEnabled:!1,listening:!1}),this.selGroup.add(this.transformerOutline)),this.transformerOutline.points(e.flatMap(e=>[e.x,e.y])))}rotationHandleGap(){return er(this.viewport.scale)}rotationHandleScreenPoint(e){return this.imgToScreen(M(e,this.rotationHandleGap()))}setRotationConnector(e){let t=this.imgToScreen(k(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:rr,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 tr(this.imgToScreen(e[0]),this.imgToScreen(e[1]))}repositionOrientedHandles(e){let t=this.orientedHandleAngle(e);if(j(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.ghostNode?.destroy(),this.ghostNode=null,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=Yn(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=g(e.flatMap(e=>e.points)),r=e.length===1&&e[0].type===o.ROTATED_RECTANGLE?e[0]:null,a=r?j(r.points):h.map(e=>_(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?[]:h){let t=this.imgToScreen(a[h.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:rr,strokeWidth:1}),r=Y(e,s);this.bindCursor(n,r),n.on(`mousedown`,t=>{t.cancelBubble=!0,this.emitCursorHint(r),this.emitInteractionMode(`resizing`);let n=Yn(this.shapes,this.selected);this.activeDrag={kind:`resize`,anchor:e,box:g(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,a=this.vertexHandleRadius(),s=new i.default.Circle({radius:a*.8,fill:`#ffffff`,opacity:.6,stroke:rr,strokeWidth:1,visible:!1,listening:!1});this.handleGroup.add(s),this.ghostNode=s;for(let t=0;t<r;t++){let r=n[t],o=n[(t+1)%n.length],c=this.imgToScreen(r),l=this.imgToScreen(o),u=new i.default.Line({points:[c.x,c.y,l.x,l.y],stroke:`#ffffff`,strokeWidth:1,opacity:0,hitStrokeWidth:Math.max(14,a*2+4)});this.bindCursor(u,`copy`);let d=()=>{let e=this.toImage(),t=o.x-r.x,n=o.y-r.y,i=t*t+n*n,a=i?Math.max(0,Math.min(1,((e.x-r.x)*t+(e.y-r.y)*n)/i)):0;return{x:r.x+a*t,y:r.y+a*n}};u.on(`mousemove`,()=>{if(this.activeDrag)return;let e=this.imgToScreen(d());s.position({x:e.x,y:e.y}),s.visible(!0),this.layer.batchDraw()}),u.on(`mouseleave`,()=>{s.visible(!1),this.layer.batchDraw()}),u.on(`mousedown`,r=>{r.cancelBubble=!0;let i=d(),a=t+1,o=[...n.slice(0,a),i,...n.slice(a)],s=this.shapes.find(t=>t.id===e.id);s&&(s.points=o),this.liveUpdateShape(e.id,o),this.selectedVertices=new Set([a]),this.drawTransformer(),this.cb.onTransformCommit?.([{id:e.id,points:o}]),this.activeDrag={kind:`vertex`,id:e.id,indices:[a],base:o,start:i},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`vertexDragging`)}),this.handleGroup.add(u),this.midNodes.push(u)}this.vertexPolygonId!==e.id&&(this.vertexPolygonId=e.id,this.selectedVertices.clear()),n.forEach((t,r)=>{let o=this.imgToScreen(t),s=this.selectedVertices.has(r),c=new i.default.Circle({x:o.x,y:o.y,radius:a,fill:s?rr:`#ffffff`,stroke:s?`#ffffff`:rr,strokeWidth:Math.max(1.5,a*.3)});this.bindCursor(c,`pointer`),c.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(c),this.vertexNodes.push(c)})}if(e.length===1&&e[0].type===o.ROTATED_RECTANGLE){let t=e[0],n=A(t.points),r=this.rotationHandleScreenPoint(t.points),a=new i.default.Circle({x:r.x,y:r.y,radius:6,fill:`#ffffff`,stroke:rr,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=qn(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){h.forEach((t,n)=>{let r=this.imgToScreen(_(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=this.imgToScreen(e[t]),r=this.imgToScreen(e[(t+1)%e.length]);this.midNodes[t]?.points([n.x,n.y,r.x,r.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=Wn(this.shapes,t),{updates:r,box:i}=Gn(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()}cancelTransform(){if(this.activeDrag){this.activeDrag=null,this.lastDragImg=null;for(let e of this.shapes)this.liveUpdateShape(e.id,e.points);this.cb.onTransformPreview?.(this.shapes.map(e=>({id:e.id,points:e.points}))),this.emitInteractionMode(`idle`),this.emitCursorHint(null),this.drawSelectionBorders()}}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}=Gn(e,t,Wn(this.shapes,e));this.commitTransformUpdates(n)}},or=2,sr=58879,cr=6725103;function $(e){if(!e)return sr;let t=e.replace(`#`,``);return Number.parseInt(t.length===3?t.replace(/./g,`$&$&`):t,16)}var lr=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.regionOverlayLayer=new a.Container,this.dimOverlayLayer=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.tileSize=In,this.region=null,this.regionDimMaskG=new a.Graphics,this.regionDimG=new a.Graphics,this.regionZoneMaskG=new a.Graphics,this.regionZoneG=new a.Graphics,this.regionOutlineG=new a.Graphics,this.baseCursor=`default`,this.strokeSize=or,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.ghostNode=null,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{pointerId:e.pointerId,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);let e=this.app.renderer.gl,t=e?.getParameter(e.MAX_TEXTURE_SIZE);typeof t==`number`&&t>1&&(this.tileSize=Math.min(In,t-1)),this.applyCursor(),this.overlayLayer.addChild(this.regionOverlayLayer,this.dimOverlayLayer),this.regionOverlayLayer.addChild(this.regionDimMaskG,this.regionDimG,this.regionZoneMaskG,this.regionZoneG,this.regionOutlineG),this.regionDimG.setMask({mask:this.regionDimMaskG,inverse:!0}),this.regionZoneG.setMask({mask:this.regionZoneMaskG}),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 n=(e,t)=>{if(this.activeDrag){this.endTransform();return}this.cb.onPointerUp(this.toImage(e),{pointerId:e.pointerId,global:{x:e.global.x,y:e.global.y},shiftKey:e.shiftKey,insideCanvas:t})};this.app.stage.on(`pointerup`,e=>n(e,!0)),this.app.stage.on(`pointerupoutside`,e=>n(e,!1)),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(),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 xn(e);if(this.destroyed||r!==this.imageLoadToken)return!0;if(!i)return this.imageWidth||=t?.width??800,this.imageHeight||=t?.height??600,!1;this.imageWidth=t?.width??i.naturalWidth,this.imageHeight=t?.height??i.naturalHeight;let o=n?.width??this.imageWidth,s=n?.height??this.imageHeight;this.bgLayer.scale.set(o/i.naturalWidth,s/i.naturalHeight),this.clearImageTiles();for(let e of Ln(i.naturalWidth,i.naturalHeight,this.tileSize)){let t=a.Texture.from(Rn(i,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)}return this.applySpriteFilter(),!0}setFilter(e,t){this.brightness=e,this.contrast=t,this.applySpriteFilter()}setRenderDefaults(e){let t=e.strokeWidth??this.strokeSize;this.strokeSize!==t&&(this.strokeSize=t,this.setShapes(this.shapes,this.selected))}vertexHandleRadius(){return Math.max(4,this.strokeSize*2.5)}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){this.setRegionOverlay(e);for(let e of this.dimOverlayLayer.removeChildren())e.destroy();if(t&&this.imageWidth){let e=St(this.host);this.dimOverlayLayer.addChild(new a.Graphics().rect(0,0,this.imageWidth,this.imageHeight).fill({color:$(e.color),alpha:e.opacity}))}!this.destroyed&&this.app.renderer&&this.app.render()}setRegionOverlay(e){if(this.region=e,this.regionDimMaskG.clear(),this.regionDimG.clear(),this.regionZoneMaskG.clear(),this.regionZoneG.clear(),this.regionOutlineG.clear(),!e)return;let t=$(e.dim.color);for(let t of e.rects)this.regionDimMaskG.rect(t.x,t.y,t.w,t.h).fill(16777215),this.regionZoneMaskG.rect(t.x,t.y,t.w,t.h).fill(16777215);this.regionDimG.rect(0,0,this.imageWidth,this.imageHeight).fill({color:t,alpha:e.dim.opacity});for(let n of e.zones)this.regionZoneG.poly(n.points.flatMap(e=>[e.x,e.y]),!0).fill({color:t,alpha:e.dim.opacity});this.redrawRegionOutline()}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??Kn(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=Jn(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())}getVertexSelection(){return[...this.selectedVertices]}setVertexSelection(e){if(!this.editingId)return;let t=new Set(e);t.size===this.selectedVertices.size&&[...t].every(e=>this.selectedVertices.has(e))||(this.selectedVertices=t,this.activeDrag||this.drawTransformer())}setTransformEnabled(e){this.transformEnabled=e,e||this.cancelTransform(),this.syncShapeCursors(),this.drawTransformer()}setPanMode(e){this.handleLayer.interactiveChildren=!e}strokeW(e){return(e?Ee(e,{strokeWidth:this.strokeSize}).strokeWidth:or)/this.world.scale.x}pointRadius(e){return Zn(e,this.strokeSize,this.world.scale.x)}dashForShape(e){let t=Ee(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(this.selected.includes(e.id)?`grab`:ft)}),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=Ee(t,{strokeWidth:this.strokeSize}),r=$(n.color),i=this.strokeW(t),a=n.opacity,s=this.dashForShape(t);if(t.type===o.POINT){e.svg(Hn(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){let i=t.type===o.POLYGON?V(t.points):null;if(i&&(i.length>1||i[0].holes.length>0))for(let t of i)for(let i=0;i<Math.min(t.layers,4);i++){e.poly(t.outline.flatMap(e=>[e.x,e.y]),!0),e.fill({color:r,alpha:n.fillAlpha*a});for(let n of t.holes)e.poly(n.flatMap(e=>[e.x,e.y]),!0),e.cut()}else this.path(e,t),e.fill({color:r,alpha:n.fillAlpha*a})}else t.type!==o.LINE&&(this.path(e,t),e.fill({color:r,alpha:0}));if(s){t.style?.alternateColor&&(this.path(e,t),e.stroke({width:i,color:$(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 Xn(this.shapes,e)}shapesAt(e){return this.shapes.filter(t=>{let n=g(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:$(r.alternateColor)}));let s=this.dashForShape(i);if(s){this.dashedStrokeShape(this.previewG,i,a,$(r.color??`#00e5ff`),r.opacity??1,s);return}this.path(this.previewG,i),this.previewG.stroke({width:a,color:$(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:$(n.alternateColor)}));let u=this.dashForShape(c);if(u?this.dashedStrokeShape(this.previewG,c,l,$(n.color??`#00e5ff`),n.opacity??1,u):(this.path(this.previewG,c),this.previewG.stroke({width:l,color:$(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=en(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=$(we);this.marqueeG.rect(n,r,i,a).fill({color:o,alpha:W}).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;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:$(r.underlayColor)}),this.strokeDashedPolyline(e,[n,o],!1,i,$(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=g(r);e.rect(t.minX,t.minY,t.maxX-t.minX,t.maxY-t.minY);return}if(n===o.ELLIPSE){let t=g(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=g(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=g(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;if(!(s>0)||!(c>0))return;let l=!0,u=0,d=null,f=()=>{if(d&&d.length>=2){e.moveTo(d[0].x,d[0].y);for(let t=1;t<d.length;t++)e.lineTo(d[t].x,d[t].y);e.stroke({width:r,color:i,alpha:a})}d=null},p=n?t.length:t.length-1;for(let e=0;e<p;e++){let n=t[e],r=t[(e+1)%t.length],i=r.x-n.x,a=r.y-n.y,o=Math.hypot(i,a);if(!o)continue;let p=0;for(;p<o;){let e=l?s:c,t=Math.min(e-u,o-p);if(l){let e=p/o,r=(p+t)/o;d||=[{x:n.x+i*e,y:n.y+a*e}],d.push({x:n.x+i*r,y:n.y+a*r})}p+=t,u+=t,u>=e-1e-4&&(u=0,l&&f(),l=!l)}}f()}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:cr})})}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:cr}))}}selectionOutlinePoints(e,t){return $n(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(x([{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 er(this.viewport.scale)}rotationHandleScreenPoint(e){return this.imgToScreen(M(e,this.rotationHandleGap()))}setRotationConnector(e){let t=this.imgToScreen(k(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 tr(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.ghostNode?.destroy(),this.ghostNode=null,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=Yn(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=g(e.flatMap(e=>e.points)),r=e.length===1&&e[0].type===o.ROTATED_RECTANGLE?e[0]:null,i=r?j(r.points):h.map(e=>_(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?[]:h){let t=this.imgToScreen(i[h.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=Y(e,s);this.bindCursor(n,r),n.on(`pointerdown`,t=>{t.stopPropagation(),this.emitCursorHint(r),this.emitInteractionMode(`resizing`);let n=Yn(this.shapes,this.selected);this.activeDrag={kind:`resize`,anchor:e,box:g(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,i=this.vertexHandleRadius(),s=new a.Graphics;s.circle(0,0,i*.8).fill({color:16777215,alpha:.6}).stroke({width:1,color:2001125}),s.visible=!1,s.eventMode=`none`,this.handleLayer.addChild(s),this.ghostNode=s;for(let t=0;t<r;t++){let r=n[t],i=n[(t+1)%n.length],o=new a.Graphics;o.hitArea=this.edgeHitQuad(r,i),o.eventMode=`static`,this.bindCursor(o,`copy`);let c=e=>{let t=this.toImage(e),n=i.x-r.x,a=i.y-r.y,o=n*n+a*a,s=o?Math.max(0,Math.min(1,((t.x-r.x)*n+(t.y-r.y)*a)/o)):0;return{x:r.x+s*n,y:r.y+s*a}};o.on(`pointermove`,e=>{if(this.activeDrag)return;let t=this.imgToScreen(c(e));s.position.set(t.x,t.y),s.visible=!0}),o.on(`pointerleave`,()=>{s.visible=!1}),o.on(`pointerdown`,r=>{r.stopPropagation();let i=c(r),a=t+1,o=[...n.slice(0,a),i,...n.slice(a)],s=this.shapes.find(t=>t.id===e.id);s&&(s.points=o),this.liveUpdateShape(e.id,o),this.selectedVertices=new Set([a]),this.drawTransformer(),this.cb.onTransformCommit?.([{id:e.id,points:o}]),this.activeDrag={kind:`vertex`,id:e.id,indices:[a],base:o,start:i},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`vertexDragging`)}),this.handleLayer.addChild(o),this.midNodes.push(o)}this.vertexPolygonId!==e.id&&(this.vertexPolygonId=e.id,this.selectedVertices.clear()),n.forEach((t,r)=>{let o=this.imgToScreen(t),s=this.selectedVertices.has(r),c=new a.Graphics;c.circle(0,0,i).fill({color:s?2001125:16777215}).stroke({width:Math.max(1.5,i*.3),color:s?16777215:2001125}),c.position.set(o.x,o.y),c.eventMode=`static`,this.bindCursor(c,`pointer`),c.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(c),this.vertexNodes.push(c)})}if(e.length===1&&e[0].type===o.ROTATED_RECTANGLE){let t=e[0],n=A(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=qn(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){h.forEach((t,n)=>{let r=this.imgToScreen(_(t,e)),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,0)}),this.setTransformerOutline(e)}repositionOrientedHandles(e){let t=this.orientedHandleAngle(e);if(j(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=this.midNodes[t];n&&(n.hitArea=this.edgeHitQuad(e[t],e[(t+1)%e.length]))}}edgeHitQuad(e,t){let n=Math.max(7,this.vertexHandleRadius()+2),r=this.imgToScreen(e),i=this.imgToScreen(t),o=i.x-r.x,s=i.y-r.y,c=Math.hypot(o,s)||1,l=-s/c*n,u=o/c*n;return new a.Polygon([r.x+l,r.y+u,i.x+l,i.y+u,i.x-l,i.y-u,r.x-l,r.y-u])}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=Wn(this.shapes,t),{updates:r,box:i}=Gn(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)}}cancelTransform(){if(!this.activeDrag)return;let e=this.activeDrag.kind===`move`;this.activeDrag=null,this.lastDragImg=null,e&&this.resetMoveOffsets();for(let e of this.shapes)this.liveUpdateShape(e.id,e.points);this.cb.onTransformPreview?.(this.shapes.map(e=>({id:e.id,points:e.points}))),this.emitInteractionMode(`idle`),this.emitCursorHint(null),this.drawSelectionBorders()}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}=Gn(e,t,Wn(this.shapes,e));e.kind===`move`&&this.resetMoveOffsets(),this.commitTransformUpdates(n)}};function ur({currentDocId:e,documentId:t,loadedUrl:n,renderedImageUrl:r}){if(!r)return e!==null||n!==null?{kind:`clear`}:{kind:`none`};let i=e!==t;return!i&&n===r?{kind:`none`}:{kind:`load`,docChange:i}}function dr({keepZoomOnImageChange:e,viewportSeeded:t}){return e&&t}function fr({backend:e,hostRef:t,engineRef:n,documentId:i,renderedImageUrl:a,makeCallbacks:o,viewRef:s,readOnlyRef:c,toolRef:l,renderShapesRef:u,coordinateSizeRef:d,imageSizeRef:f,selRef:p,regionOverlayRef:m,dimmedRef:h,syncMinimap:g,setImage:_,setImageVisible:v,setReady:y,setImageStatus:b,onContextMenuRequest:x}){let S=(0,r.useRef)(a);S.current=a;let C=(0,r.useRef)(i);C.current=i;let w=(0,r.useRef)(null),T=(0,r.useRef)(null),E=(0,r.useRef)(!1),D=(0,r.useRef)(null),O=(0,r.useRef)(!1),k=(0,r.useRef)(o);k.current=o;let A=(0,r.useRef)(x);A.current=x,(0,r.useEffect)(()=>{let r=t.current;if(!r)return;let i=!1,a=null,o=null,x=k.current(),j=e===`konva`?new ar(r,x):new lr(r,x);return n.current=j,O.current=!1,(async()=>{try{await j.init()}catch(e){i||b(`error`,Fn(e));return}if(i)return;if(j.setFilter(s.current.brightness,s.current.contrast),j.setRenderDefaults({strokeWidth:s.current.strokeSize}),j.setImageSmoothing(s.current.imageSmoothing),j.setTransformEnabled(!c.current),E.current=!0,S.current){let e=S.current,t=C.current;b(`loading`);let n=null;try{n=await j.setImage(e,d.current,f.current)}catch(t){!i&&S.current===e&&b(`error`,Fn(t))}if(i)return;if(n!==null){w.current=e,T.current=t,_({w:j.imageWidth,h:j.imageHeight}),v(!0),j.setShapes(u.current,p.current),j.setOverlays(s.current.showRegionMask?m.current:null,h.current);let r=D.current;r?.viewport&&(r.imageUrl===w.current||s.current.keepZoomOnImageChange)?j.applyViewport(r.viewport):j.fit(),O.current=!0,g(),y(!0);let a=()=>S.current===e;n?a()&&b(`ready`):Mn(e).then(e=>{!i&&a()&&b(`error`,e)})}}let e=(e,t)=>Math.exp(-Math.sign(e)*Math.min(Math.abs(e)*.01,.1)*t);a=t=>{t.preventDefault();let n=j.dom.getBoundingClientRect(),r=s.current.zoomSensitivity??1;if(t.ctrlKey||t.metaKey){j.zoomAt(t.clientX-n.left,t.clientY-n.top,e(t.deltaY,r));return}if(!s.current.wheelZoom){let e=j.viewport;j.applyViewport({scale:e.scale,x:e.x-t.deltaX,y:e.y-t.deltaY});return}j.zoomAt(t.clientX-n.left,t.clientY-n.top,e(t.deltaY,r))},j.dom.addEventListener(`wheel`,a,{passive:!1}),o=e=>{if(e.preventDefault(),l.current===U.ASSISTANT_POINT&&e.altKey)return;let t=r.getBoundingClientRect(),n=e.clientX-t.left,i=e.clientY-t.top,a=j.viewport;A.current({x:n,y:i,img:{x:(n-a.x)/a.scale,y:(i-a.y)/a.scale}})},j.dom.addEventListener(`contextmenu`,o)})(),()=>{i=!0,E.current=!1,D.current={imageUrl:w.current??``,viewport:j.viewport},n.current=null,a&&j.dom&&j.dom.removeEventListener(`wheel`,a),o&&j.dom&&j.dom.removeEventListener(`contextmenu`,o),j.destroy()}},[e]),(0,r.useEffect)(()=>{let e=n.current;if(!e||!E.current)return;let t=ur({currentDocId:T.current,documentId:i,loadedUrl:w.current,renderedImageUrl:a});if(t.kind===`none`)return;let r=()=>{y(!1),v(!1),e.clearImage(),e.setShapes([],[]),e.setOverlays(null,!1)};if(t.kind===`clear`){w.current=null,T.current=null,r(),b(`loading`);return}let o=a;t.docChange&&(T.current=null,r());let c=!1;return(async()=>{b(`loading`);let r=!1;try{r=await e.setImage(o,d.current,f.current)}catch(t){!c&&n.current===e&&b(`error`,Fn(t));return}if(c||n.current!==e)return;w.current=o;let a=()=>{if(r){b(`ready`);return}Mn(o).then(e=>{c||b(`error`,e)})};if(!t.docChange){a();return}T.current=i,_({w:e.imageWidth,h:e.imageHeight}),v(!0),e.setShapes(u.current,p.current),e.setOverlays(s.current.showRegionMask?m.current:null,h.current),dr({keepZoomOnImageChange:s.current.keepZoomOnImageChange,viewportSeeded:O.current})||e.fit(),O.current=!0,g(),y(!0),a()})(),()=>{c=!0}},[i,a])}var pr=.05,mr=20;function hr(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 gr(e){let t=e.currentTarget.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}function _r({engineRef:e,image:t,wheelZoom:n,minimapSize:i}){let a=(0,r.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=(0,r.useCallback)(()=>{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}},[e,s,u,d]),p=(0,r.useCallback)((n,r,i)=>{let a=e.current;if(!a||!t)return;let o=f();if(!o)return;let c=i?.offsetX??o.width/2,l=i?.offsetY??o.height/2,p=n.x-c+o.width/2,m=n.y-l+o.height/2,h=(p-u)/s,g=(m-d)/s;a.applyViewport({scale:r,x:a.screenSize.w/2-h*r,y:a.screenSize.h/2-g*r})},[e,f,t,s,u,d]),m=(0,r.useCallback)(t=>{let n=e.current,r=f();if(!n||!r)return;t.preventDefault(),t.stopPropagation();let i=gr(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),p(i,n.viewport.scale,o)},[p,e,f]),h=(0,r.useCallback)(t=>{let n=a.current,r=e.current;!n||!r||n.pointerId!==t.pointerId||(t.preventDefault(),t.stopPropagation(),p(gr(t),r.viewport.scale,n))},[p,e]),g=(0,r.useCallback)(e=>{let t=a.current;!t||t.pointerId!==e.pointerId||(a.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))},[]),_=(0,r.useCallback)(t=>{let r=e.current;if(!r||!n)return;t.preventDefault(),t.stopPropagation();let i=hr(t.nativeEvent)?2.5:1,a=t.deltaY*i,o=1.05,s=a>0?r.viewport.scale/o:r.viewport.scale*o,c=Math.max(pr,Math.min(mr,s));p(gr(t),c)},[p,e,n]),v=(0,r.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,r.useMemo)(()=>({mm:s,offX:u,offY:d,dispW:c,dispH:l,handleMinimapPointerDown:m,handleMinimapPointerMove:h,endMinimapDrag:g,handleMinimapWheel:_,zoomCentered:v}),[s,u,d,c,l,m,h,g,_,v])}function vr(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=g(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 yr({engineRef:e,docRef:t,overlayRef:n,zoomLabelRef:i,minimapRectRef:a,minimapSize:o,onViewportChangeRef:s}){let c=(0,r.useRef)(new Map);return{registerMinimapShape:(0,r.useCallback)((e,t)=>{t?c.current.set(e,t):c.current.delete(e)},[]),applyMinimapPreview:(0,r.useCallback)(e=>{let n=t.current.getShapes();if(!e.length){for(let e of n)vr(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&&vr(c.current.get(e.id),e,t.points)}},[t]),syncMinimap:(0,r.useCallback)(()=>{let t=e.current;if(!t?.imageWidth)return;let r=t.viewport;if(s.current?.(r),n.current){n.current.style.transform=`translate(${r.x}px, ${r.y}px) scale(${r.scale})`;let e=1/(r.scale||1);n.current.style.setProperty(`--editor-overlay-stroke`,`${e}`),n.current.style.setProperty(`--editor-overlay-dash`,`${4*e}`),n.current.style.setProperty(`--editor-overlay-inverse-scale`,`${e}`)}i.current&&(i.current.textContent=`${Math.round(r.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=`${-r.x/r.scale*l+u}px`,c.style.top=`${-r.y/r.scale*l+d}px`,c.style.width=`${f/r.scale*l}px`,c.style.height=`${p/r.scale*l}px`},[e,n,i,a,o,s])}}var br=12;function xr({doc:e,selRef:t,effectiveReadOnly:n,changeSelection:i,canMergeSelection:a,clipboardDocumentId:s,clipboardScope:c}){let d=(0,r.useRef)(0),f=(0,r.useRef)(!0),p=(0,r.useRef)(n),h=(0,r.useRef)(s),_=(0,r.useRef)(c);p.current=n,h.current=s,_.current=c,(0,r.useEffect)(()=>(f.current=!0,()=>{f.current=!1}),[]),(0,r.useEffect)(()=>{d.current=0},[s]);let v=(0,r.useCallback)(()=>i(e.getShapes().filter(e=>l(e)).map(e=>e.id)),[e,i]),y=(0,r.useCallback)(()=>i([]),[i]),b=(0,r.useCallback)(()=>e.getShapes().filter(e=>t.current.includes(e.id)&&u(e)),[e,t]),x=(0,r.useCallback)(()=>{if(n||!t.current.length)return;let r=b().map(e=>e.id);r.length&&(e.remove(r),i([]))},[e,n,i,b,t]),S=(0,r.useCallback)(()=>{let e=b();e.length&&(d.current=0,q(nt(e,s,c)))},[s,c,b]),C=(0,r.useCallback)(()=>st(c),[c]),w=(0,r.useCallback)(t=>{if(n)return;let r=s;J(c).then(n=>{if(!f.current||p.current||h.current!==r||_.current!==c||!n?.shapes.length)return;let a,o,l=n.shapes.flatMap(e=>e.points);if(t&&l.length){let e=g(l);a=t.x-(e.minX+e.maxX)/2,o=t.y-(e.minY+e.maxY)/2}else{let e=!!n.documentId&&n.documentId!==s,t=ct(d.current,e,br);a=t.offset,d.current=t.nextPasteCount,o=a}let u=n.shapes.map(e=>({...e,id:m(),points:e.points.map(e=>({x:e.x+a,y:e.y+o}))}));e.create(u),i(u.map(e=>e.id))})},[s,c,e,n,i]),T=(0,r.useCallback)(()=>{if(n||!t.current.length)return;let r=b().map(e=>({...e,id:m(),points:e.points.map(e=>({x:e.x+br,y:e.y+br}))}));r.length&&(e.create(r),i(r.map(e=>e.id)))},[e,n,i,b,t]),E=(0,r.useCallback)(()=>{if(n)return;let t=b().map(e=>e.id);t.length&&e.reorder(t,`front`)},[e,n,b]),D=(0,r.useCallback)(()=>{if(n)return;let t=b().map(e=>e.id);t.length&&e.reorder(t,`back`)},[e,n,b]),O=(0,r.useCallback)((r,i)=>{if(n||!t.current.length)return!1;let a=e.getShapes().filter(e=>t.current.includes(e.id)&&u(e));return a.length?(e.update(a.map(e=>({...e,points:e.points.map(e=>({x:e.x+r,y:e.y+i}))}))),!0):!1},[e,n,t]),k=(0,r.useCallback)(()=>b().filter(e=>e.type===o.POLYGON||e.type===o.RECTANGLE||e.type===o.ROTATED_RECTANGLE||e.type===o.ELLIPSE),[b]);return{selectAll:v,clearSelection:y,getEditableSelection:b,deleteSelection:x,copySelection:S,canPaste:C,paste:w,duplicate:T,bringToFront:E,sendToBack:D,nudgeSelection:O,getMergeTargets:k,mergeSelection:(0,r.useCallback)(()=>{if(n)return;let t=k();if(t.length<2||a&&!a(t))return;let r=Qt([],1,Zt(t));if(!r)return;let s=$t(r,1);if(!s.length)return;let c=t[0],l=s.map(e=>({id:m(),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,n,k,a,i])}}function Sr({engineRef:e,doc:t,selRef:n,zoomAnimationDuration:i,zoomBound:a,ready:o}){let s=(0,r.useRef)(null),c=(0,r.useRef)(null),l=(0,r.useCallback)(()=>{s.current?.(),s.current=null},[]),u=(0,r.useCallback)((t,n=i)=>{let r=e.current;r&&(l(),s.current=Ft(r.viewport,t,e=>r.applyViewport(e),n))},[l,i,e]),d=(0,r.useCallback)((t,n=i)=>{let r=e.current;if(!r)return;let a=Nt(t,r.screenSize.w,r.screenSize.h);a&&u(a,n)},[u,i,e]),f=(0,r.useCallback)((e,n=i)=>{let r=Mt(t.getShapes().filter(t=>e.includes(t.id)));r&&d(r,n)},[t,d,i]),p=(0,r.useCallback)(()=>{let r=t.getShapes().filter(e=>n.current.includes(e.id));if(!r.length)return;let i=e.current;if(!i)return;let a=Pt(g(r.flatMap(e=>e.points)),i.screenSize.w,i.screenSize.h,80);a&&u(a)},[t,u,e,n]),m=(0,r.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,r.useEffect)(()=>()=>l(),[l]),(0,r.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 Cr=`__draft_preview__`,wr=new Set([`copy`,`selectAll`,`clearSelection`,`zoomToSelection`]);function Tr(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Er({document:t,clipboardScope:i,renderImageState:a,dimmed:c=!1,selectedIds:d,activeTool:f,draftStyle:p,draftMeta:h,readOnly:g,disableMarquee:_,locked:v,onLockedInteraction:y,onDrawAttemptWithoutDraft:b,onIdleEscape:x,overrideShapeInteraction:S,defaultViewSettings:C,viewSettings:w,onViewSettingsChange:T,showMinimap:E=!0,minimapPosition:D=`bottom-left`,showViewSettings:O=!0,getContextMenuItems:k,strings:A,viewSettingItems:j,canMergeSelection:M,brushSize:N=20,zoomBound:ee,zoomAnimationDuration:P=300,decorationShapes:F,regionMask:I,overlayMarkers:L,renderOverlayMarker:te,onOverlayMarkerClick:ne,renderImageOverlay:re,getSelectionLabel:ie,hideSelectionLabelDot:ae,formatSelectionInfo:R,externalTools:z,assistant:B,keymap:oe,handleRef:se,backend:V=`pixi`,onActiveToolChange:H,onSelectionChange:ue,onEditingChange:de,onShapesCreated:pe,onShapesUpdated:me,onShapesDeleted:he,onDrawSessionChange:ge,onDraftShapeChange:ve,onViewportChange:Se,onShapesTransformPreview:Ce}){let we=(0,r.useRef)(null),W=(0,r.useRef)(null),Te=(0,r.useRef)(null),Ee=(0,r.useRef)(null),De=(0,r.useRef)(null),Oe=`${(0,r.useId)()}-minimap`,[G,ke]=(0,r.useState)(null),[Ae,je]=(0,r.useState)(!1),[K,Me]=(0,r.useState)(!1),[Ne,Pe]=(0,r.useState)(null),[Fe,Ie]=(0,r.useState)({active:!1,kind:`none`,canUndo:!1,canRedo:!1}),[Re,ze]=(0,r.useState)(!0),[Be,Ve]=(0,r.useState)(!1),He=t?.id??``,Ke=t?.imageUrl??``,Je=t?.displayImageUrl,Ye=t?.coordinateSize,Xe=t?.initialShapes,Ze=t?.initialSelectedIds,Qe=Je??Ke,[$e,et]=(0,r.useState)(`loading`),tt=$e===`loading`&&t!==null&&!Qe?`missing`:$e,[nt,it]=(0,r.useState)(null),at=(0,r.useCallback)((e,t)=>{et(e),it(e===`error`?t??null:null)},[]),q=dn({onShapesCreated:pe,onShapesUpdated:me,onShapesDeleted:he}),[ot,st]=(0,r.useState)([]),J=d??ot,ct=d!==void 0,lt=(0,r.useMemo)(()=>new Map((z??[]).map(e=>[e.id,e])),[z]),ut=(0,r.useRef)(lt);(0,r.useLayoutEffect)(()=>{ut.current=lt},[lt]);let dt=(0,r.useRef)(Fe);dt.current=Fe;let ft=(0,r.useMemo)(()=>{let e=Object.fromEntries(Object.entries(C??{}).filter(([,e])=>e!==void 0));return fe({...le,...e})},[C]),pt=(0,r.useRef)(ft);pt.current=ft;let[Y,mt]=(0,r.useState)(()=>pt.current),gt=(0,r.useCallback)(e=>mt(t=>fe({...t,...e})),[]),X=(0,r.useMemo)(()=>ce(A),[A]);(0,r.useEffect)(()=>{if(!w)return;let e=fe(w);mt(t=>{let n=Object.entries(e).filter(([e,n])=>n!==void 0&&t[e]!==n);return n.length?{...t,...Object.fromEntries(n)}:t})},[w]);let _t=(0,r.useRef)(T);_t.current=T;let vt=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!vt.current){vt.current=!0;return}_t.current?.(Y)},[Y]);let yt=(0,r.useMemo)(()=>!G||!I?null:Dt(I,G.w,G.h),[G,I]),bt=(0,r.useRef)(yt);bt.current=yt;let xt=(0,r.useRef)(c);xt.current=c;let St=(0,r.useRef)(G);St.current=G;let Ct=(0,r.useRef)(Ye);Ct.current=Ye;let wt=(0,r.useRef)(Ye?.imageSize);wt.current=Ye?.imageSize;let Tt=(0,r.useRef)(J);(0,r.useLayoutEffect)(()=>{Tt.current=J},[J]);let Et=(0,r.useRef)(f);Et.current=f;let Ot=(0,r.useRef)(p);Ot.current=p;let kt=(0,r.useRef)(h);kt.current=h;let At=(0,r.useRef)(N);At.current=N;let jt=(0,r.useRef)(Y.simplifyStrength);jt.current=Y.simplifyStrength;let Z=!!g||!!v,Mt=(0,r.useRef)(Z);Mt.current=Z;let Nt=(0,r.useRef)(_);Nt.current=_;let Pt=(0,r.useRef)(v);Pt.current=v;let Ft=(0,r.useRef)(y);Ft.current=y;let Rt=(0,r.useRef)(g);Rt.current=g;let zt=(0,r.useCallback)((e=!0)=>Rt.current||!Pt.current||!e?!1:(Ft.current?.(),!0),[]),Bt=(0,r.useRef)(b);Bt.current=b;let Vt=(0,r.useRef)(S);Vt.current=S;let Ht=(0,r.useRef)(q);Ht.current=q;let Ut=(0,r.useRef)(!1),Wt=(0,r.useRef)(`idle`),Gt=(0,r.useRef)(null),Kt=(0,r.useCallback)(()=>{let e=W.current;if(!e)return;let t=Et.current,n=ut.current.get(t),r=dt.current;e.setCursor(ht({tool:t,externalToolCursor:n?.cursor,isSpacePressed:Ut.current,interactionMode:Wt.current,rendererCursorHint:Gt.current,isPolygonDrawing:r.kind===`polygon`&&r.active}))},[]),qt=(0,r.useCallback)(e=>{Wt.current!==e&&(Wt.current=e,Kt())},[Kt]),Jt=(0,r.useCallback)(e=>{Gt.current!==e&&(Gt.current=e,Kt())},[Kt]),Yt=(0,r.useCallback)(e=>{let t=new Set,n=new Map(Ht.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=Vt.current?.(r);return l(i?{...r,interaction:{...r.interaction,...i}}:r)})},[]),Xt=(0,r.useCallback)(e=>{let t=Yt(e);Tr(Tt.current,t)||(ct||st(t),W.current?.setSelection(t),ue?.(t))},[Yt,ue,ct]),Zt=(0,r.useRef)(Xt);Zt.current=Xt;let[Qt,$t]=(0,r.useState)(null),en=(0,r.useCallback)(e=>$t(e),[]),tn=(0,r.useRef)(en);tn.current=en;let nn=(0,r.useRef)(null);nn.current=Qt,(0,r.useEffect)(()=>{if(!ct)return;let e=Yt(d);Tr(d,e)||ue?.(e)},[d,q.shapes,Yt,ue,ct]);let rn=(0,r.useRef)(Se);rn.current=Se;let{registerMinimapShape:an,applyMinimapPreview:on,syncMinimap:sn}=yr({engineRef:W,docRef:Ht,overlayRef:Ee,zoomLabelRef:De,minimapRectRef:Te,minimapSize:204,onViewportChangeRef:rn}),ln=(0,r.useRef)(new Map),un=(0,r.useRef)(R);un.current=R;let fn=(0,r.useCallback)((e,t)=>{t?ln.current.set(e,t):ln.current.delete(e)},[]),pn=(0,r.useRef)(null),[mn,hn]=(0,r.useState)(null),gn=(0,r.useCallback)(e=>{if(!e.length)return;let t=new Map(Ht.current.getShapes().map(e=>[e.id,e]));pn.current&&t.set(pn.current.id,pn.current);for(let{id:n,points:r}of e){let e=ln.current.get(n),i=t.get(n);if(!e||!i)continue;let a=Ue(e,r);if(a){let e=We(i,r);a.textContent=un.current?.(e)??Ge(e)}}},[]),_n=(0,r.useCallback)(e=>{on(e),gn(e),Ce?.(e)},[on,gn,Ce]),vn=(0,r.useCallback)(e=>{if(ve?.(e?{...e,meta:kt.current}:null),!e||!Ot.current){pn.current&&(pn.current=null,hn(null));return}let t={id:Cr,type:e.type,points:e.points,style:Ot.current,meta:kt.current},n=pn.current!==null;pn.current=t,n?gn([{id:Cr,points:e.points}]):hn(t)},[gn,ve]),bn=(0,r.useCallback)((e,t)=>{let n=Ot.current;if(!n||Mt.current)return;let r=m();Ht.current.create({id:r,type:e,points:t,style:n,meta:h}),Zt.current([r])},[h]),xn=(0,r.useRef)(bn);xn.current=bn;let Sn=cn({toolRef:Et,selRef:Tt,docRef:Ht,readOnlyRef:Mt,draftRef:Ot,brushSizeRef:At,simplifyEpsilonRef:jt,draftMeta:h,engineRef:W,onDrawSessionChange:(0,r.useCallback)(e=>{Ie(e),ge?.(e)},[ge]),onDraftShapeChange:ve,changeSelection:Xt,createShape:bn}),Cn=(0,r.useRef)(Sn);Cn.current=Sn;let{reset:wn,undoSession:Tn,redoSession:En,canUndoSession:Dn,canRedoSession:On,hasDraftSession:kn,hasDraftPoints:An,commitDraftSession:jn,setBrushScalarMode:Mn,getBrushScalarMode:Nn,hasBrushSession:Pn,commitBrush:Fn,cancelBrush:In,beginBrushEditFromSelection:Ln,deleteDraftSelectedPoints:Rn,handleToolChange:zn,handleBrushSelectionChange:Bn}=Sn,Vn=(0,r.useRef)(B);Vn.current=B;let Q=Lt({docRef:Ht,draftRef:Ot,draftMeta:h,changeSelection:Xt,assistantRef:Vn}),Hn=(0,r.useRef)(Q);Hn.current=Q;let Un=(0,r.useMemo)(()=>rt(He),[He]),{selectAll:Wn,clearSelection:Gn,deleteSelection:Kn,copySelection:qn,canPaste:Jn,paste:Yn,duplicate:Xn,bringToFront:Zn,sendToBack:Qn,nudgeSelection:$n,getMergeTargets:er,mergeSelection:tr}=xr({doc:q,selRef:Tt,effectiveReadOnly:Z,changeSelection:Xt,canMergeSelection:M,clipboardDocumentId:Un,clipboardScope:i??Un}),{zoomToBounds:nr,zoomToShapes:rr,zoomToSelection:ir,zoomAtCenter:ar}=Sr({engineRef:W,doc:q,selRef:Tt,zoomAnimationDuration:P,zoomBound:ee,ready:K});(0,r.useImperativeHandle)(se,()=>({previewRegionMask:e=>{let t=St.current;if(!t)return;let n=e?Dt(e,t.w,t.h):bt.current;W.current?.setRegionOverlay(or.current.showRegionMask?n:null)},undo:()=>{Mt.current||Tn()||q.undo()},redo:()=>{Mt.current||En()||q.redo()},canUndo:()=>Dn()||q.canUndo(),canRedo:()=>On()||q.canRedo(),undoSession:Tn,redoSession:En,canUndoSession:Dn,canRedoSession:On,hasDraftSession:kn,cancelDraftSession:wn,commitDraftSession:jn,setSelection:Xt,createShapes:e=>{!e.length||zt()||(q.create(e),Xt(e.map(e=>e.id)))},updateShapes:e=>{!e.length||zt()||q.update(e)},deleteShapes:e=>{!e.length||zt()||q.remove(e)},getShapes:q.getShapes,selectAll:Wn,clearSelection:Gn,deleteSelection:Kn,copySelection:qn,paste:Yn,duplicate:Xn,bringToFront:Zn,sendToBack:Qn,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:ir,zoomToShapes:rr,zoomToBounds:nr,brush:{setScalarMode:Mn,getScalarMode:Nn,hasSession:Pn,commit:Fn,cancel:In,beginEditFromSelection:Ln}}),[q,Xt,zt,Tn,En,jn,wn,Fn,In,Wn,Gn,Kn,qn,Yn,Xn,Zn,Qn,ir,rr,nr,Mn,Nn,Pn,Ln]);let or=(0,r.useRef)(Y);or.current=Y;let sr=(0,r.useCallback)(()=>It({engineRef:W,toolRef:Et,externalToolMapRef:ut,spaceRef:Ut,docRef:Ht,selRef:Tt,draftRef:Ot,readOnlyRef:Mt,disableMarqueeRef:Nt,lockedRef:Pt,onLockedInteraction:()=>Ft.current?.(),onDrawAttemptWithoutDraft:()=>Bt.current?.(),createRef:xn,selectRef:Zt,enterEditRef:tn,editingIdRef:nn,drawSessionRef:Cn,assistantRef:Hn,setCursorHint:Jt,setInteractionMode:qt,syncMinimap:sn,onTransformPreview:_n,onDrawPreview:vn}),[Jt,qt,sn,_n,vn]),cr=(0,r.useRef)([]);fr({backend:V,hostRef:we,engineRef:W,documentId:He,renderedImageUrl:Qe,makeCallbacks:sr,viewRef:or,readOnlyRef:Mt,toolRef:Et,renderShapesRef:cr,coordinateSizeRef:Ct,imageSizeRef:wt,selRef:Tt,regionOverlayRef:bt,dimmedRef:xt,syncMinimap:sn,setImage:ke,setImageVisible:je,setReady:Me,setImageStatus:at,onContextMenuRequest:Pe});let $=(0,r.useMemo)(()=>{let e=S?q.shapes.map(e=>{let t=S(e);return t?{...e,interaction:{...e.interaction,...t}}:e}):q.shapes;return F?.length?[...F.map(e=>({...e,interaction:{...e.interaction,selectable:!1,draggable:!1,editable:!1,hitTestDisabled:!0}})),...e]:e},[q.shapes,S,F]);cr.current=$,(0,r.useEffect)(()=>{W.current?.setShapes($,Tt.current),sn()},[$,sn]),(0,r.useEffect)(()=>{W.current?.setSelection(J)},[J]),(0,r.useEffect)(()=>{W.current?.setEditing(Qt)},[Qt,K]);let lr=(0,r.useRef)(de);lr.current=de,(0,r.useEffect)(()=>{lr.current?.(Qt)},[Qt]),(0,r.useEffect)(()=>{$t(null)},[f]),(0,r.useEffect)(()=>{Qt&&(J.length!==1||J[0]!==Qt)&&$t(null)},[J,Qt]),(0,r.useEffect)(()=>{let e=W.current;e&&(e.setFilter(Y.brightness,Y.contrast),e.setRenderDefaults({strokeWidth:Y.strokeSize}),e.setImageSmoothing(Y.imageSmoothing),sn())},[Y.brightness,Y.contrast,Y.strokeSize,Y.imageSmoothing,sn]),(0,r.useLayoutEffect)(()=>{K&&W.current?.setOverlays(Y.showRegionMask?yt:null,c)},[K,yt,Y.showRegionMask,c]),(0,r.useEffect)(()=>{!K||!G||sn()},[K,G,Y.showRegionMask,I,sn]),(0,r.useEffect)(()=>{K&&W.current?.setTransformEnabled(!Z&&f!==U.BRUSH)},[Z,K,f]),(0,r.useEffect)(()=>{v&&$t(null)},[v]),(0,r.useEffect)(()=>{zn(f,ut.current.has(f))},[f,zn]);let ur=Q.finalize;(0,r.useEffect)(()=>{ur()},[f,ur]),(0,r.useEffect)(()=>{Wt.current=`idle`,Gt.current=null,Kt()},[f,V,Kt]),(0,r.useEffect)(()=>{Bn(J,Z)},[J,f,Z,Bn]),(0,r.useEffect)(()=>{K&&Kt()},[f,Fe,lt,K,Kt]);let dr=(0,r.useRef)(Ze);dr.current=Ze;let pr=t!==null,mr=(0,r.useRef)(null);(0,r.useEffect)(()=>{let e=pr?He:null;mr.current!==e&&(mr.current=e,Pe(null),$t(null),Wt.current=`idle`,Gt.current=null,q.reset(pr?Xe??[]:[]),Xt(pr?dr.current??[]:[]),wn(),ur(),Kt())},[pr,He,Xe,q.reset,Xt,wn,ur,Kt]);let hr=(0,r.useCallback)(()=>{let e=nn.current;if(!e||Z)return!1;let t=W.current,n=new Set(t?.getVertexSelection()??[]);if(!n.size)return!1;let r=Ht.current.getShapes().find(t=>t.id===e);if(!r)return!1;let i=r.points.filter((e,t)=>!n.has(t)),a=r.type===o.LINE?2:3;return i.length<a?!1:(Ht.current.update([{...r,points:i}]),t?.setVertexSelection([]),!0)},[Z]),gr=()=>q.getShapes().some(e=>Tt.current.includes(e.id)&&u(e));yn({keymap:oe,hostRef:we,actions:{undo:()=>{Z||Tn()||q.undo()},redo:()=>{Z||En()||q.redo()},selectAll:Wn,copy:qn,cut:()=>{zt(gr())||(qn(),Kn())},paste:()=>{zt(Jn())||Yn()},duplicate:()=>{zt(gr())||Xn()},delete:()=>{zt(gr())||An()&&Rn()||hr()||Kn()},cancel:()=>{let e=ut.current.get(Et.current);if(!(e?.onCancel&&e.onCancel()!==!1)){if(Q.isActive()){Q.cancel();return}if(kn()){wn();return}if(Qt){$t(null);return}if(Tt.current.length){Gn();return}x?.()}},commitDraft:()=>{if(Q.isActive()){Q.finalize();return}if(kn()){jn();return}if(Z)return;if(Qt){$t(null);return}let e=Tt.current;if(e.length!==1)return;let t=Ht.current.getShapes().find(t=>t.id===e[0]);t&&(t.type===o.POLYGON||t.type===o.LINE)&&t.interaction?.editable!==!1&&!t.readOnly&&$t(e[0])},bringToFront:Zn,sendToBack:Qn,zoomIn:()=>ar(1.2),zoomOut:()=>ar(1/1.2),zoom100:()=>W.current?.zoom100(),zoomFit:()=>W.current?.fit(),toggleMinimap:()=>ze(e=>!e),toggleCursorGuide:()=>mt(e=>({...e,showCursorGuide:!e.showCursorGuide})),togglePixelation:()=>mt(e=>({...e,imageSmoothing:!e.imageSmoothing})),selectTool:()=>H?.(U.SELECT),rectangleTool:()=>H?.(U.RECTANGLE),rotatedRectangleTool:()=>H?.(U.ROTATED_RECTANGLE),circleTool:()=>H?.(U.CIRCLE),polygonTool:()=>H?.(U.POLYGON),pathTool:()=>H?.(U.PATH),brushTool:()=>H?.(U.BRUSH),pointTool:()=>H?.(U.POINT)},spaceRef:Ut,onSpaceDown:()=>{W.current?.setPanMode(!0),Kt()},onSpaceUp:()=>{W.current?.setPanMode(!1),Wt.current===`panning`?qt(`idle`):Kt()},nudge:(e,t)=>zt(gr())||$n(e,t)});let vr=(0,r.useMemo)(()=>$.filter(e=>J.includes(e.id)&&s(e)),[$,J]),br=(0,r.useMemo)(()=>mn?[...vr,mn]:vr,[vr,mn]),Er=J.length>0,Dr=q.shapes.some(e=>J.includes(e.id)&&u(e)),Or=!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})(),kr=er(),Ar=Z||kr.length<2||(M?!M(kr):!1),jr=!!B&&!Z,Mr=jr&&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,Nr=[{id:`copy`,label:X.contextMenu.copy,shortcut:`⌘C`,disabled:!Dr,onClick:qn},{id:`paste`,label:X.contextMenu.paste,shortcut:`⌘V`,disabled:Z||!Jn(),onClick:()=>Yn(Ne?.img)},{id:`duplicate`,label:X.contextMenu.duplicate,shortcut:`⌘D`,disabled:!Dr||Z,onClick:Xn},{id:`delete`,label:X.contextMenu.delete,shortcut:`Del`,danger:!0,disabled:!Dr||Z,onClick:Kn},{separator:!0},{id:`editVertices`,label:X.contextMenu.editVertices,shortcut:`Enter`,disabled:!Or,onClick:()=>$t(J[0])},{id:`merge`,label:X.contextMenu.merge,disabled:Ar,onClick:tr},...jr?[{id:`assistExpand`,label:X.contextMenu.assistExpand,icon:(0,n.jsx)(e.rr,{size:14}),disabled:!Mr,onClick:()=>{Ne&&Mr&&Q.refineShape(Mr,Ne.img,!0)}},{id:`assistExclude`,label:X.contextMenu.assistExclude,icon:(0,n.jsx)(e.rr,{size:14}),disabled:!Mr,onClick:()=>{Ne&&Mr&&Q.refineShape(Mr,Ne.img,!1)}}]:[],{id:`bringToFront`,label:X.contextMenu.bringToFront,disabled:!Dr||Z,onClick:Zn},{id:`sendToBack`,label:X.contextMenu.sendToBack,disabled:!Dr||Z,onClick:Qn},{separator:!0},{id:`undo`,label:X.contextMenu.undo,shortcut:`⌘Z`,disabled:Z||!Dn()&&!q.canUndo(),onClick:()=>{Tn()||q.undo()}},{id:`redo`,label:X.contextMenu.redo,shortcut:`⇧⌘Z`,disabled:Z||!On()&&!q.canRedo(),onClick:()=>{En()||q.redo()}},{separator:!0},{id:`selectAll`,label:X.contextMenu.selectAll,shortcut:`⌘A`,onClick:Wn},{id:`clearSelection`,label:X.contextMenu.clearSelection,disabled:!Er,onClick:Gn},{id:`zoomToSelection`,label:X.contextMenu.zoomToSelection,disabled:!Er,onClick:ir}],Pr=g?Nr.filter(e=>`separator`in e||!!e.id&&wr.has(e.id)):Nr,Fr=k?k(Pr,{selectedIds:J,readOnly:Z}):Pr,Ir=_r({engineRef:W,image:G,wheelZoom:Y.wheelZoom,minimapSize:204}),Lr=(0,r.useCallback)(()=>{W.current?.zoom100()},[]),Rr=(0,r.useCallback)(()=>{ze(e=>!e)},[]),zr=(0,r.useCallback)(()=>{Ve(e=>!e)},[]),Br=(0,r.useCallback)(()=>{Ve(!1)},[]);return(0,n.jsxs)(`div`,{className:`aivex:relative aivex:h-full aivex:w-full aivex:overflow-hidden aivex:bg-black`,children:[(0,n.jsx)(`div`,{ref:we,role:`application`,"aria-label":X.canvasLabel,tabIndex:0,onPointerDownCapture:e=>e.currentTarget.focus({preventScroll:!0}),className:`aivex:h-full aivex:w-full`,style:{opacity:+!!Ae,transition:Ae?`opacity 0.3s ease`:`none`}}),tt!==`ready`&&(0,n.jsx)(xe,{status:tt,error:nt,render:a,loadingLabel:X.imageLoading,missingLabel:X.imageMissing,errorLabel:X.imageLoadError,errorHints:X.imageErrorHints}),K&&G&&(0,n.jsx)(`div`,{className:`aivex:pointer-events-none aivex:absolute aivex:inset-0 aivex:overflow-hidden`,children:(0,n.jsxs)(`div`,{ref:Ee,style:{position:`absolute`,top:0,left:0,width:G.w,height:G.h,transformOrigin:`0 0`},children:[!!L?.length&&te&&(0,n.jsx)(`div`,{style:{position:`absolute`,left:0,top:0,width:G.w,height:G.h,pointerEvents:`none`},children:L.map(e=>(0,n.jsx)(`div`,{role:e.disabled?void 0:`button`,tabIndex:e.disabled?void 0:0,"aria-pressed":e.selected||void 0,onClick:t=>{t.stopPropagation(),e.disabled||ne?.(e)},onKeyDown:t=>{e.disabled||t.key!==`Enter`&&t.key!==` `||(t.preventDefault(),t.stopPropagation(),ne?.(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:te(e)},e.id))}),re?.({image:G,viewport:W.current?.viewport??{scale:1,x:0,y:0}}),br.length>0&&(0,n.jsx)(qe,{shapes:br,getLabel:ie,hideDot:ae,formatInfo:R,register:fn}),B&&(Q.status===`loading`||Q.boxes.length>0)&&(0,n.jsx)(_e,{image:G,points:Q.points,boxes:Q.boxes,status:Q.status})]})}),K&&Y.showCursorGuide&&(0,n.jsx)(be,{color:`#1e88e5`}),G&&E&&(0,n.jsx)(Le,{image:G,imageUrl:Qe,imageVisible:Ae,loading:!K,region:yt,roiMaskId:Oe,shapes:$,view:Y,viewDefaults:ft,onChangeView:gt,nav:Ir,registerShape:an,rectRef:Te,zoomLabelRef:De,onZoom100:Lr,open:Re,onToggleOpen:Rr,position:D,labels:X.minimap,settingsLabels:X.viewSettings,settingsItems:j,showSettings:O,settingsOpen:Be,onToggleSettings:zr,onCloseSettings:Br}),Ne&&(0,n.jsx)(ye,{x:Ne.x,y:Ne.y,items:Fr,onClose:()=>Pe(null)})]})}function Dr({viewport:e,image:t,focusPoints:n,zoomPadding:r,focusFit:i}){let a=Math.min(e.width/t.width,e.height/t.height);if(!n?.length)return{scale:a,offsetX:(e.width-t.width*a)/2,offsetY:(e.height-t.height*a)/2};let o=g(n),s=Math.max(o.maxX-o.minX,50),c=Math.max(o.maxY-o.minY,50),l=Math.min(s,c)*r,u=Math.min(e.width/(s+l*2),e.height/(c+l*2));i===`cover`&&(u=Math.max(u,Math.max(e.width/t.width,e.height/t.height)));let d=e.width/2-(o.minX+o.maxX)/2*u,f=e.height/2-(o.minY+o.maxY)/2*u;return i===`cover`&&(d=Math.min(0,Math.max(d,e.width-t.width*u)),f=Math.min(0,Math.max(f,e.height-t.height*u))),{scale:u,offsetX:d,offsetY:f}}function Or(e,t,n){let r=Math.max(0,-e.offsetX/e.scale),i=Math.max(0,-e.offsetY/e.scale),a=Math.min(n.width,(t.width-e.offsetX)/e.scale),o=Math.min(n.height,(t.height-e.offsetY)/e.scale);return a<=r||o<=i?null:{x:r,y:i,width:a-r,height:o-i}}function kr({visible:e,image:t,natural:n,density:r}){let i=n.width/t.width,a=n.height/t.height,o=Math.max(0,Math.floor(e.x*i)),s=Math.max(0,Math.floor(e.y*a)),c=Math.min(n.width,Math.ceil((e.x+e.width)*i))-o,l=Math.min(n.height,Math.ceil((e.y+e.height)*a))-s,u={x:o/i,y:s/a,width:c/i,height:l/a};return{source:{x:o,y:s,width:c,height:l},rect:u,outputWidth:Math.max(1,Math.min(c,Math.ceil(u.width*r))),outputHeight:Math.max(1,Math.min(l,Math.ceil(u.height*r)))}}function Ar(e,t,n){let r=1e-6;if(!(e.rect.x<=t.x+r&&e.rect.y<=t.y+r&&e.rect.x+e.rect.width>=t.x+t.width-r&&e.rect.y+e.rect.height>=t.y+t.height-r))return!1;let i=Math.min(n.density,n.natural.width/n.image.width),a=Math.min(n.density,n.natural.height/n.image.height);return e.outputWidth/e.rect.width>=i*.99&&e.outputHeight/e.rect.height>=a*.99}function jr(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 Mr(e,t,n,r){if(t.interaction?.visible===!1)return;let i=Ee(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 jr(e,t.points,t.type!==o.LINE);i.fillVisible&&(e.save(),e.fillStyle=i.color,e.globalAlpha*=i.fillAlpha,e.fill(`evenodd`),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()}async function Nr(e,t,n){let r=await Cn(e);if(!r)return null;try{let i={width:r.width,height:r.height},a={url:e,smoothing:t,natural:i,bitmap:null,rect:{x:0,y:0,width:0,height:0},outputWidth:0,outputHeight:0},o=n(i);if(!o?.visibleRect)return a;let s=kr({visible:o.visibleRect,natural:i,...o}),c=await createImageBitmap(r.source,s.source.x,s.source.y,s.source.width,s.source.height,{resizeWidth:s.outputWidth,resizeHeight:s.outputHeight,resizeQuality:t?`high`:`pixelated`});return{...a,...s,bitmap:c}}catch{return null}finally{r.release()}}function Pr({imageUrl:e,alt:t=`Shape preview`,coordinateSize:i,shapes:a=[],regionMask:o,focusedShapeId:s,focusFit:c=`contain`,zoomPadding:l=.3,strokeSize:u=1,brightness:d=1,contrast:p=1,imageSmoothing:m=!0,lazy:h=!0,className:g,style:_,renderImageState:v}){let y=(0,r.useRef)(null),b=(0,r.useRef)(null),x=(0,r.useRef)(null),[S,C]=(0,r.useState)(!h),[w,T]=(0,r.useState)(`loading`),[E,D]=(0,r.useState)(null),[O,k]=(0,r.useState)(0),[A,j]=(0,r.useState)(0);(0,r.useEffect)(()=>{if(!h||S)return;let e=y.current;if(!e)return;let t=new IntersectionObserver(([e])=>{e.isIntersecting&&(C(!0),t.disconnect())});return t.observe(e),()=>t.disconnect()},[h,S]),(0,r.useEffect)(()=>{let e=y.current;if(!e)return;let t=new ResizeObserver(()=>k(e=>e+1));return t.observe(e),()=>t.disconnect()},[]);let M=(0,r.useMemo)(()=>a.find(e=>e.id===s),[s,a]);return(0,r.useEffect)(()=>{if(!S||!e){T(e?`loading`:`missing`),D(null);return}let t=y.current;if(!t)return;let{width:n,height:r}=t.getBoundingClientRect();if(!n||!r)return;let a={width:n,height:r},o=e=>{let t=i??e;if(!t.width||!t.height)return null;let n=Dr({viewport:a,image:t,focusPoints:M?.points,zoomPadding:l,focusFit:c});return{image:t,visibleRect:Or(n,a,t),density:n.scale*(window.devicePixelRatio||1)}},s=x.current;if(s?.url===e&&s.smoothing===m){let e=o(s.natural);if(!e?.visibleRect||s.bitmap&&Ar(s,e.visibleRect,{...e,natural:s.natural}))return}else s?.url!==e&&(T(`loading`),D(null));let u=!0;return(async()=>{let t=await Dn(()=>u?Nr(e,m,o):Promise.resolve(void 0));if(!u){t?.bitmap?.close();return}if(t===null){x.current?.bitmap?.close(),x.current=null,T(`error`);let t=await Mn(e);u&&D(t);return}t&&(x.current?.bitmap?.close(),x.current=t,T(`ready`),j(e=>e+1))})(),()=>{u=!1}},[i,M,c,m,e,O,S,l]),(0,r.useEffect)(()=>()=>{x.current?.bitmap?.close(),x.current=null},[]),(0,r.useEffect)(()=>{if(w===`error`){let e=b.current;e?.getContext(`2d`)?.clearRect(0,0,e.width,e.height)}if(w!==`ready`)return;let e=y.current,t=b.current,n=x.current;if(!e||!t||!n)return;let{width:r,height:s}=e.getBoundingClientRect();if(!r||!s)return;let h=window.devicePixelRatio||1;t.width=Math.max(1,Math.round(r*h)),t.height=Math.max(1,Math.round(s*h)),t.style.width=`${r}px`,t.style.height=`${s}px`;let g=t.getContext(`2d`);if(!g)return;let _=i?.width??n.natural.width,v=i?.height??n.natural.height;if(!_||!v)return;let{scale:S,offsetX:C,offsetY:T}=Dr({viewport:{width:r,height:s},image:{width:_,height:v},focusPoints:M?.points,zoomPadding:l,focusFit:c});g.setTransform(h,0,0,h,0,0),g.clearRect(0,0,r,s),g.save(),g.translate(C,T),g.scale(S,S),g.imageSmoothingEnabled=m;let E=fe({brightness:d,contrast:p});if(g.filter=`brightness(${E.brightness}) contrast(${E.contrast})`,n.bitmap){let{x:e,y:t,width:r,height:i}=n.rect;g.drawImage(n.bitmap,e,t,r,i)}g.filter=`none`;let D=o?Dt(o,_,v):null;if(D&&(xt(g,D,_,v),D.outlineStyles)){let e=(e,t)=>{if(g.lineWidth=t.width/S,t.underlayColor){g.setLineDash([]),g.strokeStyle=t.underlayColor;for(let[t,n]of e)jr(g,[t,n],!1),g.stroke()}g.save(),g.globalAlpha*=t.opacity,g.setLineDash(t.dash.map(e=>e/S)),g.strokeStyle=t.color;for(let[t,n]of e)jr(g,[t,n],!1),g.stroke();g.restore()};e(D.visibleOutline,D.outlineStyles.visible),e(D.occludedOutline,D.outlineStyles.occluded)}for(let e of f(a))Mr(g,e,S,u);g.restore()},[d,p,i,M,c,m,A,o,a,O,w,u,l]),(0,n.jsxs)(`div`,{ref:y,className:g,style:{position:`relative`,width:`100%`,height:`100%`,..._},children:[(0,n.jsx)(`canvas`,{ref:b,role:`img`,"aria-label":t,style:{display:`block`}}),w!==`ready`&&(0,n.jsx)(`div`,{style:{position:`absolute`,inset:0},children:v?.(w,E)??(w===`missing`?(0,n.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,height:`100%`,padding:8,textAlign:`center`,color:`rgba(255,255,255,0.7)`,background:`rgba(13,13,18,0.85)`,fontSize:12},children:H.imageMissing}):w===`error`?(0,n.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,height:`100%`,gap:4,padding:8,textAlign:`center`,color:`rgba(255,255,255,0.85)`,background:`rgba(13,13,18,0.85)`,fontSize:12},children:[(0,n.jsx)(`span`,{"aria-hidden":!0,children:`⚠`}),(0,n.jsx)(`span`,{children:H.imageLoadError}),E&&(0,n.jsx)(`span`,{style:{fontSize:11,opacity:.7,wordBreak:`break-all`},children:H.imageErrorHints[E.kind]})]}):null)})]})}exports.DEFAULT_EDITOR_STRINGS=H,exports.DEFAULT_VIEW_SETTINGS=le,exports.SHAPE_TYPE=o,exports.ShapeEditor=Er,exports.default=Er,exports.ShapeViewer=Pr,exports.TOOL=U,exports.VIEW_SETTING_RANGES=ue,exports.clampViewSettings=fe,exports.generateId=m;
|
|
1
|
+
"use client";require(`./styles.css`),Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require(`./Button-EEErevS-.cjs`),t=require(`./keyboard-DCewgvMV.cjs`);let n=require(`react/jsx-runtime`),r=require(`react`),i=require(`konva`);i=e.ha(i,1),require(`pixi.js/unsafe-eval`);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(e,t,n){return Math.max(t,Math.min(n,e))}function m(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`id_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}var h=[`tl`,`t`,`tr`,`r`,`br`,`b`,`bl`,`l`];function g(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 _(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 v(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 y(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 b(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 x(e){let t=g(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 S(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 C(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 w(e){let t=C(e);if(t.length<3)return x(e);let n=1/0,r=x(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 T=(e,t)=>({x:e.x-t.x,y:e.y-t.y}),E=(e,t)=>e.x*t.x+e.y*t.y,D=e=>Math.hypot(e.x,e.y),O=e=>{let t=D(e)||1;return{x:e.x/t,y:e.y/t}},k=(e,t)=>({x:(e.x+t.x)/2,y:(e.y+t.y)/2}),A=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 j(e){return[e[0],k(e[0],e[1]),e[1],k(e[1],e[2]),e[2],k(e[2],e[3]),e[3],k(e[3],e[0])]}function M(e,t){let n=k(e[0],e[1]),r=O(T(e[0],e[3]));return{x:n.x+r.x*t,y:n.y+r.y*t}}function N(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 P(e,t,n){if(e.length<4)return e;let r=e[0],i=O(T(e[1],e[0])),a=O(T(e[3],e[0])),o=E(T(e[1],r),i),s=E(T(e[3],r),a),c=T(n,r);return N(v(t,{minX:0,minY:0,maxX:o,maxY:s},E(c,i),E(c,a)),r,i,a)}function F(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}))}function I(e){let t=e.length,n=Array.from({length:t},(n,r)=>{let i=e[r],a=e[(r+1)%t];return{i:r,minX:Math.min(i.x,a.x),maxX:Math.max(i.x,a.x),minY:Math.min(i.y,a.y),maxY:Math.max(i.y,a.y)}}).sort((e,t)=>e.minX-t.minX),r=[];for(let i=0;i<t;i++){let a=n[i];for(let o=i+1;o<t&&n[o].minX<=a.maxX;o++){let i=n[o];if(i.minY>a.maxY||i.maxY<a.minY)continue;let s=Math.min(a.i,i.i),c=Math.max(a.i,i.i);if(c===s+1||s===0&&c===t-1)continue;let l=L(e[s],e[(s+1)%t],e[c],e[(c+1)%t]);l&&r.push({i:s,j:c,ti:l.ti,tj:l.tj})}}return r}function L(e,t,n,r){let i=t.x-e.x,a=t.y-e.y,o=r.x-n.x,s=r.y-n.y,c=i*s-a*o;if(!c)return null;let l=((n.x-e.x)*s-(n.y-e.y)*o)/c,u=((n.x-e.x)*a-(n.y-e.y)*i)/c,d=1e-9;return l<=d||l>=1-d||u<=d||u>=1-d?null:{ti:l,tj:u}}var R=(e,t)=>e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY,ee=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x),te=(e,t,n)=>ee(e,t,n)===0&&Math.min(e.x,t.x)<=n.x&&n.x<=Math.max(e.x,t.x)&&Math.min(e.y,t.y)<=n.y&&n.y<=Math.max(e.y,t.y);function ne(e,t,n,r){let i=ee(n,r,e),a=ee(n,r,t),o=ee(e,t,n),s=ee(e,t,r);return(i>0&&a<0||i<0&&a>0)&&(o>0&&s<0||o<0&&s>0)?!0:te(n,r,e)||te(n,r,t)||te(e,t,n)||te(e,t,r)}function re(e,t,n){if(R(e,n)||R(t,n))return!0;let r={x:n.minX,y:n.minY},i={x:n.maxX,y:n.minY},a={x:n.maxX,y:n.maxY},o={x:n.minX,y:n.maxY};return ne(e,t,r,i)||ne(e,t,i,a)||ne(e,t,a,o)||ne(e,t,o,r)}function ie(e,t){let n=!1;for(let r=0,i=t.length-1;r<t.length;i=r++){let a=t[r],o=t[i];a.y>e.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(n=!n)}return n}function z(e,t,n){if(e.some(e=>R(e,t)))return!0;let r=n?e.length:e.length-1;for(let n=0;n<r;n+=1)if(re(e[n],e[(n+1)%e.length],t))return!0;return!1}function B(e,t){let n=e.points;if(!n.length)return!1;let r=g(n);if(r.minX>t.maxX||r.maxX<t.minX||r.minY>t.maxY||r.maxY<t.minY)return!1;switch(e.type){case o.POINT:return R(n[0],t);case o.RECTANGLE:return!0;case o.ELLIPSE:{let e=(r.maxX-r.minX)/2,n=(r.maxY-r.minY)/2;if(e<=0||n<=0)return!0;let i=(r.minX+r.maxX)/2,a=(r.minY+r.maxY)/2,o=p(i,t.minX,t.maxX),s=p(a,t.minY,t.maxY);return((o-i)/e)**2+((s-a)/n)**2<=1}case o.LINE:return z(n,t,!1);case o.POLYGON:case o.ROTATED_RECTANGLE:return z(n,t,!0)||n.length>=3&&ie({x:t.minX,y:t.minY},n);default:return!0}}var V=e=>{let t=0;for(let n=0,r=e.length-1;n<e.length;r=n++)t+=(e[r].x-e[n].x)*(e[r].y+e[n].y);return t/2};function ae(e,t,n,r){let i=0,a=n.length;for(let o=0,s=a-1;o<a;s=o++){let a=n[s],c=n[o],l=(a.x-e.x)*t.y-(a.y-e.y)*t.x,u=(c.x-e.x)*t.y-(c.y-e.y)*t.x;if(l>0==u>0)continue;let d=(a.x-e.x)*t.x+(a.y-e.y)*t.y;d+((c.x-e.x)*t.x+(c.y-e.y)*t.y-d)*l/(l-u)>r&&(i+=l>0?-1:1)}return i}function oe(e){let t=e[0],n=e[1],r=-(n.y-t.y),i=n.x-t.x;V(e)<0&&(r=-r,i=-i);let a=Math.hypot(r,i);return a?{x:r/a,y:i/a}:null}function H(e,t=4096){let n=[{outline:e,holes:[],layers:1}],r=e.length;if(r<4||r>t)return n;let i=I(e);if(!i.length)return n;let a=Array.from({length:r},()=>[]);for(let t of i){let n=e[t.i],i=e[(t.i+1)%r],o={x:n.x+(i.x-n.x)*t.ti,y:n.y+(i.y-n.y)*t.ti};a[t.i].push({t:t.ti,p:o}),a[t.j].push({t:t.tj,p:o})}let o=[];for(let t=0;t<r;t++){o.push(e[t]);for(let e of a[t].sort((e,t)=>e.t-t.t))o.push(e.p)}let s=new Map,c=[],l=e=>{let t=s.get(e);return t===void 0&&(t=c.length,s.set(e,t),c.push(e)),t},u=o.length,d=[],f=[];for(let e=0;e<u;e++){let t=l(o[e]),n=l(o[(e+1)%u]);t!==n&&(d.push(t,n),f.push(n,t))}let p=d.length;if(!p)return n;let m=Array.from({length:c.length},()=>[]);for(let e=0;e<p;e++)m[d[e]].push(e);for(let e of m)e.sort((e,t)=>Math.atan2(c[f[e]].y-c[d[e]].y,c[f[e]].x-c[d[e]].x)-Math.atan2(c[f[t]].y-c[d[t]].y,c[f[t]].x-c[d[t]].x));let h=e=>e%2==0?e+1:e-1,g=e=>{let t=m[f[e]];return t[(t.indexOf(h(e))-1+t.length)%t.length]},_=Array(p).fill(!1),v=[];for(let e=0;e<p;e++){if(_[e])continue;let t=[],n=e,r=0;do _[n]=!0,t.push(c[d[n]]),n=g(n);while(n!==e&&!_[n]&&r++<=p);t.length>=3&&v.push(t)}let y=v.map(V),b=Math.sign(y.reduce((e,t)=>Math.abs(t)>Math.abs(e)?t:e,0)),x=v.map((e,t)=>t).filter(e=>Math.sign(y[e])===-b),S=new Set;for(let e of a)for(let t of e)S.add(t.p);let C=e=>{let t=0,n=new Set;for(let r of e)S.has(r)&&!n.has(r)&&(n.add(r),t++);return t},w=[];for(let t of x){let n=oe(v[t]);if(!n)continue;let r=v[t][0],i=v[t][1],a=1e-9*(Math.abs(r.x-i.x)+Math.abs(r.y-i.y)+1),o=Math.abs(ae(k(r,i),n,e,a));o%2==0&&C(v[t])===1||w.push({outline:v[t],holes:[],layers:Math.max(1,o)})}return w.length?w:n}var U={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:`마우스 가이드라인 표시`,regionMask:`ROI 표시`,keepZoomOnImageChange:`이미지 변경시 확대 유지`,wheelZoom:`스크롤만 사용하여 확대 축소`,zoomSensitivity:`확대 축소 민감도`},minimap:{zoomIn:`확대`,zoomOut:`축소`,zoom100:`100%로 초기화`,viewSettings:`보기 설정`,toggleMinimap:`미니맵 접기/펼치기`},canvasLabel:`이미지 편집 영역`,imageLoading:`이미지를 불러오는 중…`,imageMissing:`표시할 이미지가 없습니다`,imageLoadError:`이미지를 불러올 수 없습니다`,imageErrorHints:{"mixed-content":`HTTPS 페이지에서 HTTP 이미지 요청은 혼합 콘텐츠 정책에 따라 차단됩니다. 이미지 스토리지의 HTTPS 전환이 필요합니다.`,cors:`이미지 스토리지 응답에 Access-Control-Allow-Origin 헤더가 없습니다. 스토리지 또는 프록시의 CORS 설정이 필요합니다.`,auth:`이미지 서버가 세션 인증(쿠키)을 요구합니다. 에디터의 이미지 요청은 자격 증명 없이 전송되므로 스토리지 인증 방식 검토가 필요합니다.`,forbidden:`이미지 접근이 거부되었습니다. 서명 URL(presigned) 만료 또는 접근 권한 설정 점검이 필요합니다.`,"not-found":`요청한 이미지가 서버에 존재하지 않습니다. 파일 삭제·이동 여부 확인이 필요합니다.`,"server-error":`이미지 서버가 내부 오류를 반환했습니다. 스토리지 서버 상태 점검이 필요합니다.`,http:`이미지 서버가 오류 상태 코드를 반환했습니다.`,offline:`네트워크 연결이 감지되지 않습니다. 클라이언트 네트워크 상태 확인이 필요합니다.`,network:`이미지 서버에 도달할 수 없습니다. 네트워크 경로·방화벽·DNS 구성 점검이 필요합니다.`,"unexpected-content":`이미지 대신 다른 형식의 응답이 수신되었습니다. 게이트웨이의 인증 리다이렉트 여부 확인이 필요합니다.`,decode:`전송은 정상이나 이미지 디코딩에 실패했습니다. 파일 손상 또는 미지원 형식일 수 있습니다.`,"csp-img":`콘텐츠 보안 정책(CSP)의 img-src 지시어가 이미지 표시를 차단하고 있습니다. 정책에 이미지 스토리지 출처 추가가 필요합니다.`,"csp-eval":`콘텐츠 보안 정책(CSP)이 동적 스크립트 실행(unsafe-eval)을 차단하여 렌더러 초기화에 실패했습니다.`,webgl:`WebGL 컨텍스트를 생성할 수 없습니다. 하드웨어 가속 설정 또는 브라우저 보안 정책(Edge 보안 강화 모드 등) 점검이 필요합니다.`,"renderer-init":`캔버스 렌더러 초기화 또는 렌더링 중 오류가 발생했습니다.`,unknown:`원인이 특정되지 않은 오류입니다. 아래 상세 정보와 함께 기술 지원에 문의하시기 바랍니다.`}};function se(e){return e?{contextMenu:{...U.contextMenu,...e.contextMenu},viewSettings:{...U.viewSettings,...e.viewSettings},minimap:{...U.minimap,...e.minimap},canvasLabel:e.canvasLabel??U.canvasLabel,imageLoading:e.imageLoading??U.imageLoading,imageMissing:e.imageMissing??U.imageMissing,imageLoadError:e.imageLoadError??U.imageLoadError,imageErrorHints:{...U.imageErrorHints,...e.imageErrorHints}}:U}var W={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`},ce={brightness:1,contrast:1,showCursorGuide:!1,imageSmoothing:!0,strokeSize:2,simplifyStrength:1.5,showRegionMask:!0,keepZoomOnImageChange:!1,wheelZoom:!0,zoomSensitivity:1},le={brightness:{min:.5,max:1.5,step:.05},contrast:{min:.5,max:1.5,step:.05},strokeSize:{min:1,max:10,step:.5},simplifyStrength:{min:.5,max:5,step:.5},zoomSensitivity:{min:.2,max:3,step:.1}},ue=Object.keys(le);function de(e){let t={};for(let n of ue){let r=e[n];if(r===void 0)continue;let{min:i,max:a}=le[n],o=Number.isFinite(r)?Math.min(a,Math.max(i,r)):ce[n];o!==r&&(t[n]=o)}return Object.keys(t).length?{...e,...t}:e}var fe=`var(--editor-overlay-inverse-scale, 1)`,pe=`#377be2`,me=`#e23c3c`;function he({point:e}){let t=e.positive?pe:me;return(0,n.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(${fe})`,transformOrigin:`center`},children:e.positive?`+`:`−`})}function ge({image:e,points:t,boxes:r,status:i}){return(0,n.jsxs)(`div`,{style:{position:`absolute`,left:0,top:0,width:e.w,height:e.h,pointerEvents:`none`},children:[(0,n.jsx)(`style`,{children:`@keyframes editorv2-assistant-shimmer{from{background-position:200% 0}to{background-position:-200% 0}}`}),r.map((e,t)=>(0,n.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,n.jsx)(he,{point:e},`pt-${t}-${e.x}-${e.y}`))]})}function _e(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 ve({x:e,y:r,items:i,onClose:a}){let o=_e(i);return(0,n.jsxs)(t.c,{open:!0,modal:!1,onOpenChange:e=>{e||a()},children:[(0,n.jsx)(t.c.Trigger,{asChild:!0,children:(0,n.jsx)(`span`,{"aria-hidden":!0,style:{position:`absolute`,left:e,top:r,width:0,height:0}})}),(0,n.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,r)=>`separator`in e?(0,n.jsx)(t.c.Separator,{className:`aivex:shrink-0`},`sep-${r}`):(0,n.jsx)(t.c.Item,{danger:e.danger,disabled:e.disabled,className:`aivex:shrink-0`,onSelect:()=>e.onClick(),children:(0,n.jsxs)(`span`,{className:`aivex:flex aivex:w-full aivex:items-center aivex:justify-between aivex:gap-6`,children:[(0,n.jsxs)(`span`,{className:`aivex:flex aivex:min-w-0 aivex:items-center aivex:gap-1.5`,children:[e.icon,(0,n.jsx)(`span`,{className:`aivex:truncate`,children:e.label})]}),e.shortcut&&(0,n.jsx)(t.c.Shortcut,{children:e.shortcut})]})},e.label))})]})}function ye({color:e=`#1e88e5`}){let t=(0,r.useRef)(null),i=(0,r.useRef)(null),a=(0,r.useRef)(null);return(0,r.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,n.jsxs)(`div`,{ref:t,className:`aivex:pointer-events-none aivex:absolute aivex:inset-0 aivex:overflow-hidden`,children:[(0,n.jsx)(`div`,{ref:i,style:{position:`absolute`,top:0,left:0,width:1,height:`100%`,background:e,opacity:.6,display:`none`}}),(0,n.jsx)(`div`,{ref:a,style:{position:`absolute`,top:0,left:0,width:`100%`,height:1,background:e,opacity:.6,display:`none`}})]})}function be({status:e,error:t,render:r,loadingLabel:i=U.imageLoading,missingLabel:a=U.imageMissing,errorLabel:o=U.imageLoadError,errorHints:s=U.imageErrorHints}){let c=r?.(e,t)??null;return(0,n.jsx)(`div`,{"data-track-id":e===`loading`?`editor-image-loading-wrap`:e===`missing`?`editor-image-missing-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:c===null?e===`missing`?(0,n.jsx)(`div`,{style:{fontSize:13,opacity:.75},children:a}):e===`loading`?(0,n.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10,fontSize:13},children:[(0,n.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`}}),i,(0,n.jsx)(`style`,{children:`@keyframes editorv2-image-spin{to{transform:rotate(360deg)}}`})]}):(0,n.jsxs)(`div`,{style:{textAlign:`center`,opacity:.85,maxWidth:420,padding:`0 16px`},children:[(0,n.jsx)(`div`,{style:{fontSize:28,marginBottom:6},children:`⚠`}),(0,n.jsx)(`div`,{style:{fontSize:13},children:o}),t&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(`div`,{style:{fontSize:12,marginTop:8,opacity:.8,lineHeight:1.5},children:s[t.kind]}),(0,n.jsx)(`div`,{style:{fontSize:11,marginTop:6,opacity:.55,fontFamily:`ui-monospace, monospace`,wordBreak:`break-all`},children:t.detail})]})]}):c})}Math.PI/12;var xe=`#00ff00`,Se=`rgba(0, 255, 0, 0.1)`,Ce=`#669DEF`,G=.1,we=[3,3];function Te(e,t={}){let n=e.style?.color??`#00e5ff`,r=e.style?.strokeWidth??t.strokeWidth??2,i=e.style?.opacity??1,a=e.style?.fillOpacity??.12549019607843137,o=e.style?.dash??(e.style?.dashed?[r*we[0],r*we[1]]:void 0);return{color:n,strokeWidth:r,opacity:i,fillAlpha:a,fillVisible:!!e.style?.filled,dash:o,pointRadius:e.style?.pointRadius??t.pointRadius??5}}function Ee(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}var De=(0,r.memo)(function({shape:e,strokeSize:t,register:r}){let{type:i,points:a}=e,s=Te(e,{strokeWidth:t}),c=t=>r?.(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,n.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=g(a);return i===o.ELLIPSE?(0,n.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,n.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,n.jsx)(`polyline`,{points:u,...l}):(0,n.jsx)(`polygon`,{points:u,fillRule:`evenodd`,...l})});function K({image:e,region:t,maskId:r,width:i,height:a,strokeWidth:o,strokeDasharray:s,style:c}){let l=[...t.visibleOutline,...t.occludedOutline];return(0,n.jsxs)(`svg`,{width:i,height:a,viewBox:`0 0 ${e.w} ${e.h}`,style:c,"aria-hidden":!0,children:[(0,n.jsx)(`defs`,{children:(0,n.jsxs)(`mask`,{id:r,children:[(0,n.jsx)(`rect`,{x:0,y:0,width:e.w,height:e.h,fill:`white`}),t.rects.map((e,t)=>(0,n.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,n.jsx)(`polygon`,{points:e.points.map(e=>`${e.x},${e.y}`).join(` `),fill:`white`},`occ-${t}`))]})}),(0,n.jsx)(`rect`,{x:0,y:0,width:e.w,height:e.h,fill:t.dim.color,fillOpacity:t.dim.opacity,mask:`url(#${r})`}),l.length>0&&(0,n.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 Oe=[`brightness`,`contrast`,`strokeSize`,`simplifyStrength`,`zoomSensitivity`,`pixelation`,`cursorGuide`,`regionMask`,`keepZoomOnImageChange`,`wheelZoom`],ke=new Set([`brightness`,`contrast`,`strokeSize`,`simplifyStrength`,`zoomSensitivity`]);function Ae({value:r,defaults:i,onChange:a,labels:o=U.viewSettings,items:s=Oe,openDown:c=!1,alignEnd:l=!1}){return(0,n.jsxs)(t.s.Content,{"aria-label":o.title,side:c?`bottom`:`top`,align:l?`end`:`start`,sideOffset:8,className:`aivex:max-h-none aivex:overflow-visible aivex:shadow-[var(--aivex-elevation-md)]`,children:[(0,n.jsx)(`div`,{className:`aivex:px-xs aivex:text-body-md`,children:o.title}),(0,n.jsxs)(`div`,{className:`aivex:flex aivex:flex-col aivex:gap-md`,children:[s.filter(e=>ke.has(e)).map(e=>{let i=Me[e];return(0,n.jsx)(Pe,{icon:i.icon,label:o[e],value:i.format(r[e]),children:(0,n.jsx)(t.i,{...le[e],value:[r[e]],onValueChange:([t])=>a({[e]:t})})},e)}),(0,n.jsx)(`div`,{className:`aivex:flex aivex:flex-col aivex:gap-xs`,children:s.filter(e=>!ke.has(e)).map(e=>{let t=Ne[e];return(0,n.jsx)(Fe,{checked:t.checked(r),label:o[e],onChange:e=>a(t.patch(e))},e)})}),(0,n.jsx)(t.a,{})]}),(0,n.jsx)(`div`,{className:`aivex:flex aivex:justify-end`,children:(0,n.jsxs)(e.t,{variant:`solid`,color:`secondary`,size:`md`,onClick:()=>a({...i}),children:[(0,n.jsx)(e.$r,{size:20}),o.reset]})})]})}function je(e){return`${Math.round(e*100)}%`}var Me={brightness:{icon:(0,n.jsx)(e.Q,{size:16}),format:je},contrast:{icon:(0,n.jsx)(e.Dt,{size:16}),format:je},strokeSize:{icon:(0,n.jsx)(e.Ai,{size:16}),format:String},simplifyStrength:{icon:(0,n.jsx)(e.Nr,{size:16}),format:String},zoomSensitivity:{icon:(0,n.jsx)(e.la,{size:16}),format:e=>e.toFixed(1)}},Ne={pixelation:{checked:e=>!e.imageSmoothing,patch:e=>({imageSmoothing:!e})},cursorGuide:{checked:e=>e.showCursorGuide,patch:e=>({showCursorGuide:e})},regionMask:{checked:e=>e.showRegionMask,patch:e=>({showRegionMask:e})},keepZoomOnImageChange:{checked:e=>e.keepZoomOnImageChange,patch:e=>({keepZoomOnImageChange:e})},wheelZoom:{checked:e=>e.wheelZoom,patch:e=>({wheelZoom:e})}};function Pe({icon:e,label:t,value:r,children:i}){return(0,n.jsxs)(`div`,{className:`aivex:flex aivex:flex-col aivex:px-md aivex:py-2xs`,children:[(0,n.jsxs)(`div`,{className:`aivex:flex aivex:items-center aivex:gap-xs`,children:[(0,n.jsx)(`span`,{className:`aivex:flex aivex:h-4 aivex:items-center aivex:text-text-secondary`,children:e}),(0,n.jsx)(`span`,{className:`aivex:flex-1 aivex:truncate aivex:text-label-md`,children:t}),(0,n.jsx)(`span`,{className:`aivex:tabular-nums aivex:text-label-md aivex:text-text-secondary`,children:r})]}),(0,n.jsx)(`div`,{className:`aivex:flex aivex:h-5 aivex:items-center`,children:i})]})}function Fe({label:e,checked:r,onChange:i}){return(0,n.jsxs)(`div`,{className:`aivex:flex aivex:items-center aivex:gap-md aivex:rounded-md aivex:px-md aivex:py-sm`,children:[(0,n.jsx)(`span`,{className:`aivex:flex-1 aivex:truncate aivex:text-label-lg`,children:e}),(0,n.jsx)(t.r,{size:`md`,checked:r,onCheckedChange:i})]})}var Ie={"bottom-left":`aivex:bottom-2 aivex:left-2`,"bottom-right":`aivex:bottom-2 aivex:right-2`,"top-left":`aivex:top-2 aivex:left-2`,"top-right":`aivex:top-2 aivex:right-2`},Le=(0,r.memo)(function({image:r,imageUrl:i,imageVisible:a=!0,loading:o=!1,region:c,roiMaskId:l,shapes:u,view:d,viewDefaults:p,onChangeView:m,nav:h,registerShape:g,rectRef:_,zoomLabelRef:v,onZoom100:y,open:b,onToggleOpen:x,position:S=`bottom-left`,showSettings:C=!0,settingsOpen:w,onToggleSettings:T,onCloseSettings:E,labels:D=U.minimap,settingsLabels:O,settingsItems:k}){let{offX:A,offY:j,dispW:M,dispH:N,zoomCentered:P}=h,F=S.startsWith(`top`),I={position:`absolute`,left:A,top:j,width:M,height:N},L=(0,n.jsx)(`div`,{className:`aivex:overflow-hidden aivex:rounded-sm aivex:transition-all aivex:duration-200 aivex:ease-in-out ${b?`${F?`aivex:mt-md`:`aivex:mb-md`} aivex:opacity-100`:`aivex:opacity-0`}`,style:{maxHeight:b?204:0},children:(0,n.jsx)(`div`,{style:{width:204,height:204},className:`aivex:relative aivex:touch-none aivex:overflow-hidden aivex:rounded-sm aivex:bg-static-gray ${o?`aivex:cursor-default`:`aivex:cursor-grab aivex:active:cursor-grabbing`}`,onPointerDown:o?void 0:h.handleMinimapPointerDown,onPointerMove:o?void 0:h.handleMinimapPointerMove,onPointerUp:o?void 0:h.endMinimapDrag,onPointerCancel:o?void 0:h.endMinimapDrag,onWheel:o?void 0:h.handleMinimapWheel,"aria-busy":o,children:(0,n.jsxs)(`div`,{style:{position:`absolute`,inset:0,opacity:+!!a,transition:a?`opacity 0.3s ease`:`none`},children:[i&&(0,n.jsx)(`img`,{src:i,alt:``,crossOrigin:`anonymous`,draggable:!1,style:I}),d.showRegionMask&&c&&c.rects.length>0&&(0,n.jsx)(K,{image:r,region:c,maskId:l,width:M,height:N,strokeWidth:1,strokeDasharray:`4 4`,style:{position:`absolute`,left:A,top:j,pointerEvents:`none`}}),(0,n.jsx)(`svg`,{viewBox:`0 0 ${r.w} ${r.h}`,width:M,height:N,style:{position:`absolute`,left:A,top:j,pointerEvents:`none`},"aria-hidden":!0,children:f(u).filter(s).map(e=>(0,n.jsx)(De,{shape:e,strokeSize:d.strokeSize,register:g},e.id))}),(0,n.jsx)(`div`,{ref:_,style:{position:`absolute`,border:`1px solid ${xe}`,background:Se,boxSizing:`border-box`,pointerEvents:`none`}})]})})}),R=(0,n.jsxs)(`div`,{className:`aivex:relative aivex:flex aivex:items-center aivex:gap-xs`,children:[(0,n.jsx)(e.t,{variant:`ghost`,size:`icon-md`,"aria-label":D.zoomOut,onClick:()=>P(1/1.2),disabled:o,children:(0,n.jsx)(e.pr,{size:20})}),(0,n.jsx)(e.t,{variant:`ghost`,size:`md`,"aria-label":D.zoom100,onClick:y,disabled:o,className:`aivex:w-[60px] aivex:tabular-nums`,children:(0,n.jsx)(`span`,{ref:v,children:`100%`})}),(0,n.jsx)(e.t,{variant:`ghost`,size:`icon-md`,"aria-label":D.zoomIn,onClick:()=>P(1.2),disabled:o,children:(0,n.jsx)(e.Wr,{size:20})}),C&&(0,n.jsxs)(t.s,{open:w,onOpenChange:e=>e?T():E(),children:[(0,n.jsx)(t.s.Trigger,{asChild:!0,children:(0,n.jsx)(e.t,{variant:`ghost`,size:`icon-md`,"aria-label":D.viewSettings,className:w?`aivex:text-text-brand`:void 0,children:(0,n.jsx)(e.pi,{size:20})})}),(0,n.jsx)(Ae,{value:d,defaults:p,onChange:m,labels:O,items:k,openDown:F,alignEnd:S.endsWith(`right`)})]}),(0,n.jsx)(e.t,{variant:`ghost`,size:`icon-md`,"aria-label":D.toggleMinimap,title:`(M)`,onClick:x,children:b?(0,n.jsx)(e.nt,{size:20,className:F?`aivex:rotate-180`:void 0}):(0,n.jsx)(e.ar,{size:20})})]});return(0,n.jsxs)(`div`,{className:`aivex:absolute ${Ie[S]} aivex:w-[220px] aivex:rounded-[12px] aivex:border aivex:border-border-subtle aivex:bg-bg-primary aivex:p-md aivex:shadow-[0_4px_12px_rgba(13,13,18,0.24)]`,children:[F?R:L,F?L:R]})}),Re=6,ze={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){let t=g(e);return{x:t.minX,y:t.minY,width:t.maxX-t.minX,height:t.maxY-t.minY}}function Ve(e,t){return`translate(${t.x+e.x*t.scale}px, ${t.y+e.y*t.scale}px)`}function He(e,t){return`translate(${e.width*t.scale}px, ${e.height*t.scale}px) translate(-100%, ${Re}px)`}function Ue(e,t,n){e.dataset.bx=String(t.x),e.dataset.by=String(t.y),e.dataset.bw=String(t.width),e.dataset.bh=String(t.height),e.style.transform=Ve(t,n);let r=e.querySelector(`[data-selinfo-dim]`);return r&&(r.style.transform=He(t,n)),r}function We(e,t,n){return Ue(e,Be(t),n)}function Ge(e,t){let{bx:n,by:r,bw:i,bh:a}=e.dataset;n==null||r==null||i==null||a==null||Ue(e,{x:Number(n),y:Number(r),width:Number(i),height:Number(a)},t)}function Ke(e,t){return{shape:e,...Be(t)}}function qe(e){return`${Math.round(e.width)} x ${Math.round(e.height)} px`}function Je({color:e,striped:t}){return(0,n.jsx)(`span`,{style:{display:`inline-block`,width:12,height:12,borderRadius:`50%`,...t?{border:`2px dashed ${e}`,background:`transparent`}:{background:e}}})}function Ye({shapes:e,getLabel:t,hideDot:r,formatInfo:i,register:a,viewport:s}){return(0,n.jsx)(n.Fragment,{children:e.map(e=>{let c=Be(e.points),l=e.type===o.POINT,u=l?void 0:t?.(e),d=e.style?.color??`#00e5ff`,f=!!e.style?.dashed||!!e.style?.dash,p=Ke(e,e.points),m=i?i(p):qe(p);return(0,n.jsxs)(`div`,{ref:t=>a(e.id,t),"data-bx":c.x,"data-by":c.y,"data-bw":c.width,"data-bh":c.height,style:{position:`absolute`,left:0,top:0,transform:Ve(c,s),pointerEvents:`none`},children:[!!u&&(0,n.jsxs)(`div`,{style:{position:`absolute`,left:0,top:0,display:`flex`,alignItems:`center`,gap:4,transform:`translateY(calc(-100% - ${Re}px))`,...ze},children:[!r&&(0,n.jsx)(Je,{color:d,striped:f}),(0,n.jsx)(`span`,{children:u})]}),!l&&!!m&&(0,n.jsx)(`div`,{"data-selinfo-dim":!0,style:{position:`absolute`,left:0,top:0,transform:He(c,s),...ze},children:m})]},e.id)})})}var Xe=`AIVEX_SHAPE_EDITOR:`,Ze=1,Qe=new Set(Object.values(o)),$e=null,et=`unavailable`,tt=0;function nt(e){if(!e||typeof e!=`object`)return!1;let t=e;return Number.isFinite(t.x)&&Number.isFinite(t.y)}function rt(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.type==`string`&&Qe.has(t.type)&&Array.isArray(t.points)&&t.points.length>0&&t.points.every(nt)}function it(e,t,n){return{kind:`aivex-shape-editor`,version:Ze,scope:n,documentId:t,shapes:e}}function at(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`fnv1a:${(t>>>0).toString(36)}`}function ot(e){return`${Xe}${JSON.stringify(e)}`}function q(e){if(!e.startsWith(Xe))return null;try{let t=JSON.parse(e.slice(19));return t.kind!==`aivex-shape-editor`||t.version!==Ze||!Array.isArray(t.shapes)||t.shapes.length===0||!t.shapes.every(rt)||t.scope!==void 0&&typeof t.scope!=`string`||t.documentId!==void 0&&typeof t.documentId!=`string`?null:t}catch{return null}}function st(e){$e=e;let t=++tt;if(typeof navigator>`u`||!navigator.clipboard?.writeText){et=`unavailable`;return}let n;try{n=ot(e)}catch{et=`unavailable`;return}et=`pending`,navigator.clipboard.writeText(n).then(()=>{t===tt&&(et=`written`)},()=>{t===tt&&(et=`unavailable`)})}function ct(e,t){return!!e&&e.scope===t}function J(e){return ct($e,e)||typeof navigator<`u`&&typeof navigator.clipboard?.readText==`function`}async function lt(e){let t=ct($e,e)?$e:null;if(t&&et!==`written`)return t;if(typeof navigator<`u`&&navigator.clipboard?.readText)try{let t=q(await navigator.clipboard.readText());return t?.scope===e?($e=t,t):null}catch{}return t}function ut(e,t,n){return{offset:n*(t?e:e+1),nextPasteCount:e+1}}var dt=new Set([W.RECTANGLE,W.ROTATED_RECTANGLE,W.CIRCLE,W.POLYGON,W.PATH,W.BRUSH,W.POINT,W.ASSISTANT_POLYGON,W.ASSISTANT_RECT,W.ASSISTANT_POINT]),ft={tl:-135,t:-90,tr:-45,r:0,br:45,b:90,bl:135,l:180},pt=[`ew-resize`,`nwse-resize`,`ns-resize`,`nesw-resize`],mt=`grab-unselected`,Y=new Set([W.RECTANGLE,W.ROTATED_RECTANGLE,W.CIRCLE]);function ht(e,t=0){let n=((ft[e]+t*180/Math.PI)%180+180)%180;return pt[Math.round(n/45)%4]}function gt({tool:e,externalToolCursor:t,isSpacePressed:n,isPolygonDrawing:r}){return n?`grab`:t||(e===W.SELECT?`default`:dt.has(e)?r?`default`:`crosshair`:`default`)}function _t({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===W.SELECT&&i?i===`grab-unselected`?`grab`:i:Y.has(e)&&i&&i!==`grab-unselected`?i:gt({tool:e,externalToolCursor:t,isSpacePressed:n,isPolygonDrawing:a}))}function X(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 vt=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 yt(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 bt(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 xt(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(...bt(s,c,e));if(n)for(let e of n)l.push(...bt(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=yt(m,o)?m:h,_=g===m?h:m;t.some(e=>e!==o&&yt(_,e))||n&&!n.some(e=>yt(g,e))||i.push([a(s,c,r),a(s,c,u)])}}return i}function St(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 Ct(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)X(e,n.points),e.fill()}e.restore()}function wt(e){let t=getComputedStyle(e);return{color:t.getPropertyValue(`--aivex-static-black`).trim()||`#17171c`,opacity:Number.parseFloat(t.getPropertyValue(`--aivex-opacity-dim`))||.32}}function Tt(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 Et={color:`#000000`,opacity:.5},Dt={color:`#ffffff`,opacity:1,width:2,dash:[6,6],underlayColor:`#000000`},Ot={color:`#dc2626`,opacity:.8,width:2,dash:[6,6],underlayColor:`#000000`},kt=(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=St(a),s={...Et,...e.dim},c=e.outline;if(c===!1)return{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:[],occludedOutline:[],outlineStyles:null};let l={visible:{...Dt,...c?.visibleStyle},occluded:{...Ot,...c?.occludedStyle}},u=i.map(vt),d=a.map(vt),f=r.map(e=>e.points);return c?.mode===`separate`?{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:Tt(u),occludedOutline:Tt(f),outlineStyles:l}:{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:[...xt(u,[...u,...f],null),...xt(f,f,d)],occludedOutline:[],outlineStyles:l}},At=.3,jt=.05;function Mt(e){return 1-(1-e)**3}function Z(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 Nt(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=g(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 Pt(e){if(!e.length)return null;let t=e.map(e=>Nt(e.type,e.points)).filter(e=>e!==null);return t.length?Z(g(t.flatMap(e=>[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y+e.height}]))):null}function Ft(e,t,n,r={}){let{containerRatio:i=At,minScale:a=jt,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 It(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(jt,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 Lt(e,t,n,r=300){let i=Date.now(),a=0,o=()=>{let s=Date.now()-i,c=Math.min(s/r,1),l=Mt(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 Rt(e){let{engineRef:t,toolRef:n,externalToolMapRef:r,spaceRef:i,docRef:a,selRef:s,draftRef:c,readOnlyRef:u,disableMarqueeRef:p,lockedRef:m,onLockedInteraction:h,onDrawAttemptWithoutDraft:_,createRef:v,selectRef:b,enterEditRef:C,editingIdRef:w,drawSessionRef:T,assistantRef:E,setCursorHint:D,setInteractionMode:O,syncMinimap:k,onTransformPreview:A,onDrawPreview:j}=e,M=()=>T.current,N=()=>E.current,P=null,F=null,I=null,L=null,R=null,ee=null,te=!1,ne=``,re=null,ie=null,z=null,B=e=>e===W.RECTANGLE||e===W.ROTATED_RECTANGLE||e===W.CIRCLE,V=e=>e===W.ASSISTANT_POLYGON||e===W.ASSISTANT_RECT,ae=e=>e===W.POLYGON,oe=e=>B(e)||V(e)||ae(e)||e===W.PATH||e===W.BRUSH||e===W.POINT,H=(e,t)=>{let n=!1;F&&!B(t)&&!V(t)&&(F=null,e.clearPreview(),j(null),n=!0),(I===`path`&&t!==W.PATH||I===`scalar`&&t!==W.BRUSH)&&(I=null,n=!0),L&&!ae(t)&&(L=null,n=!0),R&&t!==W.SELECT&&(R=null,ee=null,te=!1,e.clearMarquee(),n=!0),re&&t!==W.POINT&&(re=null,n=!0),n&&O(`idle`)},U=()=>r.current.get(n.current),se=(e,t,n,r)=>({point:t,targetId:r,event:n,readOnly:u.current,viewport:e.viewport});return{onCursorHint:D,onInteractionModeChange:O,onPointerDown:(e,r,p)=>{let v=t.current;if(!v)return;let y=n.current;if(re=null,ie=null,H(v,y),p.button===1||i.current){O(`panning`),D(null),P={px:p.global.x,py:p.global.y};return}if(p.button===2&&!(y===W.ASSISTANT_POINT&&p.altKey)){if(r&&!s.current.includes(r)){let e=a.current.getShapes().find(e=>e.id===r);e&&l(e)&&b.current([r])}return}let x=U();if(x){M().reset(),b.current([]),x.onPointerDown?.(se(v,e,p,r));return}if(m.current&&y!==W.SELECT){h();return}if(B(y)&&r&&s.current.includes(r)&&!u.current){let t=a.current.getShapes().find(e=>e.id===r);if(t&&d(t)){v.beginMove(e,s.current);return}}if(oe(y)&&!c.current){_();return}if(y===W.ASSISTANT_POINT){p.altKey?N().addPoint(e,p.button!==2):N().newPolygon(e);return}if(V(y)&&c.current){F=e,O(`drawing`);return}if(y===W.SELECT&&w.current){ee=p.shiftKey?v.getVertexSelection():[],te=r===w.current,R=e,ne=``,O(`marquee`),D(null);return}if(y===W.SELECT&&p.altKey){let t=f(a.current.getShapes()).filter(t=>{if(!l(t))return!1;let n=g(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=>s.current.includes(e.id))+1)%e.length].id];b.current(n);return}}if(r&&y===W.SELECT){let t=a.current.getShapes().find(e=>e.id===r);if(!t||!l(t))return;let n=typeof performance<`u`?performance.now():0,i=!!z&&z.id===r&&n-z.t<300;z={id:r,t:n};let c=(t.type===o.POLYGON||t.type===o.LINE)&&t.interaction?.editable!==!1&&!t.readOnly;if(i&&c&&m.current){b.current([r]),h();return}if(i&&c&&!u.current){b.current([r]),C.current(r);return}let f=s.current;if(p.shiftKey){let e=new Set(f);e.has(r)?e.delete(r):e.add(r),f=[...e]}else f.includes(r)||(f=[r]);b.current(f),d(t)&&(m.current?ie=p.global:u.current||v.beginMove(e,f));return}if(B(y)&&c.current){F=e,O(`drawing`);return}if(ae(y)&&c.current){if(!M().getDraftPointsSnapshot().length&&s.current.length&&b.current([]),M().tryClosePolygon(e,12/v.viewport.scale))return;let t=M().hitDraftPoint(e);if(t>=0){if(p.altKey){M().removeDraftPoint(t);return}let n=M().selectDraftPointForDrag(t,p.shiftKey||p.ctrlKey||p.metaKey);if(!n)return;L={start:e,base:n.base,indices:n.indices,moved:!1},O(`vertexDragging`);return}M().appendPolygonPoint(e);return}if(y===W.PATH&&c.current){s.current.length&&b.current([]),I=`path`,O(`drawing`),M().beginStroke(e);return}if(y===W.BRUSH&&c.current&&!u.current){I=`scalar`,O(`drawing`),M().beginStroke(e);return}if(y===W.POINT&&c.current&&p.button===0){re={pointerId:p.pointerId,global:p.global,cancelled:!1};return}if(y===W.SELECT){ee=null,te=!1;let t=!u.current||m.current;if(!p.shiftKey&&t&&s.current.length>=2){let t=a.current.getShapes().filter(e=>s.current.includes(e.id)&&d(e));if(t.length){let n=g(t.flatMap(e=>e.points));if(e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY){m.current?ie=p.global:v.beginMove(e,s.current);return}}}R=e,ne=``,O(`marquee`),D(null)}},onPointerMove:(e,r)=>{let i=t.current;if(!i)return;if(re&&re.pointerId===r.pointerId&&Math.hypot(r.global.x-re.global.x,r.global.y-re.global.y)>4&&(re.cancelled=!0),ie&&Math.hypot(r.global.x-ie.x,r.global.y-ie.y)>4){ie=null,h();return}if(P){i.applyViewport({scale:i.viewport.scale,x:i.viewport.x+(r.global.x-P.px),y:i.viewport.y+(r.global.y-P.py)}),P.px=r.global.x,P.py=r.global.y;return}let s=n.current;H(i,s);let l=U();if(l){l.onPointerMove?.(se(i,e,r));return}if(L){let t=e.x-L.start.x,n=e.y-L.start.y;L.moved=L.moved||Math.hypot(t,n)>.5,M().moveDraftPoints(L.base,L.indices,t,n);return}if(F&&(B(s)||V(s))){let t=r.shiftKey?y(F,e):e;i.previewBox(s===W.CIRCLE?`ellipse`:`rect`,F,t,{...c.current,color:c.current?.color??`#00e5ff`}),B(s)&&j({type:s===W.CIRCLE?o.ELLIPSE:o.RECTANGLE,points:[F,t]});return}if(I){M().appendStrokePoint(e,2/i.viewport.scale);return}if(ae(s)&&M().hasDraftPoints()){M().setDraftCursor(e);return}if(R){if(p?.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)};if(i.previewMarquee(R,e),ee){let e=(a.current.getShapes().find(e=>e.id===w.current)?.points??[]).flatMap((e,n)=>e.x>=t.minX&&e.x<=t.maxX&&e.y>=t.minY&&e.y<=t.maxY?[n]:[]),n=[...new Set([...ee,...e])].sort((e,t)=>e-t),r=n.join(`,`);r!==ne&&(ne=r,i.setVertexSelection(n));return}let n=i.shapesIntersecting(t),r=n.join(`,`);r!==ne&&(ne=r,b.current(n))}},onPointerUp:(e,r)=>{let i=t.current;if(!i)return;let a=re;if(re=null,ie=null,P){P=null,O(`idle`);return}let l=n.current;if(H(i,l),L){M().commitDraftPointDrag(L.moved),L=null,O(`idle`);return}let u=U();if(u){u.onPointerUp?.(se(i,e,r));return}let d=a?Math.hypot(r.global.x-a.global.x,r.global.y-a.global.y):1/0;if(l===W.POINT&&c.current&&a&&!a.cancelled&&a.pointerId===r.pointerId&&r.insideCanvas&&d<=4){v.current(o.POINT,[e]);return}if(I){let e=I;I=null,O(`idle`),e===`path`?M().completeFreehandStroke():M().finishScalarStroke();return}if(F&&V(l)){let t=F;F=null,O(`idle`),i.clearPreview();let n=r.shiftKey?y(t,e):e,a={x:Math.min(t.x,n.x),y:Math.min(t.y,n.y),width:Math.abs(n.x-t.x),height:Math.abs(n.y-t.y)};a.width>2&&a.height>2&&N().beginBox(a,l===W.ASSISTANT_RECT?`rect`:`polygon`);return}if(F&&B(l)){let t=r.shiftKey?y(F,e):e,n=F;F=null,O(`idle`),i.clearPreview(),j(null),Math.abs(t.x-n.x)>2&&Math.abs(t.y-n.y)>2&&(l===W.ROTATED_RECTANGLE?v.current(o.ROTATED_RECTANGLE,x([n,t])):l===W.CIRCLE?v.current(o.POLYGON,S(n,t)):v.current(o.RECTANGLE,[n,t]));return}if(R){let t=Math.abs(e.x-R.x)>3||Math.abs(e.y-R.y)>3,n=ee!==null,r=te;if(R=null,ee=null,te=!1,i.clearMarquee(),O(`idle`),n&&t)return;if(n&&r){i.setVertexSelection([]);return}!t&&s.current.length&&b.current([])}},onViewportChange:k,onTransformPreview:A,onTransformCommit:e=>{let t=a.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&&a.current.update(n)}}}function zt({docRef:e,draftRef:t,draftMeta:n,changeSelection:i,assistantRef:a}){let[s,c]=(0,r.useState)(`idle`),[l,u]=(0,r.useState)([]),[d,f]=(0,r.useState)([]),p=(0,r.useRef)([]),h=(0,r.useRef)([]),_=(0,r.useRef)([]),v=(0,r.useRef)(`idle`),y=(0,r.useRef)(0),b=(0,r.useRef)(null),x=(0,r.useRef)(null),S=(0,r.useRef)(0),C=(0,r.useCallback)(e=>{p.current=e(p.current),f(p.current)},[]),T=(0,r.useCallback)(e=>{v.current=e,c(e)},[]),E=(0,r.useCallback)((e,t,r)=>{let i=a.current?.rectResult===`rotatedRect`;return e.map(e=>{if(t===`rect`&&i)return{id:m(),type:o.ROTATED_RECTANGLE,points:w(e),style:r,meta:n};if(t===`rect`){let t=g(e);return{id:m(),type:o.RECTANGLE,points:[{x:t.minX,y:t.minY},{x:t.maxX,y:t.maxY}],style:r,meta:n}}return{id:m(),type:o.POLYGON,points:e,style:r,meta:n}})},[n,a]),D=(0,r.useCallback)(()=>{y.current++,h.current=[],_.current=[],b.current=null,x.current=null,u([]),T(`idle`)},[T]),O=(0,r.useCallback)(()=>{S.current++,C(()=>[]);let t=x.current;t?e.current.update([t]):_.current.length&&e.current.remove(_.current),D()},[e,D,C]),k=(0,r.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,r.useCallback)(async()=>{let e=a.current?.infer;if(!e)return;let t={kind:`points`,points:h.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,r.useCallback)((e,t)=>{h.current=[...h.current,{x:e.x,y:e.y,positive:t}],u([{x:e.x,y:e.y,positive:t}]),A()},[A]),M=(0,r.useCallback)(e=>{D();let t=[{x:e.x,y:e.y,positive:!0}];h.current=t,u(t),A()},[D,A]),N=(0,r.useCallback)((e,t,n)=>{(_.current.length!==1||_.current[0]!==e.id)&&(D(),_.current=[e.id],b.current=e.points,x.current=e),h.current=[...h.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,r.useCallback)((n,r=`polygon`)=>{let o=a.current?.infer,s=t.current;if(!o||!s)return;let c=S.current;C(e=>[...e,n]),(async()=>{let t=[];try{t=(await o({kind:`box`,box:n})??[]).filter(e=>e.length>=3)}catch{t=[]}if(C(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,C]),addPoint:j,newPolygon:M,refineShape:N,finalize:D,cancel:O,isActive:(0,r.useCallback)(()=>v.current===`loading`||h.current.length>0||p.current.length>0||_.current.length>0,[])}}function Bt(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 Vt(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=Bt(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 Ht=4096,Ut=4;function Wt(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 Gt(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 Kt(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 qt(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 Jt(e,t,n){let r=Gt(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=Xt(Kt(qt(r,t,n,e,a)),t,n);o.length>=3&&i.push(o)}return i}function Yt(e,t,n,r,i){return r<0||i<0||r>=t||i>=n?!1:e[(i*t+r)*4+3]>128}function Xt(e,t,n){let r=-1,i=-1;outer:for(let a=0;a<n;a++)for(let o=0;o<t;o++)if(Yt(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(Yt(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 Zt(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 Qt(e){switch(e.type){case o.RECTANGLE:return e.points.length<2?null:x(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?S({x:t.x-6,y:t.y-6},{x:t.x+6,y:t.y+6}):null}default:return null}}function $t(e){return e.map(Qt).filter(e=>!!e&&e.length>=3)}function en(e,t,n=[]){if(t<=0||!e.length&&!n.length)return null;let r=Zt(e,n);if(!r.length)return null;let i=t+4,a=g(r),o=Math.ceil(a.maxX-a.minX+i*2),s=Math.ceil(a.maxY-a.minY+i*2),c=Math.min(1,Ht/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 tn(e,t=1.5){let{canvas:n,ox:r,oy:i,scale:a}=e,o=Jt(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=Vt(n,t),i=r.length>=3?r:n;i.length>=3&&Wt(i)>=Ut&&c.push(i)}return c}function nn(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 rn(e){return e.map(e=>({mode:e.mode,points:e.points.map(e=>({...e}))}))}function an(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 on(e){return e.map(e=>({...e}))}function sn(e,t){return e.length===t.length&&e.every((e,n)=>e.x===t[n].x&&e.y===t[n].y)}var cn=10;function ln(e,t){if(e.active!==t.active||e.kind!==t.kind||e.canUndo!==t.canUndo||e.canRedo!==t.canRedo)return!1;let n=e.brush,r=t.brush;return!n||!r?n===r:n.mode===r.mode&&n.editing===r.editing&&n.editTargetIds.length===r.editTargetIds.length&&n.editTargetIds.every((e,t)=>e===r.editTargetIds[t])}function un({toolRef:e,selRef:t,docRef:n,readOnlyRef:i,draftRef:a,brushSizeRef:s,simplifyEpsilonRef:c,draftMeta:l,engineRef:d,onDrawSessionChange:f,onDraftShapeChange:p,changeSelection:h,createShape:g}){let _=(0,r.useRef)(f);_.current=f;let v=(0,r.useRef)(p);v.current=p;let y=(0,r.useRef)(l);y.current=l;let b=(0,r.useRef)(g);b.current=g;let x=(0,r.useRef)(null),S=(0,r.useRef)([]),C=(0,r.useRef)(null),w=(0,r.useRef)(new Set),T=(0,r.useRef)([[]]),E=(0,r.useRef)(0),D=(0,r.useRef)(null),O=(0,r.useRef)([]),k=(0,r.useRef)([]),A=(0,r.useRef)([]),j=(0,r.useRef)([[]]),M=(0,r.useRef)(0),N=(0,r.useRef)(`draw`),P=()=>N.current===`erase`?`erase`:`add`,F=()=>A.current.length>0||O.current.length>0||e.current===W.BRUSH&&S.current.length>0,I=()=>{let t=e.current;return t===W.BRUSH&&F()?`brush`:t===W.POLYGON&&S.current.length>0?`polygon`:t===W.PATH&&S.current.length>0?`path`:`none`},L=()=>S.current.length>0||M.current>0,R=()=>S.current.length===0&&M.current<j.current.length-1,ee=()=>E.current>0,te=()=>E.current<T.current.length-1,ne=()=>{let t=e.current;return t===W.BRUSH?L():t===W.POLYGON||t===W.PATH?ee():!1},re=()=>{let t=e.current;return t===W.BRUSH?R():t===W.POLYGON||t===W.PATH?te():!1},ie=()=>I()!==`none`,z=(0,r.useCallback)(()=>{let e=I(),t={active:e!==`none`,kind:e,canUndo:ne(),canRedo:re(),brush:e===`brush`?{mode:N.current,editing:A.current.length>0,editTargetIds:[...A.current]}:void 0},n=x.current;n&&ln(n,t)||(x.current=t,_.current?.(t))},[]),B=(0,r.useCallback)(()=>{j.current=[[]],M.current=0},[]),V=(0,r.useCallback)(()=>{let t=d.current;if(!t)return;let n=e.current;if(n===W.BRUSH){let e=[...O.current];if(S.current.length&&e.push({points:S.current,mode:P()}),!e.length&&!k.current.length){t.clearPreview();return}let n=en(e,s.current,k.current);if(!n){t.clearPreview();return}let r=a.current?.color??`#00e5ff`;t.previewScalarMask(n,r);return}let r=S.current;if(!r.length){t.clearPreview(),D.current&&(D.current=null,v.current?.(null));return}let i={...a.current,color:a.current?.color??`#00e5ff`},c=Array.from(w.current),l=n!==W.PATH;if(t.previewPoly(r,C.current,i,!1,c,l),n===W.POLYGON||n===W.PATH){let e=v.current;e&&r!==D.current&&(D.current=r,e({type:o.POLYGON,points:on(r),meta:y.current}))}},[s,a,d,e]),ae=(0,r.useCallback)(e=>{let t=rn(e),n=j.current,r=M.current,i=n[r];i&&an(i,t)||(j.current=[...n.slice(0,r+1),t],M.current+=1,z())},[z]),oe=(0,r.useCallback)(e=>{let t=T.current,n=E.current,r=t[n];r&&sn(r,e)||(T.current=[...t.slice(0,n+1),on(e)],E.current+=1)},[]),H=(0,r.useCallback)(()=>{S.current=[],O.current=[],k.current=[],A.current=[],C.current=null,w.current=new Set,T.current=[[]],E.current=0,D.current=null,B(),d.current?.clearPreview(),v.current?.(null),z()},[d,z,B]),U=(0,r.useCallback)((e,t)=>{S.current=e,w.current=new Set(Array.from(w.current).filter(t=>t>=0&&t<e.length)),t&&oe(e),V(),z()},[z,oe,V]),se=(0,r.useCallback)(()=>on(S.current),[]),ce=(0,r.useCallback)(()=>S.current.length>0,[]),le=(0,r.useCallback)((t,n)=>{if(e.current!==W.POLYGON)return!1;let r=S.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]),ue=(0,r.useCallback)(e=>{let t=S.current;return e<0||e>=t.length?!1:(U(t.filter((t,n)=>n!==e),!0),!0)},[U]),de=(0,r.useCallback)((e,t)=>{let n=S.current;if(e<0||e>=n.length)return null;let r=new Set(w.current);return t?r.has(e)?r.delete(e):r.add(e):r.has(e)||(r.clear(),r.add(e)),w.current=r,C.current=null,V(),z(),{base:on(n),indices:Array.from(r)}},[z,V]),fe=(0,r.useCallback)(e=>{w.current=new Set,C.current=e,U([...S.current,e],!0)},[U]),pe=(0,r.useCallback)(e=>{C.current=null,w.current=new Set,S.current=[{...e}],V(),z()},[z,V]),me=(0,r.useCallback)((e,t)=>{let n=S.current[S.current.length-1];return n&&Math.hypot(e.x-n.x,e.y-n.y)<t?!1:(S.current=[...S.current,{...e}],C.current=null,V(),z(),!0)},[z,V]),he=(0,r.useCallback)((e,t,n,r)=>{let i=new Set(t);S.current=e.map((e,t)=>i.has(t)?{x:e.x+n,y:e.y+r}:{...e}),C.current=null,V(),z()},[z,V]),ge=(0,r.useCallback)(e=>{e&&(oe(S.current),V(),z())},[z,oe,V]),_e=(0,r.useCallback)(e=>{C.current=e?{...e}:null,V()},[V]),ve=(0,r.useCallback)(()=>S.current.length>0?(S.current=[],V(),z(),!0):M.current<=0?!1:(--M.current,O.current=rn(j.current[M.current]),V(),z(),!0),[z,V]),ye=(0,r.useCallback)(()=>S.current.length>0||M.current>=j.current.length-1?!1:(M.current+=1,O.current=rn(j.current[M.current]),V(),z(),!0),[z,V]),be=(0,r.useCallback)(()=>E.current<=0?!1:(--E.current,S.current=on(T.current[E.current]),w.current=new Set,V(),z(),!0),[z,V]),xe=(0,r.useCallback)(()=>E.current>=T.current.length-1?!1:(E.current+=1,S.current=on(T.current[E.current]),w.current=new Set,V(),z(),!0),[z,V]),Se=(0,r.useCallback)(()=>{let t=e.current;return t===W.BRUSH?ve():t===W.POLYGON||t===W.PATH?be():!1},[e,ve,be]),Ce=(0,r.useCallback)(()=>{let t=e.current;return t===W.BRUSH?ye():t===W.POLYGON||t===W.PATH?xe():!1},[ye,xe,e]),G=(0,r.useCallback)(()=>{let e=t.current;if(!e.length)return A.current.length>0;let r=n.current.getShapes().filter(t=>e.includes(t.id)&&u(t)),i=$t(r);return i.length?(A.current=r.map(e=>e.id),k.current=i,!0):(A.current=[],k.current=[],!1)},[n,t]),we=(0,r.useCallback)(()=>{if(i.current)return!1;let e=[...O.current];S.current.length&&e.push({points:on(S.current),mode:P()});let t=k.current,r=[...A.current];if(!e.length&&!t.length)return!1;let u=en(e,s.current,t);if(!u)return H(),!1;let d=tn(u,c.current);if(r.length){let e=n.current.getShapes().filter(e=>r.includes(e.id));if(!d.length)return n.current.remove(r),H(),h([]),!0;d.sort((e,t)=>Wt(t)-Wt(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=m();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&&n.current.update(t),i.length&&n.current.create(i),s.length&&n.current.remove(s),H(),h(a),!0}if(!d.length)return H(),!1;let f=a.current;if(!f)return!1;let p=d.map(e=>({id:m(),type:o.POLYGON,points:e,style:f,meta:l}));return n.current.create(p),h(p.map(e=>e.id)),H(),!0},[s,h,n,l,a,i,H]),Te=(0,r.useCallback)(()=>{let t=e.current;if(t===W.BRUSH)return we();let n=S.current;return t===W.POLYGON&&n.length>=3?(b.current(o.POLYGON,n),H(),!0):!1},[we,H,e]),Ee=(0,r.useCallback)(()=>{let t=S.current;if(e.current===W.PATH&&t.length>=3){let e=Vt(t,c.current);e.length>=3&&b.current(o.POLYGON,e)}H()},[H,e]),De=(0,r.useCallback)(e=>{N.current=e,z(),V()},[z,V]),K=(0,r.useCallback)(()=>{if(i.current||e.current!==W.BRUSH)return!1;O.current=[],S.current=[],B();let t=G();return z(),V(),t},[z,i,V,B,G,e]),Oe=(0,r.useCallback)(()=>{let e=w.current;if(!e.size)return!1;let t=S.current.filter((t,n)=>!e.has(n));return w.current=new Set,U(t,!0),!0},[U]),ke=(0,r.useCallback)(e=>{let t=d.current,n=S.current;if(!t||!n.length)return-1;let r=cn/(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]),Ae=(0,r.useCallback)(()=>{S.current.length>=1&&(O.current.push({points:on(S.current),mode:P()}),S.current=[],ae(O.current)),V(),z()},[z,ae,V]);return{reset:H,undoSession:Se,redoSession:Ce,canUndoSession:ne,canRedoSession:re,hasDraftSession:ie,hasDraftPoints:ce,commitDraftSession:Te,completeFreehandStroke:Ee,setBrushScalarMode:De,getBrushScalarMode:()=>N.current,hasBrushSession:F,commitBrush:we,cancelBrush:(0,r.useCallback)(()=>{e.current===W.BRUSH&&H()},[H,e]),beginBrushEditFromSelection:K,deleteDraftSelectedPoints:Oe,hitDraftPoint:ke,getDraftPointsSnapshot:se,tryClosePolygon:le,removeDraftPoint:ue,selectDraftPointForDrag:de,appendPolygonPoint:fe,beginStroke:pe,appendStrokePoint:me,moveDraftPoints:he,commitDraftPointDrag:ge,setDraftCursor:_e,finishScalarStroke:Ae,handleToolChange:(0,r.useCallback)((e,t)=>{if(t){H(),N.current=`draw`;return}if(e!==W.BRUSH){H(),N.current=`draw`;return}N.current=`draw`,O.current=[],S.current=[],B(),G(),z(),V()},[z,V,H,B,G]),handleBrushSelectionChange:(0,r.useCallback)((t,n)=>{if(!(e.current!==W.BRUSH||n)){if(!t.length){z();return}[...t].sort().join(`,`)!==[...A.current].sort().join(`,`)&&(O.current.length||S.current.length||(O.current=[],S.current=[],B(),G(),z(),V()))}},[z,V,B,G,e])}}function dn(e,t){return{shapes:t,past:[...e.past,e.shapes],future:[]}}function fn(e,t){switch(t.type){case`CREATE`:return dn(e,[...e.shapes,...t.shapes]);case`UPDATE`:{let n=new Map(t.shapes.map(e=>[e.id,e]));return dn(e,e.shapes.map(e=>n.get(e.id)??e))}case`DELETE`:{let n=new Set(t.ids);return dn(e,e.shapes.filter(e=>!n.has(e.id)))}case`REPLACE`:{let n=new Set(t.removeIds);return dn(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:dn(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 pn(e){let{onShapesCreated:t,onShapesUpdated:n,onShapesDeleted:i}=e,[a,o]=(0,r.useReducer)(fn,{shapes:[],past:[],future:[]}),s=(0,r.useRef)(a);s.current=a;let c=(0,r.useCallback)(e=>{s.current=fn(s.current,e),o(e)},[]),l=(0,r.useCallback)((e,r)=>{let a=new Map(e.map(e=>[e.id,e])),o=new Map(r.map(e=>[e.id,e])),s=r.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=r.filter(e=>a.has(e.id)&&a.get(e.id)!==e);l.length&&n?.(l)},[t,n,i]),u=(0,r.useCallback)(e=>{let n=Array.isArray(e)?e:[e];n.length&&(c({type:`CREATE`,shapes:n}),t?.(n))},[t]),d=(0,r.useCallback)(e=>{c({type:`UPDATE`,shapes:e}),n?.(e)},[n]),f=(0,r.useCallback)(e=>{e.length!==0&&(c({type:`DELETE`,ids:e}),i?.(e))},[i]),p=(0,r.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,r.useCallback)((e,t)=>{e.length!==0&&c({type:`REORDER`,ids:e,edge:t})},[]),h=(0,r.useCallback)(e=>{c({type:`RESET`,shapes:e})},[]),g=(0,r.useCallback)(()=>{let e=s.current;e.past.length!==0&&(l(e.shapes,e.past[e.past.length-1]),c({type:`UNDO`}))},[l]),_=(0,r.useCallback)(()=>{let e=s.current;e.future.length!==0&&(l(e.shapes,e.future[0]),c({type:`REDO`}))},[l]),v=(0,r.useCallback)(()=>s.current.past.length>0,[]),y=(0,r.useCallback)(()=>s.current.future.length>0,[]),b=(0,r.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 mn={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`]},hn={Equal:`=`,Minus:`-`,BracketLeft:`[`,BracketRight:`]`,Semicolon:`;`,Period:`.`,Comma:`,`,Slash:`/`,Backquote:"`"},gn={Escape:`escape`,Enter:`enter`,Backspace:`backspace`,Delete:`delete`,Tab:`tab`,ArrowUp:`arrowup`,ArrowDown:`arrowdown`,ArrowLeft:`arrowleft`,ArrowRight:`arrowright`};function _n(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]:hn[t]?hn[t]:gn[e.key]?gn[e.key]:null}function vn(e){let t=_n(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 yn(e){let t=new Map;for(let n of Object.keys(mn)){let r=e?.[n],i=r===void 0?mn[n]:r===null?[]:Array.isArray(r)?r:[r];for(let e of i)t.set(e.toLowerCase(),n)}return t}var bn={ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0]};function xn(e){let{spaceRef:n}=e,i=(0,r.useMemo)(()=>yn(e.keymap),[e.keymap]),a=(0,r.useRef)(e);a.current=e;let o=(0,r.useRef)(i);o.current=i,(0,r.useEffect)(()=>{let e=a.current.hostRef.current,r=e?.ownerDocument.defaultView;if(!e||!r)return;let i=r=>{if(r.defaultPrevented&&r.key!==`Escape`||t.t(r.target)||!t.n(e,r.target))return;r.code===`Space`&&(n.current=!0,a.current.onSpaceDown());let i=bn[r.key];if(i){let e=r.shiftKey?10:1;a.current.nudge(i[0]*e,i[1]*e)!==!1&&r.preventDefault();return}let s=vn(r);if(!s)return;let c=o.current.get(s);c&&a.current.actions[c]?.()!==!1&&r.preventDefault()},s=e=>{e.code===`Space`&&n.current&&(n.current=!1,a.current.onSpaceUp())},c=()=>{n.current&&(n.current=!1,a.current.onSpaceUp())};return e.addEventListener(`keydown`,i),r.addEventListener(`keyup`,s,!0),r.addEventListener(`blur`,c),()=>{e.removeEventListener(`keydown`,i),r.removeEventListener(`keyup`,s,!0),r.removeEventListener(`blur`,c),c()}},[n])}function Sn(e,t){return new Promise(n=>{let r=new Image;t?.crossOrigin&&(r.crossOrigin=`anonymous`),r.onload=()=>n(r),r.onerror=()=>n(null),r.src=e})}async function Cn(e){let t=await Sn(e,{crossOrigin:!0});if(t)return t;try{let t=await fetch(e,{mode:`cors`,credentials:`omit`,cache:`reload`});if(!t.ok)return null;await t.blob()}catch{return null}return Sn(e,{crossOrigin:!0})}async function wn(e){for(let t of[`default`,`reload`])try{let n=await fetch(e,{mode:`cors`,credentials:`omit`,cache:t});return n.ok?await n.blob():null}catch{}return null}async function Tn(e){let t=await wn(e);if(t)try{let e=await createImageBitmap(t);return{source:e,width:e.width,height:e.height,release:()=>e.close()}}catch{}let n=await Cn(e);return n?{source:n,width:n.naturalWidth,height:n.naturalHeight,release:()=>{}}:null}var En=2,Dn=0,On=[];async function kn(e){Dn<En?Dn+=1:await new Promise(e=>On.push(e));try{return await e()}finally{let e=On.shift();e?e():--Dn}}function An(e){return new Promise(t=>{let n=null,r=!1,i=()=>{r||(r=!0,clearTimeout(o),document.removeEventListener(`securitypolicyviolation`,a),t(n))},a=t=>{let r=t.effectiveDirective??t.violatedDirective??``;r.includes(`img-src`)&&(n=`CSP ${r} blocked ${t.blockedURI||e}`)},o=setTimeout(i,1e4);document.addEventListener(`securitypolicyviolation`,a),Sn(e,{crossOrigin:!0}).then(()=>{setTimeout(i,0)})})}var jn=3e4,Mn=200,Nn=new Map;function Pn(e){let t=Nn.get(e),n=Date.now();if(t&&n-t.at<jn)return t.result;let r=Fn(e).catch(t=>(Nn.delete(e),{kind:`unknown`,detail:t instanceof Error?t.message:String(t)}));if(Nn.set(e,{at:n,result:r}),Nn.size>Mn){let e=Nn.keys().next().value;e!==void 0&&Nn.delete(e)}return r}async function Fn(e){let t=e;try{t=new URL(e,location.href).origin}catch{}if(location.protocol===`https:`&&e.startsWith(`http:`))return{kind:`mixed-content`,detail:`http image on https page (${t})`};let n;try{n=await fetch(e,{mode:`cors`,credentials:`omit`,cache:`no-store`})}catch{if(!navigator.onLine)return{kind:`offline`,detail:`navigator.onLine=false`};try{return await fetch(e,{mode:`no-cors`,cache:`no-store`}),{kind:`cors`,detail:`no Access-Control-Allow-Origin from ${t}`}}catch{return{kind:`network`,detail:`fetch failed: ${t}`}}}let{status:r}=n;if(n.ok){let t=n.headers.get(`content-type`)??``;if(t&&!t.startsWith(`image/`))return{kind:`unexpected-content`,detail:`HTTP ${r} (${t})${n.redirected?` via redirect`:``}`};let i=await An(e);return i?{kind:`csp-img`,detail:i}:{kind:`decode`,detail:`HTTP ${r}${t?` (${t})`:``}`}}if(r===401||r===403){try{let t=await fetch(e,{mode:`cors`,credentials:`include`,cache:`no-store`});if(t.ok)return{kind:`auth`,detail:`HTTP ${r} without cookies, ${t.status} with cookies`}}catch{}return{kind:`forbidden`,detail:`HTTP ${r}`}}return r===404||r===410?{kind:`not-found`,detail:`HTTP ${r}`}:r>=500?{kind:`server-error`,detail:`HTTP ${r}`}:{kind:`http`,detail:`HTTP ${r}`}}function In(){try{let e=document.createElement(`canvas`);return!!(e.getContext(`webgl2`)??e.getContext(`webgl`))}catch{return!1}}function Ln(e){let t=e instanceof Error?e.message:String(e);return/unsafe-eval/i.test(t)?{kind:`csp-eval`,detail:t}:In()?{kind:`renderer-init`,detail:t||`renderer init failed`}:{kind:`webgl`,detail:t||`WebGL context unavailable`}}var Rn=4e3;function zn(e,t,n=Rn){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 Bn(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 Vn(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=g(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 Hn=`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`,Un=`#ffffff`,Q=1.5;function Wn(e){return`<svg width="16" height="22" viewBox="0 0 16 22" xmlns="http://www.w3.org/2000/svg"><path d="${Hn}" fill="${e}" stroke="${Un}" stroke-width="${Q}"/></svg>`}var Gn=Math.PI/12;function Kn(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 qn(e,t,n){if(e.kind===`resize`){let r=n?e.box:v(e.anchor,e.box,t.x,t.y);return{updates:e.shapes.map(i=>({id:i.id,points:n?P(i.points,e.anchor,t):F(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/Gn)*Gn),{updates:[{id:e.id,points:e.points.map(t=>b(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:g(a)}}function Jn(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)}:Kn(e,t)?j(t.shapes[0].points)[h.indexOf(t.anchor)]:_(t.anchor,t.box)}function Yn(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:g(r.flatMap(e=>e.points)),shapes:r}:null}function Xn(e){return e.map(e=>({...e,points:e.points.map(e=>({...e}))}))}function Zn(e,t){let n=new Set(t);return e.filter(e=>n.has(e.id)&&u(e))}function Qn(e,t){return e.filter(e=>l(e)&&B(e,t)).map(e=>e.id)}function $n(e,t,n){return(e?Te(e,{strokeWidth:t}).pointRadius:5)/(n||1)}function er(e,t){return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}function tr(e,t,n){if(e.type===o.ROTATED_RECTANGLE)return t;let r=e.type===o.POINT?er(t[0],n):g(t);return x([{x:r.minX,y:r.minY},{x:r.maxX,y:r.maxY}])}function nr(e){return 24/(e||1)}function rr(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}var ir=2,ar=`#1e88e5`,or=`#669def`,sr=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.regionOverlayGroup=new i.default.Group({listening:!1}),this.dimOverlayGroup=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=ir,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.ghostNode=null,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.overlayGroup.add(this.regionOverlayGroup,this.dimOverlayGroup),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=>({pointerId:1,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`,e=>{if(this.lastImg=this.toImage(),this.activeDrag){this.lastDragImg=this.lastImg,this.dragTransform(this.lastImg);return}this.cb.onPointerMove(this.lastImg,{pointerId:1,global:this.stage.getPointerPosition()??{x:0,y:0},shiftKey:e.evt.shiftKey})});let t=null,n=(e,n)=>{if(t!==e){if(t=e,this.activeDrag){this.endTransform();return}this.cb.onPointerUp(this.lastImg,{pointerId:1,global:this.stage.getPointerPosition()??{x:0,y:0},shiftKey:e.shiftKey,insideCanvas:n})}};this.stage.on(`mouseup`,e=>n(e.evt,!0));let r=e=>{let t=e.target;n(e,t instanceof Node&&this.host.contains(t))};window.addEventListener(`mouseup`,r),this.upCleanup=()=>window.removeEventListener(`mouseup`,r),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}bindShapeCursor(e,t){if(!d(t))return this.bindCursor(e,`default`);this.bindCursor(e,()=>this.selected.includes(t.id)?`grab`:mt)}bindCursor(e,t){let n=()=>{if(this.activeDrag)return;let e=typeof t==`function`?t():t;e===`pointer`&&!this.transformEnabled||this.emitCursorHint(e)},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 Cn(e);if(r!==this.imageLoadToken)return!0;if(!a)return this.imageWidth||=800,this.imageHeight||=600,!1;this.imageWidth=t?.width??a.naturalWidth,this.imageHeight=t?.height??a.naturalHeight;let o=n?.width??this.imageWidth,s=n?.height??this.imageHeight;this.bgGroup.scale({x:o/a.naturalWidth,y:s/a.naturalHeight}),this.bgGroup.destroyChildren();for(let e of zn(a.naturalWidth,a.naturalHeight))this.bgGroup.add(new i.default.Image({image:a,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}));return this.layer.batchDraw(),!0}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)}setRenderDefaults(e){let t=e.strokeWidth??this.strokeSize;this.strokeSize!==t&&(this.strokeSize=t,this.setShapes(this.shapes,this.selected))}vertexHandleRadius(){return Math.max(4,this.strokeSize*2.5)}setImageSmoothing(e){this.imageSmoothing!==e&&(this.imageSmoothing=e,this.layer.imageSmoothingEnabled(e),this.layer.batchDraw())}setOverlays(e,t){if(this.setRegionOverlay(e),this.dimOverlayGroup.destroyChildren(),t&&this.imageWidth){let e=wt(this.host);this.dimOverlayGroup.add(new i.default.Rect({x:0,y:0,width:this.imageWidth,height:this.imageHeight,fill:e.color,opacity:e.opacity,listening:!1}))}this.layer.batchDraw()}setRegionOverlay(e){if(this.regionOverlayGroup.destroyChildren(),e){let{imageWidth:t,imageHeight:n}=this;if(this.regionOverlayGroup.add(new i.default.Shape({listening:!1,sceneFunc:r=>{Ct(r._context,e,t,n)}})),e.outlineStyles){let t=(e,t)=>{let n={strokeWidth:t.width,strokeScaleEnabled:!1,listening:!1};for(let[r,a]of e)t.underlayColor&&this.regionOverlayGroup.add(new i.default.Line({points:[r.x,r.y,a.x,a.y],stroke:t.underlayColor,...n})),this.regionOverlayGroup.add(new i.default.Line({points:[r.x,r.y,a.x,a.y],stroke:t.color,opacity:t.opacity,dash:t.dash,...n}))};t(e.visibleOutline,e.outlineStyles.visible),t(e.occludedOutline,e.outlineStyles.occluded)}}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??Jn(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=Xn(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=Te(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()))}getVertexSelection(){return[...this.selectedVertices]}setVertexSelection(e){if(!this.editingId)return;let t=new Set(e);t.size===this.selectedVertices.size&&[...t].every(e=>this.selectedVertices.has(e))||(this.selectedVertices=t,this.activeDrag||(this.drawTransformer(),this.layer.batchDraw()))}makeNode(e){let{type:t,points:n}=e,r=Te(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?Ee(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:Hn,x:n[0].x,y:n[0].y,offsetX:16/2,offsetY:22,scaleX:t,scaleY:t,fill:r.color,stroke:Un,strokeWidth:Q,strokeScaleEnabled:!1,shadowColor:`#000`,shadowBlur:2,shadowOpacity:.3,shadowForStrokeEnabled:!1,opacity:r.opacity,listening:a});return this.bindShapeCursor(o,e),o}if(t===o.RECTANGLE){let t=g(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.bindShapeCursor(r,e),r}if(t===o.ELLIPSE){let t=g(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.bindShapeCursor(r,e),r}let u=n.flatMap(e=>[e.x,e.y]),d=t!==o.LINE,f=new i.default.Line({points:u,closed:d,fill:d?c:void 0,fillRule:`evenodd`,lineJoin:`round`,...s});return this.bindShapeCursor(f,e),f}liveUpdateShape(e,t){let n=this.nodes.get(e),r=this.shapes.find(t=>t.id===e);if(n&&r){Vn(n,r.type,t);let a=this.altNodes.get(e);a&&Vn(a,r.type,t),r.type===o.POINT&&n instanceof i.default.Circle&&n.radius(this.pointRadius(r)),this.layer.batchDraw()}}pointRadius(e){return $n(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(Te(t,{strokeWidth:this.strokeSize}).dash))}}shapesIntersecting(e){return Qn(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:or,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 tr(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?ar:`#ffffff`,stroke:r?`#ffffff`:ar,strokeWidth:1.5,strokeScaleEnabled:!1,listening:!1}))}this.layer.batchDraw()}previewScalarMask(e,t){this.previewGroup.destroyChildren();let n=nn(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:Ee(Ce,G),stroke:Ce,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,e||this.cancelTransform(),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(x([{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:ar,strokeWidth:1,strokeScaleEnabled:!1,listening:!1}),this.selGroup.add(this.transformerOutline)),this.transformerOutline.points(e.flatMap(e=>[e.x,e.y])))}rotationHandleGap(){return nr(this.viewport.scale)}rotationHandleScreenPoint(e){return this.imgToScreen(M(e,this.rotationHandleGap()))}setRotationConnector(e){let t=this.imgToScreen(k(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:ar,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 rr(this.imgToScreen(e[0]),this.imgToScreen(e[1]))}repositionOrientedHandles(e){let t=this.orientedHandleAngle(e);if(j(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.ghostNode?.destroy(),this.ghostNode=null,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=Zn(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=g(e.flatMap(e=>e.points)),r=e.length===1&&e[0].type===o.ROTATED_RECTANGLE?e[0]:null,a=r?j(r.points):h.map(e=>_(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?[]:h){let t=this.imgToScreen(a[h.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:ar,strokeWidth:1}),r=ht(e,s);this.bindCursor(n,r),n.on(`mousedown`,t=>{t.cancelBubble=!0,this.emitCursorHint(r),this.emitInteractionMode(`resizing`);let n=Zn(this.shapes,this.selected);this.activeDrag={kind:`resize`,anchor:e,box:g(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,a=this.vertexHandleRadius(),s=new i.default.Circle({radius:a*.8,fill:`#ffffff`,opacity:.6,stroke:ar,strokeWidth:1,visible:!1,listening:!1});this.handleGroup.add(s),this.ghostNode=s;for(let t=0;t<r;t++){let r=n[t],o=n[(t+1)%n.length],c=this.imgToScreen(r),l=this.imgToScreen(o),u=new i.default.Line({points:[c.x,c.y,l.x,l.y],stroke:`#ffffff`,strokeWidth:1,opacity:0,hitStrokeWidth:Math.max(14,a*2+4)});this.bindCursor(u,`copy`);let d=()=>{let e=this.toImage(),t=o.x-r.x,n=o.y-r.y,i=t*t+n*n,a=i?Math.max(0,Math.min(1,((e.x-r.x)*t+(e.y-r.y)*n)/i)):0;return{x:r.x+a*t,y:r.y+a*n}};u.on(`mousemove`,()=>{if(this.activeDrag)return;let e=this.imgToScreen(d());s.position({x:e.x,y:e.y}),s.visible(!0),this.layer.batchDraw()}),u.on(`mouseleave`,()=>{s.visible(!1),this.layer.batchDraw()}),u.on(`mousedown`,r=>{r.cancelBubble=!0;let i=d(),a=t+1,o=[...n.slice(0,a),i,...n.slice(a)],s=this.shapes.find(t=>t.id===e.id);s&&(s.points=o),this.liveUpdateShape(e.id,o),this.selectedVertices=new Set([a]),this.drawTransformer(),this.cb.onTransformCommit?.([{id:e.id,points:o}]),this.activeDrag={kind:`vertex`,id:e.id,indices:[a],base:o,start:i},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`vertexDragging`)}),this.handleGroup.add(u),this.midNodes.push(u)}this.vertexPolygonId!==e.id&&(this.vertexPolygonId=e.id,this.selectedVertices.clear()),n.forEach((t,r)=>{let o=this.imgToScreen(t),s=this.selectedVertices.has(r),c=new i.default.Circle({x:o.x,y:o.y,radius:a,fill:s?ar:`#ffffff`,stroke:s?`#ffffff`:ar,strokeWidth:Math.max(1.5,a*.3)});this.bindCursor(c,`pointer`),c.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(c),this.vertexNodes.push(c)})}if(e.length===1&&e[0].type===o.ROTATED_RECTANGLE){let t=e[0],n=A(t.points),r=this.rotationHandleScreenPoint(t.points),a=new i.default.Circle({x:r.x,y:r.y,radius:6,fill:`#ffffff`,stroke:ar,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=Yn(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){h.forEach((t,n)=>{let r=this.imgToScreen(_(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=this.imgToScreen(e[t]),r=this.imgToScreen(e[(t+1)%e.length]);this.midNodes[t]?.points([n.x,n.y,r.x,r.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=Kn(this.shapes,t),{updates:r,box:i}=qn(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()}cancelTransform(){if(this.activeDrag){this.activeDrag=null,this.lastDragImg=null;for(let e of this.shapes)this.liveUpdateShape(e.id,e.points);this.cb.onTransformPreview?.(this.shapes.map(e=>({id:e.id,points:e.points}))),this.emitInteractionMode(`idle`),this.emitCursorHint(null),this.drawSelectionBorders()}}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}=qn(e,t,Kn(this.shapes,e));this.commitTransformUpdates(n)}},cr=2,lr=58879,ur=6725103;function $(e){if(!e)return lr;let t=e.replace(`#`,``);return Number.parseInt(t.length===3?t.replace(/./g,`$&$&`):t,16)}var dr=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.regionOverlayLayer=new a.Container,this.dimOverlayLayer=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.tileSize=Rn,this.region=null,this.regionDimMaskG=new a.Graphics,this.regionDimG=new a.Graphics,this.regionZoneMaskG=new a.Graphics,this.regionZoneG=new a.Graphics,this.regionOutlineG=new a.Graphics,this.baseCursor=`default`,this.strokeSize=cr,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.ghostNode=null,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{pointerId:e.pointerId,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);let e=this.app.renderer.gl,t=e?.getParameter(e.MAX_TEXTURE_SIZE);typeof t==`number`&&t>1&&(this.tileSize=Math.min(Rn,t-1)),this.applyCursor(),this.overlayLayer.addChild(this.regionOverlayLayer,this.dimOverlayLayer),this.regionOverlayLayer.addChild(this.regionDimMaskG,this.regionDimG,this.regionZoneMaskG,this.regionZoneG,this.regionOutlineG),this.regionDimG.setMask({mask:this.regionDimMaskG,inverse:!0}),this.regionZoneG.setMask({mask:this.regionZoneMaskG}),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 n=(e,t)=>{if(this.activeDrag){this.endTransform();return}this.cb.onPointerUp(this.toImage(e),{pointerId:e.pointerId,global:{x:e.global.x,y:e.global.y},shiftKey:e.shiftKey,insideCanvas:t})};this.app.stage.on(`pointerup`,e=>n(e,!0)),this.app.stage.on(`pointerupoutside`,e=>n(e,!1)),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(),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 Cn(e);if(this.destroyed||r!==this.imageLoadToken)return!0;if(!i)return this.imageWidth||=t?.width??800,this.imageHeight||=t?.height??600,!1;this.imageWidth=t?.width??i.naturalWidth,this.imageHeight=t?.height??i.naturalHeight;let o=n?.width??this.imageWidth,s=n?.height??this.imageHeight;this.bgLayer.scale.set(o/i.naturalWidth,s/i.naturalHeight),this.clearImageTiles();for(let e of zn(i.naturalWidth,i.naturalHeight,this.tileSize)){let t=a.Texture.from(Bn(i,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)}return this.applySpriteFilter(),!0}setFilter(e,t){this.brightness=e,this.contrast=t,this.applySpriteFilter()}setRenderDefaults(e){let t=e.strokeWidth??this.strokeSize;this.strokeSize!==t&&(this.strokeSize=t,this.setShapes(this.shapes,this.selected))}vertexHandleRadius(){return Math.max(4,this.strokeSize*2.5)}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){this.setRegionOverlay(e);for(let e of this.dimOverlayLayer.removeChildren())e.destroy();if(t&&this.imageWidth){let e=wt(this.host);this.dimOverlayLayer.addChild(new a.Graphics().rect(0,0,this.imageWidth,this.imageHeight).fill({color:$(e.color),alpha:e.opacity}))}!this.destroyed&&this.app.renderer&&this.app.render()}setRegionOverlay(e){if(this.region=e,this.regionDimMaskG.clear(),this.regionDimG.clear(),this.regionZoneMaskG.clear(),this.regionZoneG.clear(),this.regionOutlineG.clear(),!e)return;let t=$(e.dim.color);for(let t of e.rects)this.regionDimMaskG.rect(t.x,t.y,t.w,t.h).fill(16777215),this.regionZoneMaskG.rect(t.x,t.y,t.w,t.h).fill(16777215);this.regionDimG.rect(0,0,this.imageWidth,this.imageHeight).fill({color:t,alpha:e.dim.opacity});for(let n of e.zones)this.regionZoneG.poly(n.points.flatMap(e=>[e.x,e.y]),!0).fill({color:t,alpha:e.dim.opacity});this.redrawRegionOutline()}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??Jn(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=Xn(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())}getVertexSelection(){return[...this.selectedVertices]}setVertexSelection(e){if(!this.editingId)return;let t=new Set(e);t.size===this.selectedVertices.size&&[...t].every(e=>this.selectedVertices.has(e))||(this.selectedVertices=t,this.activeDrag||this.drawTransformer())}setTransformEnabled(e){this.transformEnabled=e,e||this.cancelTransform(),this.syncShapeCursors(),this.drawTransformer()}setPanMode(e){this.handleLayer.interactiveChildren=!e}strokeW(e){return(e?Te(e,{strokeWidth:this.strokeSize}).strokeWidth:cr)/this.world.scale.x}pointRadius(e){return $n(e,this.strokeSize,this.world.scale.x)}dashForShape(e){let t=Te(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(this.selected.includes(e.id)?`grab`:mt)}),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=Te(t,{strokeWidth:this.strokeSize}),r=$(n.color),i=this.strokeW(t),a=n.opacity,s=this.dashForShape(t);if(t.type===o.POINT){e.svg(Wn(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){let i=t.type===o.POLYGON?H(t.points):null;if(i&&(i.length>1||i[0].holes.length>0))for(let t of i)for(let i=0;i<Math.min(t.layers,4);i++){e.poly(t.outline.flatMap(e=>[e.x,e.y]),!0),e.fill({color:r,alpha:n.fillAlpha*a});for(let n of t.holes)e.poly(n.flatMap(e=>[e.x,e.y]),!0),e.cut()}else this.path(e,t),e.fill({color:r,alpha:n.fillAlpha*a})}else t.type!==o.LINE&&(this.path(e,t),e.fill({color:r,alpha:0}));if(s){t.style?.alternateColor&&(this.path(e,t),e.stroke({width:i,color:$(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 Qn(this.shapes,e)}shapesAt(e){return this.shapes.filter(t=>{let n=g(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:$(r.alternateColor)}));let s=this.dashForShape(i);if(s){this.dashedStrokeShape(this.previewG,i,a,$(r.color??`#00e5ff`),r.opacity??1,s);return}this.path(this.previewG,i),this.previewG.stroke({width:a,color:$(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:$(n.alternateColor)}));let u=this.dashForShape(c);if(u?this.dashedStrokeShape(this.previewG,c,l,$(n.color??`#00e5ff`),n.opacity??1,u):(this.path(this.previewG,c),this.previewG.stroke({width:l,color:$(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=nn(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=$(Ce);this.marqueeG.rect(n,r,i,a).fill({color:o,alpha:G}).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;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:$(r.underlayColor)}),this.strokeDashedPolyline(e,[n,o],!1,i,$(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=g(r);e.rect(t.minX,t.minY,t.maxX-t.minX,t.maxY-t.minY);return}if(n===o.ELLIPSE){let t=g(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=g(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=g(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;if(!(s>0)||!(c>0))return;let l=!0,u=0,d=null,f=()=>{if(d&&d.length>=2){e.moveTo(d[0].x,d[0].y);for(let t=1;t<d.length;t++)e.lineTo(d[t].x,d[t].y);e.stroke({width:r,color:i,alpha:a})}d=null},p=n?t.length:t.length-1;for(let e=0;e<p;e++){let n=t[e],r=t[(e+1)%t.length],i=r.x-n.x,a=r.y-n.y,o=Math.hypot(i,a);if(!o)continue;let p=0;for(;p<o;){let e=l?s:c,t=Math.min(e-u,o-p);if(l){let e=p/o,r=(p+t)/o;d||=[{x:n.x+i*e,y:n.y+a*e}],d.push({x:n.x+i*r,y:n.y+a*r})}p+=t,u+=t,u>=e-1e-4&&(u=0,l&&f(),l=!l)}}f()}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:ur})})}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:ur}))}}selectionOutlinePoints(e,t){return tr(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(x([{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 nr(this.viewport.scale)}rotationHandleScreenPoint(e){return this.imgToScreen(M(e,this.rotationHandleGap()))}setRotationConnector(e){let t=this.imgToScreen(k(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 rr(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.ghostNode?.destroy(),this.ghostNode=null,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=Zn(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=g(e.flatMap(e=>e.points)),r=e.length===1&&e[0].type===o.ROTATED_RECTANGLE?e[0]:null,i=r?j(r.points):h.map(e=>_(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?[]:h){let t=this.imgToScreen(i[h.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=ht(e,s);this.bindCursor(n,r),n.on(`pointerdown`,t=>{t.stopPropagation(),this.emitCursorHint(r),this.emitInteractionMode(`resizing`);let n=Zn(this.shapes,this.selected);this.activeDrag={kind:`resize`,anchor:e,box:g(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,i=this.vertexHandleRadius(),s=new a.Graphics;s.circle(0,0,i*.8).fill({color:16777215,alpha:.6}).stroke({width:1,color:2001125}),s.visible=!1,s.eventMode=`none`,this.handleLayer.addChild(s),this.ghostNode=s;for(let t=0;t<r;t++){let r=n[t],i=n[(t+1)%n.length],o=new a.Graphics;o.hitArea=this.edgeHitQuad(r,i),o.eventMode=`static`,this.bindCursor(o,`copy`);let c=e=>{let t=this.toImage(e),n=i.x-r.x,a=i.y-r.y,o=n*n+a*a,s=o?Math.max(0,Math.min(1,((t.x-r.x)*n+(t.y-r.y)*a)/o)):0;return{x:r.x+s*n,y:r.y+s*a}};o.on(`pointermove`,e=>{if(this.activeDrag)return;let t=this.imgToScreen(c(e));s.position.set(t.x,t.y),s.visible=!0}),o.on(`pointerleave`,()=>{s.visible=!1}),o.on(`pointerdown`,r=>{r.stopPropagation();let i=c(r),a=t+1,o=[...n.slice(0,a),i,...n.slice(a)],s=this.shapes.find(t=>t.id===e.id);s&&(s.points=o),this.liveUpdateShape(e.id,o),this.selectedVertices=new Set([a]),this.drawTransformer(),this.cb.onTransformCommit?.([{id:e.id,points:o}]),this.activeDrag={kind:`vertex`,id:e.id,indices:[a],base:o,start:i},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`vertexDragging`)}),this.handleLayer.addChild(o),this.midNodes.push(o)}this.vertexPolygonId!==e.id&&(this.vertexPolygonId=e.id,this.selectedVertices.clear()),n.forEach((t,r)=>{let o=this.imgToScreen(t),s=this.selectedVertices.has(r),c=new a.Graphics;c.circle(0,0,i).fill({color:s?2001125:16777215}).stroke({width:Math.max(1.5,i*.3),color:s?16777215:2001125}),c.position.set(o.x,o.y),c.eventMode=`static`,this.bindCursor(c,`pointer`),c.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(c),this.vertexNodes.push(c)})}if(e.length===1&&e[0].type===o.ROTATED_RECTANGLE){let t=e[0],n=A(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=Yn(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){h.forEach((t,n)=>{let r=this.imgToScreen(_(t,e)),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,0)}),this.setTransformerOutline(e)}repositionOrientedHandles(e){let t=this.orientedHandleAngle(e);if(j(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=this.midNodes[t];n&&(n.hitArea=this.edgeHitQuad(e[t],e[(t+1)%e.length]))}}edgeHitQuad(e,t){let n=Math.max(7,this.vertexHandleRadius()+2),r=this.imgToScreen(e),i=this.imgToScreen(t),o=i.x-r.x,s=i.y-r.y,c=Math.hypot(o,s)||1,l=-s/c*n,u=o/c*n;return new a.Polygon([r.x+l,r.y+u,i.x+l,i.y+u,i.x-l,i.y-u,r.x-l,r.y-u])}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=Kn(this.shapes,t),{updates:r,box:i}=qn(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)}}cancelTransform(){if(!this.activeDrag)return;let e=this.activeDrag.kind===`move`;this.activeDrag=null,this.lastDragImg=null,e&&this.resetMoveOffsets();for(let e of this.shapes)this.liveUpdateShape(e.id,e.points);this.cb.onTransformPreview?.(this.shapes.map(e=>({id:e.id,points:e.points}))),this.emitInteractionMode(`idle`),this.emitCursorHint(null),this.drawSelectionBorders()}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}=qn(e,t,Kn(this.shapes,e));e.kind===`move`&&this.resetMoveOffsets(),this.commitTransformUpdates(n)}};function fr({currentDocId:e,documentId:t,loadedUrl:n,renderedImageUrl:r}){if(!r)return e!==null||n!==null?{kind:`clear`}:{kind:`none`};let i=e!==t;return!i&&n===r?{kind:`none`}:{kind:`load`,docChange:i}}function pr({keepZoomOnImageChange:e,viewportSeeded:t}){return e&&t}function mr({backend:e,hostRef:t,engineRef:n,documentId:i,renderedImageUrl:a,makeCallbacks:o,viewRef:s,readOnlyRef:c,toolRef:l,renderShapesRef:u,coordinateSizeRef:d,imageSizeRef:f,selRef:p,regionOverlayRef:m,dimmedRef:h,syncMinimap:g,setImage:_,setImageVisible:v,setReady:y,setImageStatus:b,onContextMenuRequest:x}){let S=(0,r.useRef)(a);S.current=a;let C=(0,r.useRef)(i);C.current=i;let w=(0,r.useRef)(null),T=(0,r.useRef)(null),E=(0,r.useRef)(!1),D=(0,r.useRef)(null),O=(0,r.useRef)(!1),k=(0,r.useRef)(o);k.current=o;let A=(0,r.useRef)(x);A.current=x,(0,r.useEffect)(()=>{let r=t.current;if(!r)return;let i=!1,a=null,o=null,x=k.current(),j=e===`konva`?new sr(r,x):new dr(r,x);return n.current=j,O.current=!1,(async()=>{try{await j.init()}catch(e){i||b(`error`,Ln(e));return}if(i)return;if(j.setFilter(s.current.brightness,s.current.contrast),j.setRenderDefaults({strokeWidth:s.current.strokeSize}),j.setImageSmoothing(s.current.imageSmoothing),j.setTransformEnabled(!c.current),E.current=!0,S.current){let e=S.current,t=C.current;b(`loading`);let n=null;try{n=await j.setImage(e,d.current,f.current)}catch(t){!i&&S.current===e&&b(`error`,Ln(t))}if(i)return;if(n!==null){w.current=e,T.current=t,_({w:j.imageWidth,h:j.imageHeight}),v(!0),j.setShapes(u.current,p.current),j.setOverlays(s.current.showRegionMask?m.current:null,h.current);let r=D.current;r?.viewport&&(r.imageUrl===w.current||s.current.keepZoomOnImageChange)?j.applyViewport(r.viewport):j.fit(),O.current=!0,g(),y(!0);let a=()=>S.current===e;n?a()&&b(`ready`):Pn(e).then(e=>{!i&&a()&&b(`error`,e)})}}let e=(e,t)=>Math.exp(-Math.sign(e)*Math.min(Math.abs(e)*.01,.1)*t);a=t=>{t.preventDefault();let n=j.dom.getBoundingClientRect(),r=s.current.zoomSensitivity??1;if(t.ctrlKey||t.metaKey){j.zoomAt(t.clientX-n.left,t.clientY-n.top,e(t.deltaY,r));return}if(!s.current.wheelZoom){let e=j.viewport;j.applyViewport({scale:e.scale,x:e.x-t.deltaX,y:e.y-t.deltaY});return}j.zoomAt(t.clientX-n.left,t.clientY-n.top,e(t.deltaY,r))},j.dom.addEventListener(`wheel`,a,{passive:!1}),o=e=>{if(e.preventDefault(),l.current===W.ASSISTANT_POINT&&e.altKey)return;let t=r.getBoundingClientRect(),n=e.clientX-t.left,i=e.clientY-t.top,a=j.viewport;A.current({x:n,y:i,img:{x:(n-a.x)/a.scale,y:(i-a.y)/a.scale}})},j.dom.addEventListener(`contextmenu`,o)})(),()=>{i=!0,E.current=!1,D.current={imageUrl:w.current??``,viewport:j.viewport},n.current=null,a&&j.dom&&j.dom.removeEventListener(`wheel`,a),o&&j.dom&&j.dom.removeEventListener(`contextmenu`,o),j.destroy()}},[e]),(0,r.useEffect)(()=>{let e=n.current;if(!e||!E.current)return;let t=fr({currentDocId:T.current,documentId:i,loadedUrl:w.current,renderedImageUrl:a});if(t.kind===`none`)return;let r=()=>{y(!1),v(!1),e.clearImage(),e.setShapes([],[]),e.setOverlays(null,!1)};if(t.kind===`clear`){w.current=null,T.current=null,r(),b(`loading`);return}let o=a;t.docChange&&(T.current=null,r());let c=!1;return(async()=>{b(`loading`);let r=!1;try{r=await e.setImage(o,d.current,f.current)}catch(t){!c&&n.current===e&&b(`error`,Ln(t));return}if(c||n.current!==e)return;w.current=o;let a=()=>{if(r){b(`ready`);return}Pn(o).then(e=>{c||b(`error`,e)})};if(!t.docChange){a();return}T.current=i,_({w:e.imageWidth,h:e.imageHeight}),v(!0),e.setShapes(u.current,p.current),e.setOverlays(s.current.showRegionMask?m.current:null,h.current),pr({keepZoomOnImageChange:s.current.keepZoomOnImageChange,viewportSeeded:O.current})||e.fit(),O.current=!0,g(),y(!0),a()})(),()=>{c=!0}},[i,a])}var hr=.05,gr=20;function _r(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 vr(e){let t=e.currentTarget.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}function yr({engineRef:e,image:t,wheelZoom:n,minimapSize:i}){let a=(0,r.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=(0,r.useCallback)(()=>{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}},[e,s,u,d]),p=(0,r.useCallback)((n,r,i)=>{let a=e.current;if(!a||!t)return;let o=f();if(!o)return;let c=i?.offsetX??o.width/2,l=i?.offsetY??o.height/2,p=n.x-c+o.width/2,m=n.y-l+o.height/2,h=(p-u)/s,g=(m-d)/s;a.applyViewport({scale:r,x:a.screenSize.w/2-h*r,y:a.screenSize.h/2-g*r})},[e,f,t,s,u,d]),m=(0,r.useCallback)(t=>{let n=e.current,r=f();if(!n||!r)return;t.preventDefault(),t.stopPropagation();let i=vr(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),p(i,n.viewport.scale,o)},[p,e,f]),h=(0,r.useCallback)(t=>{let n=a.current,r=e.current;!n||!r||n.pointerId!==t.pointerId||(t.preventDefault(),t.stopPropagation(),p(vr(t),r.viewport.scale,n))},[p,e]),g=(0,r.useCallback)(e=>{let t=a.current;!t||t.pointerId!==e.pointerId||(a.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))},[]),_=(0,r.useCallback)(t=>{let r=e.current;if(!r||!n)return;t.preventDefault(),t.stopPropagation();let i=_r(t.nativeEvent)?2.5:1,a=t.deltaY*i,o=1.05,s=a>0?r.viewport.scale/o:r.viewport.scale*o,c=Math.max(hr,Math.min(gr,s));p(vr(t),c)},[p,e,n]),v=(0,r.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,r.useMemo)(()=>({mm:s,offX:u,offY:d,dispW:c,dispH:l,handleMinimapPointerDown:m,handleMinimapPointerMove:h,endMinimapDrag:g,handleMinimapWheel:_,zoomCentered:v}),[s,u,d,c,l,m,h,g,_,v])}function br(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=g(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 xr({engineRef:e,docRef:t,overlayRef:n,zoomLabelRef:i,minimapRectRef:a,minimapSize:o,onViewportChangeRef:s,onScreenOverlaySyncRef:c}){let l=(0,r.useRef)(new Map);return{registerMinimapShape:(0,r.useCallback)((e,t)=>{t?l.current.set(e,t):l.current.delete(e)},[]),applyMinimapPreview:(0,r.useCallback)(e=>{let n=t.current.getShapes();if(!e.length){for(let e of n)br(l.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&&br(l.current.get(e.id),e,t.points)}},[t]),syncMinimap:(0,r.useCallback)(()=>{let t=e.current;if(!t?.imageWidth)return;let r=t.viewport;if(s.current?.(r),n.current){n.current.style.transform=`translate(${r.x}px, ${r.y}px) scale(${r.scale})`;let e=1/(r.scale||1);n.current.style.setProperty(`--editor-overlay-stroke`,`${e}`),n.current.style.setProperty(`--editor-overlay-dash`,`${4*e}`),n.current.style.setProperty(`--editor-overlay-inverse-scale`,`${e}`)}c.current?.(r),i.current&&(i.current.textContent=`${Math.round(r.scale*100)}%`);let l=a.current;if(!l)return;let u=Math.min(o/t.imageWidth,o/t.imageHeight),d=(o-t.imageWidth*u)/2,f=(o-t.imageHeight*u)/2,{w:p,h:m}=t.screenSize;l.style.left=`${-r.x/r.scale*u+d}px`,l.style.top=`${-r.y/r.scale*u+f}px`,l.style.width=`${p/r.scale*u}px`,l.style.height=`${m/r.scale*u}px`},[e,n,i,a,o,s])}}var Sr=12;function Cr({doc:e,selRef:t,effectiveReadOnly:n,changeSelection:i,canMergeSelection:a,clipboardDocumentId:s,clipboardScope:c}){let d=(0,r.useRef)(0),f=(0,r.useRef)(!0),p=(0,r.useRef)(n),h=(0,r.useRef)(s),_=(0,r.useRef)(c);p.current=n,h.current=s,_.current=c,(0,r.useEffect)(()=>(f.current=!0,()=>{f.current=!1}),[]),(0,r.useEffect)(()=>{d.current=0},[s]);let v=(0,r.useCallback)(()=>i(e.getShapes().filter(e=>l(e)).map(e=>e.id)),[e,i]),y=(0,r.useCallback)(()=>i([]),[i]),b=(0,r.useCallback)(()=>e.getShapes().filter(e=>t.current.includes(e.id)&&u(e)),[e,t]),x=(0,r.useCallback)(()=>{if(n||!t.current.length)return;let r=b().map(e=>e.id);r.length&&(e.remove(r),i([]))},[e,n,i,b,t]),S=(0,r.useCallback)(()=>{let e=b();e.length&&(d.current=0,st(it(e,s,c)))},[s,c,b]),C=(0,r.useCallback)(()=>J(c),[c]),w=(0,r.useCallback)(t=>{if(n)return;let r=s;lt(c).then(n=>{if(!f.current||p.current||h.current!==r||_.current!==c||!n?.shapes.length)return;let a,o,l=n.shapes.flatMap(e=>e.points);if(t&&l.length){let e=g(l);a=t.x-(e.minX+e.maxX)/2,o=t.y-(e.minY+e.maxY)/2}else{let e=!!n.documentId&&n.documentId!==s,t=ut(d.current,e,Sr);a=t.offset,d.current=t.nextPasteCount,o=a}let u=n.shapes.map(e=>({...e,id:m(),points:e.points.map(e=>({x:e.x+a,y:e.y+o}))}));e.create(u),i(u.map(e=>e.id))})},[s,c,e,n,i]),T=(0,r.useCallback)(()=>{if(n||!t.current.length)return;let r=b().map(e=>({...e,id:m(),points:e.points.map(e=>({x:e.x+Sr,y:e.y+Sr}))}));r.length&&(e.create(r),i(r.map(e=>e.id)))},[e,n,i,b,t]),E=(0,r.useCallback)(()=>{if(n)return;let t=b().map(e=>e.id);t.length&&e.reorder(t,`front`)},[e,n,b]),D=(0,r.useCallback)(()=>{if(n)return;let t=b().map(e=>e.id);t.length&&e.reorder(t,`back`)},[e,n,b]),O=(0,r.useCallback)((r,i)=>{if(n||!t.current.length)return!1;let a=e.getShapes().filter(e=>t.current.includes(e.id)&&u(e));return a.length?(e.update(a.map(e=>({...e,points:e.points.map(e=>({x:e.x+r,y:e.y+i}))}))),!0):!1},[e,n,t]),k=(0,r.useCallback)(()=>b().filter(e=>e.type===o.POLYGON||e.type===o.RECTANGLE||e.type===o.ROTATED_RECTANGLE||e.type===o.ELLIPSE),[b]);return{selectAll:v,clearSelection:y,getEditableSelection:b,deleteSelection:x,copySelection:S,canPaste:C,paste:w,duplicate:T,bringToFront:E,sendToBack:D,nudgeSelection:O,getMergeTargets:k,mergeSelection:(0,r.useCallback)(()=>{if(n)return;let t=k();if(t.length<2||a&&!a(t))return;let r=en([],1,$t(t));if(!r)return;let s=tn(r,1);if(!s.length)return;let c=t[0],l=s.map(e=>({id:m(),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,n,k,a,i])}}function wr({engineRef:e,doc:t,selRef:n,zoomAnimationDuration:i,zoomBound:a,ready:o}){let s=(0,r.useRef)(null),c=(0,r.useRef)(null),l=(0,r.useCallback)(()=>{s.current?.(),s.current=null},[]),u=(0,r.useCallback)((t,n=i)=>{let r=e.current;r&&(l(),s.current=Lt(r.viewport,t,e=>r.applyViewport(e),n))},[l,i,e]),d=(0,r.useCallback)((t,n=i)=>{let r=e.current;if(!r)return;let a=Ft(t,r.screenSize.w,r.screenSize.h);a&&u(a,n)},[u,i,e]),f=(0,r.useCallback)((e,n=i)=>{let r=Pt(t.getShapes().filter(t=>e.includes(t.id)));r&&d(r,n)},[t,d,i]),p=(0,r.useCallback)(()=>{let r=t.getShapes().filter(e=>n.current.includes(e.id));if(!r.length)return;let i=e.current;if(!i)return;let a=It(g(r.flatMap(e=>e.points)),i.screenSize.w,i.screenSize.h,80);a&&u(a)},[t,u,e,n]),m=(0,r.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,r.useEffect)(()=>()=>l(),[l]),(0,r.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 Tr=`__draft_preview__`,Er=new Set([`copy`,`selectAll`,`clearSelection`,`zoomToSelection`]);function Dr(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Or({document:t,clipboardScope:i,renderImageState:a,dimmed:c=!1,selectedIds:d,activeTool:f,draftStyle:p,draftMeta:h,readOnly:g,disableMarquee:_,locked:v,onLockedInteraction:y,onDrawAttemptWithoutDraft:b,onIdleEscape:x,overrideShapeInteraction:S,defaultViewSettings:C,viewSettings:w,onViewSettingsChange:T,showMinimap:E=!0,minimapPosition:D=`bottom-left`,showViewSettings:O=!0,getContextMenuItems:k,strings:A,viewSettingItems:j,canMergeSelection:M,brushSize:N=20,zoomBound:P,zoomAnimationDuration:F=300,decorationShapes:I,regionMask:L,overlayMarkers:R,renderOverlayMarker:ee,onOverlayMarkerClick:te,renderImageOverlay:ne,getSelectionLabel:re,hideSelectionLabelDot:ie,formatSelectionInfo:z,externalTools:B,assistant:V,keymap:ae,handleRef:oe,backend:H=`pixi`,onActiveToolChange:U,onSelectionChange:le,onEditingChange:ue,onShapesCreated:fe,onShapesUpdated:pe,onShapesDeleted:me,onDrawSessionChange:he,onDraftShapeChange:_e,onViewportChange:xe,onShapesTransformPreview:Se}){let Ce=(0,r.useRef)(null),G=(0,r.useRef)(null),we=(0,r.useRef)(null),Te=(0,r.useRef)(null),Ee=(0,r.useRef)(null),De=`${(0,r.useId)()}-minimap`,[K,Oe]=(0,r.useState)(null),[ke,Ae]=(0,r.useState)(!1),[je,Me]=(0,r.useState)(!1),[Ne,Pe]=(0,r.useState)(null),[Fe,Ie]=(0,r.useState)({active:!1,kind:`none`,canUndo:!1,canRedo:!1}),[Re,ze]=(0,r.useState)(!0),[Be,Ve]=(0,r.useState)(!1),He=t?.id??``,Ue=t?.imageUrl??``,Je=t?.displayImageUrl,Xe=t?.coordinateSize,Ze=t?.initialShapes,Qe=t?.initialSelectedIds,$e=Je??Ue,[et,tt]=(0,r.useState)(`loading`),nt=et===`loading`&&t!==null&&!$e?`missing`:et,[rt,it]=(0,r.useState)(null),ot=(0,r.useCallback)((e,t)=>{tt(e),it(e===`error`?t??null:null)},[]),q=pn({onShapesCreated:fe,onShapesUpdated:pe,onShapesDeleted:me}),[st,ct]=(0,r.useState)([]),J=d??st,lt=d!==void 0,ut=(0,r.useMemo)(()=>new Map((B??[]).map(e=>[e.id,e])),[B]),dt=(0,r.useRef)(ut);(0,r.useLayoutEffect)(()=>{dt.current=ut},[ut]);let ft=(0,r.useRef)(Fe);ft.current=Fe;let pt=(0,r.useMemo)(()=>{let e=Object.fromEntries(Object.entries(C??{}).filter(([,e])=>e!==void 0));return de({...ce,...e})},[C]),mt=(0,r.useRef)(pt);mt.current=pt;let[Y,ht]=(0,r.useState)(()=>mt.current),gt=(0,r.useCallback)(e=>ht(t=>de({...t,...e})),[]),X=(0,r.useMemo)(()=>se(A),[A]);(0,r.useEffect)(()=>{if(!w)return;let e=de(w);ht(t=>{let n=Object.entries(e).filter(([e,n])=>n!==void 0&&t[e]!==n);return n.length?{...t,...Object.fromEntries(n)}:t})},[w]);let vt=(0,r.useRef)(T);vt.current=T;let yt=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!yt.current){yt.current=!0;return}vt.current?.(Y)},[Y]);let bt=(0,r.useMemo)(()=>!K||!L?null:kt(L,K.w,K.h),[K,L]),xt=(0,r.useRef)(bt);xt.current=bt;let St=(0,r.useRef)(c);St.current=c;let Ct=(0,r.useRef)(K);Ct.current=K;let wt=(0,r.useRef)(Xe);wt.current=Xe;let Tt=(0,r.useRef)(Xe?.imageSize);Tt.current=Xe?.imageSize;let Et=(0,r.useRef)(J);(0,r.useLayoutEffect)(()=>{Et.current=J},[J]);let Dt=(0,r.useRef)(f);Dt.current=f;let Ot=(0,r.useRef)(p);Ot.current=p;let At=(0,r.useRef)(h);At.current=h;let jt=(0,r.useRef)(N);jt.current=N;let Mt=(0,r.useRef)(Y.simplifyStrength);Mt.current=Y.simplifyStrength;let Z=!!g||!!v,Nt=(0,r.useRef)(Z);Nt.current=Z;let Pt=(0,r.useRef)(_);Pt.current=_;let Ft=(0,r.useRef)(v);Ft.current=v;let It=(0,r.useRef)(y);It.current=y;let Lt=(0,r.useRef)(g);Lt.current=g;let Bt=(0,r.useCallback)((e=!0)=>Lt.current||!Ft.current||!e?!1:(It.current?.(),!0),[]),Vt=(0,r.useRef)(b);Vt.current=b;let Ht=(0,r.useRef)(S);Ht.current=S;let Ut=(0,r.useRef)(q);Ut.current=q;let Wt=(0,r.useRef)(!1),Gt=(0,r.useRef)(`idle`),Kt=(0,r.useRef)(null),qt=(0,r.useCallback)(()=>{let e=G.current;if(!e)return;let t=Dt.current,n=dt.current.get(t),r=ft.current;e.setCursor(_t({tool:t,externalToolCursor:n?.cursor,isSpacePressed:Wt.current,interactionMode:Gt.current,rendererCursorHint:Kt.current,isPolygonDrawing:r.kind===`polygon`&&r.active}))},[]),Jt=(0,r.useCallback)(e=>{Gt.current!==e&&(Gt.current=e,qt())},[qt]),Yt=(0,r.useCallback)(e=>{Kt.current!==e&&(Kt.current=e,qt())},[qt]),Xt=(0,r.useCallback)(e=>{let t=new Set,n=new Map(Ut.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=Ht.current?.(r);return l(i?{...r,interaction:{...r.interaction,...i}}:r)})},[]),Zt=(0,r.useCallback)(e=>{let t=Xt(e);Dr(Et.current,t)||(lt||ct(t),G.current?.setSelection(t),le?.(t))},[Xt,le,lt]),Qt=(0,r.useRef)(Zt);Qt.current=Zt;let[$t,en]=(0,r.useState)(null),tn=(0,r.useCallback)(e=>en(e),[]),nn=(0,r.useRef)(tn);nn.current=tn;let rn=(0,r.useRef)(null);rn.current=$t,(0,r.useEffect)(()=>{if(!lt)return;let e=Xt(d);Dr(d,e)||le?.(e)},[d,q.shapes,Xt,le,lt]);let an=(0,r.useRef)(xe);an.current=xe;let on=(0,r.useRef)(null),{registerMinimapShape:sn,applyMinimapPreview:cn,syncMinimap:ln}=xr({engineRef:G,docRef:Ut,overlayRef:Te,zoomLabelRef:Ee,minimapRectRef:we,minimapSize:204,onViewportChangeRef:an,onScreenOverlaySyncRef:on}),dn=(0,r.useRef)(new Map),fn=(0,r.useRef)(z);fn.current=z;let mn=(0,r.useCallback)((e,t)=>{t?dn.current.set(e,t):dn.current.delete(e)},[]);on.current=e=>{for(let t of dn.current.values())Ge(t,e)};let hn=(0,r.useRef)(null),[gn,_n]=(0,r.useState)(null),vn=(0,r.useCallback)(e=>{if(!e.length)return;let t=new Map(Ut.current.getShapes().map(e=>[e.id,e]));hn.current&&t.set(hn.current.id,hn.current);for(let{id:n,points:r}of e){let e=dn.current.get(n),i=t.get(n);if(!e||!i)continue;let a=G.current?.viewport;if(!a)continue;let o=We(e,r,a);if(o){let e=Ke(i,r);o.textContent=fn.current?.(e)??qe(e)}}},[]),yn=(0,r.useCallback)(e=>{cn(e),vn(e),Se?.(e)},[cn,vn,Se]),bn=(0,r.useCallback)(e=>{if(_e?.(e?{...e,meta:At.current}:null),!e||!Ot.current){hn.current&&(hn.current=null,_n(null));return}let t={id:Tr,type:e.type,points:e.points,style:Ot.current,meta:At.current},n=hn.current!==null;hn.current=t,n?vn([{id:Tr,points:e.points}]):_n(t)},[vn,_e]),Sn=(0,r.useCallback)((e,t)=>{let n=Ot.current;if(!n||Nt.current)return;let r=m();Ut.current.create({id:r,type:e,points:t,style:n,meta:h}),Qt.current([r])},[h]),Cn=(0,r.useRef)(Sn);Cn.current=Sn;let wn=un({toolRef:Dt,selRef:Et,docRef:Ut,readOnlyRef:Nt,draftRef:Ot,brushSizeRef:jt,simplifyEpsilonRef:Mt,draftMeta:h,engineRef:G,onDrawSessionChange:(0,r.useCallback)(e=>{Ie(e),he?.(e)},[he]),onDraftShapeChange:_e,changeSelection:Zt,createShape:Sn}),Tn=(0,r.useRef)(wn);Tn.current=wn;let{reset:En,undoSession:Dn,redoSession:On,canUndoSession:kn,canRedoSession:An,hasDraftSession:jn,hasDraftPoints:Mn,commitDraftSession:Nn,setBrushScalarMode:Pn,getBrushScalarMode:Fn,hasBrushSession:In,commitBrush:Ln,cancelBrush:Rn,beginBrushEditFromSelection:zn,deleteDraftSelectedPoints:Bn,handleToolChange:Vn,handleBrushSelectionChange:Hn}=wn,Un=(0,r.useRef)(V);Un.current=V;let Q=zt({docRef:Ut,draftRef:Ot,draftMeta:h,changeSelection:Zt,assistantRef:Un}),Wn=(0,r.useRef)(Q);Wn.current=Q;let Gn=(0,r.useMemo)(()=>at(He),[He]),{selectAll:Kn,clearSelection:qn,deleteSelection:Jn,copySelection:Yn,canPaste:Xn,paste:Zn,duplicate:Qn,bringToFront:$n,sendToBack:er,nudgeSelection:tr,getMergeTargets:nr,mergeSelection:rr}=Cr({doc:q,selRef:Et,effectiveReadOnly:Z,changeSelection:Zt,canMergeSelection:M,clipboardDocumentId:Gn,clipboardScope:i??Gn}),{zoomToBounds:ir,zoomToShapes:ar,zoomToSelection:or,zoomAtCenter:sr}=wr({engineRef:G,doc:q,selRef:Et,zoomAnimationDuration:F,zoomBound:P,ready:je});(0,r.useImperativeHandle)(oe,()=>({previewRegionMask:e=>{let t=Ct.current;if(!t)return;let n=e?kt(e,t.w,t.h):xt.current;G.current?.setRegionOverlay(cr.current.showRegionMask?n:null)},undo:()=>{Nt.current||Dn()||q.undo()},redo:()=>{Nt.current||On()||q.redo()},canUndo:()=>kn()||q.canUndo(),canRedo:()=>An()||q.canRedo(),undoSession:Dn,redoSession:On,canUndoSession:kn,canRedoSession:An,hasDraftSession:jn,cancelDraftSession:En,commitDraftSession:Nn,setSelection:Zt,createShapes:e=>{!e.length||Bt()||(q.create(e),Zt(e.map(e=>e.id)))},updateShapes:e=>{!e.length||Bt()||q.update(e)},deleteShapes:e=>{!e.length||Bt()||q.remove(e)},getShapes:q.getShapes,selectAll:Kn,clearSelection:qn,deleteSelection:Jn,copySelection:Yn,paste:Zn,duplicate:Qn,bringToFront:$n,sendToBack:er,zoomFit:()=>G.current?.fit(),zoom100:()=>G.current?.zoom100(),zoomIn:()=>{let e=G.current;if(!e)return;let{w:t,h:n}=e.screenSize;e.zoomAt(t/2,n/2,1.2)},zoomOut:()=>{let e=G.current;if(!e)return;let{w:t,h:n}=e.screenSize;e.zoomAt(t/2,n/2,1/1.2)},zoomToSelection:or,zoomToShapes:ar,zoomToBounds:ir,brush:{setScalarMode:Pn,getScalarMode:Fn,hasSession:In,commit:Ln,cancel:Rn,beginEditFromSelection:zn}}),[q,Zt,Bt,Dn,On,Nn,En,Ln,Rn,Kn,qn,Jn,Yn,Zn,Qn,$n,er,or,ar,ir,Pn,Fn,In,zn]);let cr=(0,r.useRef)(Y);cr.current=Y;let lr=(0,r.useCallback)(()=>Rt({engineRef:G,toolRef:Dt,externalToolMapRef:dt,spaceRef:Wt,docRef:Ut,selRef:Et,draftRef:Ot,readOnlyRef:Nt,disableMarqueeRef:Pt,lockedRef:Ft,onLockedInteraction:()=>It.current?.(),onDrawAttemptWithoutDraft:()=>Vt.current?.(),createRef:Cn,selectRef:Qt,enterEditRef:nn,editingIdRef:rn,drawSessionRef:Tn,assistantRef:Wn,setCursorHint:Yt,setInteractionMode:Jt,syncMinimap:ln,onTransformPreview:yn,onDrawPreview:bn}),[Yt,Jt,ln,yn,bn]),ur=(0,r.useRef)([]);mr({backend:H,hostRef:Ce,engineRef:G,documentId:He,renderedImageUrl:$e,makeCallbacks:lr,viewRef:cr,readOnlyRef:Nt,toolRef:Dt,renderShapesRef:ur,coordinateSizeRef:wt,imageSizeRef:Tt,selRef:Et,regionOverlayRef:xt,dimmedRef:St,syncMinimap:ln,setImage:Oe,setImageVisible:Ae,setReady:Me,setImageStatus:ot,onContextMenuRequest:Pe});let $=(0,r.useMemo)(()=>{let e=S?q.shapes.map(e=>{let t=S(e);return t?{...e,interaction:{...e.interaction,...t}}:e}):q.shapes;return I?.length?[...I.map(e=>({...e,interaction:{...e.interaction,selectable:!1,draggable:!1,editable:!1,hitTestDisabled:!0}})),...e]:e},[q.shapes,S,I]);ur.current=$,(0,r.useEffect)(()=>{G.current?.setShapes($,Et.current),ln()},[$,ln]),(0,r.useEffect)(()=>{G.current?.setSelection(J)},[J]),(0,r.useEffect)(()=>{G.current?.setEditing($t)},[$t,je]);let dr=(0,r.useRef)(ue);dr.current=ue,(0,r.useEffect)(()=>{dr.current?.($t)},[$t]),(0,r.useEffect)(()=>{en(null)},[f]),(0,r.useEffect)(()=>{$t&&(J.length!==1||J[0]!==$t)&&en(null)},[J,$t]),(0,r.useEffect)(()=>{let e=G.current;e&&(e.setFilter(Y.brightness,Y.contrast),e.setRenderDefaults({strokeWidth:Y.strokeSize}),e.setImageSmoothing(Y.imageSmoothing),ln())},[Y.brightness,Y.contrast,Y.strokeSize,Y.imageSmoothing,ln]),(0,r.useLayoutEffect)(()=>{je&&G.current?.setOverlays(Y.showRegionMask?bt:null,c)},[je,bt,Y.showRegionMask,c]),(0,r.useEffect)(()=>{!je||!K||ln()},[je,K,Y.showRegionMask,L,ln]),(0,r.useEffect)(()=>{je&&G.current?.setTransformEnabled(!Z&&f!==W.BRUSH)},[Z,je,f]),(0,r.useEffect)(()=>{v&&en(null)},[v]),(0,r.useEffect)(()=>{Vn(f,dt.current.has(f))},[f,Vn]);let fr=Q.finalize;(0,r.useEffect)(()=>{fr()},[f,fr]),(0,r.useEffect)(()=>{Gt.current=`idle`,Kt.current=null,qt()},[f,H,qt]),(0,r.useEffect)(()=>{Hn(J,Z)},[J,f,Z,Hn]),(0,r.useEffect)(()=>{je&&qt()},[f,Fe,ut,je,qt]);let pr=(0,r.useRef)(Qe);pr.current=Qe;let hr=t!==null,gr=(0,r.useRef)(null);(0,r.useEffect)(()=>{let e=hr?He:null;gr.current!==e&&(gr.current=e,Pe(null),en(null),Gt.current=`idle`,Kt.current=null,q.reset(hr?Ze??[]:[]),Zt(hr?pr.current??[]:[]),En(),fr(),qt())},[hr,He,Ze,q.reset,Zt,En,fr,qt]);let _r=(0,r.useCallback)(()=>{let e=rn.current;if(!e||Z)return!1;let t=G.current,n=new Set(t?.getVertexSelection()??[]);if(!n.size)return!1;let r=Ut.current.getShapes().find(t=>t.id===e);if(!r)return!1;let i=r.points.filter((e,t)=>!n.has(t)),a=r.type===o.LINE?2:3;return i.length<a?!1:(Ut.current.update([{...r,points:i}]),t?.setVertexSelection([]),!0)},[Z]),vr=()=>q.getShapes().some(e=>Et.current.includes(e.id)&&u(e));xn({keymap:ae,hostRef:Ce,actions:{undo:()=>{Z||Dn()||q.undo()},redo:()=>{Z||On()||q.redo()},selectAll:Kn,copy:Yn,cut:()=>{Bt(vr())||(Yn(),Jn())},paste:()=>{Bt(Xn())||Zn()},duplicate:()=>{Bt(vr())||Qn()},delete:()=>{Bt(vr())||Mn()&&Bn()||_r()||Jn()},cancel:()=>{let e=dt.current.get(Dt.current);if(!(e?.onCancel&&e.onCancel()!==!1)){if(Q.isActive()){Q.cancel();return}if(jn()){En();return}if($t){en(null);return}if(Et.current.length){qn();return}x?.()}},commitDraft:()=>{if(Q.isActive()){Q.finalize();return}if(jn()){Nn();return}if(Z)return;if($t){en(null);return}let e=Et.current;if(e.length!==1)return;let t=Ut.current.getShapes().find(t=>t.id===e[0]);t&&(t.type===o.POLYGON||t.type===o.LINE)&&t.interaction?.editable!==!1&&!t.readOnly&&en(e[0])},bringToFront:$n,sendToBack:er,zoomIn:()=>sr(1.2),zoomOut:()=>sr(1/1.2),zoom100:()=>G.current?.zoom100(),zoomFit:()=>G.current?.fit(),toggleMinimap:()=>ze(e=>!e),toggleCursorGuide:()=>ht(e=>({...e,showCursorGuide:!e.showCursorGuide})),togglePixelation:()=>ht(e=>({...e,imageSmoothing:!e.imageSmoothing})),selectTool:()=>U?.(W.SELECT),rectangleTool:()=>U?.(W.RECTANGLE),rotatedRectangleTool:()=>U?.(W.ROTATED_RECTANGLE),circleTool:()=>U?.(W.CIRCLE),polygonTool:()=>U?.(W.POLYGON),pathTool:()=>U?.(W.PATH),brushTool:()=>U?.(W.BRUSH),pointTool:()=>U?.(W.POINT)},spaceRef:Wt,onSpaceDown:()=>{G.current?.setPanMode(!0),qt()},onSpaceUp:()=>{G.current?.setPanMode(!1),Gt.current===`panning`?Jt(`idle`):qt()},nudge:(e,t)=>Bt(vr())||tr(e,t)});let br=(0,r.useMemo)(()=>$.filter(e=>J.includes(e.id)&&s(e)),[$,J]),Sr=(0,r.useMemo)(()=>gn?[...br,gn]:br,[br,gn]),Or=J.length>0,kr=q.shapes.some(e=>J.includes(e.id)&&u(e)),Ar=!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})(),jr=nr(),Mr=Z||jr.length<2||(M?!M(jr):!1),Nr=!!V&&!Z,Pr=Nr&&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,Fr=[{id:`copy`,label:X.contextMenu.copy,shortcut:`⌘C`,disabled:!kr,onClick:Yn},{id:`paste`,label:X.contextMenu.paste,shortcut:`⌘V`,disabled:Z||!Xn(),onClick:()=>Zn(Ne?.img)},{id:`duplicate`,label:X.contextMenu.duplicate,shortcut:`⌘D`,disabled:!kr||Z,onClick:Qn},{id:`delete`,label:X.contextMenu.delete,shortcut:`Del`,danger:!0,disabled:!kr||Z,onClick:Jn},{separator:!0},{id:`editVertices`,label:X.contextMenu.editVertices,shortcut:`Enter`,disabled:!Ar,onClick:()=>en(J[0])},{id:`merge`,label:X.contextMenu.merge,disabled:Mr,onClick:rr},...Nr?[{id:`assistExpand`,label:X.contextMenu.assistExpand,icon:(0,n.jsx)(e.rr,{size:14}),disabled:!Pr,onClick:()=>{Ne&&Pr&&Q.refineShape(Pr,Ne.img,!0)}},{id:`assistExclude`,label:X.contextMenu.assistExclude,icon:(0,n.jsx)(e.rr,{size:14}),disabled:!Pr,onClick:()=>{Ne&&Pr&&Q.refineShape(Pr,Ne.img,!1)}}]:[],{id:`bringToFront`,label:X.contextMenu.bringToFront,disabled:!kr||Z,onClick:$n},{id:`sendToBack`,label:X.contextMenu.sendToBack,disabled:!kr||Z,onClick:er},{separator:!0},{id:`undo`,label:X.contextMenu.undo,shortcut:`⌘Z`,disabled:Z||!kn()&&!q.canUndo(),onClick:()=>{Dn()||q.undo()}},{id:`redo`,label:X.contextMenu.redo,shortcut:`⇧⌘Z`,disabled:Z||!An()&&!q.canRedo(),onClick:()=>{On()||q.redo()}},{separator:!0},{id:`selectAll`,label:X.contextMenu.selectAll,shortcut:`⌘A`,onClick:Kn},{id:`clearSelection`,label:X.contextMenu.clearSelection,disabled:!Or,onClick:qn},{id:`zoomToSelection`,label:X.contextMenu.zoomToSelection,disabled:!Or,onClick:or}],Ir=g?Fr.filter(e=>`separator`in e||!!e.id&&Er.has(e.id)):Fr,Lr=k?k(Ir,{selectedIds:J,readOnly:Z}):Ir,Rr=yr({engineRef:G,image:K,wheelZoom:Y.wheelZoom,minimapSize:204}),zr=(0,r.useCallback)(()=>{G.current?.zoom100()},[]),Br=(0,r.useCallback)(()=>{ze(e=>!e)},[]),Vr=(0,r.useCallback)(()=>{Ve(e=>!e)},[]),Hr=(0,r.useCallback)(()=>{Ve(!1)},[]);return(0,n.jsxs)(`div`,{className:`aivex:relative aivex:h-full aivex:w-full aivex:overflow-hidden aivex:bg-black`,children:[(0,n.jsx)(`div`,{ref:Ce,role:`application`,"aria-label":X.canvasLabel,tabIndex:0,onPointerDownCapture:e=>e.currentTarget.focus({preventScroll:!0}),className:`aivex:h-full aivex:w-full`,style:{opacity:+!!ke,transition:ke?`opacity 0.3s ease`:`none`}}),nt!==`ready`&&(0,n.jsx)(be,{status:nt,error:rt,render:a,loadingLabel:X.imageLoading,missingLabel:X.imageMissing,errorLabel:X.imageLoadError,errorHints:X.imageErrorHints}),je&&K&&(0,n.jsxs)(`div`,{className:`aivex:pointer-events-none aivex:absolute aivex:inset-0 aivex:overflow-hidden`,children:[Sr.length>0&&(0,n.jsx)(`div`,{className:`aivex:absolute aivex:inset-0`,children:(0,n.jsx)(Ye,{shapes:Sr,getLabel:re,hideDot:ie,formatInfo:z,register:mn,viewport:G.current?.viewport??{scale:1,x:0,y:0}})}),(0,n.jsxs)(`div`,{ref:Te,style:{position:`absolute`,top:0,left:0,width:K.w,height:K.h,transformOrigin:`0 0`},children:[!!R?.length&&ee&&(0,n.jsx)(`div`,{style:{position:`absolute`,left:0,top:0,width:K.w,height:K.h,pointerEvents:`none`},children:R.map(e=>(0,n.jsx)(`div`,{role:e.disabled?void 0:`button`,tabIndex:e.disabled?void 0:0,"aria-pressed":e.selected||void 0,onClick:t=>{t.stopPropagation(),e.disabled||te?.(e)},onKeyDown:t=>{e.disabled||t.key!==`Enter`&&t.key!==` `||(t.preventDefault(),t.stopPropagation(),te?.(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:ee(e)},e.id))}),ne?.({image:K,viewport:G.current?.viewport??{scale:1,x:0,y:0}}),V&&(Q.status===`loading`||Q.boxes.length>0)&&(0,n.jsx)(ge,{image:K,points:Q.points,boxes:Q.boxes,status:Q.status})]})]}),je&&Y.showCursorGuide&&(0,n.jsx)(ye,{color:`#1e88e5`}),K&&E&&(0,n.jsx)(Le,{image:K,imageUrl:$e,imageVisible:ke,loading:!je,region:bt,roiMaskId:De,shapes:$,view:Y,viewDefaults:pt,onChangeView:gt,nav:Rr,registerShape:sn,rectRef:we,zoomLabelRef:Ee,onZoom100:zr,open:Re,onToggleOpen:Br,position:D,labels:X.minimap,settingsLabels:X.viewSettings,settingsItems:j,showSettings:O,settingsOpen:Be,onToggleSettings:Vr,onCloseSettings:Hr}),Ne&&(0,n.jsx)(ve,{x:Ne.x,y:Ne.y,items:Lr,onClose:()=>Pe(null)})]})}function kr({viewport:e,image:t,focusPoints:n,zoomPadding:r,focusFit:i}){let a=Math.min(e.width/t.width,e.height/t.height);if(!n?.length)return{scale:a,offsetX:(e.width-t.width*a)/2,offsetY:(e.height-t.height*a)/2};let o=g(n),s=Math.max(o.maxX-o.minX,50),c=Math.max(o.maxY-o.minY,50),l=Math.min(s,c)*r,u=Math.min(e.width/(s+l*2),e.height/(c+l*2));i===`cover`&&(u=Math.max(u,Math.max(e.width/t.width,e.height/t.height)));let d=e.width/2-(o.minX+o.maxX)/2*u,f=e.height/2-(o.minY+o.maxY)/2*u;return i===`cover`&&(d=Math.min(0,Math.max(d,e.width-t.width*u)),f=Math.min(0,Math.max(f,e.height-t.height*u))),{scale:u,offsetX:d,offsetY:f}}function Ar(e,t,n){let r=Math.max(0,-e.offsetX/e.scale),i=Math.max(0,-e.offsetY/e.scale),a=Math.min(n.width,(t.width-e.offsetX)/e.scale),o=Math.min(n.height,(t.height-e.offsetY)/e.scale);return a<=r||o<=i?null:{x:r,y:i,width:a-r,height:o-i}}function jr({visible:e,image:t,natural:n,density:r}){let i=n.width/t.width,a=n.height/t.height,o=Math.max(0,Math.floor(e.x*i)),s=Math.max(0,Math.floor(e.y*a)),c=Math.min(n.width,Math.ceil((e.x+e.width)*i))-o,l=Math.min(n.height,Math.ceil((e.y+e.height)*a))-s,u={x:o/i,y:s/a,width:c/i,height:l/a};return{source:{x:o,y:s,width:c,height:l},rect:u,outputWidth:Math.max(1,Math.min(c,Math.ceil(u.width*r))),outputHeight:Math.max(1,Math.min(l,Math.ceil(u.height*r)))}}function Mr(e,t,n){let r=1e-6;if(!(e.rect.x<=t.x+r&&e.rect.y<=t.y+r&&e.rect.x+e.rect.width>=t.x+t.width-r&&e.rect.y+e.rect.height>=t.y+t.height-r))return!1;let i=Math.min(n.density,n.natural.width/n.image.width),a=Math.min(n.density,n.natural.height/n.image.height);return e.outputWidth/e.rect.width>=i*.99&&e.outputHeight/e.rect.height>=a*.99}function Nr(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 Pr(e,t,n,r){if(t.interaction?.visible===!1)return;let i=Te(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 Nr(e,t.points,t.type!==o.LINE);i.fillVisible&&(e.save(),e.fillStyle=i.color,e.globalAlpha*=i.fillAlpha,e.fill(`evenodd`),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()}async function Fr(e,t,n){let r=await Tn(e);if(!r)return null;try{let i={width:r.width,height:r.height},a={url:e,smoothing:t,natural:i,bitmap:null,rect:{x:0,y:0,width:0,height:0},outputWidth:0,outputHeight:0},o=n(i);if(!o?.visibleRect)return a;let s=jr({visible:o.visibleRect,natural:i,...o}),c=await createImageBitmap(r.source,s.source.x,s.source.y,s.source.width,s.source.height,{resizeWidth:s.outputWidth,resizeHeight:s.outputHeight,resizeQuality:t?`high`:`pixelated`});return{...a,...s,bitmap:c}}catch{return null}finally{r.release()}}function Ir({imageUrl:e,alt:t=`Shape preview`,coordinateSize:i,shapes:a=[],regionMask:o,focusedShapeId:s,focusFit:c=`contain`,zoomPadding:l=.3,strokeSize:u=1,brightness:d=1,contrast:p=1,imageSmoothing:m=!0,lazy:h=!0,className:g,style:_,renderImageState:v}){let y=(0,r.useRef)(null),b=(0,r.useRef)(null),x=(0,r.useRef)(null),[S,C]=(0,r.useState)(!h),[w,T]=(0,r.useState)(`loading`),[E,D]=(0,r.useState)(null),[O,k]=(0,r.useState)(0),[A,j]=(0,r.useState)(0);(0,r.useEffect)(()=>{if(!h||S)return;let e=y.current;if(!e)return;let t=new IntersectionObserver(([e])=>{e.isIntersecting&&(C(!0),t.disconnect())});return t.observe(e),()=>t.disconnect()},[h,S]),(0,r.useEffect)(()=>{let e=y.current;if(!e)return;let t=new ResizeObserver(()=>k(e=>e+1));return t.observe(e),()=>t.disconnect()},[]);let M=(0,r.useMemo)(()=>a.find(e=>e.id===s),[s,a]);return(0,r.useEffect)(()=>{if(!S||!e){T(e?`loading`:`missing`),D(null);return}let t=y.current;if(!t)return;let{width:n,height:r}=t.getBoundingClientRect();if(!n||!r)return;let a={width:n,height:r},o=e=>{let t=i??e;if(!t.width||!t.height)return null;let n=kr({viewport:a,image:t,focusPoints:M?.points,zoomPadding:l,focusFit:c});return{image:t,visibleRect:Ar(n,a,t),density:n.scale*(window.devicePixelRatio||1)}},s=x.current;if(s?.url===e&&s.smoothing===m){let e=o(s.natural);if(!e?.visibleRect||s.bitmap&&Mr(s,e.visibleRect,{...e,natural:s.natural}))return}else s?.url!==e&&(T(`loading`),D(null));let u=!0;return(async()=>{let t=await kn(()=>u?Fr(e,m,o):Promise.resolve(void 0));if(!u){t?.bitmap?.close();return}if(t===null){x.current?.bitmap?.close(),x.current=null,T(`error`);let t=await Pn(e);u&&D(t);return}t&&(x.current?.bitmap?.close(),x.current=t,T(`ready`),j(e=>e+1))})(),()=>{u=!1}},[i,M,c,m,e,O,S,l]),(0,r.useEffect)(()=>()=>{x.current?.bitmap?.close(),x.current=null},[]),(0,r.useEffect)(()=>{if(w===`error`){let e=b.current;e?.getContext(`2d`)?.clearRect(0,0,e.width,e.height)}if(w!==`ready`)return;let e=y.current,t=b.current,n=x.current;if(!e||!t||!n)return;let{width:r,height:s}=e.getBoundingClientRect();if(!r||!s)return;let h=window.devicePixelRatio||1;t.width=Math.max(1,Math.round(r*h)),t.height=Math.max(1,Math.round(s*h)),t.style.width=`${r}px`,t.style.height=`${s}px`;let g=t.getContext(`2d`);if(!g)return;let _=i?.width??n.natural.width,v=i?.height??n.natural.height;if(!_||!v)return;let{scale:S,offsetX:C,offsetY:T}=kr({viewport:{width:r,height:s},image:{width:_,height:v},focusPoints:M?.points,zoomPadding:l,focusFit:c});g.setTransform(h,0,0,h,0,0),g.clearRect(0,0,r,s),g.save(),g.translate(C,T),g.scale(S,S),g.imageSmoothingEnabled=m;let E=de({brightness:d,contrast:p});if(g.filter=`brightness(${E.brightness}) contrast(${E.contrast})`,n.bitmap){let{x:e,y:t,width:r,height:i}=n.rect;g.drawImage(n.bitmap,e,t,r,i)}g.filter=`none`;let D=o?kt(o,_,v):null;if(D&&(Ct(g,D,_,v),D.outlineStyles)){let e=(e,t)=>{if(g.lineWidth=t.width/S,t.underlayColor){g.setLineDash([]),g.strokeStyle=t.underlayColor;for(let[t,n]of e)Nr(g,[t,n],!1),g.stroke()}g.save(),g.globalAlpha*=t.opacity,g.setLineDash(t.dash.map(e=>e/S)),g.strokeStyle=t.color;for(let[t,n]of e)Nr(g,[t,n],!1),g.stroke();g.restore()};e(D.visibleOutline,D.outlineStyles.visible),e(D.occludedOutline,D.outlineStyles.occluded)}for(let e of f(a))Pr(g,e,S,u);g.restore()},[d,p,i,M,c,m,A,o,a,O,w,u,l]),(0,n.jsxs)(`div`,{ref:y,className:g,style:{position:`relative`,width:`100%`,height:`100%`,..._},children:[(0,n.jsx)(`canvas`,{ref:b,role:`img`,"aria-label":t,style:{display:`block`}}),w!==`ready`&&(0,n.jsx)(`div`,{style:{position:`absolute`,inset:0},children:v?.(w,E)??(w===`missing`?(0,n.jsx)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`center`,height:`100%`,padding:8,textAlign:`center`,color:`rgba(255,255,255,0.7)`,background:`rgba(13,13,18,0.85)`,fontSize:12},children:U.imageMissing}):w===`error`?(0,n.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,height:`100%`,gap:4,padding:8,textAlign:`center`,color:`rgba(255,255,255,0.85)`,background:`rgba(13,13,18,0.85)`,fontSize:12},children:[(0,n.jsx)(`span`,{"aria-hidden":!0,children:`⚠`}),(0,n.jsx)(`span`,{children:U.imageLoadError}),E&&(0,n.jsx)(`span`,{style:{fontSize:11,opacity:.7,wordBreak:`break-all`},children:U.imageErrorHints[E.kind]})]}):null)})]})}exports.DEFAULT_EDITOR_STRINGS=U,exports.DEFAULT_VIEW_SETTINGS=ce,exports.SHAPE_TYPE=o,exports.ShapeEditor=Or,exports.default=Or,exports.ShapeViewer=Ir,exports.TOOL=W,exports.VIEW_SETTING_RANGES=le,exports.clampViewSettings=de,exports.generateId=m;
|
|
2
2
|
//# sourceMappingURL=shape-editor.cjs.map
|