@aivex/ui 1.2.0-dev.23 → 1.2.0-dev.25
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/components/DataGrid/DataGridRows.d.ts +7 -0
- package/dist/components/DraggableScroll/DraggableScroll.d.ts +6 -1
- package/dist/components/ShapeEditor/ShapeEditor.d.ts +1 -1
- package/dist/components/ShapeEditor/ShapeViewer.d.ts +3 -1
- package/dist/components/ShapeEditor/_components/ImageStateOverlay.d.ts +6 -2
- package/dist/components/ShapeEditor/_components/Minimap.d.ts +4 -8
- package/dist/components/ShapeEditor/_components/SettingsPanel.d.ts +5 -1
- package/dist/components/ShapeEditor/_model/imageDiagnosis.d.ts +23 -0
- package/dist/components/ShapeEditor/_model/imageDiagnosis.test.d.ts +1 -0
- package/dist/components/ShapeEditor/_model/imageLoad.d.ts +13 -0
- package/dist/components/ShapeEditor/_model/imageLoad.test.d.ts +1 -0
- package/dist/components/ShapeEditor/_model/props.d.ts +11 -2
- package/dist/components/ShapeEditor/_model/strings.d.ts +3 -0
- package/dist/components/ShapeEditor/_renderers/KonvaRenderer.d.ts +1 -1
- package/dist/components/ShapeEditor/_renderers/PixiRenderer.d.ts +3 -1
- package/dist/components/ShapeEditor/_renderers/types.d.ts +3 -1
- package/dist/components/ShapeEditor/_state/useEngineLifecycle.d.ts +9 -2
- package/dist/components/ShapeEditor/index.d.ts +2 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1027 -1026
- 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 +1662 -1423
- package/dist/shape-editor.js.map +1 -1
- package/dist/styles.css +1 -1
- package/package.json +1 -1
- package/dist/components/ShapeEditor/_model/imageFetch.d.ts +0 -9
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-OQscp8mY.cjs`),t=require(`./Switch-DP8FRLJK.cjs`);let n=require(`react/jsx-runtime`),r=require(`react`),i=require(`konva`);i=e.pa(i,1);let a=require(`pixi.js`);var o={POINT:`POINT`,RECTANGLE:`RECTANGLE`,ROTATED_RECTANGLE:`ROTATED_RECTANGLE`,POLYGON:`POLYGON`,ELLIPSE:`ELLIPSE`,LINE:`LINE`};function s(e){return e.interaction?.visible!==!1}function c(e){return s(e)&&e.interaction?.hitTestDisabled!==!0}function l(e){return c(e)&&e.interaction?.selectable!==!1}function u(e){return l(e)&&!e.readOnly&&e.interaction?.editable!==!1}function d(e){return u(e)&&e.interaction?.draggable!==!1}function f(e){return e.map((e,t)=>({shape:e,index:t})).sort((e,t)=>{let n=e.shape.style?.zIndex??0,r=t.shape.style?.zIndex??0;return n===r?e.index-t.index:n-r}).map(e=>e.shape)}function p(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`id_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}var m=[`tl`,`t`,`tr`,`r`,`br`,`b`,`bl`,`l`];function h(e){let t=e.map(e=>e.x),n=e.map(e=>e.y);return{minX:Math.min(...t),minY:Math.min(...n),maxX:Math.max(...t),maxY:Math.max(...n)}}function g(e,t){let n=(t.minX+t.maxX)/2,r=(t.minY+t.maxY)/2;return{x:e.includes(`l`)?t.minX:e.includes(`r`)?t.maxX:n,y:e.includes(`t`)?t.minY:e.includes(`b`)?t.maxY:r}}function _(e,t,n,r){let i={...t};return e.includes(`l`)&&(i.minX=n),e.includes(`r`)&&(i.maxX=n),e.includes(`t`)&&(i.minY=r),e.includes(`b`)&&(i.maxY=r),i}function v(e,t){let n=t.x-e.x,r=t.y-e.y,i=Math.max(Math.abs(n),Math.abs(r));return{x:e.x+(n<0?-i:i),y:e.y+(r<0?-i:i)}}function y(e,t,n){let r=Math.cos(n),i=Math.sin(n),a=e.x-t.x,o=e.y-t.y;return{x:t.x+a*r-o*i,y:t.y+a*i+o*r}}function b(e){let t=h(e);return[{x:t.minX,y:t.minY},{x:t.maxX,y:t.minY},{x:t.maxX,y:t.maxY},{x:t.minX,y:t.maxY}]}function x(e,t,n=32){let r=(e.x+t.x)/2,i=(e.y+t.y)/2,a=Math.abs(t.x-e.x)/2,o=Math.abs(t.y-e.y)/2;return Array.from({length:n},(e,t)=>{let s=t/n*2*Math.PI;return{x:r+a*Math.cos(s),y:i+o*Math.sin(s)}})}function S(e){let t=[...e].sort((e,t)=>e.x-t.x||e.y-t.y);if(t.length<=2)return t;let n=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x),r=[];for(let e of t){for(;r.length>=2&&n(r[r.length-2],r[r.length-1],e)<=0;)r.pop();r.push(e)}let i=[];for(let e=t.length-1;e>=0;e--){let r=t[e];for(;i.length>=2&&n(i[i.length-2],i[i.length-1],r)<=0;)i.pop();i.push(r)}return r.pop(),i.pop(),r.concat(i)}function C(e){let t=S(e);if(t.length<3)return b(e);let n=1/0,r=b(e);for(let e=0;e<t.length;e++){let i=t[e],a=t[(e+1)%t.length],o=Math.hypot(a.x-i.x,a.y-i.y)||1,s=(a.x-i.x)/o,c=(a.y-i.y)/o,l=1/0,u=-1/0,d=1/0,f=-1/0;for(let e of t){let t=e.x*s+e.y*c,n=-e.x*c+e.y*s;t<l&&(l=t),t>u&&(u=t),n<d&&(d=n),n>f&&(f=n)}let p=(u-l)*(f-d);if(p<n){n=p;let e=(e,t)=>({x:e*s-t*c,y:e*c+t*s});r=[e(l,d),e(u,d),e(u,f),e(l,f)]}}return r}var w=(e,t)=>({x:e.x-t.x,y:e.y-t.y}),T=(e,t)=>e.x*t.x+e.y*t.y,E=e=>Math.hypot(e.x,e.y),D=e=>{let t=E(e)||1;return{x:e.x/t,y:e.y/t}},O=(e,t)=>({x:(e.x+t.x)/2,y:(e.y+t.y)/2}),k=e=>{let t=e.reduce((e,t)=>({x:e.x+t.x,y:e.y+t.y}),{x:0,y:0});return{x:t.x/e.length,y:t.y/e.length}};function A(e){return[e[0],O(e[0],e[1]),e[1],O(e[1],e[2]),e[2],O(e[2],e[3]),e[3],O(e[3],e[0])]}function j(e,t){let n=O(e[0],e[1]),r=D(w(e[0],e[3]));return{x:n.x+r.x*t,y:n.y+r.y*t}}function M(e,t,n,r){let i=(e,i)=>({x:t.x+e*n.x+i*r.x,y:t.y+e*n.y+i*r.y});return[i(e.minX,e.minY),i(e.maxX,e.minY),i(e.maxX,e.maxY),i(e.minX,e.maxY)]}function N(e,t,n){if(e.length<4)return e;let r=e[0],i=D(w(e[1],e[0])),a=D(w(e[3],e[0])),o=T(w(e[1],r),i),s=T(w(e[3],r),a),c=w(n,r);return M(_(t,{minX:0,minY:0,maxX:o,maxY:s},T(c,i),T(c,a)),r,i,a)}function P(e,t,n){let r=t.maxX-t.minX||1,i=t.maxY-t.minY||1,a=n.maxX-n.minX,o=n.maxY-n.minY;return e.map(e=>({x:n.minX+(e.x-t.minX)/r*a,y:n.minY+(e.y-t.minY)/i*o}))}function F(e,t,n,r){let i=(e,t,n)=>Math.sign((t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x)),a=i(e,t,n),o=i(e,t,r),s=i(n,r,e),c=i(n,r,t);return a!==o&&s!==c&&!(a===0&&o===0)}function I(e,t=256){let n=e.length;if(n<4||n>t)return!1;for(let t=0;t<n;t++){let r=e[t],i=e[(t+1)%n];for(let a=t+2;a<n;a++)if(!(t===0&&a===n-1)&&F(r,i,e[a],e[(a+1)%n]))return!0}return!1}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}}function R(e,t=256){let n=e.length;if(n<4||n>t||!I(e,t))return[e];let r=Array.from({length:n},()=>[]),i=0;for(let t=0;t<n;t++){let a=e[t],o=e[(t+1)%n];for(let s=t+2;s<n;s++){if(t===0&&s===n-1)continue;let c=L(a,o,e[s],e[(s+1)%n]);c&&(r[t].push({t:c.ti,id:i}),r[s].push({t:c.tj,id:i}),i++)}}if(!i)return[e];let a=[];for(let t=0;t<n;t++){let i=e[t],o=e[(t+1)%n];a.push({p:i,inter:-1});for(let e of r[t].sort((e,t)=>e.t-t.t))a.push({p:{x:i.x+(o.x-i.x)*e.t,y:i.y+(o.y-i.y)*e.t},inter:e.id})}let o=a.length,s=new Map;a.forEach((e,t)=>{if(e.inter>=0){let n=s.get(e.inter)??[];n.push(t),s.set(e.inter,n)}});let c=Array(o).fill(!1),l=[];for(let e=0;e<o;e++){if(c[e]||a[e].inter>=0)continue;let t=[],n=e,r=0;for(;r++<=o;){c[n]=!0,t.push(a[n].p);let i=(n+1)%o;for(;a[i].inter>=0&&!c[i]&&r++<=o;){t.push(a[i].p),c[i]=!0;let e=s.get(a[i].inter),n=e&&(e[0]===i?e[1]:e[0]);if(n===void 0)break;i=(n+1)%o}if(i===e||c[i])break;n=i}t.length>=3&&l.push(t)}return l.length?l:[e]}var z={contextMenu:{copy:`복사`,paste:`붙여넣기`,duplicate:`복제`,delete:`삭제`,bringToFront:`맨 앞으로`,sendToBack:`맨 뒤로`,editVertices:`정점 편집`,merge:`레이블 합치기`,assistExpand:`이 지점 포함하기`,assistExclude:`이 지점 제외하기`,undo:`실행 취소`,redo:`다시 실행`,zoomToSelection:`선택 영역으로 확대`,selectAll:`전체 선택`,clearSelection:`선택 해제`},viewSettings:{title:`보기 설정`,reset:`초기화`,brightness:`밝기`,contrast:`대비`,strokeSize:`선 굵기`,simplifyStrength:`단순화 강도`,pixelation:`이미지 픽셀화`,cursorGuide:`마우스 가이드라인 표시`,guideMask:`가이드 마스크`,regionMask:`ROI 표시`,keepZoomOnImageChange:`이미지 변경시 확대 유지`,wheelZoom:`스크롤만 사용하여 확대 축소`,zoomSensitivity:`확대 축소 민감도`},minimap:{zoomIn:`확대`,zoomOut:`축소`,zoom100:`100%로 초기화`,viewSettings:`보기 설정`,toggleMinimap:`미니맵 접기/펼치기`},imageLoading:`이미지를 불러오는 중…`,imageLoadError:`이미지를 불러올 수 없습니다`};function ee(e){return e?{contextMenu:{...z.contextMenu,...e.contextMenu},viewSettings:{...z.viewSettings,...e.viewSettings},minimap:{...z.minimap,...e.minimap},imageLoading:e.imageLoading??z.imageLoading,imageLoadError:e.imageLoadError??z.imageLoadError}:z}var B={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`},te={brightness:1,contrast:1,showCursorGuide:!1,imageSmoothing:!0,strokeSize:2,simplifyStrength:1.5,showGuide:!0,showRegionMask:!0,keepZoomOnImageChange:!1,wheelZoom:!0,zoomSensitivity:1},ne=`var(--editor-overlay-inverse-scale, 1)`,re=`#377be2`,V=`#e23c3c`;function H({point:e}){let t=e.positive?re:V;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(${ne})`,transformOrigin:`center`},children:e.positive?`+`:`−`})}function U({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)(H,{point:e},`pt-${t}-${e.x}-${e.y}`))]})}function ie(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 ae({x:e,y:r,items:i,onClose:a}){let o=ie(i);return(0,n.jsxs)(t.a,{open:!0,modal:!1,onOpenChange:e=>{e||a()},children:[(0,n.jsx)(t.a.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.a.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.a.Separator,{className:`aivex:shrink-0`},`sep-${r}`):(0,n.jsx)(t.a.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.a.Shortcut,{children:e.shortcut})]})},e.label))})]})}function W({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 oe({status:e,render:t,loadingLabel:r=z.imageLoading,errorLabel:i=z.imageLoadError}){return(0,n.jsx)(`div`,{"data-track-id":e===`loading`?`editor-image-loading-wrap`:`editor-image-error-wrap`,style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,background:e===`error`?`rgba(13,13,18,1)`:`rgba(13,13,18,0.6)`,backdropFilter:e===`loading`?`blur(2px)`:void 0,color:`#fff`,fontFamily:`Pretendard, sans-serif`,pointerEvents:e===`error`?`auto`:`none`},children:t?t(e):e===`loading`?(0,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`}}),r,(0,n.jsx)(`style`,{children:`@keyframes editorv2-image-spin{to{transform:rotate(360deg)}}`})]}):(0,n.jsxs)(`div`,{style:{textAlign:`center`,opacity:.85},children:[(0,n.jsx)(`div`,{style:{fontSize:28,marginBottom:6},children:`⚠`}),(0,n.jsx)(`div`,{style:{fontSize:13},children:i})]})})}Math.PI/12;var se=`#00ff00`,ce=`rgba(0, 255, 0, 0.1)`,le=`#669DEF`,ue=.1,de=[3,3];function fe(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*de[0],r*de[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 pe(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 me=(0,r.memo)(function({shape:e,strokeSize:t,register:r}){let{type:i,points:a}=e,s=fe(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=h(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,...l})});function he({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`})]})}function ge({value:i,defaults:a,onChange:o,onClose:s,labels:c=z.viewSettings}){return(0,r.useEffect)(()=>{let e=e=>{e.key===`Escape`&&s()},t=()=>s();return window.addEventListener(`keydown`,e),window.addEventListener(`pointerdown`,t),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`pointerdown`,t)}},[s]),(0,n.jsxs)(`div`,{className:`aivex:absolute aivex:bottom-full aivex:left-0 aivex:mb-md aivex:flex aivex:w-[277px] aivex:flex-col aivex:gap-lg aivex:rounded-xl aivex:border aivex:border-border-subtle aivex:bg-bg-primary aivex:p-xl aivex:text-text-primary aivex:shadow-[var(--aivex-elevation-md)]`,onPointerDown:e=>e.stopPropagation(),children:[(0,n.jsx)(`div`,{className:`aivex:px-xs aivex:text-body-md`,children:c.title}),(0,n.jsxs)(`div`,{className:`aivex:flex aivex:flex-col aivex:gap-md`,children:[(0,n.jsx)(_e,{icon:(0,n.jsx)(e.Q,{size:16}),label:c.brightness,value:i.brightness.toFixed(2),children:(0,n.jsx)(t.n,{min:0,max:3,step:.05,value:[i.brightness],onValueChange:([e])=>o({brightness:e})})}),(0,n.jsx)(_e,{icon:(0,n.jsx)(e.Dt,{size:16}),label:c.contrast,value:i.contrast.toFixed(2),children:(0,n.jsx)(t.n,{min:0,max:3,step:.05,value:[i.contrast],onValueChange:([e])=>o({contrast:e})})}),(0,n.jsx)(_e,{icon:(0,n.jsx)(e.Di,{size:16}),label:c.strokeSize,value:String(i.strokeSize),children:(0,n.jsx)(t.n,{min:1,max:10,step:.5,value:[i.strokeSize],onValueChange:([e])=>o({strokeSize:e})})}),(0,n.jsx)(_e,{icon:(0,n.jsx)(e.Ar,{size:16}),label:c.simplifyStrength,value:String(i.simplifyStrength),children:(0,n.jsx)(t.n,{min:.5,max:5,step:.5,value:[i.simplifyStrength],onValueChange:([e])=>o({simplifyStrength:e})})}),(0,n.jsx)(_e,{icon:(0,n.jsx)(e.oa,{size:16}),label:c.zoomSensitivity,value:i.zoomSensitivity.toFixed(1),children:(0,n.jsx)(t.n,{min:.2,max:3,step:.1,value:[i.zoomSensitivity],onValueChange:([e])=>o({zoomSensitivity:e})})}),(0,n.jsxs)(`div`,{className:`aivex:flex aivex:flex-col aivex:gap-xs`,children:[(0,n.jsx)(ve,{label:c.pixelation,checked:!i.imageSmoothing,onChange:e=>o({imageSmoothing:!e})}),(0,n.jsx)(ve,{label:c.cursorGuide,checked:i.showCursorGuide,onChange:e=>o({showCursorGuide:e})}),(0,n.jsx)(ve,{label:c.guideMask,checked:i.showGuide,onChange:e=>o({showGuide:e})}),(0,n.jsx)(ve,{label:c.regionMask,checked:i.showRegionMask,onChange:e=>o({showRegionMask:e})}),(0,n.jsx)(ve,{label:c.keepZoomOnImageChange,checked:i.keepZoomOnImageChange,onChange:e=>o({keepZoomOnImageChange:e})}),(0,n.jsx)(ve,{label:c.wheelZoom,checked:i.wheelZoom,onChange:e=>o({wheelZoom:e})})]}),(0,n.jsx)(t.r,{})]}),(0,n.jsx)(`div`,{className:`aivex:flex aivex:justify-end`,children:(0,n.jsxs)(e.t,{variant:`solid`,color:`secondary`,size:`md`,onClick:()=>o({...a}),children:[(0,n.jsx)(e.Xr,{size:20}),c.reset]})})]})}function _e({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 ve({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.t,{size:`md`,checked:r,onCheckedChange:i})]})}var ye=(0,r.memo)(function({image:t,imageUrl:r,imageVisible:i=!0,loading:a=!1,maskDataUrl:o,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,showSettings:S=!0,settingsOpen:C,onToggleSettings:w,onCloseSettings:T,labels:E=z.minimap,settingsLabels:D}){let{offX:O,offY:k,dispW:A,dispH:j,zoomCentered:M}=h,N={position:`absolute`,left:O,top:k,width:A,height:j};return(0,n.jsxs)(`div`,{className:`aivex:absolute aivex:bottom-2 aivex:left-2 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:[(0,n.jsx)(`div`,{className:`aivex:overflow-hidden aivex:rounded-sm aivex:transition-all aivex:duration-200 aivex:ease-in-out ${b?`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 ${a?`aivex:cursor-default`:`aivex:cursor-grab aivex:active:cursor-grabbing`}`,onPointerDown:a?void 0:h.handleMinimapPointerDown,onPointerMove:a?void 0:h.handleMinimapPointerMove,onPointerUp:a?void 0:h.endMinimapDrag,onPointerCancel:a?void 0:h.endMinimapDrag,onWheel:a?void 0:h.handleMinimapWheel,"aria-busy":a,children:(0,n.jsxs)(`div`,{style:{position:`absolute`,inset:0,opacity:+!!i,transition:i?`opacity 0.3s ease`:`none`},children:[r&&(0,n.jsx)(`img`,{src:r,alt:``,draggable:!1,style:N}),o&&d.showGuide&&(0,n.jsx)(`img`,{src:o,alt:``,draggable:!1,style:{...N,opacity:.55,imageRendering:`pixelated`,pointerEvents:`none`}}),d.showRegionMask&&c&&c.rects.length>0&&(0,n.jsx)(he,{image:t,region:c,maskId:l,width:A,height:j,strokeWidth:1,strokeDasharray:`4 4`,style:{position:`absolute`,left:O,top:k,pointerEvents:`none`}}),(0,n.jsx)(`svg`,{viewBox:`0 0 ${t.w} ${t.h}`,width:A,height:j,style:{position:`absolute`,left:O,top:k,pointerEvents:`none`},"aria-hidden":!0,children:f(u).filter(s).map(e=>(0,n.jsx)(me,{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`}})]})})}),(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":E.zoomOut,onClick:()=>M(1/1.2),disabled:a,children:(0,n.jsx)(e.ur,{size:20})}),(0,n.jsx)(e.t,{variant:`ghost`,size:`md`,"aria-label":E.zoom100,onClick:y,disabled:a,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":E.zoomIn,onClick:()=>M(1.2),disabled:a,children:(0,n.jsx)(e.Vr,{size:20})}),S&&(0,n.jsxs)(`div`,{className:`aivex:relative`,children:[(0,n.jsx)(e.t,{variant:`ghost`,size:`icon-md`,"aria-label":E.viewSettings,onClick:w,onPointerDown:e=>e.stopPropagation(),className:C?`aivex:text-text-brand`:void 0,children:(0,n.jsx)(e.ui,{size:20})}),C&&(0,n.jsx)(ge,{value:d,defaults:p,onChange:m,onClose:T,labels:D})]}),(0,n.jsx)(e.t,{variant:`ghost`,size:`icon-md`,"aria-label":E.toggleMinimap,title:`(M)`,onClick:x,children:b?(0,n.jsx)(e.nt,{size:20}):(0,n.jsx)(e.nr,{size:20})})]})]})}),be=`var(--editor-overlay-inverse-scale, 1)`,xe=6,Se={fontFamily:`Pretendard, sans-serif`,fontSize:12,fontWeight:500,lineHeight:`16px`,color:`#fff`,textShadow:`0 0 4px #000, 0 0 4px #000`,whiteSpace:`nowrap`};function G(e){let t=h(e);return{x:t.minX,y:t.minY,width:t.maxX-t.minX,height:t.maxY-t.minY}}function Ce(e){return`translate3d(${e.width}px, ${e.height}px, 0) scale(${be}) translate(-100%, ${xe}px)`}function we(e,t){let n=G(t);e.style.transform=`translate3d(${n.x}px, ${n.y}px, 0)`;let r=e.querySelector(`[data-selinfo-dim]`);return r&&(r.style.transform=Ce(n)),r}function Te(e,t){return{shape:e,...G(t)}}function Ee(e){return`${Math.round(e.width)} x ${Math.round(e.height)} px`}function De({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 Oe({shapes:e,getLabel:t,hideDot:r,formatInfo:i,register:a}){return(0,n.jsx)(n.Fragment,{children:e.map(e=>{let s=G(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=Te(e,e.points),p=i?i(f):Ee(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(${be}) translateY(calc(-100% - ${xe}px))`,transformOrigin:`left top`,...Se},children:[!r&&(0,n.jsx)(De,{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:Ce(s),transformOrigin:`left top`,willChange:`transform`,...Se},children:p})]},e.id)})})}var ke=`AIVEX_SHAPE_EDITOR:`,Ae=1,K=new Set(Object.values(o)),je=null,Me=`unavailable`,Ne=0;function Pe(e){if(!e||typeof e!=`object`)return!1;let t=e;return Number.isFinite(t.x)&&Number.isFinite(t.y)}function Fe(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.type==`string`&&K.has(t.type)&&Array.isArray(t.points)&&t.points.length>0&&t.points.every(Pe)}function Ie(e,t,n){return{kind:`aivex-shape-editor`,version:Ae,scope:n,documentId:t,shapes:e}}function Le(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 Re(e){return`${ke}${JSON.stringify(e)}`}function ze(e){if(!e.startsWith(ke))return null;try{let t=JSON.parse(e.slice(19));return t.kind!==`aivex-shape-editor`||t.version!==Ae||!Array.isArray(t.shapes)||t.shapes.length===0||!t.shapes.every(Fe)||t.scope!==void 0&&typeof t.scope!=`string`||t.documentId!==void 0&&typeof t.documentId!=`string`?null:t}catch{return null}}function Be(e){je=e;let t=++Ne;if(typeof navigator>`u`||!navigator.clipboard?.writeText){Me=`unavailable`;return}let n;try{n=Re(e)}catch{Me=`unavailable`;return}Me=`pending`,navigator.clipboard.writeText(n).then(()=>{t===Ne&&(Me=`written`)},()=>{t===Ne&&(Me=`unavailable`)})}function Ve(e,t){return!!e&&e.scope===t}function He(e){return Ve(je,e)||typeof navigator<`u`&&typeof navigator.clipboard?.readText==`function`}async function Ue(e){let t=Ve(je,e)?je:null;if(t&&Me!==`written`)return t;if(typeof navigator<`u`&&navigator.clipboard?.readText)try{let t=ze(await navigator.clipboard.readText());return t?.scope===e?(je=t,t):null}catch{}return t}function We(e,t,n){return{offset:n*(t?e:e+1),nextPasteCount:e+1}}var Ge=new Set([B.RECTANGLE,B.ROTATED_RECTANGLE,B.CIRCLE,B.POLYGON,B.PATH,B.BRUSH,B.POINT,B.ASSISTANT_POLYGON,B.ASSISTANT_RECT,B.ASSISTANT_POINT]),Ke={tl:-135,t:-90,tr:-45,r:0,br:45,b:90,bl:135,l:180},qe=[`ew-resize`,`nwse-resize`,`ns-resize`,`nesw-resize`];function Je(e,t=0){let n=((Ke[e]+t*180/Math.PI)%180+180)%180;return qe[Math.round(n/45)%4]}function Ye({tool:e,externalToolCursor:t,isSpacePressed:n,isPolygonDrawing:r}){return n?`grab`:t||(e===B.SELECT?`default`:Ge.has(e)?r?`default`:`crosshair`:`default`)}function Xe({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===B.SELECT&&i?i:Ye({tool:e,externalToolCursor:t,isSpacePressed:n,isPolygonDrawing:a}))}var Ze=e=>Math.min(255,Math.max(0,e)),Qe=e=>{let t=e.replace(`#`,``).trim();if(![3,4,6,8].includes(t.length))return null;let n=e=>e.length===1?`${e}${e}`:e,r=t.length<=4,i=n(t.slice(0,r?1:2)),a=n(t.slice(r?1:2,r?2:4)),o=n(t.slice(r?2:4,r?3:6)),s=t.length===4?n(t.slice(3,4)):t.length===8?n(t.slice(6,8)):`ff`,c=e=>Number.parseInt(e,16),l=[c(i),c(a),c(o),c(s)];return l.some(e=>Number.isNaN(e))?null:l.map(Ze)},$e=(e,t)=>{let{width:n,height:r,indices:i,transparent:a}=e;if(!n||!r||i.length<n*r)return null;let o={};for(let[e,n]of Object.entries(t)){let t=Qe(n);t&&(o[Number(e)]=t)}if(!Object.keys(o).length)return null;let s=document.createElement(`canvas`);s.width=n,s.height=r;let c=s.getContext(`2d`);if(!c)return null;let l=new Uint8ClampedArray(n*r*4),u=n*r;for(let e=0;e<u;e+=1){let t=i[e];if(t===a)continue;let n=o[t];if(!n)continue;let r=e*4;l[r]=n[0],l[r+1]=n[1],l[r+2]=n[2],l[r+3]=n[3]}return c.putImageData(new ImageData(l,n,r),0,0),s};function et(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 tt=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 q(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 nt(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 rt(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(...nt(s,c,e));if(n)for(let e of n)l.push(...nt(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=q(m,o)?m:h,_=g===m?h:m;t.some(e=>e!==o&&q(_,e))||n&&!n.some(e=>q(g,e))||i.push([a(s,c,r),a(s,c,u)])}}return i}function J(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 it(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)et(e,n.points),e.fill()}e.restore()}function at(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 ot={color:`#000000`,opacity:.5},st={color:`#ffffff`,opacity:1,width:2,dash:[6,6],underlayColor:`#000000`},ct={color:`#dc2626`,opacity:.8,width:2,dash:[6,6],underlayColor:`#000000`},lt=(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=J(a),s={...ot,...e.dim},c=e.outline;if(c===!1)return{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:[],occludedOutline:[],outlineStyles:null};let l={visible:{...st,...c?.visibleStyle},occluded:{...ct,...c?.occludedStyle}},u=i.map(tt),d=a.map(tt),f=r.map(e=>e.points);return c?.mode===`separate`?{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:at(u),occludedOutline:at(f),outlineStyles:l}:{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:[...rt(u,[...u,...f],null),...rt(f,f,d)],occludedOutline:[],outlineStyles:l}},ut=.3,Y=.05;function dt(e){return 1-(1-e)**3}function ft(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 X(e,t){if(!t.length)return null;if(e===o.POINT){let e=t[0];return{x:e.x-8,y:e.y-8,width:16,height:16}}let n=h(t),r=Math.max(1,n.maxX-n.minX),i=Math.max(1,n.maxY-n.minY);return{x:n.minX,y:n.minY,width:r,height:i}}function pt(e){if(!e.length)return null;let t=e.map(e=>X(e.type,e.points)).filter(e=>e!==null);return t.length?ft(h(t.flatMap(e=>[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y+e.height}]))):null}function mt(e,t,n,r={}){let{containerRatio:i=ut,minScale:a=Y,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 ht(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(Y,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 gt(e,t,n,r=300){let i=Date.now(),a=0,o=()=>{let s=Date.now()-i,c=Math.min(s/r,1),l=dt(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 _t(e){let{engineRef:t,toolRef:n,externalToolMapRef:r,spaceRef:i,shiftRef:a,docRef:s,selRef:c,draftRef:u,readOnlyRef:p,disableMarqueeRef:m,lockedRef:g,onLockedInteraction:_,createRef:y,selectRef:S,enterEditRef:C,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,z=null,ee=``,te=null,ne=null,re=e=>e===B.RECTANGLE||e===B.ROTATED_RECTANGLE||e===B.CIRCLE,V=e=>e===B.ASSISTANT_POLYGON||e===B.ASSISTANT_RECT,H=e=>e===B.POLYGON,U=(e,t)=>{let n=!1;F&&!re(t)&&!V(t)&&(F=null,e.clearPreview(),j(null),n=!0),(I===`path`&&t!==B.PATH||I===`scalar`&&t!==B.BRUSH)&&(I=null,n=!0),L&&!H(t)&&(L=null,n=!0),R&&t!==B.SELECT&&(R=null,z=null,e.clearMarquee(),n=!0),te&&t!==B.POINT&&(te=null,n=!0),n&&O(`idle`)},ie=()=>r.current.get(n.current),ae=(e,t,n,r)=>({point:t,targetId:r,event:n,readOnly:p.current,viewport:e.viewport});return{onCursorHint:D,onInteractionModeChange:O,onPointerDown:(e,r,m)=>{let v=t.current;if(!v)return;let y=n.current;if(te=null,U(v,y),m.button===1||i.current){O(`panning`),D(null),P={px:m.global.x,py:m.global.y};return}if(m.button===2&&!(y===B.ASSISTANT_POINT&&m.altKey)){if(r&&!c.current.includes(r)){let e=s.current.getShapes().find(e=>e.id===r);e&&l(e)&&S.current([r])}return}let b=ie();if(b){M().reset(),S.current([]),b.onPointerDown?.(ae(v,e,m,r));return}if(g.current){_();return}if(y===B.ASSISTANT_POINT){m.altKey?N().addPoint(e,m.button!==2):N().newPolygon(e);return}if(V(y)&&u.current){F=e,O(`drawing`);return}if(y===B.SELECT&&m.altKey){let t=f(s.current.getShapes()).filter(t=>{if(!l(t))return!1;let n=h(t.points);return e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY});if(t.length){let e=[...t].reverse(),n=[e[(e.findIndex(e=>c.current.includes(e.id))+1)%e.length].id];S.current(n);return}}if(r&&y===B.SELECT){let t=s.current.getShapes().find(e=>e.id===r);if(!t||!l(t))return;let n=typeof performance<`u`?performance.now():0,i=!!ne&&ne.id===r&&n-ne.t<300;ne={id:r,t:n};let u=(t.type===o.POLYGON||t.type===o.LINE)&&!p.current&&t.interaction?.editable!==!1&&!t.readOnly;if(i&&u){S.current([r]),C.current(r);return}let f=c.current;if(a.current){let e=new Set(f);e.has(r)?e.delete(r):e.add(r),f=[...e]}else f.includes(r)||(f=[r]);S.current(f),!p.current&&d(t)&&v.beginMove(e,f);return}if(re(y)&&u.current){F=e,O(`drawing`);return}if(H(y)&&u.current){if(!M().getDraftPointsSnapshot().length&&c.current.length&&S.current([]),M().tryClosePolygon(e,12/v.viewport.scale))return;let t=M().hitDraftPoint(e);if(t>=0){if(m.altKey){M().removeDraftPoint(t);return}let n=M().selectDraftPointForDrag(t,m.shiftKey||m.ctrlKey||m.metaKey);if(!n)return;L={start:e,base:n.base,indices:n.indices,moved:!1},O(`vertexDragging`);return}M().appendPolygonPoint(e);return}if(y===B.PATH&&u.current){c.current.length&&S.current([]),I=`path`,O(`drawing`),M().beginStroke(e);return}if(y===B.BRUSH&&u.current&&!p.current){I=`scalar`,O(`drawing`),M().beginStroke(e);return}if(y===B.POINT&&u.current&&m.button===0){te={pointerId:m.pointerId,global:m.global,cancelled:!1};return}if(y===B.SELECT){if(z=w.current?a.current?v.getVertexSelection():[]:null,!a.current&&!p.current&&c.current.length>=2){let t=s.current.getShapes().filter(e=>c.current.includes(e.id)&&d(e));if(t.length){let n=h(t.flatMap(e=>e.points));if(e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY){v.beginMove(e,c.current);return}}}R=e,ee=``,O(`marquee`),D(null)}},onPointerMove:(e,r)=>{let i=t.current;if(!i)return;if(te&&te.pointerId===r.pointerId&&Math.hypot(r.global.x-te.global.x,r.global.y-te.global.y)>4&&(te.cancelled=!0),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 c=n.current;U(i,c);let l=ie();if(l){l.onPointerMove?.(ae(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&&(re(c)||V(c))){let t=a.current?v(F,e):e;i.previewBox(c===B.CIRCLE?`ellipse`:`rect`,F,t,{...u.current,color:u.current?.color??`#00e5ff`}),re(c)&&j({type:c===B.CIRCLE?o.ELLIPSE:o.RECTANGLE,points:[F,t]});return}if(I){M().appendStrokePoint(e,2/i.viewport.scale);return}if(H(c)&&M().hasDraftPoints()){M().setDraftCursor(e);return}if(R){if(m?.current)return;let t={minX:Math.min(R.x,e.x),minY:Math.min(R.y,e.y),maxX:Math.max(R.x,e.x),maxY:Math.max(R.y,e.y)};if(i.previewMarquee(R,e),z){let e=(s.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([...z,...e])].sort((e,t)=>e-t),r=n.join(`,`);r!==ee&&(ee=r,i.setVertexSelection(n));return}let n=i.shapesIntersecting(t),r=n.join(`,`);r!==ee&&(ee=r,S.current(n))}},onPointerUp:(e,r)=>{let i=t.current;if(!i)return;let s=te;if(te=null,P){P=null,O(`idle`);return}let l=n.current;if(U(i,l),L){M().commitDraftPointDrag(L.moved),L=null,O(`idle`);return}let d=ie();if(d){d.onPointerUp?.(ae(i,e,r));return}let f=s?Math.hypot(r.global.x-s.global.x,r.global.y-s.global.y):1/0;if(l===B.POINT&&u.current&&s&&!s.cancelled&&s.pointerId===r.pointerId&&r.insideCanvas&&f<=4){y.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={x:Math.min(t.x,e.x),y:Math.min(t.y,e.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)};n.width>2&&n.height>2&&N().beginBox(n,l===B.ASSISTANT_RECT?`rect`:`polygon`);return}if(F&&re(l)){let t=a.current?v(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===B.ROTATED_RECTANGLE?y.current(o.ROTATED_RECTANGLE,b([n,t])):l===B.CIRCLE?y.current(o.POLYGON,x(n,t)):y.current(o.RECTANGLE,[n,t]));return}if(R){let t=Math.abs(e.x-R.x)>3||Math.abs(e.y-R.y)>3,n=z!==null;if(R=null,z=null,i.clearMarquee(),O(`idle`),n&&t)return;!t&&c.current.length&&S.current([])}},onViewportChange:k,onTransformPreview:A,onTransformCommit:e=>{let t=s.current.getShapes(),n=e.map(e=>{let n=t.find(t=>t.id===e.id);return n?{...n,points:e.points}:null}).filter(e=>!!e);n.length&&s.current.update(n)}}}function vt({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)([]),m=(0,r.useRef)([]),g=(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),w=(0,r.useCallback)(e=>{m.current=e(m.current),f(m.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:p(),type:o.ROTATED_RECTANGLE,points:C(e),style:r,meta:n};if(t===`rect`){let t=h(e);return{id:p(),type:o.RECTANGLE,points:[{x:t.minX,y:t.minY},{x:t.maxX,y:t.maxY}],style:r,meta:n}}return{id:p(),type:o.POLYGON,points:e,style:r,meta:n}})},[n,a]),D=(0,r.useCallback)(()=>{y.current++,g.current=[],_.current=[],b.current=null,x.current=null,u([]),T(`idle`)},[T]),O=(0,r.useCallback)(()=>{S.current++,w(()=>[]);let t=x.current;t?e.current.update([t]):_.current.length&&e.current.remove(_.current),D()},[e,D,w]),k=(0,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:g.current,base:b.current??void 0},n=++y.current;T(`loading`);let r=[];try{r=(await e(t)??[]).filter(e=>e.length>=3)}catch{r=[]}n===y.current&&(k(r),T(`ready`))},[a,k,T]),j=(0,r.useCallback)((e,t)=>{g.current=[...g.current,{x:e.x,y:e.y,positive:t}],u([{x:e.x,y:e.y,positive:t}]),A()},[A]),M=(0,r.useCallback)(e=>{D();let t=[{x:e.x,y:e.y,positive:!0}];g.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),g.current=[...g.current,{x:t.x,y:t.y,positive:n}],u([{x:t.x,y:t.y,positive:n}]),A()},[D,A]);return{status:s,points:l,boxes:d,beginBox:(0,r.useCallback)((n,r=`polygon`)=>{let o=a.current?.infer,s=t.current;if(!o||!s)return;let c=S.current;w(e=>[...e,n]),(async()=>{let t=[];try{t=(await o({kind:`box`,box:n})??[]).filter(e=>e.length>=3)}catch{t=[]}if(w(e=>e.filter(e=>e!==n)),c!==S.current)return;let a=E(t,r,s);a?.length&&(e.current.create(a),i(a.map(e=>e.id)))})()},[a,t,E,i,e,w]),addPoint:j,newPolygon:M,refineShape:N,finalize:D,cancel:O,isActive:(0,r.useCallback)(()=>v.current===`loading`||g.current.length>0||m.current.length>0||_.current.length>0,[])}}function yt(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 bt(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=yt(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 xt=4096,St=4;function Ct(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 wt(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 Tt(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 Et(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 Dt(e,t,n){let r=wt(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=kt(Tt(Et(r,t,n,e,a)),t,n);o.length>=3&&i.push(o)}return i}function Ot(e,t,n,r,i){return r<0||i<0||r>=t||i>=n?!1:e[(i*t+r)*4+3]>128}function kt(e,t,n){let r=-1,i=-1;outer:for(let a=0;a<n;a++)for(let o=0;o<t;o++)if(Ot(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(Ot(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 At(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 jt(e){switch(e.type){case o.RECTANGLE:return e.points.length<2?null:b(e.points);case o.POLYGON:case o.ROTATED_RECTANGLE:case o.ELLIPSE:return e.points.length>=3?e.points:null;case o.POINT:{let t=e.points[0];return t?x({x:t.x-6,y:t.y-6},{x:t.x+6,y:t.y+6}):null}default:return null}}function Z(e){return e.map(jt).filter(e=>!!e&&e.length>=3)}function Mt(e,t,n=[]){if(t<=0||!e.length&&!n.length)return null;let r=At(e,n);if(!r.length)return null;let i=t+4,a=h(r),o=Math.ceil(a.maxX-a.minX+i*2),s=Math.ceil(a.maxY-a.minY+i*2),c=Math.min(1,xt/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 Nt(e,t=1.5){let{canvas:n,ox:r,oy:i,scale:a}=e,o=Dt(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=bt(n,t),i=r.length>=3?r:n;i.length>=3&&Ct(i)>=St&&c.push(i)}return c}function Pt(e,t){let{canvas:n}=e,r=document.createElement(`canvas`);r.width=n.width,r.height=n.height;let i=r.getContext(`2d`);return i?(i.drawImage(n,0,0),i.globalCompositeOperation=`source-in`,i.fillStyle=t,i.fillRect(0,0,r.width,r.height),r):n}function Ft(e){return e.map(e=>({mode:e.mode,points:e.points.map(e=>({...e}))}))}function It(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 Q(e){return e.map(e=>({...e}))}function Lt(e,t){return e.length===t.length&&e.every((e,n)=>e.x===t[n].x&&e.y===t[n].y)}var Rt=10;function zt(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 Bt({toolRef:e,selRef:t,docRef:n,readOnlyRef:i,draftRef:a,brushSizeRef:s,simplifyEpsilonRef:c,draftMeta:l,engineRef:d,onDrawSessionChange:f,onDraftShapeChange:m,changeSelection:h,createShape:g}){let _=(0,r.useRef)(f);_.current=f;let v=(0,r.useRef)(m);v.current=m;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===B.BRUSH&&S.current.length>0,I=()=>{let t=e.current;return t===B.BRUSH&&F()?`brush`:t===B.POLYGON&&S.current.length>0?`polygon`:t===B.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,z=()=>E.current>0,ee=()=>E.current<T.current.length-1,te=()=>{let t=e.current;return t===B.BRUSH?L():t===B.POLYGON||t===B.PATH?z():!1},ne=()=>{let t=e.current;return t===B.BRUSH?R():t===B.POLYGON||t===B.PATH?ee():!1},re=()=>I()!==`none`,V=(0,r.useCallback)(()=>{let e=I(),t={active:e!==`none`,kind:e,canUndo:te(),canRedo:ne(),brush:e===`brush`?{mode:N.current,editing:A.current.length>0,editTargetIds:[...A.current]}:void 0},n=x.current;n&&zt(n,t)||(x.current=t,_.current?.(t))},[]),H=(0,r.useCallback)(()=>{j.current=[[]],M.current=0},[]),U=(0,r.useCallback)(()=>{let t=d.current;if(!t)return;let n=e.current;if(n===B.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=Mt(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!==B.PATH;if(t.previewPoly(r,C.current,i,!1,c,l),n===B.POLYGON||n===B.PATH){let e=v.current;e&&r!==D.current&&(D.current=r,e({type:o.POLYGON,points:Q(r),meta:y.current}))}},[s,a,d,e]),ie=(0,r.useCallback)(e=>{let t=Ft(e),n=j.current,r=M.current,i=n[r];i&&It(i,t)||(j.current=[...n.slice(0,r+1),t],M.current+=1,V())},[V]),ae=(0,r.useCallback)(e=>{let t=T.current,n=E.current,r=t[n];r&&Lt(r,e)||(T.current=[...t.slice(0,n+1),Q(e)],E.current+=1)},[]),W=(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,H(),d.current?.clearPreview(),v.current?.(null),V()},[d,V,H]),oe=(0,r.useCallback)((e,t)=>{S.current=e,w.current=new Set(Array.from(w.current).filter(t=>t>=0&&t<e.length)),t&&ae(e),U(),V()},[V,ae,U]),se=(0,r.useCallback)(()=>Q(S.current),[]),ce=(0,r.useCallback)(()=>S.current.length>0,[]),le=(0,r.useCallback)((t,n)=>{if(e.current!==B.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),W(),!0)},[W,e]),ue=(0,r.useCallback)(e=>{let t=S.current;return e<0||e>=t.length?!1:(oe(t.filter((t,n)=>n!==e),!0),!0)},[oe]),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,U(),V(),{base:Q(n),indices:Array.from(r)}},[V,U]),fe=(0,r.useCallback)(e=>{w.current=new Set,C.current=e,oe([...S.current,e],!0)},[oe]),pe=(0,r.useCallback)(e=>{C.current=null,w.current=new Set,S.current=[{...e}],U(),V()},[V,U]),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,U(),V(),!0)},[V,U]),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,U(),V()},[V,U]),ge=(0,r.useCallback)(e=>{e&&(ae(S.current),U(),V())},[V,ae,U]),_e=(0,r.useCallback)(e=>{C.current=e?{...e}:null,U()},[U]),ve=(0,r.useCallback)(()=>S.current.length>0?(S.current=[],U(),V(),!0):M.current<=0?!1:(--M.current,O.current=Ft(j.current[M.current]),U(),V(),!0),[V,U]),ye=(0,r.useCallback)(()=>S.current.length>0||M.current>=j.current.length-1?!1:(M.current+=1,O.current=Ft(j.current[M.current]),U(),V(),!0),[V,U]),be=(0,r.useCallback)(()=>E.current<=0?!1:(--E.current,S.current=Q(T.current[E.current]),w.current=new Set,U(),V(),!0),[V,U]),xe=(0,r.useCallback)(()=>E.current>=T.current.length-1?!1:(E.current+=1,S.current=Q(T.current[E.current]),w.current=new Set,U(),V(),!0),[V,U]),Se=(0,r.useCallback)(()=>{let t=e.current;return t===B.BRUSH?ve():t===B.POLYGON||t===B.PATH?be():!1},[e,ve,be]),G=(0,r.useCallback)(()=>{let t=e.current;return t===B.BRUSH?ye():t===B.POLYGON||t===B.PATH?xe():!1},[ye,xe,e]),Ce=(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=Z(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:Q(S.current),mode:P()});let t=k.current,r=[...A.current];if(!e.length&&!t.length)return!1;let u=Mt(e,s.current,t);if(!u)return W(),!1;let d=Nt(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),W(),h([]),!0;d.sort((e,t)=>Ct(t)-Ct(e));let t=[],i=[],a=[];for(let n=0;n<d.length;n++){let r=d[n];if(n<e.length){let i=e[n];t.push({...i,type:o.POLYGON,points:r}),a.push(i.id)}else{let t=e[0],n=p();i.push({...t,id:n,type:o.POLYGON,points:r}),a.push(n)}}let s=e.slice(d.length).map(e=>e.id);return t.length&&n.current.update(t),i.length&&n.current.create(i),s.length&&n.current.remove(s),W(),h(a),!0}if(!d.length)return W(),!1;let f=a.current;if(!f)return!1;let m=d.map(e=>({id:p(),type:o.POLYGON,points:e,style:f,meta:l}));return n.current.create(m),h(m.map(e=>e.id)),W(),!0},[s,h,n,l,a,i,W]),Te=(0,r.useCallback)(()=>{let t=e.current;if(t===B.BRUSH)return we();let n=S.current;return t===B.POLYGON&&n.length>=3?(b.current(o.POLYGON,n),W(),!0):!1},[we,W,e]),Ee=(0,r.useCallback)(()=>{let t=S.current;if(e.current===B.PATH&&t.length>=3){let e=bt(t,c.current);e.length>=3&&b.current(o.POLYGON,e)}W()},[W,e]),De=(0,r.useCallback)(e=>{N.current=e,V(),U()},[V,U]),Oe=(0,r.useCallback)(()=>{if(i.current||e.current!==B.BRUSH)return!1;O.current=[],S.current=[],H();let t=Ce();return V(),U(),t},[V,i,U,H,Ce,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,oe(t,!0),!0},[oe]),Ae=(0,r.useCallback)(e=>{let t=d.current,n=S.current;if(!t||!n.length)return-1;let r=Rt/(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]),K=(0,r.useCallback)(()=>{S.current.length>=1&&(O.current.push({points:Q(S.current),mode:P()}),S.current=[],ie(O.current)),U(),V()},[V,ie,U]);return{reset:W,undoSession:Se,redoSession:G,canUndoSession:te,canRedoSession:ne,hasDraftSession:re,hasDraftPoints:ce,commitDraftSession:Te,completeFreehandStroke:Ee,setBrushScalarMode:De,getBrushScalarMode:()=>N.current,hasBrushSession:F,commitBrush:we,cancelBrush:(0,r.useCallback)(()=>{e.current===B.BRUSH&&W()},[W,e]),beginBrushEditFromSelection:Oe,deleteDraftSelectedPoints:ke,hitDraftPoint:Ae,getDraftPointsSnapshot:se,tryClosePolygon:le,removeDraftPoint:ue,selectDraftPointForDrag:de,appendPolygonPoint:fe,beginStroke:pe,appendStrokePoint:me,moveDraftPoints:he,commitDraftPointDrag:ge,setDraftCursor:_e,finishScalarStroke:K,handleToolChange:(0,r.useCallback)((e,t)=>{if(t){W(),N.current=`draw`;return}if(e!==B.BRUSH){W(),N.current=`draw`;return}N.current=`draw`,O.current=[],S.current=[],H(),Ce(),V(),U()},[V,U,W,H,Ce]),handleBrushSelectionChange:(0,r.useCallback)((t,n)=>{if(!(e.current!==B.BRUSH||n)){if(!t.length){V();return}[...t].sort().join(`,`)!==[...A.current].sort().join(`,`)&&(O.current.length||S.current.length||(O.current=[],S.current=[],H(),Ce(),V(),U()))}},[V,U,H,Ce,e])}}function Vt(e,t){return{shapes:t,past:[...e.past,e.shapes],future:[]}}function Ht(e,t){switch(t.type){case`CREATE`:return Vt(e,[...e.shapes,...t.shapes]);case`UPDATE`:{let n=new Map(t.shapes.map(e=>[e.id,e]));return Vt(e,e.shapes.map(e=>n.get(e.id)??e))}case`DELETE`:{let n=new Set(t.ids);return Vt(e,e.shapes.filter(e=>!n.has(e.id)))}case`REPLACE`:{let n=new Set(t.removeIds);return Vt(e,[...e.shapes.filter(e=>!n.has(e.id)),...t.shapes])}case`REORDER`:{let n=new Set(t.ids),r=e.shapes.filter(e=>n.has(e.id)),i=e.shapes.filter(e=>!n.has(e.id));return r.length===0?e:Vt(e,t.edge===`front`?[...i,...r]:[...r,...i])}case`RESET`:return{shapes:t.shapes,past:[],future:[]};case`UNDO`:return e.past.length===0?e:{shapes:e.past[e.past.length-1],past:e.past.slice(0,-1),future:[e.shapes,...e.future]};case`REDO`:return e.future.length===0?e:{shapes:e.future[0],past:[...e.past,e.shapes],future:e.future.slice(1)};default:return e}}function Ut(e){let{onShapesCreated:t,onShapesUpdated:n,onShapesDeleted:i}=e,[a,o]=(0,r.useReducer)(Ht,{shapes:[],past:[],future:[]}),s=(0,r.useRef)(a);s.current=a;let c=(0,r.useCallback)(e=>{s.current=Ht(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 Wt={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`]},Gt={Equal:`=`,Minus:`-`,BracketLeft:`[`,BracketRight:`]`,Semicolon:`;`,Period:`.`,Comma:`,`,Slash:`/`,Backquote:"`"},Kt={Escape:`escape`,Enter:`enter`,Backspace:`backspace`,Delete:`delete`,Tab:`tab`,ArrowUp:`arrowup`,ArrowDown:`arrowdown`,ArrowLeft:`arrowleft`,ArrowRight:`arrowright`};function qt(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]:Gt[t]?Gt[t]:Kt[e.key]?Kt[e.key]:null}function Jt(e){let t=qt(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 Yt(e){let t=new Map;for(let n of Object.keys(Wt)){let r=e?.[n],i=r===void 0?Wt[n]:r===null?[]:Array.isArray(r)?r:[r];for(let e of i)t.set(e.toLowerCase(),n)}return t}var Xt={ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0]};function Zt(){let e=document.activeElement;return!!e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable)}function Qt(e,t){if(!t||!(e instanceof Element))return!1;let n=e.closest(`[role="dialog"],[aria-modal="true"]`);return!!n&&!n.contains(t)}function $t(e){let{spaceRef:t,shiftRef:n}=e,i=(0,r.useMemo)(()=>Yt(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=e=>{if(e.code===`Space`&&(t.current=!0,a.current.onSpaceDown()),e.key===`Shift`&&(n.current=!0),Zt()||Qt(e.target,a.current.hostRef.current))return;let r=Xt[e.key];if(r){e.preventDefault();let t=e.shiftKey?10:1;a.current.nudge(r[0]*t,r[1]*t);return}let i=Jt(e);if(!i)return;let s=o.current.get(i);s&&a.current.actions[s]?.()!==!1&&e.preventDefault()},r=e=>{e.code===`Space`&&(t.current=!1,a.current.onSpaceUp()),e.key===`Shift`&&(n.current=!1)};return window.addEventListener(`keydown`,e,{capture:!0}),window.addEventListener(`keyup`,r,{capture:!0}),()=>{window.removeEventListener(`keydown`,e,{capture:!0}),window.removeEventListener(`keyup`,r,{capture:!0})}},[t,n])}async function en(e){for(let t of[`default`,`reload`])try{let n=await fetch(e,{mode:`cors`,credentials:`omit`,cache:t});if(n.ok)return URL.createObjectURL(await n.blob())}catch{}return null}var tn=4e3;function nn(e,t,n=tn){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 an(e,t,n){if(t===o.POINT){e.setAttrs({x:n[0].x,y:n[0].y});return}if(t===o.RECTANGLE){let[t,r]=n;e.setAttrs({x:Math.min(t.x,r.x),y:Math.min(t.y,r.y),width:Math.abs(r.x-t.x),height:Math.abs(r.y-t.y)});return}if(t===o.ELLIPSE){let t=h(n);e.setAttrs({x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2,radiusX:(t.maxX-t.minX)/2,radiusY:(t.maxY-t.minY)/2});return}e.setAttrs({x:0,y:0,points:n.flatMap(e=>[e.x,e.y])})}var on=`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`,sn=`#ffffff`,cn=1.5;function ln(e){return`<svg width="16" height="22" viewBox="0 0 16 22" xmlns="http://www.w3.org/2000/svg"><path d="${on}" fill="${e}" stroke="${sn}" stroke-width="${cn}"/></svg>`}var un=Math.PI/12;function dn(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 fn(e,t,n){if(e.kind===`resize`){let r=n?e.box:_(e.anchor,e.box,t.x,t.y);return{updates:e.shapes.map(i=>({id:i.id,points:n?N(i.points,e.anchor,t):P(i.points,e.box,r)})),box:r}}if(e.kind===`move`){let n=t.x-e.start.x,r=t.y-e.start.y;return{updates:e.shapes.map(e=>({id:e.id,points:e.points.map(e=>({x:e.x+n,y:e.y+r}))})),box:{minX:e.box.minX+n,minY:e.box.minY+r,maxX:e.box.maxX+n,maxY:e.box.maxY+r}}}if(e.kind===`rotate`){let n=Math.atan2(t.y-e.center.y,t.x-e.center.x)-e.startAngle;return e.shiftKey&&(n=Math.round(n/un)*un),{updates:[{id:e.id,points:e.points.map(t=>y(t,e.center,n))}],box:null}}let r=t.x-e.start.x,i=t.y-e.start.y,a=e.base.map((t,n)=>e.indices.includes(n)?{x:t.x+r,y:t.y+i}:t);return{updates:[{id:e.id,points:a}],box:h(a)}}function pn(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)}:dn(e,t)?A(t.shapes[0].points)[m.indexOf(t.anchor)]:g(t.anchor,t.box)}function mn(e,t,n){let r=e.filter(e=>t.includes(e.id)&&d(e)).map(e=>({id:e.id,points:e.points}));return r.length?{kind:`move`,start:n,box:h(r.flatMap(e=>e.points)),shapes:r}:null}function hn(e){return e.map(e=>({...e,points:e.points.map(e=>({...e}))}))}function gn(e,t){let n=new Set(t);return e.filter(e=>n.has(e.id)&&u(e))}function _n(e,t){return e.filter(e=>{if(!l(e))return!1;let n=h(e.points);return n.minX<=t.maxX&&n.maxX>=t.minX&&n.minY<=t.maxY&&n.maxY>=t.minY}).map(e=>e.id)}function vn(e,t,n){return(e?fe(e,{strokeWidth:t}).pointRadius:5)/(n||1)}function yn(e,t){return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}function bn(e,t,n){if(e.type===o.ROTATED_RECTANGLE)return t;let r=e.type===o.POINT?yn(t[0],n):h(t);return b([{x:r.minX,y:r.minY},{x:r.maxX,y:r.maxY}])}function xn(e){return 24/(e||1)}function Sn(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}var Cn=2,wn=`#1e88e5`,Tn=`#669def`,En=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.guideOverlayGroup=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=Cn,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.guideOverlayGroup,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`,()=>{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}})});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},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}bindCursor(e,t){let n=()=>{this.activeDrag||t===`pointer`&&!this.transformEnabled||this.emitCursorHint(t)},r=()=>{this.activeDrag||this.emitCursorHint(null)};e.on(`mouseenter`,n),e.on(`mouseover`,n),e.on(`mouseleave`,r),e.on(`mouseout`,r)}toImage(){let e=this.world.getRelativePointerPosition();return e?{x:e.x,y:e.y}:this.lastImg}imgToScreen(e){return this.world.getAbsoluteTransform().point(e)}async setImage(e,t,n){let r=++this.imageLoadToken,a=await en(e);await new Promise(o=>{let s=new Image;a||(s.crossOrigin=`anonymous`),s.onload=()=>{if(a&&URL.revokeObjectURL(a),r!==this.imageLoadToken)return o();this.imageWidth=t?.width??s.naturalWidth,this.imageHeight=t?.height??s.naturalHeight;let e=n?.width??this.imageWidth,c=n?.height??this.imageHeight;this.bgGroup.scale({x:e/s.naturalWidth,y:c/s.naturalHeight}),this.bgGroup.destroyChildren();for(let e of nn(s.naturalWidth,s.naturalHeight))this.bgGroup.add(new i.default.Image({image:s,x:e.x,y:e.y,width:e.width,height:e.height,crop:{x:e.srcX,y:e.srcY,width:e.width,height:e.height},listening:!1}));this.layer.batchDraw(),o()},s.onerror=()=>{a&&URL.revokeObjectURL(a),this.imageWidth||=800,this.imageHeight||=600,o()},s.src=a??e})}clearImage(){this.imageLoadToken++,this.bgGroup.destroyChildren(),this.layer.batchDraw()}setFilter(e,t){let n=e!==1||t!==1?`brightness(${e}) contrast(${t})`:``,r=this.stage.container().querySelector(`canvas`);r&&(r.style.filter=n)}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,n){this.guideOverlayGroup.destroyChildren(),e&&this.guideOverlayGroup.add(new i.default.Image({image:e,opacity:.55,imageSmoothingEnabled:!1,listening:!1})),this.setRegionOverlay(t),this.dimOverlayGroup.destroyChildren(),n&&this.imageWidth&&this.dimOverlayGroup.add(new i.default.Rect({x:0,y:0,width:this.imageWidth,height:this.imageHeight,fill:`#0d0d12`,opacity:.3,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=>{it(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??pn(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=hn(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=fe(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=fe(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?pe(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:on,x:n[0].x,y:n[0].y,offsetX:16/2,offsetY:22,scaleX:t,scaleY:t,fill:r.color,stroke:sn,strokeWidth:cn,strokeScaleEnabled:!1,shadowColor:`#000`,shadowBlur:2,shadowOpacity:.3,shadowForStrokeEnabled:!1,opacity:r.opacity,listening:a});return this.bindCursor(o,d(e)?`grab`:`default`),o}if(t===o.RECTANGLE){let t=h(n),r=new i.default.Rect({x:t.minX,y:t.minY,width:t.maxX-t.minX,height:t.maxY-t.minY,fill:c,...s});return this.bindCursor(r,d(e)?`grab`:`default`),r}if(t===o.ELLIPSE){let t=h(n),r=new i.default.Ellipse({x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2,radiusX:(t.maxX-t.minX)/2,radiusY:(t.maxY-t.minY)/2,fill:c,...s});return this.bindCursor(r,d(e)?`grab`:`default`),r}let u=n.flatMap(e=>[e.x,e.y]),f=t!==o.LINE,p=new i.default.Line({points:u,closed:f,fill:f?c:void 0,lineJoin:`round`,...s});return this.bindCursor(p,d(e)?`grab`:`default`),p}liveUpdateShape(e,t){let n=this.nodes.get(e),r=this.shapes.find(t=>t.id===e);if(n&&r){an(n,r.type,t);let a=this.altNodes.get(e);a&&an(a,r.type,t),r.type===o.POINT&&n instanceof i.default.Circle&&n.radius(this.pointRadius(r)),this.layer.batchDraw()}}pointRadius(e){return vn(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(fe(t,{strokeWidth:this.strokeSize}).dash))}}shapesIntersecting(e){return _n(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:Tn,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 bn(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?wn:`#ffffff`,stroke:r?`#ffffff`:wn,strokeWidth:1.5,strokeScaleEnabled:!1,listening:!1}))}this.layer.batchDraw()}previewScalarMask(e,t){this.previewGroup.destroyChildren();let n=Pt(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:pe(le,ue),stroke:le,strokeWidth:1,strokeScaleEnabled:!1,listening:!1,perfectDrawEnabled:!1}),this.previewGroup.add(this.marquee)),this.marquee.setAttrs({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(t.x-e.x),height:Math.abs(t.y-e.y)}),this.layer.batchDraw()}setTransformEnabled(e){this.transformEnabled=e,this.drawTransformer(),this.layer.batchDraw()}setPanMode(e){this.handleGroup.listening(!e),this.layer.batchDraw()}setTransformerOutline(e){let t=Math.max(0,e.maxX-e.minX),n=Math.max(0,e.maxY-e.minY);!t&&!n||this.setTransformerOutlinePoints(b([{x:e.minX,y:e.minY},{x:e.maxX,y:e.maxY}]))}setTransformerOutlinePoints(e){e.length<2||(this.transformerOutline||(this.transformerOutline=new i.default.Line({closed:!0,stroke:wn,strokeWidth:1,strokeScaleEnabled:!1,listening:!1}),this.selGroup.add(this.transformerOutline)),this.transformerOutline.points(e.flatMap(e=>[e.x,e.y])))}rotationHandleGap(){return xn(this.viewport.scale)}rotationHandleScreenPoint(e){return this.imgToScreen(j(e,this.rotationHandleGap()))}setRotationConnector(e){let t=this.imgToScreen(O(e[0],e[1])),n=this.rotationHandleScreenPoint(e);this.rotLineNode?this.rotLineNode.points([t.x,t.y,n.x,n.y]):(this.rotLineNode=new i.default.Line({points:[t.x,t.y,n.x,n.y],stroke:wn,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 Sn(this.imgToScreen(e[0]),this.imgToScreen(e[1]))}repositionOrientedHandles(e){let t=this.orientedHandleAngle(e);if(A(e).forEach((e,n)=>{let r=this.imgToScreen(e),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,t)}),this.setTransformerOutlinePoints(e),this.rotNode){let t=this.rotationHandleScreenPoint(e);this.rotNode.position({x:t.x,y:t.y})}this.rotLineNode&&this.setRotationConnector(e)}drawTransformer(){if(this.activeDrag)return;for(let e of this.handleNodes)e.destroy();for(let e of this.vertexNodes)e.destroy();for(let e of this.midNodes)e.destroy();if(this.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=gn(this.shapes,this.selected);if(!e.length||e.length===1&&e[0].type===o.POINT)return;let t=e.length===1&&(e[0].type===o.POLYGON||e[0].type===o.LINE)&&this.editingId===e[0].id?e[0]:null,n=h(e.flatMap(e=>e.points)),r=e.length===1&&e[0].type===o.ROTATED_RECTANGLE?e[0]:null,a=r?A(r.points):m.map(e=>g(e,n));r?this.setTransformerOutlinePoints(r.points):this.setTransformerOutline(n),r&&this.setRotationConnector(r.points);let s=r?this.orientedHandleAngle(r.points):0;for(let e of t?[]:m){let t=this.imgToScreen(a[m.indexOf(e)]),n=new i.default.Rect({x:t.x,y:t.y,width:8,height:8,offsetX:4,offsetY:4,rotation:s*180/Math.PI,fill:`#ffffff`,stroke:wn,strokeWidth:1}),r=Je(e,s);this.bindCursor(n,r),n.on(`mousedown`,t=>{t.cancelBubble=!0,this.emitCursorHint(r),this.emitInteractionMode(`resizing`);let n=gn(this.shapes,this.selected);this.activeDrag={kind:`resize`,anchor:e,box:h(n.flatMap(e=>e.points)),shapes:n.map(e=>({id:e.id,points:e.points}))},this.lastDragImg=null}),this.handleGroup.add(n),this.handleNodes.push(n)}if(t){let e=t,n=e.points,r=e.type===o.POLYGON?n.length:n.length-1,a=this.vertexHandleRadius(),s=new i.default.Circle({radius:a*.8,fill:`#ffffff`,opacity:.6,stroke:wn,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?wn:`#ffffff`,stroke:s?`#ffffff`:wn,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=k(t.points),r=this.rotationHandleScreenPoint(t.points),a=new i.default.Circle({x:r.x,y:r.y,radius:6,fill:`#ffffff`,stroke:wn,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=mn(this.shapes,t,e);n&&(this.transformEnabled&&!this.handleNodes.length&&this.drawTransformer(),this.activeDrag=n,this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`moving`),(n.shapes.length===1?this.shapes.find(e=>e.id===n.shapes[0].id):null)?.type===o.ROTATED_RECTANGLE?this.setTransformerOutlinePoints(n.shapes[0].points):this.setTransformerOutline(n.box),this.updateSelectionBordersLive(e=>e.points))}repositionHandles(e){m.forEach((t,n)=>{let r=this.imgToScreen(g(t,e)),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,0)}),this.setTransformerOutline(e)}repositionPolygonHandles(e,t){if(!this.vertexNodes.length)return;e.forEach((e,t)=>{let n=this.imgToScreen(e);this.vertexNodes[t]?.position({x:n.x,y:n.y})});let n=t?e.length:e.length-1;for(let t=0;t<n;t++){let n=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=dn(this.shapes,t),{updates:r,box:i}=fn(t,e,n);for(let e of r)this.liveUpdateShape(e.id,e.points);if(this.cb.onTransformPreview?.(r),this.updateSelectionBordersLive(e=>r.find(t=>t.id===e.id)?.points??e.points),t.kind===`resize`||t.kind===`move`){n?this.repositionOrientedHandles(r[0].points):i&&this.repositionHandles(i);let e=t.shapes.length===1?this.shapes.find(e=>e.id===t.shapes[0].id):null,a=e?.type===o.POLYGON||e?.type===o.LINE;(t.kind===`resize`?a:this.vertexNodes.length>0&&t.shapes.length===1)&&this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}else if(t.kind===`rotate`){this.repositionOrientedHandles(r[0].points);let e=this.shapes.find(e=>e.id===t.id);e&&(e.type===o.POLYGON||e.type===o.LINE)&&this.repositionPolygonHandles(r[0].points,e.type===o.POLYGON)}else{i&&this.repositionHandles(i);let e=this.shapes.find(e=>e.id===t.id);this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}this.layer.batchDraw()}endTransform(){let e=this.activeDrag,t=this.lastDragImg;if(this.activeDrag=null,this.emitInteractionMode(`idle`),this.emitCursorHint(e?.kind===`move`?`grab`:null),!e||!t){this.cb.onTransformPreview?.([]),this.drawTransformer();return}if(e.kind===`move`&&t.x===e.start.x&&t.y===e.start.y){this.cb.onTransformPreview?.([]),this.drawTransformer();return}let{updates:n}=fn(e,t,dn(this.shapes,e));this.commitTransformUpdates(n)}},Dn=2,On=58879,kn=6725103;function An(e){if(!e)return On;let t=e.replace(`#`,``);return Number.parseInt(t.length===3?t.replace(/./g,`$&$&`):t,16)}var jn=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.guideOverlayLayer=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.overlayTextures=[],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=Dn,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),this.applyCursor(),this.overlayLayer.addChild(this.guideOverlayLayer,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 e=(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},insideCanvas:t})};this.app.stage.on(`pointerup`,t=>e(t,!0)),this.app.stage.on(`pointerupoutside`,t=>e(t,!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();for(let e of this.overlayTextures)e.destroy(!0);this.overlayTextures=[],this.app.renderer&&this.app.destroy(!0,{children:!0})}get screenSize(){return{w:this.app.renderer.screen.width,h:this.app.renderer.screen.height}}setCursor(e){this.baseCursor=e,this.syncShapeCursors(),this.applyCursor()}emitCursorHint(e){this.cb.onCursorHint?.(e)}emitInteractionMode(e){this.cb.onInteractionModeChange?.(e)}applyCursor(){if(this.destroyed||!this.app.renderer)return;let e=this.app.canvas;e&&(e.style.cursor=this.baseCursor)}syncShapeCursors(){for(let e of this.nodes.values())e.cursor=void 0}bindCursor(e,t){e.cursor=void 0,e.on(`pointerover`,()=>{this.activeDrag||this.emitCursorHint(t)}),e.on(`pointerout`,()=>{this.activeDrag||this.emitCursorHint(null)})}get dom(){return this.app.canvas}toImage(e){let t=this.world.toLocal(e.global);return{x:t.x,y:t.y}}async setImage(e,t,n){let r=++this.imageLoadToken,i=await en(e);if(this.destroyed){i&&URL.revokeObjectURL(i);return}await new Promise(o=>{let s=new Image;i||(s.crossOrigin=`anonymous`),s.onload=()=>{if(i&&URL.revokeObjectURL(i),this.destroyed||r!==this.imageLoadToken)return o();this.imageWidth=t?.width??s.naturalWidth,this.imageHeight=t?.height??s.naturalHeight;let e=n?.width??this.imageWidth,c=n?.height??this.imageHeight;this.bgLayer.scale.set(e/s.naturalWidth,c/s.naturalHeight),this.clearImageTiles();for(let e of nn(s.naturalWidth,s.naturalHeight)){let t=a.Texture.from(rn(s,e));t.source.scaleMode=this.imageSmoothing?`linear`:`nearest`,this.imageTileTextures.push(t);let n=new a.Sprite(t);n.x=e.x,n.y=e.y,n.width=e.width,n.height=e.height,this.bgLayer.addChild(n)}this.applySpriteFilter(),o()},s.onerror=()=>{i&&URL.revokeObjectURL(i),this.imageWidth||=t?.width??800,this.imageHeight||=t?.height??600,o()},s.src=i??e})}setFilter(e,t){this.brightness=e,this.contrast=t,this.applySpriteFilter()}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,n){for(let e of this.guideOverlayLayer.removeChildren())e.destroy();for(let e of this.overlayTextures)e.destroy(!0);if(this.overlayTextures=[],e){let t=a.Texture.from(e);t.source.scaleMode=`nearest`,this.overlayTextures.push(t);let n=new a.Sprite(t);n.alpha=.55,this.guideOverlayLayer.addChild(n)}this.setRegionOverlay(t);for(let e of this.dimOverlayLayer.removeChildren())e.destroy();n&&this.imageWidth&&this.dimOverlayLayer.addChild(new a.Graphics().rect(0,0,this.imageWidth,this.imageHeight).fill({color:855314,alpha:.3})),!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=An(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??pn(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=hn(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,this.syncShapeCursors(),this.drawTransformer()}setPanMode(e){this.handleLayer.interactiveChildren=!e}strokeW(e){return(e?fe(e,{strokeWidth:this.strokeSize}).strokeWidth:Dn)/this.world.scale.x}pointRadius(e){return vn(e,this.strokeSize,this.world.scale.x)}dashForShape(e){let t=fe(e,{strokeWidth:this.strokeSize}).dash;if(!t?.length)return null;let n=this.world.scale.x||1;return[t[0]/n,(t[1]??t[0])/n]}drawShapes(){this.shapeLayer.removeChildren();for(let e of this.nodes.values())e.destroy();this.nodes.clear();for(let e of f(this.shapes).filter(s)){let t=new a.Graphics;this.paintShape(t,e),t.eventMode=l(e)?`static`:`none`,t.cursor=void 0,l(e)&&d(e)&&(t.on(`pointerover`,()=>{!this.activeDrag&&this.transformEnabled&&this.emitCursorHint(`grab`)}),t.on(`pointerout`,()=>{this.activeDrag||this.emitCursorHint(null)})),t.on(`pointerdown`,t=>{t.stopPropagation(),this.cb.onPointerDown(this.toImage(t),e.id,this.ev(t))}),this.shapeLayer.addChild(t),this.nodes.set(e.id,t)}}paintShape(e,t){e.clear();let n=fe(t,{strokeWidth:this.strokeSize}),r=An(n.color),i=this.strokeW(t),a=n.opacity,s=this.dashForShape(t);if(t.type===o.POINT){e.svg(ln(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?R(t.points):null;if(i&&i.length>1)for(let t of i)e.poly(t.flatMap(e=>[e.x,e.y]),!0),e.fill({color:r,alpha:n.fillAlpha*a});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:An(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 _n(this.shapes,e)}shapesAt(e){return this.shapes.filter(t=>{let n=h(t.points);return e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY}).map(e=>e.id)}repaintPreview(){let e=this.lastPreview;e&&(e.kind===`poly`?this.previewPoly(e.points,e.cursor,e.style,e.closed,e.selectedPointIndices,e.showVertices):this.previewBox(e.boxKind,e.a,e.b,e.style))}ensurePreview(){this.previewReady||=(this.previewLayer.addChild(this.previewG,this.marqueeG),!0)}clearPreview(){this.lastPreview=null,this.previewG.clear(),this.previewMaskSprite&&(this.previewMaskSprite.visible=!1)}clearMarquee(){this.marqueeG.clear()}previewBox(e,t,n,r){this.lastPreview={kind:`box`,boxKind:e,a:t,b:n,style:r},this.ensurePreview(),this.previewG.clear();let i={id:`__preview__`,type:e===`ellipse`?o.ELLIPSE:o.RECTANGLE,points:[t,n],style:r},a=this.strokeW(i);r.alternateColor&&(this.path(this.previewG,i),this.previewG.stroke({width:a,color:An(r.alternateColor)}));let s=this.dashForShape(i);if(s){this.dashedStrokeShape(this.previewG,i,a,An(r.color??`#00e5ff`),r.opacity??1,s);return}this.path(this.previewG,i),this.previewG.stroke({width:a,color:An(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:An(n.alternateColor)}));let u=this.dashForShape(c);if(u?this.dashedStrokeShape(this.previewG,c,l,An(n.color??`#00e5ff`),n.opacity??1,u):(this.path(this.previewG,c),this.previewG.stroke({width:l,color:An(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=Pt(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=An(le);this.marqueeG.rect(n,r,i,a).fill({color:o,alpha:ue}).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:An(r.underlayColor)}),this.strokeDashedPolyline(e,[n,o],!1,i,An(r.color),r.opacity,a)};r(this.region.visibleOutline,t.visible),r(this.region.occludedOutline,t.occluded)}path(e,t){let{type:n,points:r}=t;if(n===o.POINT){e.circle(r[0].x,r[0].y,this.pointRadius(t));return}if(n===o.RECTANGLE){let t=h(r);e.rect(t.minX,t.minY,t.maxX-t.minX,t.maxY-t.minY);return}if(n===o.ELLIPSE){let t=h(r);e.ellipse((t.minX+t.maxX)/2,(t.minY+t.maxY)/2,(t.maxX-t.minX)/2,(t.maxY-t.minY)/2);return}let i=r.flatMap(e=>[e.x,e.y]);e.poly(i,n!==o.LINE)}dashedStrokeShape(e,t,n,r,i,a){let{type:s,points:c}=t;if(s===o.RECTANGLE){let t=h(c);this.strokeDashedPolyline(e,[{x:t.minX,y:t.minY},{x:t.maxX,y:t.minY},{x:t.maxX,y:t.maxY},{x:t.minX,y:t.maxY}],!0,n,r,i,a);return}if(s===o.ELLIPSE){let t=h(c),o=(t.minX+t.maxX)/2,s=(t.minY+t.maxY)/2,l=(t.maxX-t.minX)/2,u=(t.maxY-t.minY)/2,d=Array.from({length:96},(e,t)=>{let n=t/96*Math.PI*2;return{x:o+Math.cos(n)*l,y:s+Math.sin(n)*u}});this.strokeDashedPolyline(e,d,!0,n,r,i,a);return}this.strokeDashedPolyline(e,c,s!==o.LINE,n,r,i,a)}strokeDashedPolyline(e,t,n,r,i,a,o){if(t.length<2)return;let[s,c]=o;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:kn})})}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:kn}))}}selectionOutlinePoints(e,t){return bn(e,t,this.pointRadius(e))}imgToScreen(e){let t=this.world.toGlobal({x:e.x,y:e.y});return{x:t.x,y:t.y}}setTransformerOutline(e){let t=e.maxX-e.minX,n=e.maxY-e.minY;t<=0&&n<=0||this.setTransformerOutlinePoints(b([{x:e.minX,y:e.minY},{x:e.maxX,y:e.maxY}]))}setTransformerOutlinePoints(e){e.length<2||(this.transformerOutline||(this.transformerOutline=new a.Graphics,this.selLayer.addChild(this.transformerOutline)),this.transformerOutline.clear(),this.transformerOutline.poly(e.flatMap(e=>[e.x,e.y]),!0).stroke({width:1/this.world.scale.x,color:2001125}))}rotationHandleGap(){return xn(this.viewport.scale)}rotationHandleScreenPoint(e){return this.imgToScreen(j(e,this.rotationHandleGap()))}setRotationConnector(e){let t=this.imgToScreen(O(e[0],e[1])),n=this.rotationHandleScreenPoint(e);this.rotLineNode||(this.rotLineNode=new a.Graphics,this.rotLineNode.eventMode=`none`,this.handleLayer.addChild(this.rotLineNode)),this.rotLineNode.clear(),this.rotLineNode.moveTo(t.x,t.y).lineTo(n.x,n.y).stroke({width:1,color:2001125})}layoutResizeHandle(e,t,n){e.position.set(t.x,t.y),e.rotation=n}orientedHandleAngle(e){return Sn(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=gn(this.shapes,this.selected);if(e.length===0||e.length===1&&e[0].type===o.POINT)return;let t=e.length===1&&(e[0].type===o.POLYGON||e[0].type===o.LINE)&&this.editingId===e[0].id?e[0]:null,n=h(e.flatMap(e=>e.points)),r=e.length===1&&e[0].type===o.ROTATED_RECTANGLE?e[0]:null,i=r?A(r.points):m.map(e=>g(e,n));r?this.setTransformerOutlinePoints(r.points):this.setTransformerOutline(n),r&&this.setRotationConnector(r.points);let s=r?this.orientedHandleAngle(r.points):0;for(let e of t?[]:m){let t=this.imgToScreen(i[m.indexOf(e)]),n=new a.Graphics;n.rect(-4,-4,8,8).fill({color:16777215}).stroke({width:1,color:2001125}),this.layoutResizeHandle(n,t,s),n.eventMode=`static`;let r=Je(e,s);this.bindCursor(n,r),n.on(`pointerdown`,t=>{t.stopPropagation(),this.emitCursorHint(r),this.emitInteractionMode(`resizing`);let n=gn(this.shapes,this.selected);this.activeDrag={kind:`resize`,anchor:e,box:h(n.flatMap(e=>e.points)),shapes:n.map(e=>({id:e.id,points:e.points}))},this.lastDragImg=null}),this.handleLayer.addChild(n),this.handleNodes.push(n)}if(t){let e=t,n=e.points,r=e.type===o.POLYGON?n.length:n.length-1,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=k(t.points),r=this.rotationHandleScreenPoint(t.points),i=new a.Graphics;i.circle(0,0,6).fill({color:16777215}).stroke({width:1.5,color:2001125}),i.position.set(r.x,r.y),i.eventMode=`static`,this.bindCursor(i,`grab`),i.on(`pointerdown`,e=>{e.stopPropagation();let r=this.toImage(e);this.activeDrag={kind:`rotate`,id:t.id,center:n,startAngle:Math.atan2(r.y-n.y,r.x-n.x),points:t.points,shiftKey:e.shiftKey},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`rotating`)}),this.handleLayer.addChild(i),this.rotNode=i}}beginMove(e,t){let n=mn(this.shapes,t,e);n&&(this.transformEnabled&&!this.handleNodes.length&&this.drawTransformer(),this.activeDrag=n,this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`moving`),(n.shapes.length===1?this.shapes.find(e=>e.id===n.shapes[0].id):null)?.type===o.ROTATED_RECTANGLE?this.setTransformerOutlinePoints(n.shapes[0].points):this.setTransformerOutline(n.box),this.updateSelectionBordersLive(e=>e.points))}repositionHandlesForBox(e){m.forEach((t,n)=>{let r=this.imgToScreen(g(t,e)),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,0)}),this.setTransformerOutline(e)}repositionOrientedHandles(e){let t=this.orientedHandleAngle(e);if(A(e).forEach((e,n)=>{let r=this.imgToScreen(e),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,t)}),this.setTransformerOutlinePoints(e),this.rotNode){let t=this.rotationHandleScreenPoint(e);this.rotNode.position.set(t.x,t.y)}this.rotLineNode&&this.setRotationConnector(e)}repositionPolygonHandles(e,t){if(!this.vertexNodes.length)return;e.forEach((e,t)=>{let n=this.imgToScreen(e);this.vertexNodes[t]?.position.set(n.x,n.y)});let n=t?e.length:e.length-1;for(let t=0;t<n;t++){let n=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=dn(this.shapes,t),{updates:r,box:i}=fn(t,e,n);if(t.kind===`move`){let n=e.x-t.start.x,r=e.y-t.start.y;for(let e of t.shapes){let t=this.nodes.get(e.id);t&&(this.shapes.find(t=>t.id===e.id)?.type===o.POINT?t.position.set(e.points[0].x+n,e.points[0].y+r):t.position.set(n,r))}}else for(let e of r)this.liveUpdateShape(e.id,e.points);if(this.cb.onTransformPreview?.(r),this.updateSelectionBordersLive(e=>r.find(t=>t.id===e.id)?.points??e.points),t.kind===`resize`||t.kind===`move`){n?this.repositionOrientedHandles(r[0].points):i&&this.repositionHandlesForBox(i);let e=t.shapes.length===1?this.shapes.find(e=>e.id===t.shapes[0].id):null,a=e?.type===o.POLYGON||e?.type===o.LINE;(t.kind===`resize`?a:this.vertexNodes.length>0&&t.shapes.length===1)&&this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}else if(t.kind===`rotate`){this.repositionOrientedHandles(r[0].points);let e=this.shapes.find(e=>e.id===t.id);e&&(e.type===o.POLYGON||e.type===o.LINE)&&this.repositionPolygonHandles(r[0].points,e.type===o.POLYGON)}else{i&&this.repositionHandlesForBox(i);let e=this.shapes.find(e=>e.id===t.id);this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}}endTransform(){let e=this.activeDrag,t=this.lastDragImg;if(this.activeDrag=null,this.emitInteractionMode(`idle`),this.emitCursorHint(e?.kind===`move`?`grab`:null),!e||!t){this.cb.onTransformPreview?.([]),this.drawTransformer();return}if(e.kind===`move`&&t.x===e.start.x&&t.y===e.start.y){this.cb.onTransformPreview?.([]),this.drawTransformer();return}let{updates:n}=fn(e,t,dn(this.shapes,e));e.kind===`move`&&this.resetMoveOffsets(),this.commitTransformUpdates(n)}};function Mn({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 Nn({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,maskCanvasRef:m,regionOverlayRef:h,dimmedRef:g,syncMinimap:_,setImage:v,setImageVisible:y,setReady:b,setImageStatus:x,onContextMenuRequest:S}){let C=(0,r.useRef)(a);C.current=a;let w=(0,r.useRef)(i);w.current=i;let T=(0,r.useRef)(null),E=(0,r.useRef)(null),D=(0,r.useRef)(!1),O=(0,r.useRef)(null),k=(0,r.useRef)(o);k.current=o;let A=(0,r.useRef)(S);A.current=S,(0,r.useEffect)(()=>{let r=t.current;if(!r)return;let i=!1,a=null,o=null,x=k.current(),S=e===`konva`?new En(r,x):new jn(r,x);return n.current=S,(async()=>{if(await S.init(),i)return;if(S.setFilter(s.current.brightness,s.current.contrast),S.setRenderDefaults({strokeWidth:s.current.strokeSize}),S.setImageSmoothing(s.current.imageSmoothing),S.setTransformEnabled(!c.current),D.current=!0,C.current){if(await S.setImage(C.current,d.current,f.current),i)return;T.current=C.current,E.current=w.current,v({w:S.imageWidth,h:S.imageHeight}),y(!0),S.setShapes(u.current,p.current),S.setOverlays(s.current.showGuide?m.current:null,s.current.showRegionMask?h.current:null,g.current);let e=O.current;e?.viewport&&(e.imageUrl===T.current||s.current.keepZoomOnImageChange)?S.applyViewport(e.viewport):S.fit(),_(),b(!0)}let e=(e,t)=>Math.exp(-Math.sign(e)*Math.min(Math.abs(e)*.01,.1)*t);a=t=>{t.preventDefault();let n=S.dom.getBoundingClientRect(),r=s.current.zoomSensitivity??1;if(t.ctrlKey||t.metaKey){S.zoomAt(t.clientX-n.left,t.clientY-n.top,e(t.deltaY,r));return}if(!s.current.wheelZoom){let e=S.viewport;S.applyViewport({scale:e.scale,x:e.x-t.deltaX,y:e.y-t.deltaY});return}S.zoomAt(t.clientX-n.left,t.clientY-n.top,e(t.deltaY,r))},S.dom.addEventListener(`wheel`,a,{passive:!1}),o=e=>{if(e.preventDefault(),l.current===B.ASSISTANT_POINT&&e.altKey)return;let t=r.getBoundingClientRect(),n=e.clientX-t.left,i=e.clientY-t.top,a=S.viewport;A.current({x:n,y:i,img:{x:(n-a.x)/a.scale,y:(i-a.y)/a.scale}})},S.dom.addEventListener(`contextmenu`,o)})(),()=>{i=!0,D.current=!1,O.current={imageUrl:T.current??``,viewport:S.viewport},n.current=null,a&&S.dom&&S.dom.removeEventListener(`wheel`,a),o&&S.dom&&S.dom.removeEventListener(`contextmenu`,o),S.destroy()}},[e]),(0,r.useEffect)(()=>{let e=n.current;if(!e||!D.current)return;let t=Mn({currentDocId:E.current,documentId:i,loadedUrl:T.current,renderedImageUrl:a});if(t.kind===`none`)return;let r=()=>{b(!1),y(!1),e.clearImage(),e.setShapes([],[]),e.setOverlays(null,null,!1)};if(t.kind===`clear`){T.current=null,E.current=null,r();return}let o=a;t.docChange&&(E.current=null,r());let c=!1;return(async()=>{await e.setImage(o,d.current,f.current),!(c||n.current!==e)&&(T.current=o,t.docChange&&(E.current=i,v({w:e.imageWidth,h:e.imageHeight}),y(!0),e.setShapes(u.current,p.current),e.setOverlays(s.current.showGuide?m.current:null,s.current.showRegionMask?h.current:null,g.current),s.current.keepZoomOnImageChange||e.fit(),_(),b(!0)))})(),()=>{c=!0}},[i,a]),(0,r.useEffect)(()=>{let e=!1;if(!a){x(`loading`);return}x(`loading`);let t=new Image;return t.onload=()=>{e||x(`ready`)},t.onerror=()=>{e||x(`error`)},t.src=a,()=>{e=!0}},[a])}var Pn=.05,Fn=20;function In(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 Ln(e){let t=e.currentTarget.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}function Rn({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=Ln(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(Ln(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=In(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(Pn,Math.min(Fn,s));p(Ln(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 $(e,t,n){if(!(!e||!n.length)){if(t.type===o.POINT){e.setAttribute(`cx`,String(n[0].x)),e.setAttribute(`cy`,String(n[0].y));return}if(t.type===o.RECTANGLE||t.type===o.ELLIPSE){let r=h(n);if(t.type===o.ELLIPSE){e.setAttribute(`cx`,String((r.minX+r.maxX)/2)),e.setAttribute(`cy`,String((r.minY+r.maxY)/2)),e.setAttribute(`rx`,String((r.maxX-r.minX)/2)),e.setAttribute(`ry`,String((r.maxY-r.minY)/2));return}e.setAttribute(`x`,String(r.minX)),e.setAttribute(`y`,String(r.minY)),e.setAttribute(`width`,String(r.maxX-r.minX)),e.setAttribute(`height`,String(r.maxY-r.minY));return}e.setAttribute(`points`,n.map(e=>`${e.x},${e.y}`).join(` `))}}function zn({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)$(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&&$(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 Bn=12;function Vn({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),m=(0,r.useRef)(n),g=(0,r.useRef)(s),_=(0,r.useRef)(c);m.current=n,g.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,Be(Ie(e,s,c)))},[s,c,b]),C=(0,r.useCallback)(()=>He(c),[c]),w=(0,r.useCallback)(t=>{if(n)return;let r=s;Ue(c).then(n=>{if(!f.current||m.current||g.current!==r||_.current!==c||!n?.shapes.length)return;let a,o,l=n.shapes.flatMap(e=>e.points);if(t&&l.length){let e=h(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=We(d.current,e,Bn);a=t.offset,d.current=t.nextPasteCount,o=a}let u=n.shapes.map(e=>({...e,id:p(),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:p(),points:e.points.map(e=>({x:e.x+Bn,y:e.y+Bn}))}));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;let a=e.getShapes().filter(e=>t.current.includes(e.id)&&u(e));a.length&&e.update(a.map(e=>({...e,points:e.points.map(e=>({x:e.x+r,y:e.y+i}))})))},[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=Mt([],1,Z(t));if(!r)return;let s=Nt(r,1);if(!s.length)return;let c=t[0],l=s.map(e=>({id:p(),type:o.POLYGON,points:e,style:c.style,meta:c.meta}));e.replace(t.map(e=>e.id),l),i(l.map(e=>e.id))},[e,n,k,a,i])}}function Hn({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=gt(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=mt(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=ht(h(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 Un=`__draft_preview__`,Wn=new Set([`copy`,`selectAll`,`clearSelection`,`zoomToSelection`]);function Gn(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Kn({document:t,clipboardScope:i,renderImageState:a,dimmed:c=!1,selectedIds:d,activeTool:f,draftStyle:m,draftMeta:h,readOnly:g,disableMarquee:_,locked:v,onLockedInteraction:y,onIdleEscape:b,overrideShapeInteraction:x,defaultViewSettings:S,viewSettings:C,onViewSettingsChange:w,showMinimap:T=!0,showViewSettings:E=!0,getContextMenuItems:D,strings:O,canMergeSelection:k,brushSize:A=20,zoomBound:j,zoomAnimationDuration:M=300,decorationShapes:N,regionMask:P,guideMask:F,maskPalette:I,overlayMarkers:L,renderOverlayMarker:R,onOverlayMarkerClick:z,renderImageOverlay:ne,getSelectionLabel:re,hideSelectionLabelDot:V,formatSelectionInfo:H,externalTools:ie,assistant:se,keymap:ce,handleRef:le,backend:ue=`pixi`,onActiveToolChange:de,onSelectionChange:fe,onEditingChange:pe,onShapesCreated:me,onShapesUpdated:he,onShapesDeleted:ge,onDrawSessionChange:_e,onDraftShapeChange:ve,onViewportChange:be,onShapesTransformPreview:xe}){let Se=(0,r.useRef)(null),G=(0,r.useRef)(null),Ce=(0,r.useRef)(null),De=(0,r.useRef)(null),ke=(0,r.useRef)(null),Ae=`${(0,r.useId)()}-minimap`,[K,je]=(0,r.useState)(null),[Me,Ne]=(0,r.useState)(!1),[Pe,Fe]=(0,r.useState)(!1),[Ie,Re]=(0,r.useState)(null),[ze,Be]=(0,r.useState)({active:!1,kind:`none`,canUndo:!1,canRedo:!1}),[Ve,He]=(0,r.useState)(!0),[Ue,We]=(0,r.useState)(!1),Ge=t?.id??``,Ke=t?.imageUrl??``,qe=t?.displayImageUrl,Je=t?.coordinateSize,Ye=t?.initialShapes,Ze=t?.initialSelectedIds,Qe=qe??Ke,[et,tt]=(0,r.useState)(`loading`),q=Ut({onShapesCreated:me,onShapesUpdated:he,onShapesDeleted:ge}),[nt,rt]=(0,r.useState)([]),J=d??nt,it=d!==void 0,at=(0,r.useMemo)(()=>new Map((ie??[]).map(e=>[e.id,e])),[ie]),ot=(0,r.useRef)(at);(0,r.useLayoutEffect)(()=>{ot.current=at},[at]);let st=(0,r.useRef)(ze);st.current=ze;let ct=(0,r.useMemo)(()=>{let e=Object.fromEntries(Object.entries(S??{}).filter(([,e])=>e!==void 0));return{...te,...e}},[S]),ut=(0,r.useRef)(ct);ut.current=ct;let[Y,dt]=(0,r.useState)(()=>ut.current),ft=(0,r.useCallback)(e=>dt(t=>({...t,...e})),[]),X=(0,r.useMemo)(()=>ee(O),[O]);(0,r.useEffect)(()=>{C&&dt(e=>{let t=Object.entries(C).filter(([t,n])=>n!==void 0&&e[t]!==n);return t.length?{...e,...Object.fromEntries(t)}:e})},[C]);let pt=(0,r.useRef)(w);pt.current=w;let mt=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!mt.current){mt.current=!0;return}pt.current?.(Y)},[Y]);let ht=(0,r.useMemo)(()=>!F||!I?null:$e(F,I),[F,I]),gt=(0,r.useMemo)(()=>ht?.toDataURL()??null,[ht]),yt=(0,r.useMemo)(()=>!K||!P?null:lt(P,K.w,K.h),[K,P]),bt=(0,r.useRef)(ht);bt.current=ht;let xt=(0,r.useRef)(yt);xt.current=yt;let St=(0,r.useRef)(c);St.current=c;let Ct=(0,r.useRef)(K);Ct.current=K;let wt=(0,r.useRef)(Je);wt.current=Je;let Tt=(0,r.useRef)(Je?.imageSize);Tt.current=Je?.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)(m);Ot.current=m;let kt=(0,r.useRef)(h);kt.current=h;let At=(0,r.useRef)(A);At.current=A;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 It=(0,r.useRef)(x);It.current=x;let Q=(0,r.useRef)(q);Q.current=q;let Lt=(0,r.useRef)(!1),Rt=(0,r.useRef)(!1),zt=(0,r.useRef)(`idle`),Vt=(0,r.useRef)(null),Ht=(0,r.useCallback)(()=>{let e=G.current;if(!e)return;let t=Dt.current,n=ot.current.get(t),r=st.current;e.setCursor(Xe({tool:t,externalToolCursor:n?.cursor,isSpacePressed:Lt.current,interactionMode:zt.current,rendererCursorHint:Vt.current,isPolygonDrawing:r.kind===`polygon`&&r.active}))},[]),Wt=(0,r.useCallback)(e=>{zt.current!==e&&(zt.current=e,Ht())},[Ht]),Gt=(0,r.useCallback)(e=>{Vt.current!==e&&(Vt.current=e,Ht())},[Ht]),Kt=(0,r.useCallback)(e=>{let t=new Set,n=new Map(Q.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=It.current?.(r);return l(i?{...r,interaction:{...r.interaction,...i}}:r)})},[]),qt=(0,r.useCallback)(e=>{let t=Kt(e);Gn(Et.current,t)||(it||rt(t),G.current?.setSelection(t),fe?.(t))},[Kt,fe,it]),Jt=(0,r.useRef)(qt);Jt.current=qt;let[Yt,Xt]=(0,r.useState)(null),Zt=(0,r.useCallback)(e=>Xt(e),[]),Qt=(0,r.useRef)(Zt);Qt.current=Zt;let en=(0,r.useRef)(null);en.current=Yt,(0,r.useEffect)(()=>{if(!it)return;let e=Kt(d);Gn(d,e)||fe?.(e)},[d,q.shapes,Kt,fe,it]);let tn=(0,r.useRef)(be);tn.current=be;let{registerMinimapShape:nn,applyMinimapPreview:rn,syncMinimap:an}=zn({engineRef:G,docRef:Q,overlayRef:De,zoomLabelRef:ke,minimapRectRef:Ce,minimapSize:204,onViewportChangeRef:tn}),on=(0,r.useRef)(new Map),sn=(0,r.useRef)(H);sn.current=H;let cn=(0,r.useCallback)((e,t)=>{t?on.current.set(e,t):on.current.delete(e)},[]),ln=(0,r.useRef)(null),[un,dn]=(0,r.useState)(null),fn=(0,r.useCallback)(e=>{if(!e.length)return;let t=new Map(Q.current.getShapes().map(e=>[e.id,e]));ln.current&&t.set(ln.current.id,ln.current);for(let{id:n,points:r}of e){let e=on.current.get(n),i=t.get(n);if(!e||!i)continue;let a=we(e,r);if(a){let e=Te(i,r);a.textContent=sn.current?.(e)??Ee(e)}}},[]),pn=(0,r.useCallback)(e=>{rn(e),fn(e),xe?.(e)},[rn,fn,xe]),mn=(0,r.useCallback)(e=>{if(ve?.(e?{...e,meta:kt.current}:null),!e||!Ot.current){ln.current&&(ln.current=null,dn(null));return}let t={id:Un,type:e.type,points:e.points,style:Ot.current,meta:kt.current},n=ln.current!==null;ln.current=t,n?fn([{id:Un,points:e.points}]):dn(t)},[fn,ve]),hn=(0,r.useCallback)((e,t)=>{let n=Ot.current;if(!n||Mt.current)return;let r=p();Q.current.create({id:r,type:e,points:t,style:n,meta:h}),Jt.current([r])},[h]),gn=(0,r.useRef)(hn);gn.current=hn;let _n=Bt({toolRef:Dt,selRef:Et,docRef:Q,readOnlyRef:Mt,draftRef:Ot,brushSizeRef:At,simplifyEpsilonRef:jt,draftMeta:h,engineRef:G,onDrawSessionChange:(0,r.useCallback)(e=>{Be(e),_e?.(e)},[_e]),onDraftShapeChange:ve,changeSelection:qt,createShape:hn}),vn=(0,r.useRef)(_n);vn.current=_n;let{reset:yn,undoSession:bn,redoSession:xn,canUndoSession:Sn,canRedoSession:Cn,hasDraftSession:wn,hasDraftPoints:Tn,commitDraftSession:En,setBrushScalarMode:Dn,getBrushScalarMode:On,hasBrushSession:kn,commitBrush:An,cancelBrush:jn,beginBrushEditFromSelection:Mn,deleteDraftSelectedPoints:Pn,handleToolChange:Fn,handleBrushSelectionChange:In}=_n,Ln=(0,r.useRef)(se);Ln.current=se;let $=vt({docRef:Q,draftRef:Ot,draftMeta:h,changeSelection:qt,assistantRef:Ln}),Bn=(0,r.useRef)($);Bn.current=$;let Kn=(0,r.useMemo)(()=>Le(Ge),[Ge]),{selectAll:qn,clearSelection:Jn,deleteSelection:Yn,copySelection:Xn,canPaste:Zn,paste:Qn,duplicate:$n,bringToFront:er,sendToBack:tr,nudgeSelection:nr,getMergeTargets:rr,mergeSelection:ir}=Vn({doc:q,selRef:Et,effectiveReadOnly:Z,changeSelection:qt,canMergeSelection:k,clipboardDocumentId:Kn,clipboardScope:i??Kn}),{zoomToBounds:ar,zoomToShapes:or,zoomToSelection:sr,zoomAtCenter:cr}=Hn({engineRef:G,doc:q,selRef:Et,zoomAnimationDuration:M,zoomBound:j,ready:Pe});(0,r.useImperativeHandle)(le,()=>({previewRegionMask:e=>{let t=Ct.current;if(!t)return;let n=e?lt(e,t.w,t.h):xt.current;G.current?.setRegionOverlay(lr.current.showRegionMask?n:null)},undo:()=>{bn()||q.undo()},redo:()=>{xn()||q.redo()},canUndo:()=>Sn()||q.canUndo(),canRedo:()=>Cn()||q.canRedo(),undoSession:bn,redoSession:xn,canUndoSession:Sn,canRedoSession:Cn,hasDraftSession:wn,cancelDraftSession:yn,commitDraftSession:En,setSelection:qt,createShapes:e=>{e.length&&(q.create(e),qt(e.map(e=>e.id)))},updateShapes:q.update,deleteShapes:q.remove,getShapes:q.getShapes,selectAll:qn,clearSelection:Jn,deleteSelection:Yn,copySelection:Xn,paste:Qn,duplicate:$n,bringToFront:er,sendToBack:tr,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:sr,zoomToShapes:or,zoomToBounds:ar,brush:{setScalarMode:Dn,getScalarMode:On,hasSession:kn,commit:An,cancel:jn,beginEditFromSelection:Mn}}),[q,qt,bn,xn,En,yn,An,jn,qn,Jn,Yn,Xn,Qn,$n,er,tr,sr,or,ar,Dn,On,kn,Mn]);let lr=(0,r.useRef)(Y);lr.current=Y;let ur=(0,r.useCallback)(()=>_t({engineRef:G,toolRef:Dt,externalToolMapRef:ot,spaceRef:Lt,shiftRef:Rt,docRef:Q,selRef:Et,draftRef:Ot,readOnlyRef:Mt,disableMarqueeRef:Nt,lockedRef:Pt,onLockedInteraction:()=>Ft.current?.(),createRef:gn,selectRef:Jt,enterEditRef:Qt,editingIdRef:en,drawSessionRef:vn,assistantRef:Bn,setCursorHint:Gt,setInteractionMode:Wt,syncMinimap:an,onTransformPreview:pn,onDrawPreview:mn}),[Gt,Wt,an,pn,mn]),dr=(0,r.useRef)([]);Nn({backend:ue,hostRef:Se,engineRef:G,documentId:Ge,renderedImageUrl:Qe,makeCallbacks:ur,viewRef:lr,readOnlyRef:Mt,toolRef:Dt,renderShapesRef:dr,coordinateSizeRef:wt,imageSizeRef:Tt,selRef:Et,maskCanvasRef:bt,regionOverlayRef:xt,dimmedRef:St,syncMinimap:an,setImage:je,setImageVisible:Ne,setReady:Fe,setImageStatus:tt,onContextMenuRequest:Re});let fr=(0,r.useMemo)(()=>{let e=x?q.shapes.map(e=>{let t=x(e);return t?{...e,interaction:{...e.interaction,...t}}:e}):q.shapes;return N?.length?[...N.map(e=>({...e,interaction:{...e.interaction,selectable:!1,draggable:!1,editable:!1,hitTestDisabled:!0}})),...e]:e},[q.shapes,x,N]);dr.current=fr,(0,r.useEffect)(()=>{G.current?.setShapes(fr,Et.current),an()},[fr,an]),(0,r.useEffect)(()=>{G.current?.setSelection(J)},[J]),(0,r.useEffect)(()=>{G.current?.setEditing(Yt)},[Yt,Pe]);let pr=(0,r.useRef)(pe);pr.current=pe,(0,r.useEffect)(()=>{pr.current?.(Yt)},[Yt]),(0,r.useEffect)(()=>{Xt(null)},[f]),(0,r.useEffect)(()=>{Yt&&(J.length!==1||J[0]!==Yt)&&Xt(null)},[J,Yt]),(0,r.useEffect)(()=>{let e=G.current;e&&(e.setFilter(Y.brightness,Y.contrast),e.setRenderDefaults({strokeWidth:Y.strokeSize}),e.setImageSmoothing(Y.imageSmoothing),an())},[Y.brightness,Y.contrast,Y.strokeSize,Y.imageSmoothing,an]),(0,r.useLayoutEffect)(()=>{Pe&&G.current?.setOverlays(Y.showGuide?ht:null,Y.showRegionMask?yt:null,c)},[Pe,ht,yt,Y.showGuide,Y.showRegionMask,c]),(0,r.useEffect)(()=>{!Pe||!K||an()},[Pe,K,gt,Y.showGuide,Y.showRegionMask,P,an]),(0,r.useEffect)(()=>{Pe&&G.current?.setTransformEnabled(!Z&&f!==B.BRUSH)},[Z,Pe,f]),(0,r.useEffect)(()=>{Fn(f,ot.current.has(f))},[f,Fn]);let mr=$.finalize;(0,r.useEffect)(()=>{mr()},[f,mr]),(0,r.useEffect)(()=>{zt.current=`idle`,Vt.current=null,Ht()},[f,ue,Ht]),(0,r.useEffect)(()=>{In(J,Z)},[J,f,Z,In]),(0,r.useEffect)(()=>{Pe&&Ht()},[f,ze,at,Pe,Ht]);let hr=(0,r.useRef)(Ze);hr.current=Ze;let gr=t!==null,_r=(0,r.useRef)(null);(0,r.useEffect)(()=>{let e=gr?Ge:null;_r.current!==e&&(_r.current=e,Re(null),Xt(null),zt.current=`idle`,Vt.current=null,q.reset(gr?Ye??[]:[]),qt(gr?hr.current??[]:[]),yn(),mr(),Ht())},[gr,Ge,Ye,q.reset,qt,yn,mr,Ht]);let vr=(0,r.useCallback)(()=>{let e=en.current;if(!e||Z)return!1;let t=G.current,n=new Set(t?.getVertexSelection()??[]);if(!n.size)return!1;let r=Q.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:(Q.current.update([{...r,points:i}]),t?.setVertexSelection([]),!0)},[Z]);$t({keymap:ce,hostRef:Se,actions:{undo:()=>{Z||bn()||q.undo()},redo:()=>{Z||xn()||q.redo()},selectAll:qn,copy:Xn,cut:()=>{Xn(),Yn()},paste:Qn,duplicate:$n,delete:()=>{Tn()&&Pn()||vr()||Yn()},cancel:()=>{let e=ot.current.get(Dt.current);if(!(e?.onCancel&&e.onCancel()!==!1)){if($.isActive()){$.cancel();return}if(wn()){yn();return}if(Yt){Xt(null);return}if(Et.current.length){Jn();return}b?.()}},commitDraft:()=>{if($.isActive()){$.finalize();return}if(wn()){En();return}if(Z)return;if(Yt){Xt(null);return}let e=Et.current;if(e.length!==1)return;let t=Q.current.getShapes().find(t=>t.id===e[0]);t&&(t.type===o.POLYGON||t.type===o.LINE)&&t.interaction?.editable!==!1&&!t.readOnly&&Xt(e[0])},bringToFront:er,sendToBack:tr,zoomIn:()=>cr(1.2),zoomOut:()=>cr(1/1.2),zoom100:()=>G.current?.zoom100(),zoomFit:()=>G.current?.fit(),toggleMinimap:()=>He(e=>!e),toggleCursorGuide:()=>dt(e=>({...e,showCursorGuide:!e.showCursorGuide})),togglePixelation:()=>dt(e=>({...e,imageSmoothing:!e.imageSmoothing})),selectTool:()=>de?.(B.SELECT),rectangleTool:()=>de?.(B.RECTANGLE),rotatedRectangleTool:()=>de?.(B.ROTATED_RECTANGLE),circleTool:()=>de?.(B.CIRCLE),polygonTool:()=>de?.(B.POLYGON),pathTool:()=>de?.(B.PATH),brushTool:()=>de?.(B.BRUSH),pointTool:()=>de?.(B.POINT)},spaceRef:Lt,shiftRef:Rt,onSpaceDown:()=>{G.current?.setPanMode(!0),Ht()},onSpaceUp:()=>{G.current?.setPanMode(!1),zt.current===`panning`?Wt(`idle`):Ht()},nudge:nr});let yr=(0,r.useMemo)(()=>fr.filter(e=>J.includes(e.id)&&s(e)),[fr,J]),br=(0,r.useMemo)(()=>un?[...yr,un]:yr,[yr,un]),xr=J.length>0,Sr=q.shapes.some(e=>J.includes(e.id)&&u(e)),Cr=!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})(),wr=rr(),Tr=Z||wr.length<2||(k?!k(wr):!1),Er=!!se&&!Z,Dr=Er&&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,Or=[{id:`copy`,label:X.contextMenu.copy,shortcut:`⌘C`,disabled:!Sr,onClick:Xn},{id:`paste`,label:X.contextMenu.paste,shortcut:`⌘V`,disabled:Z||!Zn(),onClick:()=>Qn(Ie?.img)},{id:`duplicate`,label:X.contextMenu.duplicate,shortcut:`⌘D`,disabled:!Sr||Z,onClick:$n},{id:`delete`,label:X.contextMenu.delete,shortcut:`Del`,danger:!0,disabled:!Sr||Z,onClick:Yn},{separator:!0},{id:`editVertices`,label:X.contextMenu.editVertices,shortcut:`Enter`,disabled:!Cr,onClick:()=>Xt(J[0])},{id:`merge`,label:X.contextMenu.merge,disabled:Tr,onClick:ir},...Er?[{id:`assistExpand`,label:X.contextMenu.assistExpand,icon:(0,n.jsx)(e.er,{size:14}),disabled:!Dr,onClick:()=>{Ie&&Dr&&$.refineShape(Dr,Ie.img,!0)}},{id:`assistExclude`,label:X.contextMenu.assistExclude,icon:(0,n.jsx)(e.er,{size:14}),disabled:!Dr,onClick:()=>{Ie&&Dr&&$.refineShape(Dr,Ie.img,!1)}}]:[],{id:`bringToFront`,label:X.contextMenu.bringToFront,disabled:!Sr||Z,onClick:er},{id:`sendToBack`,label:X.contextMenu.sendToBack,disabled:!Sr||Z,onClick:tr},{separator:!0},{id:`undo`,label:X.contextMenu.undo,shortcut:`⌘Z`,disabled:Z||!Sn()&&!q.canUndo(),onClick:()=>{bn()||q.undo()}},{id:`redo`,label:X.contextMenu.redo,shortcut:`⇧⌘Z`,disabled:Z||!Cn()&&!q.canRedo(),onClick:()=>{xn()||q.redo()}},{separator:!0},{id:`selectAll`,label:X.contextMenu.selectAll,shortcut:`⌘A`,onClick:qn},{id:`clearSelection`,label:X.contextMenu.clearSelection,disabled:!xr,onClick:Jn},{id:`zoomToSelection`,label:X.contextMenu.zoomToSelection,disabled:!xr,onClick:sr}],kr=g?Or.filter(e=>`separator`in e||!!e.id&&Wn.has(e.id)):Or,Ar=D?D(kr,{selectedIds:J,readOnly:Z}):kr,jr=Rn({engineRef:G,image:K,wheelZoom:Y.wheelZoom,minimapSize:204}),Mr=(0,r.useCallback)(()=>{G.current?.zoom100()},[]),Nr=(0,r.useCallback)(()=>{He(e=>!e)},[]),Pr=(0,r.useCallback)(()=>{We(e=>!e)},[]),Fr=(0,r.useCallback)(()=>{We(!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:Se,className:`aivex:h-full aivex:w-full`,style:{opacity:+!!Me,transition:Me?`opacity 0.3s ease`:`none`}}),et!==`ready`&&(0,n.jsx)(oe,{status:et,render:a,loadingLabel:X.imageLoading,errorLabel:X.imageLoadError}),Pe&&K&&(0,n.jsx)(`div`,{className:`aivex:pointer-events-none aivex:absolute aivex:inset-0 aivex:overflow-hidden`,children:(0,n.jsxs)(`div`,{ref:De,style:{position:`absolute`,top:0,left:0,width:K.w,height:K.h,transformOrigin:`0 0`},children:[!!L?.length&&R&&(0,n.jsx)(`div`,{style:{position:`absolute`,left:0,top:0,width:K.w,height:K.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,onPointerDown:e=>e.stopPropagation(),onClick:t=>{t.stopPropagation(),e.disabled||z?.(e)},onKeyDown:t=>{e.disabled||t.key!==`Enter`&&t.key!==` `||(t.preventDefault(),t.stopPropagation(),z?.(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:R(e)},e.id))}),ne?.({image:K,viewport:G.current?.viewport??{scale:1,x:0,y:0}}),br.length>0&&(0,n.jsx)(Oe,{shapes:br,getLabel:re,hideDot:V,formatInfo:H,register:cn}),se&&($.status===`loading`||$.boxes.length>0)&&(0,n.jsx)(U,{image:K,points:$.points,boxes:$.boxes,status:$.status})]})}),Pe&&Y.showCursorGuide&&(0,n.jsx)(W,{color:`#1e88e5`}),K&&T&&(0,n.jsx)(ye,{image:K,imageUrl:Qe,imageVisible:Me,loading:!Pe,maskDataUrl:gt,region:yt,roiMaskId:Ae,shapes:fr,view:Y,viewDefaults:ct,onChangeView:ft,nav:jr,registerShape:nn,rectRef:Ce,zoomLabelRef:ke,onZoom100:Mr,open:Ve,onToggleOpen:Nr,labels:X.minimap,settingsLabels:X.viewSettings,showSettings:E,settingsOpen:Ue,onToggleSettings:Pr,onCloseSettings:Fr}),Ie&&(0,n.jsx)(ae,{x:Ie.x,y:Ie.y,items:Ar,onClose:()=>Re(null)})]})}async function qn(e){let t=await en(e);return await new Promise((n,r)=>{let i=new Image;t||(i.crossOrigin=`anonymous`),i.onload=()=>n({image:i,revoke:t?()=>URL.revokeObjectURL(t):null}),i.onerror=()=>{t&&URL.revokeObjectURL(t),r(Error(`Failed to load image`))},i.src=t??e})}function Jn(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 Yn(e,t,n,r){if(t.interaction?.visible===!1)return;let i=fe(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 Jn(e,t.points,t.type!==o.LINE);i.fillVisible&&(e.save(),e.fillStyle=i.color,e.globalAlpha*=i.fillAlpha,e.fill(),e.restore()),t.style?.alternateColor&&i.dash?.length&&(e.setLineDash([]),e.strokeStyle=t.style.alternateColor,e.stroke()),e.setLineDash((i.dash??[]).map(e=>e/n)),e.strokeStyle=i.color,e.stroke(),e.restore()}function Xn({imageUrl:e,alt:t=`Shape preview`,coordinateSize:i,shapes:a=[],regionMask:o,guideMask:s,maskPalette:c,focusedShapeId:l,focusFit:u=`contain`,zoomPadding:d=.3,strokeSize:p=1,brightness:m=1,contrast:g=1,imageSmoothing:_=!0,lazy:v=!0,className:y,style:b,renderImageState:x}){let S=(0,r.useRef)(null),C=(0,r.useRef)(null),w=(0,r.useRef)(null),[T,E]=(0,r.useState)(!v),[D,O]=(0,r.useState)(`loading`),[k,A]=(0,r.useState)(0);(0,r.useEffect)(()=>{if(!v||T)return;let e=S.current;if(!e)return;let t=new IntersectionObserver(([e])=>{e.isIntersecting&&(E(!0),t.disconnect())});return t.observe(e),()=>t.disconnect()},[v,T]),(0,r.useEffect)(()=>{let e=S.current;if(!e)return;let t=new ResizeObserver(()=>A(e=>e+1));return t.observe(e),()=>t.disconnect()},[]),(0,r.useEffect)(()=>{if(!T||!e){O(e?`loading`:`error`);return}let t=!0;return O(`loading`),qn(e).then(e=>{if(!t){e.revoke?.();return}w.current?.revoke?.(),w.current=e,O(`ready`)}).catch(()=>{t&&(w.current?.revoke?.(),w.current=null,O(`error`))}),()=>{t=!1}},[e,T]),(0,r.useEffect)(()=>()=>{w.current?.revoke?.(),w.current=null},[]);let j=(0,r.useMemo)(()=>a.find(e=>e.id===l),[l,a]),M=(0,r.useMemo)(()=>s&&c?$e(s,c):null,[s,c]);return(0,r.useEffect)(()=>{if(D===`error`){let e=C.current;e?.getContext(`2d`)?.clearRect(0,0,e.width,e.height)}if(D!==`ready`)return;let e=S.current,t=C.current,n=w.current;if(!e||!t||!n)return;let{width:r,height:s}=e.getBoundingClientRect();if(!r||!s)return;let c=window.devicePixelRatio||1;t.width=Math.max(1,Math.round(r*c)),t.height=Math.max(1,Math.round(s*c)),t.style.width=`${r}px`,t.style.height=`${s}px`;let l=t.getContext(`2d`);if(!l)return;let v=i?.width??n.image.naturalWidth,y=i?.height??n.image.naturalHeight;if(!v||!y)return;let b=Math.min(r/v,s/y),x=(r-v*b)/2,T=(s-y*b)/2;if(j&&j.points.length>0){let e=h(j.points),t=Math.max(e.maxX-e.minX,50),n=Math.max(e.maxY-e.minY,50),i=Math.min(t,n)*d;b=Math.min(r/(t+i*2),s/(n+i*2)),u===`cover`&&(b=Math.max(b,Math.max(r/v,s/y))),x=r/2-(e.minX+e.maxX)/2*b,T=s/2-(e.minY+e.maxY)/2*b,u===`cover`&&(x=Math.min(0,Math.max(x,r-v*b)),T=Math.min(0,Math.max(T,s-y*b)))}l.setTransform(c,0,0,c,0,0),l.clearRect(0,0,r,s),l.save(),l.translate(x,T),l.scale(b,b),l.imageSmoothingEnabled=_,l.filter=`brightness(${m}) contrast(${g})`,l.drawImage(n.image,0,0,v,y),l.filter=`none`,M&&(l.save(),l.globalAlpha=.55,l.drawImage(M,0,0,v,y),l.restore());let E=o?lt(o,v,y):null;if(E&&(it(l,E,v,y),E.outlineStyles)){let e=(e,t)=>{if(l.lineWidth=t.width/b,t.underlayColor){l.setLineDash([]),l.strokeStyle=t.underlayColor;for(let[t,n]of e)Jn(l,[t,n],!1),l.stroke()}l.save(),l.globalAlpha*=t.opacity,l.setLineDash(t.dash.map(e=>e/b)),l.strokeStyle=t.color;for(let[t,n]of e)Jn(l,[t,n],!1),l.stroke();l.restore()};e(E.visibleOutline,E.outlineStyles.visible),e(E.occludedOutline,E.outlineStyles.occluded)}for(let e of f(a))Yn(l,e,b,p);l.restore()},[m,g,i,j,u,_,M,o,a,k,D,p,d]),(0,n.jsxs)(`div`,{ref:S,className:y,style:{position:`relative`,width:`100%`,height:`100%`,...b},children:[(0,n.jsx)(`canvas`,{ref:C,role:`img`,"aria-label":t,style:{display:`block`}}),D!==`ready`&&x&&(0,n.jsx)(`div`,{style:{position:`absolute`,inset:0},children:x(D===`error`?`error`:`loading`)})]})}exports.DEFAULT_EDITOR_STRINGS=z,exports.DEFAULT_VIEW_SETTINGS=te,exports.SHAPE_TYPE=o,exports.ShapeEditor=Kn,exports.default=Kn,exports.ShapeViewer=Xn,exports.TOOL=B,exports.generateId=p;
|
|
1
|
+
"use client";require(`./styles.css`),Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require(`./Button-OQscp8mY.cjs`),t=require(`./Switch-DP8FRLJK.cjs`);let n=require(`react/jsx-runtime`),r=require(`react`),i=require(`konva`);i=e.pa(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(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`id_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}var m=[`tl`,`t`,`tr`,`r`,`br`,`b`,`bl`,`l`];function h(e){let t=e.map(e=>e.x),n=e.map(e=>e.y);return{minX:Math.min(...t),minY:Math.min(...n),maxX:Math.max(...t),maxY:Math.max(...n)}}function g(e,t){let n=(t.minX+t.maxX)/2,r=(t.minY+t.maxY)/2;return{x:e.includes(`l`)?t.minX:e.includes(`r`)?t.maxX:n,y:e.includes(`t`)?t.minY:e.includes(`b`)?t.maxY:r}}function _(e,t,n,r){let i={...t};return e.includes(`l`)&&(i.minX=n),e.includes(`r`)&&(i.maxX=n),e.includes(`t`)&&(i.minY=r),e.includes(`b`)&&(i.maxY=r),i}function v(e,t){let n=t.x-e.x,r=t.y-e.y,i=Math.max(Math.abs(n),Math.abs(r));return{x:e.x+(n<0?-i:i),y:e.y+(r<0?-i:i)}}function y(e,t,n){let r=Math.cos(n),i=Math.sin(n),a=e.x-t.x,o=e.y-t.y;return{x:t.x+a*r-o*i,y:t.y+a*i+o*r}}function b(e){let t=h(e);return[{x:t.minX,y:t.minY},{x:t.maxX,y:t.minY},{x:t.maxX,y:t.maxY},{x:t.minX,y:t.maxY}]}function x(e,t,n=32){let r=(e.x+t.x)/2,i=(e.y+t.y)/2,a=Math.abs(t.x-e.x)/2,o=Math.abs(t.y-e.y)/2;return Array.from({length:n},(e,t)=>{let s=t/n*2*Math.PI;return{x:r+a*Math.cos(s),y:i+o*Math.sin(s)}})}function S(e){let t=[...e].sort((e,t)=>e.x-t.x||e.y-t.y);if(t.length<=2)return t;let n=(e,t,n)=>(t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x),r=[];for(let e of t){for(;r.length>=2&&n(r[r.length-2],r[r.length-1],e)<=0;)r.pop();r.push(e)}let i=[];for(let e=t.length-1;e>=0;e--){let r=t[e];for(;i.length>=2&&n(i[i.length-2],i[i.length-1],r)<=0;)i.pop();i.push(r)}return r.pop(),i.pop(),r.concat(i)}function C(e){let t=S(e);if(t.length<3)return b(e);let n=1/0,r=b(e);for(let e=0;e<t.length;e++){let i=t[e],a=t[(e+1)%t.length],o=Math.hypot(a.x-i.x,a.y-i.y)||1,s=(a.x-i.x)/o,c=(a.y-i.y)/o,l=1/0,u=-1/0,d=1/0,f=-1/0;for(let e of t){let t=e.x*s+e.y*c,n=-e.x*c+e.y*s;t<l&&(l=t),t>u&&(u=t),n<d&&(d=n),n>f&&(f=n)}let p=(u-l)*(f-d);if(p<n){n=p;let e=(e,t)=>({x:e*s-t*c,y:e*c+t*s});r=[e(l,d),e(u,d),e(u,f),e(l,f)]}}return r}var w=(e,t)=>({x:e.x-t.x,y:e.y-t.y}),T=(e,t)=>e.x*t.x+e.y*t.y,E=e=>Math.hypot(e.x,e.y),D=e=>{let t=E(e)||1;return{x:e.x/t,y:e.y/t}},O=(e,t)=>({x:(e.x+t.x)/2,y:(e.y+t.y)/2}),k=e=>{let t=e.reduce((e,t)=>({x:e.x+t.x,y:e.y+t.y}),{x:0,y:0});return{x:t.x/e.length,y:t.y/e.length}};function A(e){return[e[0],O(e[0],e[1]),e[1],O(e[1],e[2]),e[2],O(e[2],e[3]),e[3],O(e[3],e[0])]}function j(e,t){let n=O(e[0],e[1]),r=D(w(e[0],e[3]));return{x:n.x+r.x*t,y:n.y+r.y*t}}function M(e,t,n,r){let i=(e,i)=>({x:t.x+e*n.x+i*r.x,y:t.y+e*n.y+i*r.y});return[i(e.minX,e.minY),i(e.maxX,e.minY),i(e.maxX,e.maxY),i(e.minX,e.maxY)]}function N(e,t,n){if(e.length<4)return e;let r=e[0],i=D(w(e[1],e[0])),a=D(w(e[3],e[0])),o=T(w(e[1],r),i),s=T(w(e[3],r),a),c=w(n,r);return M(_(t,{minX:0,minY:0,maxX:o,maxY:s},T(c,i),T(c,a)),r,i,a)}function P(e,t,n){let r=t.maxX-t.minX||1,i=t.maxY-t.minY||1,a=n.maxX-n.minX,o=n.maxY-n.minY;return e.map(e=>({x:n.minX+(e.x-t.minX)/r*a,y:n.minY+(e.y-t.minY)/i*o}))}function F(e,t,n,r){let i=(e,t,n)=>Math.sign((t.x-e.x)*(n.y-e.y)-(t.y-e.y)*(n.x-e.x)),a=i(e,t,n),o=i(e,t,r),s=i(n,r,e),c=i(n,r,t);return a!==o&&s!==c&&!(a===0&&o===0)}function I(e,t=256){let n=e.length;if(n<4||n>t)return!1;for(let t=0;t<n;t++){let r=e[t],i=e[(t+1)%n];for(let a=t+2;a<n;a++)if(!(t===0&&a===n-1)&&F(r,i,e[a],e[(a+1)%n]))return!0}return!1}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}}function R(e,t=256){let n=e.length;if(n<4||n>t||!I(e,t))return[e];let r=Array.from({length:n},()=>[]),i=0;for(let t=0;t<n;t++){let a=e[t],o=e[(t+1)%n];for(let s=t+2;s<n;s++){if(t===0&&s===n-1)continue;let c=L(a,o,e[s],e[(s+1)%n]);c&&(r[t].push({t:c.ti,id:i}),r[s].push({t:c.tj,id:i}),i++)}}if(!i)return[e];let a=[];for(let t=0;t<n;t++){let i=e[t],o=e[(t+1)%n];a.push({p:i,inter:-1});for(let e of r[t].sort((e,t)=>e.t-t.t))a.push({p:{x:i.x+(o.x-i.x)*e.t,y:i.y+(o.y-i.y)*e.t},inter:e.id})}let o=a.length,s=new Map;a.forEach((e,t)=>{if(e.inter>=0){let n=s.get(e.inter)??[];n.push(t),s.set(e.inter,n)}});let c=Array(o).fill(!1),l=[];for(let e=0;e<o;e++){if(c[e]||a[e].inter>=0)continue;let t=[],n=e,r=0;for(;r++<=o;){c[n]=!0,t.push(a[n].p);let i=(n+1)%o;for(;a[i].inter>=0&&!c[i]&&r++<=o;){t.push(a[i].p),c[i]=!0;let e=s.get(a[i].inter),n=e&&(e[0]===i?e[1]:e[0]);if(n===void 0)break;i=(n+1)%o}if(i===e||c[i])break;n=i}t.length>=3&&l.push(t)}return l.length?l:[e]}var z={contextMenu:{copy:`복사`,paste:`붙여넣기`,duplicate:`복제`,delete:`삭제`,bringToFront:`맨 앞으로`,sendToBack:`맨 뒤로`,editVertices:`정점 편집`,merge:`레이블 합치기`,assistExpand:`이 지점 포함하기`,assistExclude:`이 지점 제외하기`,undo:`실행 취소`,redo:`다시 실행`,zoomToSelection:`선택 영역으로 확대`,selectAll:`전체 선택`,clearSelection:`선택 해제`},viewSettings:{title:`보기 설정`,reset:`초기화`,brightness:`밝기`,contrast:`대비`,strokeSize:`선 굵기`,simplifyStrength:`단순화 강도`,pixelation:`이미지 픽셀화`,cursorGuide:`마우스 가이드라인 표시`,guideMask:`가이드 마스크`,regionMask:`ROI 표시`,keepZoomOnImageChange:`이미지 변경시 확대 유지`,wheelZoom:`스크롤만 사용하여 확대 축소`,zoomSensitivity:`확대 축소 민감도`},minimap:{zoomIn:`확대`,zoomOut:`축소`,zoom100:`100%로 초기화`,viewSettings:`보기 설정`,toggleMinimap:`미니맵 접기/펼치기`},imageLoading:`이미지를 불러오는 중…`,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 ee(e){return e?{contextMenu:{...z.contextMenu,...e.contextMenu},viewSettings:{...z.viewSettings,...e.viewSettings},minimap:{...z.minimap,...e.minimap},imageLoading:e.imageLoading??z.imageLoading,imageLoadError:e.imageLoadError??z.imageLoadError,imageErrorHints:{...z.imageErrorHints,...e.imageErrorHints}}:z}var B={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`},V={brightness:1,contrast:1,showCursorGuide:!1,imageSmoothing:!0,strokeSize:2,simplifyStrength:1.5,showGuide:!0,showRegionMask:!0,keepZoomOnImageChange:!1,wheelZoom:!0,zoomSensitivity:1},te=`var(--editor-overlay-inverse-scale, 1)`,ne=`#377be2`,H=`#e23c3c`;function re({point:e}){let t=e.positive?ne:H;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(${te})`,transformOrigin:`center`},children:e.positive?`+`:`−`})}function U({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)(re,{point:e},`pt-${t}-${e.x}-${e.y}`))]})}function ie(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 ae({x:e,y:r,items:i,onClose:a}){let o=ie(i);return(0,n.jsxs)(t.a,{open:!0,modal:!1,onOpenChange:e=>{e||a()},children:[(0,n.jsx)(t.a.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.a.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.a.Separator,{className:`aivex:shrink-0`},`sep-${r}`):(0,n.jsx)(t.a.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.a.Shortcut,{children:e.shortcut})]})},e.label))})]})}function W({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 oe({status:e,error:t,render:r,loadingLabel:i=z.imageLoading,errorLabel:a=z.imageLoadError,errorHints:o=z.imageErrorHints}){let s=r?.(e,t)??null;return(0,n.jsx)(`div`,{"data-track-id":e===`loading`?`editor-image-loading-wrap`:`editor-image-error-wrap`,style:{position:`absolute`,inset:0,display:`flex`,alignItems:`center`,justifyContent:`center`,background:e===`error`?`rgba(13,13,18,1)`:`rgba(13,13,18,0.6)`,backdropFilter:e===`loading`?`blur(2px)`:void 0,color:`#fff`,fontFamily:`Pretendard, sans-serif`,pointerEvents:e===`error`?`auto`:`none`},children:s===null?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:a}),t&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(`div`,{style:{fontSize:12,marginTop:8,opacity:.8,lineHeight:1.5},children:o[t.kind]}),(0,n.jsx)(`div`,{style:{fontSize:11,marginTop:6,opacity:.55,fontFamily:`ui-monospace, monospace`,wordBreak:`break-all`},children:t.detail})]})]}):s})}Math.PI/12;var se=`#00ff00`,ce=`rgba(0, 255, 0, 0.1)`,le=`#669DEF`,ue=.1,de=[3,3];function G(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*de[0],r*de[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 fe(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 pe=(0,r.memo)(function({shape:e,strokeSize:t,register:r}){let{type:i,points:a}=e,s=G(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=h(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,...l})});function me({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`})]})}function he({value:i,defaults:a,onChange:o,onClose:s,labels:c=z.viewSettings,openDown:l=!1,alignEnd:u=!1}){return(0,r.useEffect)(()=>{let e=e=>{e.key===`Escape`&&s()},t=()=>s();return window.addEventListener(`keydown`,e),window.addEventListener(`pointerdown`,t),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`pointerdown`,t)}},[s]),(0,n.jsxs)(`div`,{className:`aivex:absolute ${l?`aivex:top-full aivex:mt-md`:`aivex:bottom-full aivex:mb-md`} ${u?`aivex:right-0`:`aivex:left-0`} aivex:flex aivex:w-[277px] aivex:flex-col aivex:gap-lg aivex:rounded-xl aivex:border aivex:border-border-subtle aivex:bg-bg-primary aivex:p-xl aivex:text-text-primary aivex:shadow-[var(--aivex-elevation-md)]`,onPointerDown:e=>e.stopPropagation(),children:[(0,n.jsx)(`div`,{className:`aivex:px-xs aivex:text-body-md`,children:c.title}),(0,n.jsxs)(`div`,{className:`aivex:flex aivex:flex-col aivex:gap-md`,children:[(0,n.jsx)(ge,{icon:(0,n.jsx)(e.Q,{size:16}),label:c.brightness,value:i.brightness.toFixed(2),children:(0,n.jsx)(t.n,{min:0,max:3,step:.05,value:[i.brightness],onValueChange:([e])=>o({brightness:e})})}),(0,n.jsx)(ge,{icon:(0,n.jsx)(e.Dt,{size:16}),label:c.contrast,value:i.contrast.toFixed(2),children:(0,n.jsx)(t.n,{min:0,max:3,step:.05,value:[i.contrast],onValueChange:([e])=>o({contrast:e})})}),(0,n.jsx)(ge,{icon:(0,n.jsx)(e.Di,{size:16}),label:c.strokeSize,value:String(i.strokeSize),children:(0,n.jsx)(t.n,{min:1,max:10,step:.5,value:[i.strokeSize],onValueChange:([e])=>o({strokeSize:e})})}),(0,n.jsx)(ge,{icon:(0,n.jsx)(e.Ar,{size:16}),label:c.simplifyStrength,value:String(i.simplifyStrength),children:(0,n.jsx)(t.n,{min:.5,max:5,step:.5,value:[i.simplifyStrength],onValueChange:([e])=>o({simplifyStrength:e})})}),(0,n.jsx)(ge,{icon:(0,n.jsx)(e.oa,{size:16}),label:c.zoomSensitivity,value:i.zoomSensitivity.toFixed(1),children:(0,n.jsx)(t.n,{min:.2,max:3,step:.1,value:[i.zoomSensitivity],onValueChange:([e])=>o({zoomSensitivity:e})})}),(0,n.jsxs)(`div`,{className:`aivex:flex aivex:flex-col aivex:gap-xs`,children:[(0,n.jsx)(_e,{label:c.pixelation,checked:!i.imageSmoothing,onChange:e=>o({imageSmoothing:!e})}),(0,n.jsx)(_e,{label:c.cursorGuide,checked:i.showCursorGuide,onChange:e=>o({showCursorGuide:e})}),(0,n.jsx)(_e,{label:c.guideMask,checked:i.showGuide,onChange:e=>o({showGuide:e})}),(0,n.jsx)(_e,{label:c.regionMask,checked:i.showRegionMask,onChange:e=>o({showRegionMask:e})}),(0,n.jsx)(_e,{label:c.keepZoomOnImageChange,checked:i.keepZoomOnImageChange,onChange:e=>o({keepZoomOnImageChange:e})}),(0,n.jsx)(_e,{label:c.wheelZoom,checked:i.wheelZoom,onChange:e=>o({wheelZoom:e})})]}),(0,n.jsx)(t.r,{})]}),(0,n.jsx)(`div`,{className:`aivex:flex aivex:justify-end`,children:(0,n.jsxs)(e.t,{variant:`solid`,color:`secondary`,size:`md`,onClick:()=>o({...a}),children:[(0,n.jsx)(e.Xr,{size:20}),c.reset]})})]})}function ge({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 _e({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.t,{size:`md`,checked:r,onCheckedChange:i})]})}var ve={"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`},ye=(0,r.memo)(function({image:t,imageUrl:r,imageVisible:i=!0,loading:a=!1,maskDataUrl:o,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=z.minimap,settingsLabels:O}){let{offX:k,offY:A,dispW:j,dispH:M,zoomCentered:N}=h,P=S.startsWith(`top`),F={position:`absolute`,left:k,top:A,width:j,height:M},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 ${a?`aivex:cursor-default`:`aivex:cursor-grab aivex:active:cursor-grabbing`}`,onPointerDown:a?void 0:h.handleMinimapPointerDown,onPointerMove:a?void 0:h.handleMinimapPointerMove,onPointerUp:a?void 0:h.endMinimapDrag,onPointerCancel:a?void 0:h.endMinimapDrag,onWheel:a?void 0:h.handleMinimapWheel,"aria-busy":a,children:(0,n.jsxs)(`div`,{style:{position:`absolute`,inset:0,opacity:+!!i,transition:i?`opacity 0.3s ease`:`none`},children:[r&&(0,n.jsx)(`img`,{src:r,alt:``,crossOrigin:`anonymous`,draggable:!1,style:F}),o&&d.showGuide&&(0,n.jsx)(`img`,{src:o,alt:``,draggable:!1,style:{...F,opacity:.55,imageRendering:`pixelated`,pointerEvents:`none`}}),d.showRegionMask&&c&&c.rects.length>0&&(0,n.jsx)(me,{image:t,region:c,maskId:l,width:j,height:M,strokeWidth:1,strokeDasharray:`4 4`,style:{position:`absolute`,left:k,top:A,pointerEvents:`none`}}),(0,n.jsx)(`svg`,{viewBox:`0 0 ${t.w} ${t.h}`,width:j,height:M,style:{position:`absolute`,left:k,top:A,pointerEvents:`none`},"aria-hidden":!0,children:f(u).filter(s).map(e=>(0,n.jsx)(pe,{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:()=>N(1/1.2),disabled:a,children:(0,n.jsx)(e.ur,{size:20})}),(0,n.jsx)(e.t,{variant:`ghost`,size:`md`,"aria-label":D.zoom100,onClick:y,disabled:a,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:()=>N(1.2),disabled:a,children:(0,n.jsx)(e.Vr,{size:20})}),C&&(0,n.jsxs)(`div`,{className:`aivex:relative`,children:[(0,n.jsx)(e.t,{variant:`ghost`,size:`icon-md`,"aria-label":D.viewSettings,onClick:T,onPointerDown:e=>e.stopPropagation(),className:w?`aivex:text-text-brand`:void 0,children:(0,n.jsx)(e.ui,{size:20})}),w&&(0,n.jsx)(he,{value:d,defaults:p,onChange:m,onClose:E,labels:O,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.nr,{size:20})})]});return(0,n.jsxs)(`div`,{className:`aivex:absolute ${ve[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]})}),be=`var(--editor-overlay-inverse-scale, 1)`,xe=6,Se={fontFamily:`Pretendard, sans-serif`,fontSize:12,fontWeight:500,lineHeight:`16px`,color:`#fff`,textShadow:`0 0 4px #000, 0 0 4px #000`,whiteSpace:`nowrap`};function K(e){let t=h(e);return{x:t.minX,y:t.minY,width:t.maxX-t.minX,height:t.maxY-t.minY}}function Ce(e){return`translate3d(${e.width}px, ${e.height}px, 0) scale(${be}) translate(-100%, ${xe}px)`}function we(e,t){let n=K(t);e.style.transform=`translate3d(${n.x}px, ${n.y}px, 0)`;let r=e.querySelector(`[data-selinfo-dim]`);return r&&(r.style.transform=Ce(n)),r}function Te(e,t){return{shape:e,...K(t)}}function Ee(e){return`${Math.round(e.width)} x ${Math.round(e.height)} px`}function De({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 Oe({shapes:e,getLabel:t,hideDot:r,formatInfo:i,register:a}){return(0,n.jsx)(n.Fragment,{children:e.map(e=>{let s=K(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=Te(e,e.points),p=i?i(f):Ee(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(${be}) translateY(calc(-100% - ${xe}px))`,transformOrigin:`left top`,...Se},children:[!r&&(0,n.jsx)(De,{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:Ce(s),transformOrigin:`left top`,willChange:`transform`,...Se},children:p})]},e.id)})})}var ke=`AIVEX_SHAPE_EDITOR:`,Ae=1,q=new Set(Object.values(o)),je=null,Me=`unavailable`,Ne=0;function Pe(e){if(!e||typeof e!=`object`)return!1;let t=e;return Number.isFinite(t.x)&&Number.isFinite(t.y)}function Fe(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.type==`string`&&q.has(t.type)&&Array.isArray(t.points)&&t.points.length>0&&t.points.every(Pe)}function Ie(e,t,n){return{kind:`aivex-shape-editor`,version:Ae,scope:n,documentId:t,shapes:e}}function Le(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 Re(e){return`${ke}${JSON.stringify(e)}`}function ze(e){if(!e.startsWith(ke))return null;try{let t=JSON.parse(e.slice(19));return t.kind!==`aivex-shape-editor`||t.version!==Ae||!Array.isArray(t.shapes)||t.shapes.length===0||!t.shapes.every(Fe)||t.scope!==void 0&&typeof t.scope!=`string`||t.documentId!==void 0&&typeof t.documentId!=`string`?null:t}catch{return null}}function Be(e){je=e;let t=++Ne;if(typeof navigator>`u`||!navigator.clipboard?.writeText){Me=`unavailable`;return}let n;try{n=Re(e)}catch{Me=`unavailable`;return}Me=`pending`,navigator.clipboard.writeText(n).then(()=>{t===Ne&&(Me=`written`)},()=>{t===Ne&&(Me=`unavailable`)})}function Ve(e,t){return!!e&&e.scope===t}function He(e){return Ve(je,e)||typeof navigator<`u`&&typeof navigator.clipboard?.readText==`function`}async function Ue(e){let t=Ve(je,e)?je:null;if(t&&Me!==`written`)return t;if(typeof navigator<`u`&&navigator.clipboard?.readText)try{let t=ze(await navigator.clipboard.readText());return t?.scope===e?(je=t,t):null}catch{}return t}function We(e,t,n){return{offset:n*(t?e:e+1),nextPasteCount:e+1}}var Ge=new Set([B.RECTANGLE,B.ROTATED_RECTANGLE,B.CIRCLE,B.POLYGON,B.PATH,B.BRUSH,B.POINT,B.ASSISTANT_POLYGON,B.ASSISTANT_RECT,B.ASSISTANT_POINT]),Ke={tl:-135,t:-90,tr:-45,r:0,br:45,b:90,bl:135,l:180},qe=[`ew-resize`,`nwse-resize`,`ns-resize`,`nesw-resize`];function Je(e,t=0){let n=((Ke[e]+t*180/Math.PI)%180+180)%180;return qe[Math.round(n/45)%4]}function Ye({tool:e,externalToolCursor:t,isSpacePressed:n,isPolygonDrawing:r}){return n?`grab`:t||(e===B.SELECT?`default`:Ge.has(e)?r?`default`:`crosshair`:`default`)}function Xe({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===B.SELECT&&i?i:Ye({tool:e,externalToolCursor:t,isSpacePressed:n,isPolygonDrawing:a}))}var Ze=e=>Math.min(255,Math.max(0,e)),Qe=e=>{let t=e.replace(`#`,``).trim();if(![3,4,6,8].includes(t.length))return null;let n=e=>e.length===1?`${e}${e}`:e,r=t.length<=4,i=n(t.slice(0,r?1:2)),a=n(t.slice(r?1:2,r?2:4)),o=n(t.slice(r?2:4,r?3:6)),s=t.length===4?n(t.slice(3,4)):t.length===8?n(t.slice(6,8)):`ff`,c=e=>Number.parseInt(e,16),l=[c(i),c(a),c(o),c(s)];return l.some(e=>Number.isNaN(e))?null:l.map(Ze)},$e=(e,t)=>{let{width:n,height:r,indices:i,transparent:a}=e;if(!n||!r||i.length<n*r)return null;let o={};for(let[e,n]of Object.entries(t)){let t=Qe(n);t&&(o[Number(e)]=t)}if(!Object.keys(o).length)return null;let s=document.createElement(`canvas`);s.width=n,s.height=r;let c=s.getContext(`2d`);if(!c)return null;let l=new Uint8ClampedArray(n*r*4),u=n*r;for(let e=0;e<u;e+=1){let t=i[e];if(t===a)continue;let n=o[t];if(!n)continue;let r=e*4;l[r]=n[0],l[r+1]=n[1],l[r+2]=n[2],l[r+3]=n[3]}return c.putImageData(new ImageData(l,n,r),0,0),s};function et(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 tt=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 nt(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 rt(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 it(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(...rt(s,c,e));if(n)for(let e of n)l.push(...rt(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=nt(m,o)?m:h,_=g===m?h:m;t.some(e=>e!==o&&nt(_,e))||n&&!n.some(e=>nt(g,e))||i.push([a(s,c,r),a(s,c,u)])}}return i}function J(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 at(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)et(e,n.points),e.fill()}e.restore()}function ot(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 Y={color:`#000000`,opacity:.5},st={color:`#ffffff`,opacity:1,width:2,dash:[6,6],underlayColor:`#000000`},ct={color:`#dc2626`,opacity:.8,width:2,dash:[6,6],underlayColor:`#000000`},lt=(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=J(a),s={...Y,...e.dim},c=e.outline;if(c===!1)return{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:[],occludedOutline:[],outlineStyles:null};let l={visible:{...st,...c?.visibleStyle},occluded:{...ct,...c?.occludedStyle}},u=i.map(tt),d=a.map(tt),f=r.map(e=>e.points);return c?.mode===`separate`?{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:ot(u),occludedOutline:ot(f),outlineStyles:l}:{rects:a,zones:r,dimHoles:o,dim:s,visibleOutline:[...it(u,[...u,...f],null),...it(f,f,d)],occludedOutline:[],outlineStyles:l}},ut=.3,dt=.05;function ft(e){return 1-(1-e)**3}function pt(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 X(e,t){if(!t.length)return null;if(e===o.POINT){let e=t[0];return{x:e.x-8,y:e.y-8,width:16,height:16}}let n=h(t),r=Math.max(1,n.maxX-n.minX),i=Math.max(1,n.maxY-n.minY);return{x:n.minX,y:n.minY,width:r,height:i}}function mt(e){if(!e.length)return null;let t=e.map(e=>X(e.type,e.points)).filter(e=>e!==null);return t.length?pt(h(t.flatMap(e=>[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y+e.height}]))):null}function ht(e,t,n,r={}){let{containerRatio:i=ut,minScale:a=dt,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 Z(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(dt,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 gt(e,t,n,r=300){let i=Date.now(),a=0,o=()=>{let s=Date.now()-i,c=Math.min(s/r,1),l=ft(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 _t(e){let{engineRef:t,toolRef:n,externalToolMapRef:r,spaceRef:i,shiftRef:a,docRef:s,selRef:c,draftRef:u,readOnlyRef:p,disableMarqueeRef:m,lockedRef:g,onLockedInteraction:_,createRef:y,selectRef:S,enterEditRef:C,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,z=null,ee=``,V=null,te=null,ne=e=>e===B.RECTANGLE||e===B.ROTATED_RECTANGLE||e===B.CIRCLE,H=e=>e===B.ASSISTANT_POLYGON||e===B.ASSISTANT_RECT,re=e=>e===B.POLYGON,U=(e,t)=>{let n=!1;F&&!ne(t)&&!H(t)&&(F=null,e.clearPreview(),j(null),n=!0),(I===`path`&&t!==B.PATH||I===`scalar`&&t!==B.BRUSH)&&(I=null,n=!0),L&&!re(t)&&(L=null,n=!0),R&&t!==B.SELECT&&(R=null,z=null,e.clearMarquee(),n=!0),V&&t!==B.POINT&&(V=null,n=!0),n&&O(`idle`)},ie=()=>r.current.get(n.current),ae=(e,t,n,r)=>({point:t,targetId:r,event:n,readOnly:p.current,viewport:e.viewport});return{onCursorHint:D,onInteractionModeChange:O,onPointerDown:(e,r,m)=>{let v=t.current;if(!v)return;let y=n.current;if(V=null,U(v,y),m.button===1||i.current){O(`panning`),D(null),P={px:m.global.x,py:m.global.y};return}if(m.button===2&&!(y===B.ASSISTANT_POINT&&m.altKey)){if(r&&!c.current.includes(r)){let e=s.current.getShapes().find(e=>e.id===r);e&&l(e)&&S.current([r])}return}let b=ie();if(b){M().reset(),S.current([]),b.onPointerDown?.(ae(v,e,m,r));return}if(g.current){_();return}if(y===B.ASSISTANT_POINT){m.altKey?N().addPoint(e,m.button!==2):N().newPolygon(e);return}if(H(y)&&u.current){F=e,O(`drawing`);return}if(y===B.SELECT&&m.altKey){let t=f(s.current.getShapes()).filter(t=>{if(!l(t))return!1;let n=h(t.points);return e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY});if(t.length){let e=[...t].reverse(),n=[e[(e.findIndex(e=>c.current.includes(e.id))+1)%e.length].id];S.current(n);return}}if(r&&y===B.SELECT){let t=s.current.getShapes().find(e=>e.id===r);if(!t||!l(t))return;let n=typeof performance<`u`?performance.now():0,i=!!te&&te.id===r&&n-te.t<300;te={id:r,t:n};let u=(t.type===o.POLYGON||t.type===o.LINE)&&!p.current&&t.interaction?.editable!==!1&&!t.readOnly;if(i&&u){S.current([r]),C.current(r);return}let f=c.current;if(a.current){let e=new Set(f);e.has(r)?e.delete(r):e.add(r),f=[...e]}else f.includes(r)||(f=[r]);S.current(f),!p.current&&d(t)&&v.beginMove(e,f);return}if(ne(y)&&u.current){F=e,O(`drawing`);return}if(re(y)&&u.current){if(!M().getDraftPointsSnapshot().length&&c.current.length&&S.current([]),M().tryClosePolygon(e,12/v.viewport.scale))return;let t=M().hitDraftPoint(e);if(t>=0){if(m.altKey){M().removeDraftPoint(t);return}let n=M().selectDraftPointForDrag(t,m.shiftKey||m.ctrlKey||m.metaKey);if(!n)return;L={start:e,base:n.base,indices:n.indices,moved:!1},O(`vertexDragging`);return}M().appendPolygonPoint(e);return}if(y===B.PATH&&u.current){c.current.length&&S.current([]),I=`path`,O(`drawing`),M().beginStroke(e);return}if(y===B.BRUSH&&u.current&&!p.current){I=`scalar`,O(`drawing`),M().beginStroke(e);return}if(y===B.POINT&&u.current&&m.button===0){V={pointerId:m.pointerId,global:m.global,cancelled:!1};return}if(y===B.SELECT){if(z=w.current?a.current?v.getVertexSelection():[]:null,!a.current&&!p.current&&c.current.length>=2){let t=s.current.getShapes().filter(e=>c.current.includes(e.id)&&d(e));if(t.length){let n=h(t.flatMap(e=>e.points));if(e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY){v.beginMove(e,c.current);return}}}R=e,ee=``,O(`marquee`),D(null)}},onPointerMove:(e,r)=>{let i=t.current;if(!i)return;if(V&&V.pointerId===r.pointerId&&Math.hypot(r.global.x-V.global.x,r.global.y-V.global.y)>4&&(V.cancelled=!0),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 c=n.current;U(i,c);let l=ie();if(l){l.onPointerMove?.(ae(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&&(ne(c)||H(c))){let t=a.current?v(F,e):e;i.previewBox(c===B.CIRCLE?`ellipse`:`rect`,F,t,{...u.current,color:u.current?.color??`#00e5ff`}),ne(c)&&j({type:c===B.CIRCLE?o.ELLIPSE:o.RECTANGLE,points:[F,t]});return}if(I){M().appendStrokePoint(e,2/i.viewport.scale);return}if(re(c)&&M().hasDraftPoints()){M().setDraftCursor(e);return}if(R){if(m?.current)return;let t={minX:Math.min(R.x,e.x),minY:Math.min(R.y,e.y),maxX:Math.max(R.x,e.x),maxY:Math.max(R.y,e.y)};if(i.previewMarquee(R,e),z){let e=(s.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([...z,...e])].sort((e,t)=>e-t),r=n.join(`,`);r!==ee&&(ee=r,i.setVertexSelection(n));return}let n=i.shapesIntersecting(t),r=n.join(`,`);r!==ee&&(ee=r,S.current(n))}},onPointerUp:(e,r)=>{let i=t.current;if(!i)return;let s=V;if(V=null,P){P=null,O(`idle`);return}let l=n.current;if(U(i,l),L){M().commitDraftPointDrag(L.moved),L=null,O(`idle`);return}let d=ie();if(d){d.onPointerUp?.(ae(i,e,r));return}let f=s?Math.hypot(r.global.x-s.global.x,r.global.y-s.global.y):1/0;if(l===B.POINT&&u.current&&s&&!s.cancelled&&s.pointerId===r.pointerId&&r.insideCanvas&&f<=4){y.current(o.POINT,[e]);return}if(I){let e=I;I=null,O(`idle`),e===`path`?M().completeFreehandStroke():M().finishScalarStroke();return}if(F&&H(l)){let t=F;F=null,O(`idle`),i.clearPreview();let n={x:Math.min(t.x,e.x),y:Math.min(t.y,e.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)};n.width>2&&n.height>2&&N().beginBox(n,l===B.ASSISTANT_RECT?`rect`:`polygon`);return}if(F&&ne(l)){let t=a.current?v(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===B.ROTATED_RECTANGLE?y.current(o.ROTATED_RECTANGLE,b([n,t])):l===B.CIRCLE?y.current(o.POLYGON,x(n,t)):y.current(o.RECTANGLE,[n,t]));return}if(R){let t=Math.abs(e.x-R.x)>3||Math.abs(e.y-R.y)>3,n=z!==null;if(R=null,z=null,i.clearMarquee(),O(`idle`),n&&t)return;!t&&c.current.length&&S.current([])}},onViewportChange:k,onTransformPreview:A,onTransformCommit:e=>{let t=s.current.getShapes(),n=e.map(e=>{let n=t.find(t=>t.id===e.id);return n?{...n,points:e.points}:null}).filter(e=>!!e);n.length&&s.current.update(n)}}}function vt({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)([]),m=(0,r.useRef)([]),g=(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),w=(0,r.useCallback)(e=>{m.current=e(m.current),f(m.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:p(),type:o.ROTATED_RECTANGLE,points:C(e),style:r,meta:n};if(t===`rect`){let t=h(e);return{id:p(),type:o.RECTANGLE,points:[{x:t.minX,y:t.minY},{x:t.maxX,y:t.maxY}],style:r,meta:n}}return{id:p(),type:o.POLYGON,points:e,style:r,meta:n}})},[n,a]),D=(0,r.useCallback)(()=>{y.current++,g.current=[],_.current=[],b.current=null,x.current=null,u([]),T(`idle`)},[T]),O=(0,r.useCallback)(()=>{S.current++,w(()=>[]);let t=x.current;t?e.current.update([t]):_.current.length&&e.current.remove(_.current),D()},[e,D,w]),k=(0,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:g.current,base:b.current??void 0},n=++y.current;T(`loading`);let r=[];try{r=(await e(t)??[]).filter(e=>e.length>=3)}catch{r=[]}n===y.current&&(k(r),T(`ready`))},[a,k,T]),j=(0,r.useCallback)((e,t)=>{g.current=[...g.current,{x:e.x,y:e.y,positive:t}],u([{x:e.x,y:e.y,positive:t}]),A()},[A]),M=(0,r.useCallback)(e=>{D();let t=[{x:e.x,y:e.y,positive:!0}];g.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),g.current=[...g.current,{x:t.x,y:t.y,positive:n}],u([{x:t.x,y:t.y,positive:n}]),A()},[D,A]);return{status:s,points:l,boxes:d,beginBox:(0,r.useCallback)((n,r=`polygon`)=>{let o=a.current?.infer,s=t.current;if(!o||!s)return;let c=S.current;w(e=>[...e,n]),(async()=>{let t=[];try{t=(await o({kind:`box`,box:n})??[]).filter(e=>e.length>=3)}catch{t=[]}if(w(e=>e.filter(e=>e!==n)),c!==S.current)return;let a=E(t,r,s);a?.length&&(e.current.create(a),i(a.map(e=>e.id)))})()},[a,t,E,i,e,w]),addPoint:j,newPolygon:M,refineShape:N,finalize:D,cancel:O,isActive:(0,r.useCallback)(()=>v.current===`loading`||g.current.length>0||m.current.length>0||_.current.length>0,[])}}function yt(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 bt(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=yt(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 xt=4096,St=4;function Ct(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 wt(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 Tt(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 Et(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 Dt(e,t,n){let r=wt(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=kt(Tt(Et(r,t,n,e,a)),t,n);o.length>=3&&i.push(o)}return i}function Ot(e,t,n,r,i){return r<0||i<0||r>=t||i>=n?!1:e[(i*t+r)*4+3]>128}function kt(e,t,n){let r=-1,i=-1;outer:for(let a=0;a<n;a++)for(let o=0;o<t;o++)if(Ot(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(Ot(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 At(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 jt(e){switch(e.type){case o.RECTANGLE:return e.points.length<2?null:b(e.points);case o.POLYGON:case o.ROTATED_RECTANGLE:case o.ELLIPSE:return e.points.length>=3?e.points:null;case o.POINT:{let t=e.points[0];return t?x({x:t.x-6,y:t.y-6},{x:t.x+6,y:t.y+6}):null}default:return null}}function Mt(e){return e.map(jt).filter(e=>!!e&&e.length>=3)}function Nt(e,t,n=[]){if(t<=0||!e.length&&!n.length)return null;let r=At(e,n);if(!r.length)return null;let i=t+4,a=h(r),o=Math.ceil(a.maxX-a.minX+i*2),s=Math.ceil(a.maxY-a.minY+i*2),c=Math.min(1,xt/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 Pt(e,t=1.5){let{canvas:n,ox:r,oy:i,scale:a}=e,o=Dt(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=bt(n,t),i=r.length>=3?r:n;i.length>=3&&Ct(i)>=St&&c.push(i)}return c}function Q(e,t){let{canvas:n}=e,r=document.createElement(`canvas`);r.width=n.width,r.height=n.height;let i=r.getContext(`2d`);return i?(i.drawImage(n,0,0),i.globalCompositeOperation=`source-in`,i.fillStyle=t,i.fillRect(0,0,r.width,r.height),r):n}function Ft(e){return e.map(e=>({mode:e.mode,points:e.points.map(e=>({...e}))}))}function It(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 Lt(e){return e.map(e=>({...e}))}function Rt(e,t){return e.length===t.length&&e.every((e,n)=>e.x===t[n].x&&e.y===t[n].y)}var zt=10;function Bt(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 Vt({toolRef:e,selRef:t,docRef:n,readOnlyRef:i,draftRef:a,brushSizeRef:s,simplifyEpsilonRef:c,draftMeta:l,engineRef:d,onDrawSessionChange:f,onDraftShapeChange:m,changeSelection:h,createShape:g}){let _=(0,r.useRef)(f);_.current=f;let v=(0,r.useRef)(m);v.current=m;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===B.BRUSH&&S.current.length>0,I=()=>{let t=e.current;return t===B.BRUSH&&F()?`brush`:t===B.POLYGON&&S.current.length>0?`polygon`:t===B.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,z=()=>E.current>0,ee=()=>E.current<T.current.length-1,V=()=>{let t=e.current;return t===B.BRUSH?L():t===B.POLYGON||t===B.PATH?z():!1},te=()=>{let t=e.current;return t===B.BRUSH?R():t===B.POLYGON||t===B.PATH?ee():!1},ne=()=>I()!==`none`,H=(0,r.useCallback)(()=>{let e=I(),t={active:e!==`none`,kind:e,canUndo:V(),canRedo:te(),brush:e===`brush`?{mode:N.current,editing:A.current.length>0,editTargetIds:[...A.current]}:void 0},n=x.current;n&&Bt(n,t)||(x.current=t,_.current?.(t))},[]),re=(0,r.useCallback)(()=>{j.current=[[]],M.current=0},[]),U=(0,r.useCallback)(()=>{let t=d.current;if(!t)return;let n=e.current;if(n===B.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=Nt(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!==B.PATH;if(t.previewPoly(r,C.current,i,!1,c,l),n===B.POLYGON||n===B.PATH){let e=v.current;e&&r!==D.current&&(D.current=r,e({type:o.POLYGON,points:Lt(r),meta:y.current}))}},[s,a,d,e]),ie=(0,r.useCallback)(e=>{let t=Ft(e),n=j.current,r=M.current,i=n[r];i&&It(i,t)||(j.current=[...n.slice(0,r+1),t],M.current+=1,H())},[H]),ae=(0,r.useCallback)(e=>{let t=T.current,n=E.current,r=t[n];r&&Rt(r,e)||(T.current=[...t.slice(0,n+1),Lt(e)],E.current+=1)},[]),W=(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,re(),d.current?.clearPreview(),v.current?.(null),H()},[d,H,re]),oe=(0,r.useCallback)((e,t)=>{S.current=e,w.current=new Set(Array.from(w.current).filter(t=>t>=0&&t<e.length)),t&&ae(e),U(),H()},[H,ae,U]),se=(0,r.useCallback)(()=>Lt(S.current),[]),ce=(0,r.useCallback)(()=>S.current.length>0,[]),le=(0,r.useCallback)((t,n)=>{if(e.current!==B.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),W(),!0)},[W,e]),ue=(0,r.useCallback)(e=>{let t=S.current;return e<0||e>=t.length?!1:(oe(t.filter((t,n)=>n!==e),!0),!0)},[oe]),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,U(),H(),{base:Lt(n),indices:Array.from(r)}},[H,U]),G=(0,r.useCallback)(e=>{w.current=new Set,C.current=e,oe([...S.current,e],!0)},[oe]),fe=(0,r.useCallback)(e=>{C.current=null,w.current=new Set,S.current=[{...e}],U(),H()},[H,U]),pe=(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,U(),H(),!0)},[H,U]),me=(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,U(),H()},[H,U]),he=(0,r.useCallback)(e=>{e&&(ae(S.current),U(),H())},[H,ae,U]),ge=(0,r.useCallback)(e=>{C.current=e?{...e}:null,U()},[U]),_e=(0,r.useCallback)(()=>S.current.length>0?(S.current=[],U(),H(),!0):M.current<=0?!1:(--M.current,O.current=Ft(j.current[M.current]),U(),H(),!0),[H,U]),ve=(0,r.useCallback)(()=>S.current.length>0||M.current>=j.current.length-1?!1:(M.current+=1,O.current=Ft(j.current[M.current]),U(),H(),!0),[H,U]),ye=(0,r.useCallback)(()=>E.current<=0?!1:(--E.current,S.current=Lt(T.current[E.current]),w.current=new Set,U(),H(),!0),[H,U]),be=(0,r.useCallback)(()=>E.current>=T.current.length-1?!1:(E.current+=1,S.current=Lt(T.current[E.current]),w.current=new Set,U(),H(),!0),[H,U]),xe=(0,r.useCallback)(()=>{let t=e.current;return t===B.BRUSH?_e():t===B.POLYGON||t===B.PATH?ye():!1},[e,_e,ye]),Se=(0,r.useCallback)(()=>{let t=e.current;return t===B.BRUSH?ve():t===B.POLYGON||t===B.PATH?be():!1},[ve,be,e]),K=(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=Mt(r);return i.length?(A.current=r.map(e=>e.id),k.current=i,!0):(A.current=[],k.current=[],!1)},[n,t]),Ce=(0,r.useCallback)(()=>{if(i.current)return!1;let e=[...O.current];S.current.length&&e.push({points:Lt(S.current),mode:P()});let t=k.current,r=[...A.current];if(!e.length&&!t.length)return!1;let u=Nt(e,s.current,t);if(!u)return W(),!1;let d=Pt(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),W(),h([]),!0;d.sort((e,t)=>Ct(t)-Ct(e));let t=[],i=[],a=[];for(let n=0;n<d.length;n++){let r=d[n];if(n<e.length){let i=e[n];t.push({...i,type:o.POLYGON,points:r}),a.push(i.id)}else{let t=e[0],n=p();i.push({...t,id:n,type:o.POLYGON,points:r}),a.push(n)}}let s=e.slice(d.length).map(e=>e.id);return t.length&&n.current.update(t),i.length&&n.current.create(i),s.length&&n.current.remove(s),W(),h(a),!0}if(!d.length)return W(),!1;let f=a.current;if(!f)return!1;let m=d.map(e=>({id:p(),type:o.POLYGON,points:e,style:f,meta:l}));return n.current.create(m),h(m.map(e=>e.id)),W(),!0},[s,h,n,l,a,i,W]),we=(0,r.useCallback)(()=>{let t=e.current;if(t===B.BRUSH)return Ce();let n=S.current;return t===B.POLYGON&&n.length>=3?(b.current(o.POLYGON,n),W(),!0):!1},[Ce,W,e]),Te=(0,r.useCallback)(()=>{let t=S.current;if(e.current===B.PATH&&t.length>=3){let e=bt(t,c.current);e.length>=3&&b.current(o.POLYGON,e)}W()},[W,e]),Ee=(0,r.useCallback)(e=>{N.current=e,H(),U()},[H,U]),De=(0,r.useCallback)(()=>{if(i.current||e.current!==B.BRUSH)return!1;O.current=[],S.current=[],re();let t=K();return H(),U(),t},[H,i,U,re,K,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,oe(t,!0),!0},[oe]),ke=(0,r.useCallback)(e=>{let t=d.current,n=S.current;if(!t||!n.length)return-1;let r=zt/(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:Lt(S.current),mode:P()}),S.current=[],ie(O.current)),U(),H()},[H,ie,U]);return{reset:W,undoSession:xe,redoSession:Se,canUndoSession:V,canRedoSession:te,hasDraftSession:ne,hasDraftPoints:ce,commitDraftSession:we,completeFreehandStroke:Te,setBrushScalarMode:Ee,getBrushScalarMode:()=>N.current,hasBrushSession:F,commitBrush:Ce,cancelBrush:(0,r.useCallback)(()=>{e.current===B.BRUSH&&W()},[W,e]),beginBrushEditFromSelection:De,deleteDraftSelectedPoints:Oe,hitDraftPoint:ke,getDraftPointsSnapshot:se,tryClosePolygon:le,removeDraftPoint:ue,selectDraftPointForDrag:de,appendPolygonPoint:G,beginStroke:fe,appendStrokePoint:pe,moveDraftPoints:me,commitDraftPointDrag:he,setDraftCursor:ge,finishScalarStroke:Ae,handleToolChange:(0,r.useCallback)((e,t)=>{if(t){W(),N.current=`draw`;return}if(e!==B.BRUSH){W(),N.current=`draw`;return}N.current=`draw`,O.current=[],S.current=[],re(),K(),H(),U()},[H,U,W,re,K]),handleBrushSelectionChange:(0,r.useCallback)((t,n)=>{if(!(e.current!==B.BRUSH||n)){if(!t.length){H();return}[...t].sort().join(`,`)!==[...A.current].sort().join(`,`)&&(O.current.length||S.current.length||(O.current=[],S.current=[],re(),K(),H(),U()))}},[H,U,re,K,e])}}function Ht(e,t){return{shapes:t,past:[...e.past,e.shapes],future:[]}}function Ut(e,t){switch(t.type){case`CREATE`:return Ht(e,[...e.shapes,...t.shapes]);case`UPDATE`:{let n=new Map(t.shapes.map(e=>[e.id,e]));return Ht(e,e.shapes.map(e=>n.get(e.id)??e))}case`DELETE`:{let n=new Set(t.ids);return Ht(e,e.shapes.filter(e=>!n.has(e.id)))}case`REPLACE`:{let n=new Set(t.removeIds);return Ht(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:Ht(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 Wt(e){let{onShapesCreated:t,onShapesUpdated:n,onShapesDeleted:i}=e,[a,o]=(0,r.useReducer)(Ut,{shapes:[],past:[],future:[]}),s=(0,r.useRef)(a);s.current=a;let c=(0,r.useCallback)(e=>{s.current=Ut(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 Gt={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`]},Kt={Equal:`=`,Minus:`-`,BracketLeft:`[`,BracketRight:`]`,Semicolon:`;`,Period:`.`,Comma:`,`,Slash:`/`,Backquote:"`"},qt={Escape:`escape`,Enter:`enter`,Backspace:`backspace`,Delete:`delete`,Tab:`tab`,ArrowUp:`arrowup`,ArrowDown:`arrowdown`,ArrowLeft:`arrowleft`,ArrowRight:`arrowright`};function Jt(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]:Kt[t]?Kt[t]:qt[e.key]?qt[e.key]:null}function Yt(e){let t=Jt(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 Xt(e){let t=new Map;for(let n of Object.keys(Gt)){let r=e?.[n],i=r===void 0?Gt[n]:r===null?[]:Array.isArray(r)?r:[r];for(let e of i)t.set(e.toLowerCase(),n)}return t}var Zt={ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0]};function Qt(){let e=document.activeElement;return!!e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable)}function $t(e,t){if(!t||!(e instanceof Element))return!1;let n=e.closest(`[role="dialog"],[aria-modal="true"]`);return!!n&&!n.contains(t)}function en(e){let{spaceRef:t,shiftRef:n}=e,i=(0,r.useMemo)(()=>Xt(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=e=>{if(e.code===`Space`&&(t.current=!0,a.current.onSpaceDown()),e.key===`Shift`&&(n.current=!0),Qt()||$t(e.target,a.current.hostRef.current))return;let r=Zt[e.key];if(r){e.preventDefault();let t=e.shiftKey?10:1;a.current.nudge(r[0]*t,r[1]*t);return}let i=Yt(e);if(!i)return;let s=o.current.get(i);s&&a.current.actions[s]?.()!==!1&&e.preventDefault()},r=e=>{e.code===`Space`&&(t.current=!1,a.current.onSpaceUp()),e.key===`Shift`&&(n.current=!1)};return window.addEventListener(`keydown`,e,{capture:!0}),window.addEventListener(`keyup`,r,{capture:!0}),()=>{window.removeEventListener(`keydown`,e,{capture:!0}),window.removeEventListener(`keyup`,r,{capture:!0})}},[t,n])}function tn(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 nn(e){let t=await tn(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 tn(e,{crossOrigin:!0})}function rn(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),tn(e,{crossOrigin:!0}).then(()=>{setTimeout(i,0)})})}var an=3e4,on=200,sn=new Map;function cn(e){let t=sn.get(e),n=Date.now();if(t&&n-t.at<an)return t.result;let r=ln(e).catch(t=>(sn.delete(e),{kind:`unknown`,detail:t instanceof Error?t.message:String(t)}));if(sn.set(e,{at:n,result:r}),sn.size>on){let e=sn.keys().next().value;e!==void 0&&sn.delete(e)}return r}async function ln(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 rn(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 un(){try{let e=document.createElement(`canvas`);return!!(e.getContext(`webgl2`)??e.getContext(`webgl`))}catch{return!1}}function dn(e){let t=e instanceof Error?e.message:String(e);return/unsafe-eval/i.test(t)?{kind:`csp-eval`,detail:t}:un()?{kind:`renderer-init`,detail:t||`renderer init failed`}:{kind:`webgl`,detail:t||`WebGL context unavailable`}}var fn=4e3;function pn(e,t,n=fn){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 mn(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 hn(e,t,n){if(t===o.POINT){e.setAttrs({x:n[0].x,y:n[0].y});return}if(t===o.RECTANGLE){let[t,r]=n;e.setAttrs({x:Math.min(t.x,r.x),y:Math.min(t.y,r.y),width:Math.abs(r.x-t.x),height:Math.abs(r.y-t.y)});return}if(t===o.ELLIPSE){let t=h(n);e.setAttrs({x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2,radiusX:(t.maxX-t.minX)/2,radiusY:(t.maxY-t.minY)/2});return}e.setAttrs({x:0,y:0,points:n.flatMap(e=>[e.x,e.y])})}var gn=`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`,_n=`#ffffff`,vn=1.5;function yn(e){return`<svg width="16" height="22" viewBox="0 0 16 22" xmlns="http://www.w3.org/2000/svg"><path d="${gn}" fill="${e}" stroke="${_n}" stroke-width="${vn}"/></svg>`}var bn=Math.PI/12;function xn(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 Sn(e,t,n){if(e.kind===`resize`){let r=n?e.box:_(e.anchor,e.box,t.x,t.y);return{updates:e.shapes.map(i=>({id:i.id,points:n?N(i.points,e.anchor,t):P(i.points,e.box,r)})),box:r}}if(e.kind===`move`){let n=t.x-e.start.x,r=t.y-e.start.y;return{updates:e.shapes.map(e=>({id:e.id,points:e.points.map(e=>({x:e.x+n,y:e.y+r}))})),box:{minX:e.box.minX+n,minY:e.box.minY+r,maxX:e.box.maxX+n,maxY:e.box.maxY+r}}}if(e.kind===`rotate`){let n=Math.atan2(t.y-e.center.y,t.x-e.center.x)-e.startAngle;return e.shiftKey&&(n=Math.round(n/bn)*bn),{updates:[{id:e.id,points:e.points.map(t=>y(t,e.center,n))}],box:null}}let r=t.x-e.start.x,i=t.y-e.start.y,a=e.base.map((t,n)=>e.indices.includes(n)?{x:t.x+r,y:t.y+i}:t);return{updates:[{id:e.id,points:a}],box:h(a)}}function Cn(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)}:xn(e,t)?A(t.shapes[0].points)[m.indexOf(t.anchor)]:g(t.anchor,t.box)}function wn(e,t,n){let r=e.filter(e=>t.includes(e.id)&&d(e)).map(e=>({id:e.id,points:e.points}));return r.length?{kind:`move`,start:n,box:h(r.flatMap(e=>e.points)),shapes:r}:null}function Tn(e){return e.map(e=>({...e,points:e.points.map(e=>({...e}))}))}function En(e,t){let n=new Set(t);return e.filter(e=>n.has(e.id)&&u(e))}function Dn(e,t){return e.filter(e=>{if(!l(e))return!1;let n=h(e.points);return n.minX<=t.maxX&&n.maxX>=t.minX&&n.minY<=t.maxY&&n.maxY>=t.minY}).map(e=>e.id)}function On(e,t,n){return(e?G(e,{strokeWidth:t}).pointRadius:5)/(n||1)}function kn(e,t){return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}function An(e,t,n){if(e.type===o.ROTATED_RECTANGLE)return t;let r=e.type===o.POINT?kn(t[0],n):h(t);return b([{x:r.minX,y:r.minY},{x:r.maxX,y:r.maxY}])}function jn(e){return 24/(e||1)}function Mn(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}var Nn=2,Pn=`#1e88e5`,Fn=`#669def`,In=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.guideOverlayGroup=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=Nn,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.guideOverlayGroup,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`,()=>{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}})});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},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}bindCursor(e,t){let n=()=>{this.activeDrag||t===`pointer`&&!this.transformEnabled||this.emitCursorHint(t)},r=()=>{this.activeDrag||this.emitCursorHint(null)};e.on(`mouseenter`,n),e.on(`mouseover`,n),e.on(`mouseleave`,r),e.on(`mouseout`,r)}toImage(){let e=this.world.getRelativePointerPosition();return e?{x:e.x,y:e.y}:this.lastImg}imgToScreen(e){return this.world.getAbsoluteTransform().point(e)}async setImage(e,t,n){let r=++this.imageLoadToken,a=await nn(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 pn(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,n){this.guideOverlayGroup.destroyChildren(),e&&this.guideOverlayGroup.add(new i.default.Image({image:e,opacity:.55,imageSmoothingEnabled:!1,listening:!1})),this.setRegionOverlay(t),this.dimOverlayGroup.destroyChildren(),n&&this.imageWidth&&this.dimOverlayGroup.add(new i.default.Rect({x:0,y:0,width:this.imageWidth,height:this.imageHeight,fill:`#0d0d12`,opacity:.3,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=>{at(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??Cn(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=Tn(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=G(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=G(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?fe(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:gn,x:n[0].x,y:n[0].y,offsetX:16/2,offsetY:22,scaleX:t,scaleY:t,fill:r.color,stroke:_n,strokeWidth:vn,strokeScaleEnabled:!1,shadowColor:`#000`,shadowBlur:2,shadowOpacity:.3,shadowForStrokeEnabled:!1,opacity:r.opacity,listening:a});return this.bindCursor(o,d(e)?`grab`:`default`),o}if(t===o.RECTANGLE){let t=h(n),r=new i.default.Rect({x:t.minX,y:t.minY,width:t.maxX-t.minX,height:t.maxY-t.minY,fill:c,...s});return this.bindCursor(r,d(e)?`grab`:`default`),r}if(t===o.ELLIPSE){let t=h(n),r=new i.default.Ellipse({x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2,radiusX:(t.maxX-t.minX)/2,radiusY:(t.maxY-t.minY)/2,fill:c,...s});return this.bindCursor(r,d(e)?`grab`:`default`),r}let u=n.flatMap(e=>[e.x,e.y]),f=t!==o.LINE,p=new i.default.Line({points:u,closed:f,fill:f?c:void 0,lineJoin:`round`,...s});return this.bindCursor(p,d(e)?`grab`:`default`),p}liveUpdateShape(e,t){let n=this.nodes.get(e),r=this.shapes.find(t=>t.id===e);if(n&&r){hn(n,r.type,t);let a=this.altNodes.get(e);a&&hn(a,r.type,t),r.type===o.POINT&&n instanceof i.default.Circle&&n.radius(this.pointRadius(r)),this.layer.batchDraw()}}pointRadius(e){return On(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(G(t,{strokeWidth:this.strokeSize}).dash))}}shapesIntersecting(e){return Dn(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:Fn,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 An(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?Pn:`#ffffff`,stroke:r?`#ffffff`:Pn,strokeWidth:1.5,strokeScaleEnabled:!1,listening:!1}))}this.layer.batchDraw()}previewScalarMask(e,t){this.previewGroup.destroyChildren();let n=Q(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:fe(le,ue),stroke:le,strokeWidth:1,strokeScaleEnabled:!1,listening:!1,perfectDrawEnabled:!1}),this.previewGroup.add(this.marquee)),this.marquee.setAttrs({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(t.x-e.x),height:Math.abs(t.y-e.y)}),this.layer.batchDraw()}setTransformEnabled(e){this.transformEnabled=e,this.drawTransformer(),this.layer.batchDraw()}setPanMode(e){this.handleGroup.listening(!e),this.layer.batchDraw()}setTransformerOutline(e){let t=Math.max(0,e.maxX-e.minX),n=Math.max(0,e.maxY-e.minY);!t&&!n||this.setTransformerOutlinePoints(b([{x:e.minX,y:e.minY},{x:e.maxX,y:e.maxY}]))}setTransformerOutlinePoints(e){e.length<2||(this.transformerOutline||(this.transformerOutline=new i.default.Line({closed:!0,stroke:Pn,strokeWidth:1,strokeScaleEnabled:!1,listening:!1}),this.selGroup.add(this.transformerOutline)),this.transformerOutline.points(e.flatMap(e=>[e.x,e.y])))}rotationHandleGap(){return jn(this.viewport.scale)}rotationHandleScreenPoint(e){return this.imgToScreen(j(e,this.rotationHandleGap()))}setRotationConnector(e){let t=this.imgToScreen(O(e[0],e[1])),n=this.rotationHandleScreenPoint(e);this.rotLineNode?this.rotLineNode.points([t.x,t.y,n.x,n.y]):(this.rotLineNode=new i.default.Line({points:[t.x,t.y,n.x,n.y],stroke:Pn,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 Mn(this.imgToScreen(e[0]),this.imgToScreen(e[1]))}repositionOrientedHandles(e){let t=this.orientedHandleAngle(e);if(A(e).forEach((e,n)=>{let r=this.imgToScreen(e),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,t)}),this.setTransformerOutlinePoints(e),this.rotNode){let t=this.rotationHandleScreenPoint(e);this.rotNode.position({x:t.x,y:t.y})}this.rotLineNode&&this.setRotationConnector(e)}drawTransformer(){if(this.activeDrag)return;for(let e of this.handleNodes)e.destroy();for(let e of this.vertexNodes)e.destroy();for(let e of this.midNodes)e.destroy();if(this.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=En(this.shapes,this.selected);if(!e.length||e.length===1&&e[0].type===o.POINT)return;let t=e.length===1&&(e[0].type===o.POLYGON||e[0].type===o.LINE)&&this.editingId===e[0].id?e[0]:null,n=h(e.flatMap(e=>e.points)),r=e.length===1&&e[0].type===o.ROTATED_RECTANGLE?e[0]:null,a=r?A(r.points):m.map(e=>g(e,n));r?this.setTransformerOutlinePoints(r.points):this.setTransformerOutline(n),r&&this.setRotationConnector(r.points);let s=r?this.orientedHandleAngle(r.points):0;for(let e of t?[]:m){let t=this.imgToScreen(a[m.indexOf(e)]),n=new i.default.Rect({x:t.x,y:t.y,width:8,height:8,offsetX:4,offsetY:4,rotation:s*180/Math.PI,fill:`#ffffff`,stroke:Pn,strokeWidth:1}),r=Je(e,s);this.bindCursor(n,r),n.on(`mousedown`,t=>{t.cancelBubble=!0,this.emitCursorHint(r),this.emitInteractionMode(`resizing`);let n=En(this.shapes,this.selected);this.activeDrag={kind:`resize`,anchor:e,box:h(n.flatMap(e=>e.points)),shapes:n.map(e=>({id:e.id,points:e.points}))},this.lastDragImg=null}),this.handleGroup.add(n),this.handleNodes.push(n)}if(t){let e=t,n=e.points,r=e.type===o.POLYGON?n.length:n.length-1,a=this.vertexHandleRadius(),s=new i.default.Circle({radius:a*.8,fill:`#ffffff`,opacity:.6,stroke:Pn,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?Pn:`#ffffff`,stroke:s?`#ffffff`:Pn,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=k(t.points),r=this.rotationHandleScreenPoint(t.points),a=new i.default.Circle({x:r.x,y:r.y,radius:6,fill:`#ffffff`,stroke:Pn,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=wn(this.shapes,t,e);n&&(this.transformEnabled&&!this.handleNodes.length&&this.drawTransformer(),this.activeDrag=n,this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`moving`),(n.shapes.length===1?this.shapes.find(e=>e.id===n.shapes[0].id):null)?.type===o.ROTATED_RECTANGLE?this.setTransformerOutlinePoints(n.shapes[0].points):this.setTransformerOutline(n.box),this.updateSelectionBordersLive(e=>e.points))}repositionHandles(e){m.forEach((t,n)=>{let r=this.imgToScreen(g(t,e)),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,0)}),this.setTransformerOutline(e)}repositionPolygonHandles(e,t){if(!this.vertexNodes.length)return;e.forEach((e,t)=>{let n=this.imgToScreen(e);this.vertexNodes[t]?.position({x:n.x,y:n.y})});let n=t?e.length:e.length-1;for(let t=0;t<n;t++){let n=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=xn(this.shapes,t),{updates:r,box:i}=Sn(t,e,n);for(let e of r)this.liveUpdateShape(e.id,e.points);if(this.cb.onTransformPreview?.(r),this.updateSelectionBordersLive(e=>r.find(t=>t.id===e.id)?.points??e.points),t.kind===`resize`||t.kind===`move`){n?this.repositionOrientedHandles(r[0].points):i&&this.repositionHandles(i);let e=t.shapes.length===1?this.shapes.find(e=>e.id===t.shapes[0].id):null,a=e?.type===o.POLYGON||e?.type===o.LINE;(t.kind===`resize`?a:this.vertexNodes.length>0&&t.shapes.length===1)&&this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}else if(t.kind===`rotate`){this.repositionOrientedHandles(r[0].points);let e=this.shapes.find(e=>e.id===t.id);e&&(e.type===o.POLYGON||e.type===o.LINE)&&this.repositionPolygonHandles(r[0].points,e.type===o.POLYGON)}else{i&&this.repositionHandles(i);let e=this.shapes.find(e=>e.id===t.id);this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}this.layer.batchDraw()}endTransform(){let e=this.activeDrag,t=this.lastDragImg;if(this.activeDrag=null,this.emitInteractionMode(`idle`),this.emitCursorHint(e?.kind===`move`?`grab`:null),!e||!t){this.cb.onTransformPreview?.([]),this.drawTransformer();return}if(e.kind===`move`&&t.x===e.start.x&&t.y===e.start.y){this.cb.onTransformPreview?.([]),this.drawTransformer();return}let{updates:n}=Sn(e,t,xn(this.shapes,e));this.commitTransformUpdates(n)}},Ln=2,Rn=58879,zn=6725103;function Bn(e){if(!e)return Rn;let t=e.replace(`#`,``);return Number.parseInt(t.length===3?t.replace(/./g,`$&$&`):t,16)}var $=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.guideOverlayLayer=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=fn,this.overlayTextures=[],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=Ln,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(fn,t-1)),this.applyCursor(),this.overlayLayer.addChild(this.guideOverlayLayer,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},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();for(let e of this.overlayTextures)e.destroy(!0);this.overlayTextures=[],this.app.renderer&&this.app.destroy(!0,{children:!0})}get screenSize(){return{w:this.app.renderer.screen.width,h:this.app.renderer.screen.height}}setCursor(e){this.baseCursor=e,this.syncShapeCursors(),this.applyCursor()}emitCursorHint(e){this.cb.onCursorHint?.(e)}emitInteractionMode(e){this.cb.onInteractionModeChange?.(e)}applyCursor(){if(this.destroyed||!this.app.renderer)return;let e=this.app.canvas;e&&(e.style.cursor=this.baseCursor)}syncShapeCursors(){for(let e of this.nodes.values())e.cursor=void 0}bindCursor(e,t){e.cursor=void 0,e.on(`pointerover`,()=>{this.activeDrag||this.emitCursorHint(t)}),e.on(`pointerout`,()=>{this.activeDrag||this.emitCursorHint(null)})}get dom(){return this.app.canvas}toImage(e){let t=this.world.toLocal(e.global);return{x:t.x,y:t.y}}async setImage(e,t,n){let r=++this.imageLoadToken,i=await nn(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 pn(i.naturalWidth,i.naturalHeight,this.tileSize)){let t=a.Texture.from(mn(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,n){for(let e of this.guideOverlayLayer.removeChildren())e.destroy();for(let e of this.overlayTextures)e.destroy(!0);if(this.overlayTextures=[],e){let t=a.Texture.from(e);t.source.scaleMode=`nearest`,this.overlayTextures.push(t);let n=new a.Sprite(t);n.alpha=.55,this.guideOverlayLayer.addChild(n)}this.setRegionOverlay(t);for(let e of this.dimOverlayLayer.removeChildren())e.destroy();n&&this.imageWidth&&this.dimOverlayLayer.addChild(new a.Graphics().rect(0,0,this.imageWidth,this.imageHeight).fill({color:855314,alpha:.3})),!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=Bn(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??Cn(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=Tn(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,this.syncShapeCursors(),this.drawTransformer()}setPanMode(e){this.handleLayer.interactiveChildren=!e}strokeW(e){return(e?G(e,{strokeWidth:this.strokeSize}).strokeWidth:Ln)/this.world.scale.x}pointRadius(e){return On(e,this.strokeSize,this.world.scale.x)}dashForShape(e){let t=G(e,{strokeWidth:this.strokeSize}).dash;if(!t?.length)return null;let n=this.world.scale.x||1;return[t[0]/n,(t[1]??t[0])/n]}drawShapes(){this.shapeLayer.removeChildren();for(let e of this.nodes.values())e.destroy();this.nodes.clear();for(let e of f(this.shapes).filter(s)){let t=new a.Graphics;this.paintShape(t,e),t.eventMode=l(e)?`static`:`none`,t.cursor=void 0,l(e)&&d(e)&&(t.on(`pointerover`,()=>{!this.activeDrag&&this.transformEnabled&&this.emitCursorHint(`grab`)}),t.on(`pointerout`,()=>{this.activeDrag||this.emitCursorHint(null)})),t.on(`pointerdown`,t=>{t.stopPropagation(),this.cb.onPointerDown(this.toImage(t),e.id,this.ev(t))}),this.shapeLayer.addChild(t),this.nodes.set(e.id,t)}}paintShape(e,t){e.clear();let n=G(t,{strokeWidth:this.strokeSize}),r=Bn(n.color),i=this.strokeW(t),a=n.opacity,s=this.dashForShape(t);if(t.type===o.POINT){e.svg(yn(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?R(t.points):null;if(i&&i.length>1)for(let t of i)e.poly(t.flatMap(e=>[e.x,e.y]),!0),e.fill({color:r,alpha:n.fillAlpha*a});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:Bn(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 Dn(this.shapes,e)}shapesAt(e){return this.shapes.filter(t=>{let n=h(t.points);return e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY}).map(e=>e.id)}repaintPreview(){let e=this.lastPreview;e&&(e.kind===`poly`?this.previewPoly(e.points,e.cursor,e.style,e.closed,e.selectedPointIndices,e.showVertices):this.previewBox(e.boxKind,e.a,e.b,e.style))}ensurePreview(){this.previewReady||=(this.previewLayer.addChild(this.previewG,this.marqueeG),!0)}clearPreview(){this.lastPreview=null,this.previewG.clear(),this.previewMaskSprite&&(this.previewMaskSprite.visible=!1)}clearMarquee(){this.marqueeG.clear()}previewBox(e,t,n,r){this.lastPreview={kind:`box`,boxKind:e,a:t,b:n,style:r},this.ensurePreview(),this.previewG.clear();let i={id:`__preview__`,type:e===`ellipse`?o.ELLIPSE:o.RECTANGLE,points:[t,n],style:r},a=this.strokeW(i);r.alternateColor&&(this.path(this.previewG,i),this.previewG.stroke({width:a,color:Bn(r.alternateColor)}));let s=this.dashForShape(i);if(s){this.dashedStrokeShape(this.previewG,i,a,Bn(r.color??`#00e5ff`),r.opacity??1,s);return}this.path(this.previewG,i),this.previewG.stroke({width:a,color:Bn(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:Bn(n.alternateColor)}));let u=this.dashForShape(c);if(u?this.dashedStrokeShape(this.previewG,c,l,Bn(n.color??`#00e5ff`),n.opacity??1,u):(this.path(this.previewG,c),this.previewG.stroke({width:l,color:Bn(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=Q(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=Bn(le);this.marqueeG.rect(n,r,i,a).fill({color:o,alpha:ue}).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:Bn(r.underlayColor)}),this.strokeDashedPolyline(e,[n,o],!1,i,Bn(r.color),r.opacity,a)};r(this.region.visibleOutline,t.visible),r(this.region.occludedOutline,t.occluded)}path(e,t){let{type:n,points:r}=t;if(n===o.POINT){e.circle(r[0].x,r[0].y,this.pointRadius(t));return}if(n===o.RECTANGLE){let t=h(r);e.rect(t.minX,t.minY,t.maxX-t.minX,t.maxY-t.minY);return}if(n===o.ELLIPSE){let t=h(r);e.ellipse((t.minX+t.maxX)/2,(t.minY+t.maxY)/2,(t.maxX-t.minX)/2,(t.maxY-t.minY)/2);return}let i=r.flatMap(e=>[e.x,e.y]);e.poly(i,n!==o.LINE)}dashedStrokeShape(e,t,n,r,i,a){let{type:s,points:c}=t;if(s===o.RECTANGLE){let t=h(c);this.strokeDashedPolyline(e,[{x:t.minX,y:t.minY},{x:t.maxX,y:t.minY},{x:t.maxX,y:t.maxY},{x:t.minX,y:t.maxY}],!0,n,r,i,a);return}if(s===o.ELLIPSE){let t=h(c),o=(t.minX+t.maxX)/2,s=(t.minY+t.maxY)/2,l=(t.maxX-t.minX)/2,u=(t.maxY-t.minY)/2,d=Array.from({length:96},(e,t)=>{let n=t/96*Math.PI*2;return{x:o+Math.cos(n)*l,y:s+Math.sin(n)*u}});this.strokeDashedPolyline(e,d,!0,n,r,i,a);return}this.strokeDashedPolyline(e,c,s!==o.LINE,n,r,i,a)}strokeDashedPolyline(e,t,n,r,i,a,o){if(t.length<2)return;let[s,c]=o;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:zn})})}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:zn}))}}selectionOutlinePoints(e,t){return An(e,t,this.pointRadius(e))}imgToScreen(e){let t=this.world.toGlobal({x:e.x,y:e.y});return{x:t.x,y:t.y}}setTransformerOutline(e){let t=e.maxX-e.minX,n=e.maxY-e.minY;t<=0&&n<=0||this.setTransformerOutlinePoints(b([{x:e.minX,y:e.minY},{x:e.maxX,y:e.maxY}]))}setTransformerOutlinePoints(e){e.length<2||(this.transformerOutline||(this.transformerOutline=new a.Graphics,this.selLayer.addChild(this.transformerOutline)),this.transformerOutline.clear(),this.transformerOutline.poly(e.flatMap(e=>[e.x,e.y]),!0).stroke({width:1/this.world.scale.x,color:2001125}))}rotationHandleGap(){return jn(this.viewport.scale)}rotationHandleScreenPoint(e){return this.imgToScreen(j(e,this.rotationHandleGap()))}setRotationConnector(e){let t=this.imgToScreen(O(e[0],e[1])),n=this.rotationHandleScreenPoint(e);this.rotLineNode||(this.rotLineNode=new a.Graphics,this.rotLineNode.eventMode=`none`,this.handleLayer.addChild(this.rotLineNode)),this.rotLineNode.clear(),this.rotLineNode.moveTo(t.x,t.y).lineTo(n.x,n.y).stroke({width:1,color:2001125})}layoutResizeHandle(e,t,n){e.position.set(t.x,t.y),e.rotation=n}orientedHandleAngle(e){return Mn(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=En(this.shapes,this.selected);if(e.length===0||e.length===1&&e[0].type===o.POINT)return;let t=e.length===1&&(e[0].type===o.POLYGON||e[0].type===o.LINE)&&this.editingId===e[0].id?e[0]:null,n=h(e.flatMap(e=>e.points)),r=e.length===1&&e[0].type===o.ROTATED_RECTANGLE?e[0]:null,i=r?A(r.points):m.map(e=>g(e,n));r?this.setTransformerOutlinePoints(r.points):this.setTransformerOutline(n),r&&this.setRotationConnector(r.points);let s=r?this.orientedHandleAngle(r.points):0;for(let e of t?[]:m){let t=this.imgToScreen(i[m.indexOf(e)]),n=new a.Graphics;n.rect(-4,-4,8,8).fill({color:16777215}).stroke({width:1,color:2001125}),this.layoutResizeHandle(n,t,s),n.eventMode=`static`;let r=Je(e,s);this.bindCursor(n,r),n.on(`pointerdown`,t=>{t.stopPropagation(),this.emitCursorHint(r),this.emitInteractionMode(`resizing`);let n=En(this.shapes,this.selected);this.activeDrag={kind:`resize`,anchor:e,box:h(n.flatMap(e=>e.points)),shapes:n.map(e=>({id:e.id,points:e.points}))},this.lastDragImg=null}),this.handleLayer.addChild(n),this.handleNodes.push(n)}if(t){let e=t,n=e.points,r=e.type===o.POLYGON?n.length:n.length-1,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=k(t.points),r=this.rotationHandleScreenPoint(t.points),i=new a.Graphics;i.circle(0,0,6).fill({color:16777215}).stroke({width:1.5,color:2001125}),i.position.set(r.x,r.y),i.eventMode=`static`,this.bindCursor(i,`grab`),i.on(`pointerdown`,e=>{e.stopPropagation();let r=this.toImage(e);this.activeDrag={kind:`rotate`,id:t.id,center:n,startAngle:Math.atan2(r.y-n.y,r.x-n.x),points:t.points,shiftKey:e.shiftKey},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`rotating`)}),this.handleLayer.addChild(i),this.rotNode=i}}beginMove(e,t){let n=wn(this.shapes,t,e);n&&(this.transformEnabled&&!this.handleNodes.length&&this.drawTransformer(),this.activeDrag=n,this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`moving`),(n.shapes.length===1?this.shapes.find(e=>e.id===n.shapes[0].id):null)?.type===o.ROTATED_RECTANGLE?this.setTransformerOutlinePoints(n.shapes[0].points):this.setTransformerOutline(n.box),this.updateSelectionBordersLive(e=>e.points))}repositionHandlesForBox(e){m.forEach((t,n)=>{let r=this.imgToScreen(g(t,e)),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,0)}),this.setTransformerOutline(e)}repositionOrientedHandles(e){let t=this.orientedHandleAngle(e);if(A(e).forEach((e,n)=>{let r=this.imgToScreen(e),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,t)}),this.setTransformerOutlinePoints(e),this.rotNode){let t=this.rotationHandleScreenPoint(e);this.rotNode.position.set(t.x,t.y)}this.rotLineNode&&this.setRotationConnector(e)}repositionPolygonHandles(e,t){if(!this.vertexNodes.length)return;e.forEach((e,t)=>{let n=this.imgToScreen(e);this.vertexNodes[t]?.position.set(n.x,n.y)});let n=t?e.length:e.length-1;for(let t=0;t<n;t++){let n=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=xn(this.shapes,t),{updates:r,box:i}=Sn(t,e,n);if(t.kind===`move`){let n=e.x-t.start.x,r=e.y-t.start.y;for(let e of t.shapes){let t=this.nodes.get(e.id);t&&(this.shapes.find(t=>t.id===e.id)?.type===o.POINT?t.position.set(e.points[0].x+n,e.points[0].y+r):t.position.set(n,r))}}else for(let e of r)this.liveUpdateShape(e.id,e.points);if(this.cb.onTransformPreview?.(r),this.updateSelectionBordersLive(e=>r.find(t=>t.id===e.id)?.points??e.points),t.kind===`resize`||t.kind===`move`){n?this.repositionOrientedHandles(r[0].points):i&&this.repositionHandlesForBox(i);let e=t.shapes.length===1?this.shapes.find(e=>e.id===t.shapes[0].id):null,a=e?.type===o.POLYGON||e?.type===o.LINE;(t.kind===`resize`?a:this.vertexNodes.length>0&&t.shapes.length===1)&&this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}else if(t.kind===`rotate`){this.repositionOrientedHandles(r[0].points);let e=this.shapes.find(e=>e.id===t.id);e&&(e.type===o.POLYGON||e.type===o.LINE)&&this.repositionPolygonHandles(r[0].points,e.type===o.POLYGON)}else{i&&this.repositionHandlesForBox(i);let e=this.shapes.find(e=>e.id===t.id);this.repositionPolygonHandles(r[0].points,e?.type===o.POLYGON)}}endTransform(){let e=this.activeDrag,t=this.lastDragImg;if(this.activeDrag=null,this.emitInteractionMode(`idle`),this.emitCursorHint(e?.kind===`move`?`grab`:null),!e||!t){this.cb.onTransformPreview?.([]),this.drawTransformer();return}if(e.kind===`move`&&t.x===e.start.x&&t.y===e.start.y){this.cb.onTransformPreview?.([]),this.drawTransformer();return}let{updates:n}=Sn(e,t,xn(this.shapes,e));e.kind===`move`&&this.resetMoveOffsets(),this.commitTransformUpdates(n)}};function Vn({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 Hn({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,maskCanvasRef:m,regionOverlayRef:h,dimmedRef:g,syncMinimap:_,setImage:v,setImageVisible:y,setReady:b,setImageStatus:x,onContextMenuRequest:S}){let C=(0,r.useRef)(a);C.current=a;let w=(0,r.useRef)(i);w.current=i;let T=(0,r.useRef)(null),E=(0,r.useRef)(null),D=(0,r.useRef)(!1),O=(0,r.useRef)(null),k=(0,r.useRef)(o);k.current=o;let A=(0,r.useRef)(S);A.current=S,(0,r.useEffect)(()=>{let r=t.current;if(!r)return;let i=!1,a=null,o=null,S=k.current(),j=e===`konva`?new In(r,S):new $(r,S);return n.current=j,(async()=>{try{await j.init()}catch(e){i||x(`error`,dn(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),D.current=!0,C.current){let e=C.current,t=w.current;x(`loading`);let n=null;try{n=await j.setImage(e,d.current,f.current)}catch(t){!i&&C.current===e&&x(`error`,dn(t))}if(i)return;if(n!==null){T.current=e,E.current=t,v({w:j.imageWidth,h:j.imageHeight}),y(!0),j.setShapes(u.current,p.current),j.setOverlays(s.current.showGuide?m.current:null,s.current.showRegionMask?h.current:null,g.current);let r=O.current;r?.viewport&&(r.imageUrl===T.current||s.current.keepZoomOnImageChange)?j.applyViewport(r.viewport):j.fit(),_(),b(!0);let a=()=>C.current===e;n?a()&&x(`ready`):cn(e).then(e=>{!i&&a()&&x(`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===B.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,D.current=!1,O.current={imageUrl:T.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||!D.current)return;let t=Vn({currentDocId:E.current,documentId:i,loadedUrl:T.current,renderedImageUrl:a});if(t.kind===`none`)return;let r=()=>{b(!1),y(!1),e.clearImage(),e.setShapes([],[]),e.setOverlays(null,null,!1)};if(t.kind===`clear`){T.current=null,E.current=null,r(),x(`loading`);return}let o=a;t.docChange&&(E.current=null,r());let c=!1;return(async()=>{x(`loading`);let r=!1;try{r=await e.setImage(o,d.current,f.current)}catch(t){!c&&n.current===e&&x(`error`,dn(t));return}if(c||n.current!==e)return;T.current=o;let a=()=>{if(r){x(`ready`);return}cn(o).then(e=>{c||x(`error`,e)})};if(!t.docChange){a();return}E.current=i,v({w:e.imageWidth,h:e.imageHeight}),y(!0),e.setShapes(u.current,p.current),e.setOverlays(s.current.showGuide?m.current:null,s.current.showRegionMask?h.current:null,g.current),s.current.keepZoomOnImageChange||e.fit(),_(),b(!0),a()})(),()=>{c=!0}},[i,a])}var Un=.05,Wn=20;function Gn(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 Kn(e){let t=e.currentTarget.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}function qn({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=Kn(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(Kn(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=Gn(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(Un,Math.min(Wn,s));p(Kn(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 Jn(e,t,n){if(!(!e||!n.length)){if(t.type===o.POINT){e.setAttribute(`cx`,String(n[0].x)),e.setAttribute(`cy`,String(n[0].y));return}if(t.type===o.RECTANGLE||t.type===o.ELLIPSE){let r=h(n);if(t.type===o.ELLIPSE){e.setAttribute(`cx`,String((r.minX+r.maxX)/2)),e.setAttribute(`cy`,String((r.minY+r.maxY)/2)),e.setAttribute(`rx`,String((r.maxX-r.minX)/2)),e.setAttribute(`ry`,String((r.maxY-r.minY)/2));return}e.setAttribute(`x`,String(r.minX)),e.setAttribute(`y`,String(r.minY)),e.setAttribute(`width`,String(r.maxX-r.minX)),e.setAttribute(`height`,String(r.maxY-r.minY));return}e.setAttribute(`points`,n.map(e=>`${e.x},${e.y}`).join(` `))}}function Yn({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)Jn(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&&Jn(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 Xn=12;function Zn({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),m=(0,r.useRef)(n),g=(0,r.useRef)(s),_=(0,r.useRef)(c);m.current=n,g.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,Be(Ie(e,s,c)))},[s,c,b]),C=(0,r.useCallback)(()=>He(c),[c]),w=(0,r.useCallback)(t=>{if(n)return;let r=s;Ue(c).then(n=>{if(!f.current||m.current||g.current!==r||_.current!==c||!n?.shapes.length)return;let a,o,l=n.shapes.flatMap(e=>e.points);if(t&&l.length){let e=h(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=We(d.current,e,Xn);a=t.offset,d.current=t.nextPasteCount,o=a}let u=n.shapes.map(e=>({...e,id:p(),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:p(),points:e.points.map(e=>({x:e.x+Xn,y:e.y+Xn}))}));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;let a=e.getShapes().filter(e=>t.current.includes(e.id)&&u(e));a.length&&e.update(a.map(e=>({...e,points:e.points.map(e=>({x:e.x+r,y:e.y+i}))})))},[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=Nt([],1,Mt(t));if(!r)return;let s=Pt(r,1);if(!s.length)return;let c=t[0],l=s.map(e=>({id:p(),type:o.POLYGON,points:e,style:c.style,meta:c.meta}));e.replace(t.map(e=>e.id),l),i(l.map(e=>e.id))},[e,n,k,a,i])}}function Qn({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=gt(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=ht(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=Z(h(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 $n=`__draft_preview__`,er=new Set([`copy`,`selectAll`,`clearSelection`,`zoomToSelection`]);function tr(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function nr({document:t,clipboardScope:i,renderImageState:a,dimmed:c=!1,selectedIds:d,activeTool:f,draftStyle:m,draftMeta:h,readOnly:g,disableMarquee:_,locked:v,onLockedInteraction:y,onIdleEscape:b,overrideShapeInteraction:x,defaultViewSettings:S,viewSettings:C,onViewSettingsChange:w,showMinimap:T=!0,minimapPosition:E=`bottom-left`,showViewSettings:D=!0,getContextMenuItems:O,strings:k,canMergeSelection:A,brushSize:j=20,zoomBound:M,zoomAnimationDuration:N=300,decorationShapes:P,regionMask:F,guideMask:I,maskPalette:L,overlayMarkers:R,renderOverlayMarker:z,onOverlayMarkerClick:te,renderImageOverlay:ne,getSelectionLabel:H,hideSelectionLabelDot:re,formatSelectionInfo:ie,externalTools:se,assistant:ce,keymap:le,handleRef:ue,backend:de=`pixi`,onActiveToolChange:G,onSelectionChange:fe,onEditingChange:pe,onShapesCreated:me,onShapesUpdated:he,onShapesDeleted:ge,onDrawSessionChange:_e,onDraftShapeChange:ve,onViewportChange:be,onShapesTransformPreview:xe}){let Se=(0,r.useRef)(null),K=(0,r.useRef)(null),Ce=(0,r.useRef)(null),De=(0,r.useRef)(null),ke=(0,r.useRef)(null),Ae=`${(0,r.useId)()}-minimap`,[q,je]=(0,r.useState)(null),[Me,Ne]=(0,r.useState)(!1),[Pe,Fe]=(0,r.useState)(!1),[Ie,Re]=(0,r.useState)(null),[ze,Be]=(0,r.useState)({active:!1,kind:`none`,canUndo:!1,canRedo:!1}),[Ve,He]=(0,r.useState)(!0),[Ue,We]=(0,r.useState)(!1),Ge=t?.id??``,Ke=t?.imageUrl??``,qe=t?.displayImageUrl,Je=t?.coordinateSize,Ye=t?.initialShapes,Ze=t?.initialSelectedIds,Qe=qe??Ke,[et,tt]=(0,r.useState)(`loading`),[nt,rt]=(0,r.useState)(null),it=(0,r.useCallback)((e,t)=>{tt(e),rt(e===`error`?t??null:null)},[]),J=Wt({onShapesCreated:me,onShapesUpdated:he,onShapesDeleted:ge}),[at,ot]=(0,r.useState)([]),Y=d??at,st=d!==void 0,ct=(0,r.useMemo)(()=>new Map((se??[]).map(e=>[e.id,e])),[se]),ut=(0,r.useRef)(ct);(0,r.useLayoutEffect)(()=>{ut.current=ct},[ct]);let dt=(0,r.useRef)(ze);dt.current=ze;let ft=(0,r.useMemo)(()=>{let e=Object.fromEntries(Object.entries(S??{}).filter(([,e])=>e!==void 0));return{...V,...e}},[S]),pt=(0,r.useRef)(ft);pt.current=ft;let[X,mt]=(0,r.useState)(()=>pt.current),ht=(0,r.useCallback)(e=>mt(t=>({...t,...e})),[]),Z=(0,r.useMemo)(()=>ee(k),[k]);(0,r.useEffect)(()=>{C&&mt(e=>{let t=Object.entries(C).filter(([t,n])=>n!==void 0&&e[t]!==n);return t.length?{...e,...Object.fromEntries(t)}:e})},[C]);let gt=(0,r.useRef)(w);gt.current=w;let yt=(0,r.useRef)(!1);(0,r.useEffect)(()=>{if(!yt.current){yt.current=!0;return}gt.current?.(X)},[X]);let bt=(0,r.useMemo)(()=>!I||!L?null:$e(I,L),[I,L]),xt=(0,r.useMemo)(()=>bt?.toDataURL()??null,[bt]),St=(0,r.useMemo)(()=>!q||!F?null:lt(F,q.w,q.h),[q,F]),Ct=(0,r.useRef)(bt);Ct.current=bt;let wt=(0,r.useRef)(St);wt.current=St;let Tt=(0,r.useRef)(c);Tt.current=c;let Et=(0,r.useRef)(q);Et.current=q;let Dt=(0,r.useRef)(Je);Dt.current=Je;let Ot=(0,r.useRef)(Je?.imageSize);Ot.current=Je?.imageSize;let kt=(0,r.useRef)(Y);(0,r.useLayoutEffect)(()=>{kt.current=Y},[Y]);let At=(0,r.useRef)(f);At.current=f;let jt=(0,r.useRef)(m);jt.current=m;let Mt=(0,r.useRef)(h);Mt.current=h;let Nt=(0,r.useRef)(j);Nt.current=j;let Pt=(0,r.useRef)(X.simplifyStrength);Pt.current=X.simplifyStrength;let Q=!!g||!!v,Ft=(0,r.useRef)(Q);Ft.current=Q;let It=(0,r.useRef)(_);It.current=_;let Lt=(0,r.useRef)(v);Lt.current=v;let Rt=(0,r.useRef)(y);Rt.current=y;let zt=(0,r.useRef)(x);zt.current=x;let Bt=(0,r.useRef)(J);Bt.current=J;let Ht=(0,r.useRef)(!1),Ut=(0,r.useRef)(!1),Gt=(0,r.useRef)(`idle`),Kt=(0,r.useRef)(null),qt=(0,r.useCallback)(()=>{let e=K.current;if(!e)return;let t=At.current,n=ut.current.get(t),r=dt.current;e.setCursor(Xe({tool:t,externalToolCursor:n?.cursor,isSpacePressed:Ht.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(Bt.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=zt.current?.(r);return l(i?{...r,interaction:{...r.interaction,...i}}:r)})},[]),Zt=(0,r.useCallback)(e=>{let t=Xt(e);tr(kt.current,t)||(st||ot(t),K.current?.setSelection(t),fe?.(t))},[Xt,fe,st]),Qt=(0,r.useRef)(Zt);Qt.current=Zt;let[$t,tn]=(0,r.useState)(null),nn=(0,r.useCallback)(e=>tn(e),[]),rn=(0,r.useRef)(nn);rn.current=nn;let an=(0,r.useRef)(null);an.current=$t,(0,r.useEffect)(()=>{if(!st)return;let e=Xt(d);tr(d,e)||fe?.(e)},[d,J.shapes,Xt,fe,st]);let on=(0,r.useRef)(be);on.current=be;let{registerMinimapShape:sn,applyMinimapPreview:cn,syncMinimap:ln}=Yn({engineRef:K,docRef:Bt,overlayRef:De,zoomLabelRef:ke,minimapRectRef:Ce,minimapSize:204,onViewportChangeRef:on}),un=(0,r.useRef)(new Map),dn=(0,r.useRef)(ie);dn.current=ie;let fn=(0,r.useCallback)((e,t)=>{t?un.current.set(e,t):un.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(Bt.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=un.current.get(n),i=t.get(n);if(!e||!i)continue;let a=we(e,r);if(a){let e=Te(i,r);a.textContent=dn.current?.(e)??Ee(e)}}},[]),_n=(0,r.useCallback)(e=>{cn(e),gn(e),xe?.(e)},[cn,gn,xe]),vn=(0,r.useCallback)(e=>{if(ve?.(e?{...e,meta:Mt.current}:null),!e||!jt.current){pn.current&&(pn.current=null,hn(null));return}let t={id:$n,type:e.type,points:e.points,style:jt.current,meta:Mt.current},n=pn.current!==null;pn.current=t,n?gn([{id:$n,points:e.points}]):hn(t)},[gn,ve]),yn=(0,r.useCallback)((e,t)=>{let n=jt.current;if(!n||Ft.current)return;let r=p();Bt.current.create({id:r,type:e,points:t,style:n,meta:h}),Qt.current([r])},[h]),bn=(0,r.useRef)(yn);bn.current=yn;let xn=Vt({toolRef:At,selRef:kt,docRef:Bt,readOnlyRef:Ft,draftRef:jt,brushSizeRef:Nt,simplifyEpsilonRef:Pt,draftMeta:h,engineRef:K,onDrawSessionChange:(0,r.useCallback)(e=>{Be(e),_e?.(e)},[_e]),onDraftShapeChange:ve,changeSelection:Zt,createShape:yn}),Sn=(0,r.useRef)(xn);Sn.current=xn;let{reset:Cn,undoSession:wn,redoSession:Tn,canUndoSession:En,canRedoSession:Dn,hasDraftSession:On,hasDraftPoints:kn,commitDraftSession:An,setBrushScalarMode:jn,getBrushScalarMode:Mn,hasBrushSession:Nn,commitBrush:Pn,cancelBrush:Fn,beginBrushEditFromSelection:In,deleteDraftSelectedPoints:Ln,handleToolChange:Rn,handleBrushSelectionChange:zn}=xn,Bn=(0,r.useRef)(ce);Bn.current=ce;let $=vt({docRef:Bt,draftRef:jt,draftMeta:h,changeSelection:Zt,assistantRef:Bn}),Vn=(0,r.useRef)($);Vn.current=$;let Un=(0,r.useMemo)(()=>Le(Ge),[Ge]),{selectAll:Wn,clearSelection:Gn,deleteSelection:Kn,copySelection:Jn,canPaste:Xn,paste:nr,duplicate:rr,bringToFront:ir,sendToBack:ar,nudgeSelection:or,getMergeTargets:sr,mergeSelection:cr}=Zn({doc:J,selRef:kt,effectiveReadOnly:Q,changeSelection:Zt,canMergeSelection:A,clipboardDocumentId:Un,clipboardScope:i??Un}),{zoomToBounds:lr,zoomToShapes:ur,zoomToSelection:dr,zoomAtCenter:fr}=Qn({engineRef:K,doc:J,selRef:kt,zoomAnimationDuration:N,zoomBound:M,ready:Pe});(0,r.useImperativeHandle)(ue,()=>({previewRegionMask:e=>{let t=Et.current;if(!t)return;let n=e?lt(e,t.w,t.h):wt.current;K.current?.setRegionOverlay(pr.current.showRegionMask?n:null)},undo:()=>{wn()||J.undo()},redo:()=>{Tn()||J.redo()},canUndo:()=>En()||J.canUndo(),canRedo:()=>Dn()||J.canRedo(),undoSession:wn,redoSession:Tn,canUndoSession:En,canRedoSession:Dn,hasDraftSession:On,cancelDraftSession:Cn,commitDraftSession:An,setSelection:Zt,createShapes:e=>{e.length&&(J.create(e),Zt(e.map(e=>e.id)))},updateShapes:J.update,deleteShapes:J.remove,getShapes:J.getShapes,selectAll:Wn,clearSelection:Gn,deleteSelection:Kn,copySelection:Jn,paste:nr,duplicate:rr,bringToFront:ir,sendToBack:ar,zoomFit:()=>K.current?.fit(),zoom100:()=>K.current?.zoom100(),zoomIn:()=>{let e=K.current;if(!e)return;let{w:t,h:n}=e.screenSize;e.zoomAt(t/2,n/2,1.2)},zoomOut:()=>{let e=K.current;if(!e)return;let{w:t,h:n}=e.screenSize;e.zoomAt(t/2,n/2,1/1.2)},zoomToSelection:dr,zoomToShapes:ur,zoomToBounds:lr,brush:{setScalarMode:jn,getScalarMode:Mn,hasSession:Nn,commit:Pn,cancel:Fn,beginEditFromSelection:In}}),[J,Zt,wn,Tn,An,Cn,Pn,Fn,Wn,Gn,Kn,Jn,nr,rr,ir,ar,dr,ur,lr,jn,Mn,Nn,In]);let pr=(0,r.useRef)(X);pr.current=X;let mr=(0,r.useCallback)(()=>_t({engineRef:K,toolRef:At,externalToolMapRef:ut,spaceRef:Ht,shiftRef:Ut,docRef:Bt,selRef:kt,draftRef:jt,readOnlyRef:Ft,disableMarqueeRef:It,lockedRef:Lt,onLockedInteraction:()=>Rt.current?.(),createRef:bn,selectRef:Qt,enterEditRef:rn,editingIdRef:an,drawSessionRef:Sn,assistantRef:Vn,setCursorHint:Yt,setInteractionMode:Jt,syncMinimap:ln,onTransformPreview:_n,onDrawPreview:vn}),[Yt,Jt,ln,_n,vn]),hr=(0,r.useRef)([]);Hn({backend:de,hostRef:Se,engineRef:K,documentId:Ge,renderedImageUrl:Qe,makeCallbacks:mr,viewRef:pr,readOnlyRef:Ft,toolRef:At,renderShapesRef:hr,coordinateSizeRef:Dt,imageSizeRef:Ot,selRef:kt,maskCanvasRef:Ct,regionOverlayRef:wt,dimmedRef:Tt,syncMinimap:ln,setImage:je,setImageVisible:Ne,setReady:Fe,setImageStatus:it,onContextMenuRequest:Re});let gr=(0,r.useMemo)(()=>{let e=x?J.shapes.map(e=>{let t=x(e);return t?{...e,interaction:{...e.interaction,...t}}:e}):J.shapes;return P?.length?[...P.map(e=>({...e,interaction:{...e.interaction,selectable:!1,draggable:!1,editable:!1,hitTestDisabled:!0}})),...e]:e},[J.shapes,x,P]);hr.current=gr,(0,r.useEffect)(()=>{K.current?.setShapes(gr,kt.current),ln()},[gr,ln]),(0,r.useEffect)(()=>{K.current?.setSelection(Y)},[Y]),(0,r.useEffect)(()=>{K.current?.setEditing($t)},[$t,Pe]);let _r=(0,r.useRef)(pe);_r.current=pe,(0,r.useEffect)(()=>{_r.current?.($t)},[$t]),(0,r.useEffect)(()=>{tn(null)},[f]),(0,r.useEffect)(()=>{$t&&(Y.length!==1||Y[0]!==$t)&&tn(null)},[Y,$t]),(0,r.useEffect)(()=>{let e=K.current;e&&(e.setFilter(X.brightness,X.contrast),e.setRenderDefaults({strokeWidth:X.strokeSize}),e.setImageSmoothing(X.imageSmoothing),ln())},[X.brightness,X.contrast,X.strokeSize,X.imageSmoothing,ln]),(0,r.useLayoutEffect)(()=>{Pe&&K.current?.setOverlays(X.showGuide?bt:null,X.showRegionMask?St:null,c)},[Pe,bt,St,X.showGuide,X.showRegionMask,c]),(0,r.useEffect)(()=>{!Pe||!q||ln()},[Pe,q,xt,X.showGuide,X.showRegionMask,F,ln]),(0,r.useEffect)(()=>{Pe&&K.current?.setTransformEnabled(!Q&&f!==B.BRUSH)},[Q,Pe,f]),(0,r.useEffect)(()=>{Rn(f,ut.current.has(f))},[f,Rn]);let vr=$.finalize;(0,r.useEffect)(()=>{vr()},[f,vr]),(0,r.useEffect)(()=>{Gt.current=`idle`,Kt.current=null,qt()},[f,de,qt]),(0,r.useEffect)(()=>{zn(Y,Q)},[Y,f,Q,zn]),(0,r.useEffect)(()=>{Pe&&qt()},[f,ze,ct,Pe,qt]);let yr=(0,r.useRef)(Ze);yr.current=Ze;let br=t!==null,xr=(0,r.useRef)(null);(0,r.useEffect)(()=>{let e=br?Ge:null;xr.current!==e&&(xr.current=e,Re(null),tn(null),Gt.current=`idle`,Kt.current=null,J.reset(br?Ye??[]:[]),Zt(br?yr.current??[]:[]),Cn(),vr(),qt())},[br,Ge,Ye,J.reset,Zt,Cn,vr,qt]);let Sr=(0,r.useCallback)(()=>{let e=an.current;if(!e||Q)return!1;let t=K.current,n=new Set(t?.getVertexSelection()??[]);if(!n.size)return!1;let r=Bt.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:(Bt.current.update([{...r,points:i}]),t?.setVertexSelection([]),!0)},[Q]);en({keymap:le,hostRef:Se,actions:{undo:()=>{Q||wn()||J.undo()},redo:()=>{Q||Tn()||J.redo()},selectAll:Wn,copy:Jn,cut:()=>{Jn(),Kn()},paste:nr,duplicate:rr,delete:()=>{kn()&&Ln()||Sr()||Kn()},cancel:()=>{let e=ut.current.get(At.current);if(!(e?.onCancel&&e.onCancel()!==!1)){if($.isActive()){$.cancel();return}if(On()){Cn();return}if($t){tn(null);return}if(kt.current.length){Gn();return}b?.()}},commitDraft:()=>{if($.isActive()){$.finalize();return}if(On()){An();return}if(Q)return;if($t){tn(null);return}let e=kt.current;if(e.length!==1)return;let t=Bt.current.getShapes().find(t=>t.id===e[0]);t&&(t.type===o.POLYGON||t.type===o.LINE)&&t.interaction?.editable!==!1&&!t.readOnly&&tn(e[0])},bringToFront:ir,sendToBack:ar,zoomIn:()=>fr(1.2),zoomOut:()=>fr(1/1.2),zoom100:()=>K.current?.zoom100(),zoomFit:()=>K.current?.fit(),toggleMinimap:()=>He(e=>!e),toggleCursorGuide:()=>mt(e=>({...e,showCursorGuide:!e.showCursorGuide})),togglePixelation:()=>mt(e=>({...e,imageSmoothing:!e.imageSmoothing})),selectTool:()=>G?.(B.SELECT),rectangleTool:()=>G?.(B.RECTANGLE),rotatedRectangleTool:()=>G?.(B.ROTATED_RECTANGLE),circleTool:()=>G?.(B.CIRCLE),polygonTool:()=>G?.(B.POLYGON),pathTool:()=>G?.(B.PATH),brushTool:()=>G?.(B.BRUSH),pointTool:()=>G?.(B.POINT)},spaceRef:Ht,shiftRef:Ut,onSpaceDown:()=>{K.current?.setPanMode(!0),qt()},onSpaceUp:()=>{K.current?.setPanMode(!1),Gt.current===`panning`?Jt(`idle`):qt()},nudge:or});let Cr=(0,r.useMemo)(()=>gr.filter(e=>Y.includes(e.id)&&s(e)),[gr,Y]),wr=(0,r.useMemo)(()=>mn?[...Cr,mn]:Cr,[Cr,mn]),Tr=Y.length>0,Er=J.shapes.some(e=>Y.includes(e.id)&&u(e)),Dr=!Q&&Y.length===1&&(()=>{let e=J.shapes.find(e=>e.id===Y[0]);return!!e&&(e.type===o.POLYGON||e.type===o.LINE)&&e.interaction?.editable!==!1&&!e.readOnly})(),Or=sr(),kr=Q||Or.length<2||(A?!A(Or):!1),Ar=!!ce&&!Q,jr=Ar&&Y.length===1?(()=>{let e=J.shapes.find(e=>e.id===Y[0]);return e&&e.type===o.POLYGON&&e.interaction?.editable!==!1&&!e.readOnly?e:null})():null,Mr=[{id:`copy`,label:Z.contextMenu.copy,shortcut:`⌘C`,disabled:!Er,onClick:Jn},{id:`paste`,label:Z.contextMenu.paste,shortcut:`⌘V`,disabled:Q||!Xn(),onClick:()=>nr(Ie?.img)},{id:`duplicate`,label:Z.contextMenu.duplicate,shortcut:`⌘D`,disabled:!Er||Q,onClick:rr},{id:`delete`,label:Z.contextMenu.delete,shortcut:`Del`,danger:!0,disabled:!Er||Q,onClick:Kn},{separator:!0},{id:`editVertices`,label:Z.contextMenu.editVertices,shortcut:`Enter`,disabled:!Dr,onClick:()=>tn(Y[0])},{id:`merge`,label:Z.contextMenu.merge,disabled:kr,onClick:cr},...Ar?[{id:`assistExpand`,label:Z.contextMenu.assistExpand,icon:(0,n.jsx)(e.er,{size:14}),disabled:!jr,onClick:()=>{Ie&&jr&&$.refineShape(jr,Ie.img,!0)}},{id:`assistExclude`,label:Z.contextMenu.assistExclude,icon:(0,n.jsx)(e.er,{size:14}),disabled:!jr,onClick:()=>{Ie&&jr&&$.refineShape(jr,Ie.img,!1)}}]:[],{id:`bringToFront`,label:Z.contextMenu.bringToFront,disabled:!Er||Q,onClick:ir},{id:`sendToBack`,label:Z.contextMenu.sendToBack,disabled:!Er||Q,onClick:ar},{separator:!0},{id:`undo`,label:Z.contextMenu.undo,shortcut:`⌘Z`,disabled:Q||!En()&&!J.canUndo(),onClick:()=>{wn()||J.undo()}},{id:`redo`,label:Z.contextMenu.redo,shortcut:`⇧⌘Z`,disabled:Q||!Dn()&&!J.canRedo(),onClick:()=>{Tn()||J.redo()}},{separator:!0},{id:`selectAll`,label:Z.contextMenu.selectAll,shortcut:`⌘A`,onClick:Wn},{id:`clearSelection`,label:Z.contextMenu.clearSelection,disabled:!Tr,onClick:Gn},{id:`zoomToSelection`,label:Z.contextMenu.zoomToSelection,disabled:!Tr,onClick:dr}],Nr=g?Mr.filter(e=>`separator`in e||!!e.id&&er.has(e.id)):Mr,Pr=O?O(Nr,{selectedIds:Y,readOnly:Q}):Nr,Fr=qn({engineRef:K,image:q,wheelZoom:X.wheelZoom,minimapSize:204}),Ir=(0,r.useCallback)(()=>{K.current?.zoom100()},[]),Lr=(0,r.useCallback)(()=>{He(e=>!e)},[]),Rr=(0,r.useCallback)(()=>{We(e=>!e)},[]),zr=(0,r.useCallback)(()=>{We(!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:Se,className:`aivex:h-full aivex:w-full`,style:{opacity:+!!Me,transition:Me?`opacity 0.3s ease`:`none`}}),et!==`ready`&&(0,n.jsx)(oe,{status:et,error:nt,render:a,loadingLabel:Z.imageLoading,errorLabel:Z.imageLoadError,errorHints:Z.imageErrorHints}),Pe&&q&&(0,n.jsx)(`div`,{className:`aivex:pointer-events-none aivex:absolute aivex:inset-0 aivex:overflow-hidden`,children:(0,n.jsxs)(`div`,{ref:De,style:{position:`absolute`,top:0,left:0,width:q.w,height:q.h,transformOrigin:`0 0`},children:[!!R?.length&&z&&(0,n.jsx)(`div`,{style:{position:`absolute`,left:0,top:0,width:q.w,height:q.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,onPointerDown:e=>e.stopPropagation(),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:z(e)},e.id))}),ne?.({image:q,viewport:K.current?.viewport??{scale:1,x:0,y:0}}),wr.length>0&&(0,n.jsx)(Oe,{shapes:wr,getLabel:H,hideDot:re,formatInfo:ie,register:fn}),ce&&($.status===`loading`||$.boxes.length>0)&&(0,n.jsx)(U,{image:q,points:$.points,boxes:$.boxes,status:$.status})]})}),Pe&&X.showCursorGuide&&(0,n.jsx)(W,{color:`#1e88e5`}),q&&T&&(0,n.jsx)(ye,{image:q,imageUrl:Qe,imageVisible:Me,loading:!Pe,maskDataUrl:xt,region:St,roiMaskId:Ae,shapes:gr,view:X,viewDefaults:ft,onChangeView:ht,nav:Fr,registerShape:sn,rectRef:Ce,zoomLabelRef:ke,onZoom100:Ir,open:Ve,onToggleOpen:Lr,position:E,labels:Z.minimap,settingsLabels:Z.viewSettings,showSettings:D,settingsOpen:Ue,onToggleSettings:Rr,onCloseSettings:zr}),Ie&&(0,n.jsx)(ae,{x:Ie.x,y:Ie.y,items:Pr,onClose:()=>Re(null)})]})}function rr(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 ir(e,t,n,r){if(t.interaction?.visible===!1)return;let i=G(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 rr(e,t.points,t.type!==o.LINE);i.fillVisible&&(e.save(),e.fillStyle=i.color,e.globalAlpha*=i.fillAlpha,e.fill(),e.restore()),t.style?.alternateColor&&i.dash?.length&&(e.setLineDash([]),e.strokeStyle=t.style.alternateColor,e.stroke()),e.setLineDash((i.dash??[]).map(e=>e/n)),e.strokeStyle=i.color,e.stroke(),e.restore()}function ar({imageUrl:e,alt:t=`Shape preview`,coordinateSize:i,shapes:a=[],regionMask:o,guideMask:s,maskPalette:c,focusedShapeId:l,focusFit:u=`contain`,zoomPadding:d=.3,strokeSize:p=1,brightness:m=1,contrast:g=1,imageSmoothing:_=!0,lazy:v=!0,className:y,style:b,renderImageState:x}){let S=(0,r.useRef)(null),C=(0,r.useRef)(null),w=(0,r.useRef)(null),[T,E]=(0,r.useState)(!v),[D,O]=(0,r.useState)(`loading`),[k,A]=(0,r.useState)(null),[j,M]=(0,r.useState)(0);(0,r.useEffect)(()=>{if(!v||T)return;let e=S.current;if(!e)return;let t=new IntersectionObserver(([e])=>{e.isIntersecting&&(E(!0),t.disconnect())});return t.observe(e),()=>t.disconnect()},[v,T]),(0,r.useEffect)(()=>{let e=S.current;if(!e)return;let t=new ResizeObserver(()=>M(e=>e+1));return t.observe(e),()=>t.disconnect()},[]),(0,r.useEffect)(()=>{if(!T||!e){O(e?`loading`:`error`),A(null);return}let t=!0;return O(`loading`),A(null),nn(e).then(async n=>{if(!t)return;if(n){w.current=n,O(`ready`);return}w.current=null,O(`error`);let r=await cn(e);t&&A(r)}),()=>{t=!1}},[e,T]),(0,r.useEffect)(()=>()=>{w.current=null},[]);let N=(0,r.useMemo)(()=>a.find(e=>e.id===l),[l,a]),P=(0,r.useMemo)(()=>s&&c?$e(s,c):null,[s,c]);return(0,r.useEffect)(()=>{if(D===`error`){let e=C.current;e?.getContext(`2d`)?.clearRect(0,0,e.width,e.height)}if(D!==`ready`)return;let e=S.current,t=C.current,n=w.current;if(!e||!t||!n)return;let{width:r,height:s}=e.getBoundingClientRect();if(!r||!s)return;let c=window.devicePixelRatio||1;t.width=Math.max(1,Math.round(r*c)),t.height=Math.max(1,Math.round(s*c)),t.style.width=`${r}px`,t.style.height=`${s}px`;let l=t.getContext(`2d`);if(!l)return;let v=i?.width??n.naturalWidth,y=i?.height??n.naturalHeight;if(!v||!y)return;let b=Math.min(r/v,s/y),x=(r-v*b)/2,T=(s-y*b)/2;if(N&&N.points.length>0){let e=h(N.points),t=Math.max(e.maxX-e.minX,50),n=Math.max(e.maxY-e.minY,50),i=Math.min(t,n)*d;b=Math.min(r/(t+i*2),s/(n+i*2)),u===`cover`&&(b=Math.max(b,Math.max(r/v,s/y))),x=r/2-(e.minX+e.maxX)/2*b,T=s/2-(e.minY+e.maxY)/2*b,u===`cover`&&(x=Math.min(0,Math.max(x,r-v*b)),T=Math.min(0,Math.max(T,s-y*b)))}l.setTransform(c,0,0,c,0,0),l.clearRect(0,0,r,s),l.save(),l.translate(x,T),l.scale(b,b),l.imageSmoothingEnabled=_,l.filter=`brightness(${m}) contrast(${g})`,l.drawImage(n,0,0,v,y),l.filter=`none`,P&&(l.save(),l.globalAlpha=.55,l.drawImage(P,0,0,v,y),l.restore());let E=o?lt(o,v,y):null;if(E&&(at(l,E,v,y),E.outlineStyles)){let e=(e,t)=>{if(l.lineWidth=t.width/b,t.underlayColor){l.setLineDash([]),l.strokeStyle=t.underlayColor;for(let[t,n]of e)rr(l,[t,n],!1),l.stroke()}l.save(),l.globalAlpha*=t.opacity,l.setLineDash(t.dash.map(e=>e/b)),l.strokeStyle=t.color;for(let[t,n]of e)rr(l,[t,n],!1),l.stroke();l.restore()};e(E.visibleOutline,E.outlineStyles.visible),e(E.occludedOutline,E.outlineStyles.occluded)}for(let e of f(a))ir(l,e,b,p);l.restore()},[m,g,i,N,u,_,P,o,a,j,D,p,d]),(0,n.jsxs)(`div`,{ref:S,className:y,style:{position:`relative`,width:`100%`,height:`100%`,...b},children:[(0,n.jsx)(`canvas`,{ref:C,role:`img`,"aria-label":t,style:{display:`block`}}),D!==`ready`&&(0,n.jsx)(`div`,{style:{position:`absolute`,inset:0},children:x?.(D===`error`?`error`:`loading`,k)??(D===`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:z.imageLoadError}),k&&(0,n.jsx)(`span`,{style:{fontSize:11,opacity:.7,wordBreak:`break-all`},children:z.imageErrorHints[k.kind]})]}):null)})]})}exports.DEFAULT_EDITOR_STRINGS=z,exports.DEFAULT_VIEW_SETTINGS=V,exports.SHAPE_TYPE=o,exports.ShapeEditor=nr,exports.default=nr,exports.ShapeViewer=ar,exports.TOOL=B,exports.generateId=p;
|
|
2
2
|
//# sourceMappingURL=shape-editor.cjs.map
|