@aivex/ui 1.1.0 → 1.2.0-dev.2
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/Switch-DX-FkCbT.cjs +42 -0
- package/dist/Switch-DX-FkCbT.cjs.map +1 -0
- package/dist/Switch-c8rHebeK.js +11243 -0
- package/dist/Switch-c8rHebeK.js.map +1 -0
- package/dist/components/Badge/Badge.d.ts +2 -2
- package/dist/components/Chips/index.d.ts +19 -2
- package/dist/components/DatePicker/Calendar.d.ts +27 -0
- package/dist/components/DatePicker/DatePicker.d.ts +119 -0
- package/dist/components/DatePicker/date.d.ts +24 -0
- package/dist/components/DatePicker/index.d.ts +4 -0
- package/dist/components/Icon/index.d.ts +5 -4
- package/dist/components/Messagebox/Messagebox.d.ts +3 -1
- package/dist/components/Popover/Popover.d.ts +47 -0
- package/dist/components/Popover/index.d.ts +2 -0
- package/dist/components/ShapeEditor/ShapeEditor.d.ts +9 -0
- package/dist/components/ShapeEditor/_components/AssistantOverlay.d.ts +17 -0
- package/dist/components/ShapeEditor/_components/ContextMenu.d.ts +13 -0
- package/dist/components/ShapeEditor/_components/CursorGuide.d.ts +8 -0
- package/dist/components/ShapeEditor/_components/ImageStateOverlay.d.ts +11 -0
- package/dist/components/ShapeEditor/_components/Minimap.d.ts +45 -0
- package/dist/components/ShapeEditor/_components/MinimapShape.d.ts +6 -0
- package/dist/components/ShapeEditor/_components/RoiOverlay.d.ts +21 -0
- package/dist/components/ShapeEditor/_components/SelectionInfo.d.ts +12 -0
- package/dist/components/ShapeEditor/_components/SettingsPanel.d.ts +15 -0
- package/dist/components/ShapeEditor/_constants.d.ts +33 -0
- package/dist/components/ShapeEditor/_model/brush.d.ts +3 -0
- package/dist/components/ShapeEditor/_model/cursors.d.ts +18 -0
- package/dist/components/ShapeEditor/_model/geometry.d.ts +128 -0
- package/dist/components/ShapeEditor/_model/imageTiles.d.ts +11 -0
- package/dist/components/ShapeEditor/_model/keymap.d.ts +15 -0
- package/dist/components/ShapeEditor/_model/konva.d.ts +4 -0
- package/dist/components/ShapeEditor/_model/overlays.d.ts +55 -0
- package/dist/components/ShapeEditor/_model/pinIcon.d.ts +13 -0
- package/dist/components/ShapeEditor/_model/props.d.ts +398 -0
- package/dist/components/ShapeEditor/_model/scalarMask.d.ts +21 -0
- package/dist/components/ShapeEditor/_model/shapeRenderStyle.d.ts +16 -0
- package/dist/components/ShapeEditor/_model/strings.d.ts +55 -0
- package/dist/components/ShapeEditor/_model/tools.d.ts +27 -0
- package/dist/components/ShapeEditor/_model/viewSettings.d.ts +15 -0
- package/dist/components/ShapeEditor/_model/viewport.d.ts +28 -0
- package/dist/components/ShapeEditor/_renderers/KonvaRenderer.d.ts +114 -0
- package/dist/components/ShapeEditor/_renderers/PixiRenderer.d.ts +159 -0
- package/dist/components/ShapeEditor/_renderers/transformSession.d.ts +63 -0
- package/dist/components/ShapeEditor/_renderers/types.d.ts +94 -0
- package/dist/components/ShapeEditor/_state/createInteractionController.d.ts +52 -0
- package/dist/components/ShapeEditor/_state/drawSessionState.d.ts +6 -0
- package/dist/components/ShapeEditor/_state/useAssistant.d.ts +48 -0
- package/dist/components/ShapeEditor/_state/useDrawSession.d.ts +60 -0
- package/dist/components/ShapeEditor/_state/useEditorDocument.d.ts +23 -0
- package/dist/components/ShapeEditor/_state/useEditorHotkeys.d.ts +23 -0
- package/dist/components/ShapeEditor/_state/useEngineLifecycle.d.ts +48 -0
- package/dist/components/ShapeEditor/_state/useMinimapNavigation.d.ts +27 -0
- package/dist/components/ShapeEditor/_state/useMinimapSync.d.ts +24 -0
- package/dist/components/ShapeEditor/_state/useSelectionActions.d.ts +29 -0
- package/dist/components/ShapeEditor/_state/useViewportControls.d.ts +23 -0
- package/dist/components/ShapeEditor/index.d.ts +6 -0
- package/dist/components/ToggleButton/ToggleButton.d.ts +17 -0
- package/dist/components/ToggleButton/index.d.ts +2 -0
- package/dist/index.cjs +6 -46
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.js +4541 -15017
- package/dist/index.js.map +1 -1
- package/dist/shape-editor.cjs +2 -0
- package/dist/shape-editor.cjs.map +1 -0
- package/dist/shape-editor.js +5271 -0
- package/dist/shape-editor.js.map +1 -0
- package/dist/styles.css +1 -1
- package/package.json +8 -1
- package/dist/components/Chips/Chips.d.ts +0 -17
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";require(`./styles.css`),Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require(`./Switch-DX-FkCbT.cjs`);let t=require(`react`),n=require(`react/jsx-runtime`),r=require(`konva`);r=e.oo(r,1);let i=require(`pixi.js`);var a={POINT:`POINT`,RECTANGLE:`RECTANGLE`,ROTATED_RECTANGLE:`ROTATED_RECTANGLE`,POLYGON:`POLYGON`,ELLIPSE:`ELLIPSE`,LINE:`LINE`};function o(e){return e.interaction?.visible!==!1}function s(e){return o(e)&&e.interaction?.hitTestDisabled!==!0}function c(e){return s(e)&&e.interaction?.selectable!==!1}function l(e){return c(e)&&!e.readOnly&&e.interaction?.editable!==!1}function u(e){return l(e)&&e.interaction?.draggable!==!1}function d(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 f(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`id_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`}var p=[`tl`,`t`,`tr`,`r`,`br`,`b`,`bl`,`l`];function m(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 h(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 g(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 _(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 v(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 y(e){let t=m(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 b(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 x(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 S(e){let t=x(e);if(t.length<3)return y(e);let n=1/0,r=y(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 C=(e,t)=>({x:e.x-t.x,y:e.y-t.y}),w=(e,t)=>e.x*t.x+e.y*t.y,T=e=>Math.hypot(e.x,e.y),E=e=>{let t=T(e)||1;return{x:e.x/t,y:e.y/t}},D=(e,t)=>({x:(e.x+t.x)/2,y:(e.y+t.y)/2}),O=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 k(e){return[e[0],D(e[0],e[1]),e[1],D(e[1],e[2]),e[2],D(e[2],e[3]),e[3],D(e[3],e[0])]}function A(e,t){let n=D(e[0],e[1]),r=E(C(e[0],e[3]));return{x:n.x+r.x*t,y:n.y+r.y*t}}function ee(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 j(e,t,n){if(e.length<4)return e;let r=e[0],i=E(C(e[1],e[0])),a=E(C(e[3],e[0])),o=w(C(e[1],r),i),s=w(C(e[3],r),a),c=C(n,r);return ee(g(t,{minX:0,minY:0,maxX:o,maxY:s},w(c,i),w(c,a)),r,i,a)}function M(e,t,n){let r=t.maxX-t.minX||1,i=t.maxY-t.minY||1,a=n.maxX-n.minX,o=n.maxY-n.minY;return e.map(e=>({x:n.minX+(e.x-t.minX)/r*a,y:n.minY+(e.y-t.minY)/i*o}))}var N={contextMenu:{copy:`복사`,paste:`붙여넣기`,duplicate:`복제`,delete:`삭제`,bringToFront:`맨 앞으로`,sendToBack:`맨 뒤로`,flipHorizontal:`좌우 반전`,flipVertical:`상하 반전`,editVertices:`정점 편집`,merge:`레이블 합치기`,assistExpand:`이 지점 포함하기`,assistExclude:`이 지점 제외하기`,undo:`실행 취소`,redo:`다시 실행`,zoomToSelection:`선택 영역으로 확대`,selectAll:`전체 선택`,clearSelection:`선택 해제`},viewSettings:{title:`보기 설정`,reset:`보기설정 초기화`,brightness:`밝기`,contrast:`대비`,strokeSize:`선 두께`,simplifyStrength:`단순화 강도`,pixelation:`이미지 픽셀화`,cursorGuide:`커서 가이드라인`,guideMask:`가이드 마스크`,roi:`ROI 표시`,keepZoomOnImageChange:`이미지 변경 시 줌 유지`,wheelZoom:`스크롤로 확대·축소`},minimap:{zoomIn:`확대`,zoomOut:`축소`,zoom100:`100%로 초기화`,viewSettings:`보기 설정`,toggleMinimap:`미니맵 접기/펼치기`},imageLoading:`이미지를 불러오는 중…`,imageLoadError:`이미지를 불러올 수 없습니다`};function P(e){return e?{contextMenu:{...N.contextMenu,...e.contextMenu},viewSettings:{...N.viewSettings,...e.viewSettings},minimap:{...N.minimap,...e.minimap},imageLoading:e.imageLoading??N.imageLoading,imageLoadError:e.imageLoadError??N.imageLoadError}:N}var F={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`},I={brightness:1,contrast:1,showCursorGuide:!1,imageSmoothing:!0,strokeSize:2,simplifyStrength:1.5,showGuide:!0,showRoi:!0,keepZoomOnImageChange:!1,wheelZoom:!0},te=`var(--editor-overlay-inverse-scale, 1)`,ne=`#377be2`,L=`#e23c3c`;function R({point:e}){let t=e.positive?ne:L;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 z({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)(R,{point:e},`pt-${t}-${e.x}-${e.y}`))]})}function re({x:t,y:r,items:i,onClose:a}){return(0,n.jsxs)(e._,{open:!0,modal:!1,onOpenChange:e=>{e||a()},children:[(0,n.jsx)(e._.Trigger,{asChild:!0,children:(0,n.jsx)(`span`,{"aria-hidden":!0,style:{position:`absolute`,left:t,top:r,width:0,height:0}})}),(0,n.jsx)(e._.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:i.map((t,r)=>`separator`in t?(0,n.jsx)(e._.Separator,{className:`aivex:shrink-0`},`sep-${r}`):(0,n.jsx)(e._.Item,{danger:t.danger,disabled:t.disabled,className:`aivex:shrink-0`,onSelect:()=>t.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:[t.icon,(0,n.jsx)(`span`,{className:`aivex:truncate`,children:t.label})]}),t.shortcut&&(0,n.jsx)(e._.Shortcut,{children:t.shortcut})]})},t.label))})]})}function ie({color:e=`#1e88e5`}){let r=(0,t.useRef)(null),i=(0,t.useRef)(null),a=(0,t.useRef)(null);return(0,t.useEffect)(()=>{let e=r.current,t=i.current,n=a.current;if(!e||!t||!n)return;let o=r=>{let i=e.getBoundingClientRect(),a=r.clientX-i.left,o=r.clientY-i.top;if(a<0||o<0||a>i.width||o>i.height){t.style.display=`none`,n.style.display=`none`;return}t.style.display=`block`,n.style.display=`block`,t.style.transform=`translateX(${a}px)`,n.style.transform=`translateY(${o}px)`},s=()=>{t.style.display=`none`,n.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:r,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 B({status:e,render:t,loadingLabel:r=N.imageLoading,errorLabel:i=N.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 ae=`#669DEF`,oe=.1,se=`#ffffff`,ce=[6,6],le=.7,ue=2.5;function V(e,t={}){let n=e.style?.color??`#00e5ff`,r=!!e.readOnly,i=e.style?.strokeWidth??t.strokeWidth??2,a=r?i*ue:i,o=r?le:e.style?.opacity??1,s=e.style?.fillOpacity??.12549019607843137,c=e.style?.dash??(r?[a,a*2]:void 0);return{color:n,strokeWidth:a,opacity:o,fillAlpha:s,fillVisible:!!e.style?.filled,dash:c,pointRadius:e.style?.pointRadius??t.pointRadius??5}}function de(e,t){let n=Math.max(0,Math.min(1,t)),r=e.trim().replace(`#`,``);if(r.length===3||r.length===6){let e=r.length===3?r.replace(/./g,e=>e+e):r,t=Number.parseInt(e,16);if(!Number.isNaN(t))return`rgba(${t>>16&255}, ${t>>8&255}, ${t&255}, ${n})`}return e}function fe({shape:e,strokeSize:t,register:r}){let{type:i,points:o}=e,s=V(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!==a.LINE?s.color:`none`,fillOpacity:s.fillAlpha,vectorEffect:`non-scaling-stroke`};if(i===a.POINT)return(0,n.jsx)(`circle`,{ref:c,cx:o[0].x,cy:o[0].y,r:s.pointRadius,fill:s.color,opacity:s.opacity});if(i===a.RECTANGLE||i===a.ELLIPSE){let e=m(o);return i===a.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=o.map(e=>`${e.x},${e.y}`).join(` `);return i===a.LINE?(0,n.jsx)(`polyline`,{points:u,...l}):(0,n.jsx)(`polygon`,{points:u,...l})}function pe({image:e,rois:t,excludedZones:r,maskId:i,width:a,height:o,strokeWidth:s,strokeDasharray:c,style:l}){return(0,n.jsxs)(`svg`,{width:a,height:o,viewBox:`0 0 ${e.w} ${e.h}`,style:l,"aria-hidden":!0,children:[(0,n.jsx)(`defs`,{children:(0,n.jsxs)(`mask`,{id:i,children:[(0,n.jsx)(`rect`,{x:0,y:0,width:e.w,height:e.h,fill:`white`}),t.map((e,t)=>(0,n.jsx)(`rect`,{x:e.x,y:e.y,width:e.w,height:e.h,fill:`black`},e.id??`roi-${t}`)),r?.map((e,t)=>(0,n.jsx)(`polygon`,{points:e.points.map(e=>`${e.x},${e.y}`).join(` `),fill:`white`},`exz-${t}`))]})}),(0,n.jsx)(`rect`,{x:0,y:0,width:e.w,height:e.h,fill:`rgba(0,0,0,0.5)`,mask:`url(#${i})`}),t.map((e,t)=>(0,n.jsx)(`rect`,{x:e.x,y:e.y,width:e.w,height:e.h,fill:`none`,stroke:`#fff`,strokeWidth:s,strokeDasharray:c,vectorEffect:`non-scaling-stroke`},e.id??`roib-${t}`)),r?.map((e,t)=>(0,n.jsx)(`polygon`,{points:e.points.map(e=>`${e.x},${e.y}`).join(` `),fill:`none`,stroke:`#fff`,strokeWidth:s,strokeDasharray:c,vectorEffect:`non-scaling-stroke`},`exzb-${t}`))]})}function me({value:r,onChange:i,onClose:a,labels:o=N.viewSettings}){return(0,t.useEffect)(()=>{let e=e=>{e.key===`Escape`&&a()},t=()=>a();return window.addEventListener(`keydown`,e),window.addEventListener(`pointerdown`,t),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`pointerdown`,t)}},[a]),(0,n.jsxs)(`div`,{className:`aivex:absolute aivex:bottom-full aivex:left-0 aivex:mb-1 aivex:w-[220px] aivex:rounded-[8px] aivex:border aivex:border-border-default aivex:bg-bg-primary aivex:p-3 aivex:text-text-primary aivex:text-xs aivex:shadow-lg`,onPointerDown:e=>e.stopPropagation(),children:[(0,n.jsxs)(`div`,{className:`aivex:mb-2 aivex:flex aivex:items-center aivex:justify-between`,children:[(0,n.jsx)(`span`,{className:`aivex:font-semibold aivex:text-text-secondary`,children:o.title}),(0,n.jsx)(e.h,{variant:`ghost`,size:`sm`,onClick:()=>i({...I}),children:o.reset})]}),(0,n.jsx)(he,{label:`${o.brightness} ${r.brightness.toFixed(2)}`,children:(0,n.jsx)(e.n,{min:0,max:3,step:.05,value:[r.brightness],onValueChange:([e])=>i({brightness:e})})}),(0,n.jsx)(he,{label:`${o.contrast} ${r.contrast.toFixed(2)}`,children:(0,n.jsx)(e.n,{min:0,max:3,step:.05,value:[r.contrast],onValueChange:([e])=>i({contrast:e})})}),(0,n.jsx)(he,{label:`${o.strokeSize} ${r.strokeSize}`,children:(0,n.jsx)(e.n,{min:1,max:10,step:.5,value:[r.strokeSize],onValueChange:([e])=>i({strokeSize:e})})}),(0,n.jsx)(he,{label:`${o.simplifyStrength} ${r.simplifyStrength}`,children:(0,n.jsx)(e.n,{min:.5,max:5,step:.5,value:[r.simplifyStrength],onValueChange:([e])=>i({simplifyStrength:e})})}),(0,n.jsx)(`div`,{className:`aivex:my-2`,children:(0,n.jsx)(e.f,{})}),(0,n.jsx)(ge,{label:o.pixelation,checked:!r.imageSmoothing,onChange:e=>i({imageSmoothing:!e})}),(0,n.jsx)(ge,{label:o.cursorGuide,checked:r.showCursorGuide,onChange:e=>i({showCursorGuide:e})}),(0,n.jsx)(ge,{label:o.guideMask,checked:r.showGuide,onChange:e=>i({showGuide:e})}),(0,n.jsx)(ge,{label:o.roi,checked:r.showRoi,onChange:e=>i({showRoi:e})}),(0,n.jsx)(ge,{label:o.keepZoomOnImageChange,checked:r.keepZoomOnImageChange,onChange:e=>i({keepZoomOnImageChange:e})}),(0,n.jsx)(ge,{label:o.wheelZoom,checked:r.wheelZoom,onChange:e=>i({wheelZoom:e})})]})}function he({label:e,children:t}){return(0,n.jsxs)(`div`,{className:`aivex:mb-2 aivex:block`,children:[(0,n.jsx)(`span`,{className:`aivex:mb-1 aivex:block aivex:text-text-secondary`,children:e}),t]})}function ge({label:t,checked:r,onChange:i}){return(0,n.jsxs)(`div`,{className:`aivex:flex aivex:items-center aivex:justify-between aivex:py-1`,children:[(0,n.jsx)(`span`,{children:t}),(0,n.jsx)(e.t,{size:`sm`,checked:r,onCheckedChange:i})]})}function _e({image:t,imageUrl:r,imageVisible:i=!0,maskDataUrl:a,rois:s,excludedZones:c,roiMaskId:l,shapes:u,view:f,onChangeView:p,nav:m,registerShape:h,rectRef:g,zoomLabelRef:_,onZoom100:v,open:y,onToggleOpen:b,showSettings:x=!0,settingsOpen:S,onToggleSettings:C,onCloseSettings:w,labels:T=N.minimap,settingsLabels:E}){let{offX:D,offY:O,dispW:k,dispH:A,zoomCentered:ee}=m,j={position:`absolute`,left:D,top:O,width:k,height:A};return(0,n.jsxs)(`div`,{className:`aivex:absolute aivex:bottom-2 aivex:left-2 aivex:w-[188px] aivex:rounded-[8px] aivex:border aivex:border-border-default aivex:bg-bg-primary aivex:p-[4px] aivex:shadow-lg`,children:[(0,n.jsx)(`div`,{className:`aivex:overflow-hidden aivex:rounded-[4px] aivex:transition-all aivex:duration-200 aivex:ease-in-out ${y?`aivex:mb-1 aivex:max-h-[180px] aivex:opacity-100`:`aivex:max-h-0 aivex:opacity-0`}`,children:(0,n.jsx)(`div`,{className:`aivex:relative aivex:h-[180px] aivex:w-[180px] aivex:cursor-grab aivex:touch-none aivex:overflow-hidden aivex:rounded-[4px] aivex:bg-black aivex:active:cursor-grabbing`,onPointerDown:m.handleMinimapPointerDown,onPointerMove:m.handleMinimapPointerMove,onPointerUp:m.endMinimapDrag,onPointerCancel:m.endMinimapDrag,onWheel:m.handleMinimapWheel,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:j}),a&&f.showGuide&&(0,n.jsx)(`img`,{src:a,alt:``,draggable:!1,style:{...j,opacity:.55,imageRendering:`pixelated`,pointerEvents:`none`}}),f.showRoi&&s&&s.length>0&&(0,n.jsx)(pe,{image:t,rois:s,excludedZones:c,maskId:l,width:k,height:A,strokeWidth:1,strokeDasharray:`4 4`,style:{position:`absolute`,left:D,top:O,pointerEvents:`none`}}),(0,n.jsx)(`svg`,{viewBox:`0 0 ${t.w} ${t.h}`,width:k,height:A,style:{position:`absolute`,left:D,top:O,pointerEvents:`none`},"aria-hidden":!0,children:d(u).filter(o).map(e=>(0,n.jsx)(fe,{shape:e,strokeSize:f.strokeSize,register:h},e.id))}),(0,n.jsx)(`div`,{ref:g,style:{position:`absolute`,border:`1px solid #00ff00`,background:`rgba(0,255,0,0.1)`,boxSizing:`border-box`,pointerEvents:`none`}})]})})}),(0,n.jsxs)(`div`,{className:`aivex:flex aivex:items-center aivex:justify-between`,children:[(0,n.jsxs)(`div`,{className:`aivex:flex aivex:items-center aivex:gap-0.5`,children:[(0,n.jsx)(e.h,{variant:`ghost`,size:`icon-sm`,"aria-label":T.zoomOut,onClick:()=>ee(1/1.2),children:(0,n.jsx)(e.Cr,{size:16})}),(0,n.jsx)(e.h,{variant:`ghost`,size:`sm`,"aria-label":T.zoom100,onClick:v,className:`aivex:min-w-[44px] aivex:px-1 aivex:tabular-nums`,children:(0,n.jsx)(`span`,{ref:_,children:`100%`})}),(0,n.jsx)(e.h,{variant:`ghost`,size:`icon-sm`,"aria-label":T.zoomIn,onClick:()=>ee(1.2),children:(0,n.jsx)(e.ei,{size:16})})]}),(0,n.jsxs)(`div`,{className:`aivex:relative aivex:flex aivex:items-center aivex:gap-0.5`,children:[x&&(0,n.jsx)(e.h,{variant:`ghost`,size:`icon-sm`,"aria-label":T.viewSettings,onClick:C,onPointerDown:e=>e.stopPropagation(),className:S?`aivex:text-text-brand`:void 0,children:(0,n.jsx)(e.Ci,{size:16})}),(0,n.jsx)(e.h,{variant:`ghost`,size:`icon-sm`,"aria-label":T.toggleMinimap,title:`(M)`,onClick:b,children:y?(0,n.jsx)(e._t,{size:16}):(0,n.jsx)(e.bt,{size:16})}),x&&S&&(0,n.jsx)(me,{value:f,onChange:p,onClose:w,labels:E})]})]})]})}var ve=`var(--editor-overlay-inverse-scale, 1)`,ye=6,be={fontFamily:`Pretendard, sans-serif`,fontSize:12,fontWeight:500,lineHeight:`16px`,color:`#fff`,textShadow:`0 0 4px #000, 0 0 4px #000`,whiteSpace:`nowrap`};function xe(e,t){let n=m(t);return{shape:e,x:n.minX,y:n.minY,width:n.maxX-n.minX,height:n.maxY-n.minY}}function Se(e){return`${Math.round(e.width)} x ${Math.round(e.height)} px`}function Ce({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 we({shapes:e,getLabel:t,formatInfo:r,register:i}){return(0,n.jsx)(n.Fragment,{children:e.map(e=>{let o=m(e.points),s=e.type===a.POINT,c=t?.(e),l=e.style?.color??`#00e5ff`,u=!!e.readOnly||!!e.style?.dash,d=xe(e,e.points),f=r?r(d):Se(d);return(0,n.jsxs)(`div`,{ref:t=>i(e.id,t),style:{position:`absolute`,left:o.minX,top:o.minY,width:o.maxX-o.minX,height:o.maxY-o.minY,pointerEvents:`none`},children:[!!c&&(0,n.jsxs)(`div`,{style:{position:`absolute`,left:0,top:0,display:`flex`,alignItems:`center`,gap:4,transform:`scale(${ve}) translateY(calc(-100% - ${ye}px))`,transformOrigin:`left top`,...be},children:[(0,n.jsx)(Ce,{color:l,striped:u}),(0,n.jsx)(`span`,{children:c})]}),!s&&!!f&&(0,n.jsx)(`div`,{"data-selinfo-dim":!0,style:{position:`absolute`,right:0,top:`100%`,transform:`scale(${ve}) translateY(${ye}px)`,transformOrigin:`right top`,...be},children:f})]},e.id)})})}var Te=new Set([F.RECTANGLE,F.ROTATED_RECTANGLE,F.CIRCLE,F.POLYGON,F.PATH,F.BRUSH,F.POINT,F.ASSISTANT_POLYGON,F.ASSISTANT_RECT,F.ASSISTANT_POINT]),Ee={tl:-135,t:-90,tr:-45,r:0,br:45,b:90,bl:135,l:180},H=[`ew-resize`,`nwse-resize`,`ns-resize`,`nesw-resize`];function De(e,t=0){let n=((Ee[e]+t*180/Math.PI)%180+180)%180;return H[Math.round(n/45)%4]}function Oe({tool:e,externalToolCursor:t,isSpacePressed:n,isPolygonDrawing:r}){return n?`grab`:t||(e===F.SELECT?`default`:Te.has(e)?r?`default`:`crosshair`:`default`)}function ke({tool:e,externalToolCursor:t,isSpacePressed:n,interactionMode:r,rendererCursorHint:i,isPolygonDrawing:a}){return r===`marquee`?`default`:r===`moving`||r===`panning`||r===`vertexDragging`?`grabbing`:r===`resizing`||r===`rotating`?i??`grabbing`:r===`drawing`?`crosshair`:n?`grab`:t||(e===F.SELECT&&i?i:Oe({tool:e,externalToolCursor:t,isSpacePressed:n,isPolygonDrawing:a}))}var Ae=e=>Math.min(255,Math.max(0,e)),je=e=>{let t=e.replace(`#`,``).trim();if(![3,4,6,8].includes(t.length))return null;let n=e=>e.length===1?`${e}${e}`:e,r=t.length<=4,i=n(t.slice(0,r?1:2)),a=n(t.slice(r?1:2,r?2:4)),o=n(t.slice(r?2:4,r?3:6)),s=t.length===4?n(t.slice(3,4)):t.length===8?n(t.slice(6,8)):`ff`,c=e=>Number.parseInt(e,16),l=[c(i),c(a),c(o),c(s)];return l.some(e=>Number.isNaN(e))?null:l.map(Ae)},Me=(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=je(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 U(e,t){e.beginPath(),e.moveTo(t[0].x,t[0].y);for(let n=1;n<t.length;n+=1)e.lineTo(t[n].x,t[n].y);e.closePath()}var Ne=(e,t,n,r)=>{if(!n||!r||!e.length)return null;let i=document.createElement(`canvas`);i.width=n,i.height=r;let a=i.getContext(`2d`);if(!a)return null;let o=`rgba(0,0,0,0.5)`;a.fillStyle=o,a.fillRect(0,0,n,r);for(let t of e)a.clearRect(t.x,t.y,t.w,t.h);let s=t?.filter(e=>e.points.length>=3)??[];a.fillStyle=o;for(let e of s)U(a,e.points),a.fill();return{dimCanvas:i,rects:e,zones:s}},Pe=.3,Fe=.05;function Ie(e){return 1-(1-e)**3}function W(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 Le(e,t){if(!t.length)return null;if(e===a.POINT){let e=t[0];return{x:e.x-8,y:e.y-8,width:16,height:16}}let n=m(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 Re(e){if(!e.length)return null;let t=e.map(e=>Le(e.type,e.points)).filter(e=>e!==null);return t.length?W(m(t.flatMap(e=>[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y+e.height}]))):null}function ze(e,t,n,r={}){let{containerRatio:i=Pe,minScale:a=Fe,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 Be(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(Fe,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 Ve(e,t,n,r=300){let i=Date.now(),a=0,o=()=>{let s=Date.now()-i,c=Math.min(s/r,1),l=Ie(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 He(e){let{engineRef:t,toolRef:n,externalToolMapRef:r,spaceRef:i,shiftRef:o,docRef:s,selRef:l,draftRef:f,readOnlyRef:p,lockedRef:h,onLockedInteraction:g,createRef:v,selectRef:x,enterEditRef:S,drawSessionRef:C,assistantRef:w,setCursorHint:T,setInteractionMode:E,syncMinimap:D,onTransformPreview:O,onDrawPreview:k}=e,A=()=>C.current,ee=()=>w.current,j=null,M=null,N=null,P=null,I=null,te=``,ne=null,L=e=>e===F.RECTANGLE||e===F.ROTATED_RECTANGLE||e===F.CIRCLE,R=e=>e===F.ASSISTANT_POLYGON||e===F.ASSISTANT_RECT,z=e=>e===F.POLYGON,re=()=>r.current.get(n.current),ie=(e,t,n,r)=>({point:t,targetId:r,event:n,readOnly:p.current,viewport:e.viewport});return{onCursorHint:T,onInteractionModeChange:E,onPointerDown:(e,r,_)=>{let v=t.current;if(!v)return;let y=n.current;if(_.button===1||i.current){E(`panning`),T(null),j={x:v.viewport.x,y:v.viewport.y,px:_.global.x,py:_.global.y};return}if(_.button===2&&!(y===F.ASSISTANT_POINT&&_.altKey))return;let b=re();if(b){A().reset(),x.current([]),b.onPointerDown?.(ie(v,e,_,r));return}if(h.current){g();return}if(y===F.ASSISTANT_POINT){_.altKey?ee().addPoint(e,_.button!==2):ee().newPolygon(e);return}if(R(y)&&f.current){M=e,E(`drawing`);return}if(y===F.SELECT&&_.altKey){let t=d(s.current.getShapes()).filter(t=>{if(!c(t))return!1;let n=m(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=>l.current.includes(e.id))+1)%e.length].id];x.current(n);return}}if(r&&y===F.SELECT){let t=s.current.getShapes().find(e=>e.id===r);if(!t||!c(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 d=(t.type===a.POLYGON||t.type===a.LINE)&&!p.current&&t.interaction?.editable!==!1&&!t.readOnly;if(i&&d){x.current([r]),S.current(r);return}let f=l.current;if(o.current){let e=new Set(f);e.has(r)?e.delete(r):e.add(r),f=[...e]}else f.includes(r)||(f=[r]);x.current(f),!p.current&&u(t)&&v.beginMove(e,f);return}if(L(y)&&f.current){M=e,E(`drawing`);return}if(z(y)&&f.current){if(!A().getDraftPointsSnapshot().length&&l.current.length&&x.current([]),A().tryClosePolygon(e,12/v.viewport.scale))return;let t=A().hitDraftPoint(e);if(t>=0){if(_.altKey){A().removeDraftPoint(t);return}let n=A().selectDraftPointForDrag(t,_.shiftKey||_.ctrlKey||_.metaKey);if(!n)return;P={start:e,base:n.base,indices:n.indices,moved:!1},E(`vertexDragging`);return}A().appendPolygonPoint(e);return}if(y===F.PATH&&f.current){l.current.length&&x.current([]),N=`path`,E(`drawing`),A().beginStroke(e);return}if(y===F.BRUSH&&f.current&&!p.current){N=`scalar`,E(`drawing`),A().beginStroke(e);return}if(y===F.SELECT){if(!o.current&&!p.current&&l.current.length>=2){let t=s.current.getShapes().filter(e=>l.current.includes(e.id)&&u(e));if(t.length){let n=m(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,l.current);return}}}I=e,te=``,E(`marquee`),T(null)}},onPointerMove:(e,r)=>{let i=t.current;if(!i)return;if(j){i.applyViewport({scale:i.viewport.scale,x:j.x+(r.global.x-j.px),y:j.y+(r.global.y-j.py)});return}let s=n.current,c=re();if(c){c.onPointerMove?.(ie(i,e,r));return}if(P){let t=e.x-P.start.x,n=e.y-P.start.y;P.moved=P.moved||Math.hypot(t,n)>.5,A().moveDraftPoints(P.base,P.indices,t,n);return}if(M&&(L(s)||R(s))){let t=o.current?_(M,e):e,n=f.current?.color??`#00e5ff`;i.previewBox(s===F.CIRCLE?`ellipse`:`rect`,M,t,n),L(s)&&k({type:s===F.CIRCLE?a.ELLIPSE:a.RECTANGLE,points:[M,t]});return}if(N){A().appendStrokePoint(e,2/i.viewport.scale);return}if(z(s)&&A().hasDraftPoints()){A().setDraftCursor(e);return}if(I){let t={minX:Math.min(I.x,e.x),minY:Math.min(I.y,e.y),maxX:Math.max(I.x,e.x),maxY:Math.max(I.y,e.y)};i.previewMarquee(I,e);let n=i.shapesIntersecting(t),r=n.join(`,`);r!==te&&(te=r,x.current(n))}},onPointerUp:e=>{let r=t.current;if(!r)return;if(j){j=null,E(`idle`);return}if(P){A().commitDraftPointDrag(P.moved),P=null,E(`idle`);return}let i=n.current,s=re();if(s){s.onPointerUp?.(ie(r,e,{}));return}if(i===F.POINT&&f.current){v.current(a.POINT,[e]);return}if(N){let e=N;N=null,E(`idle`),e===`path`?A().completeFreehandStroke():A().finishScalarStroke();return}if(M&&R(i)){let t=M;M=null,E(`idle`),r.clearPreview();let n={x:Math.min(t.x,e.x),y:Math.min(t.y,e.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)};n.width>2&&n.height>2&&ee().beginBox(n,i===F.ASSISTANT_RECT?`rect`:`polygon`);return}if(M&&L(i)){let t=o.current?_(M,e):e,n=M;M=null,E(`idle`),r.clearPreview(),k(null),Math.abs(t.x-n.x)>2&&Math.abs(t.y-n.y)>2&&(i===F.ROTATED_RECTANGLE?v.current(a.ROTATED_RECTANGLE,y([n,t])):i===F.CIRCLE?v.current(a.POLYGON,b(n,t)):v.current(a.RECTANGLE,[n,t]));return}if(I){let t=Math.abs(e.x-I.x)>3||Math.abs(e.y-I.y)>3;I=null,r.clearMarquee(),E(`idle`),!t&&l.current.length&&x.current([])}},onViewportChange:D,onTransformPreview:O,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 Ue({docRef:e,draftRef:n,draftMeta:r,changeSelection:i,assistantRef:o}){let[s,c]=(0,t.useState)(`idle`),[l,u]=(0,t.useState)([]),[d,p]=(0,t.useState)([]),h=(0,t.useRef)([]),g=(0,t.useRef)([]),_=(0,t.useRef)([]),v=(0,t.useRef)(`idle`),y=(0,t.useRef)(0),b=(0,t.useRef)(null),x=(0,t.useRef)(null),C=(0,t.useRef)(0),w=(0,t.useCallback)(e=>{h.current=e(h.current),p(h.current)},[]),T=(0,t.useCallback)(e=>{v.current=e,c(e)},[]),E=(0,t.useCallback)((e,t,n)=>{let i=o.current?.rectResult===`rotatedRect`;return e.map(e=>{if(t===`rect`&&i)return{id:f(),type:a.ROTATED_RECTANGLE,points:S(e),style:n,meta:r};if(t===`rect`){let t=m(e);return{id:f(),type:a.RECTANGLE,points:[{x:t.minX,y:t.minY},{x:t.maxX,y:t.maxY}],style:n,meta:r}}return{id:f(),type:a.POLYGON,points:e,style:n,meta:r}})},[r,o]),D=(0,t.useCallback)(()=>{y.current++,g.current=[],_.current=[],b.current=null,x.current=null,u([]),T(`idle`)},[T]),O=(0,t.useCallback)(()=>{C.current++,w(()=>[]);let t=x.current;t?e.current.update([t]):_.current.length&&e.current.remove(_.current),D()},[e,D,w]),k=(0,t.useCallback)(t=>{let r=_.current;if(!t.length){r.length&&(e.current.remove(r),_.current=[]);return}if(r.length===t.length){let n=e.current.getShapes(),i=t.map((e,t)=>{let i=n.find(e=>e.id===r[t]);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=n.current;if(!a)return;let o=E(t,`polygon`,a);o?.length&&(e.current.create(o),_.current=o.map(e=>e.id),i(_.current))},[e,n,i,E]),A=(0,t.useCallback)(async()=>{let e=o.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`))},[o,k,T]),ee=(0,t.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]),j=(0,t.useCallback)(e=>{D();let t=[{x:e.x,y:e.y,positive:!0}];g.current=t,u(t),A()},[D,A]),M=(0,t.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,t.useCallback)((t,r=`polygon`)=>{let a=o.current?.infer,s=n.current;if(!a||!s)return;let c=C.current;w(e=>[...e,t]),(async()=>{let n=[];try{n=(await a({kind:`box`,box:t})??[]).filter(e=>e.length>=3)}catch{n=[]}if(w(e=>e.filter(e=>e!==t)),c!==C.current)return;let o=E(n,r,s);o?.length&&(e.current.create(o),i(o.map(e=>e.id)))})()},[o,n,E,i,e,w]),addPoint:ee,newPolygon:j,refineShape:M,finalize:D,cancel:O,isActive:(0,t.useCallback)(()=>v.current===`loading`||g.current.length>0||h.current.length>0||_.current.length>0,[])}}function We(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 Ge(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=We(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 Ke=4096,qe=4;function Je(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 Ye(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 Xe(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 G(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 Ze(e,t,n){let r=Ye(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=K(Xe(G(r,t,n,e,a)),t,n);o.length>=3&&i.push(o)}return i}function Qe(e,t,n,r,i){return r<0||i<0||r>=t||i>=n?!1:e[(i*t+r)*4+3]>128}function K(e,t,n){let r=-1,i=-1;outer:for(let a=0;a<n;a++)for(let o=0;o<t;o++)if(Qe(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(Qe(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 $e(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 et(e){switch(e.type){case a.RECTANGLE:return e.points.length<2?null:y(e.points);case a.POLYGON:case a.ROTATED_RECTANGLE:case a.ELLIPSE:return e.points.length>=3?e.points:null;case a.POINT:{let t=e.points[0];return t?b({x:t.x-6,y:t.y-6},{x:t.x+6,y:t.y+6}):null}default:return null}}function tt(e){return e.map(et).filter(e=>!!e&&e.length>=3)}function nt(e,t,n=[]){if(t<=0||!e.length&&!n.length)return null;let r=$e(e,n);if(!r.length)return null;let i=t+4,a=m(r),o=Math.ceil(a.maxX-a.minX+i*2),s=Math.ceil(a.maxY-a.minY+i*2),c=Math.min(1,Ke/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 q(e,t=1.5){let{canvas:n,ox:r,oy:i,scale:a}=e,o=Ze(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=Ge(n,t),i=r.length>=3?r:n;i.length>=3&&Je(i)>=qe&&c.push(i)}return c}function rt(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 it(e){return e.map(e=>({mode:e.mode,points:e.points.map(e=>({...e}))}))}function J(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 at(e){return e.map(e=>({...e}))}function ot(e,t){return e.length===t.length&&e.every((e,n)=>e.x===t[n].x&&e.y===t[n].y)}var st=10;function ct({toolRef:e,selRef:n,docRef:r,readOnlyRef:i,draftRef:o,brushSizeRef:s,simplifyEpsilonRef:c,draftMeta:u,engineRef:d,onDrawSessionChange:p,changeSelection:m,createShape:h}){let g=(0,t.useRef)(p);g.current=p;let _=(0,t.useRef)(h);_.current=h;let v=(0,t.useRef)([]),y=(0,t.useRef)(null),b=(0,t.useRef)(new Set),x=(0,t.useRef)([[]]),S=(0,t.useRef)(0),C=(0,t.useRef)([]),w=(0,t.useRef)([]),T=(0,t.useRef)([]),E=(0,t.useRef)([[]]),D=(0,t.useRef)(0),O=(0,t.useRef)(`draw`),k=()=>O.current===`erase`?`erase`:`add`,A=()=>T.current.length>0||C.current.length>0||e.current===F.BRUSH&&v.current.length>0,ee=()=>{let t=e.current;return t===F.BRUSH&&A()?`brush`:t===F.POLYGON&&v.current.length>0?`polygon`:t===F.PATH&&v.current.length>0?`path`:`none`},j=()=>v.current.length>0||D.current>0,M=()=>v.current.length===0&&D.current<E.current.length-1,N=()=>S.current>0,P=()=>S.current<x.current.length-1,I=()=>{let t=e.current;return t===F.BRUSH?j():t===F.POLYGON||t===F.PATH?N():!1},te=()=>{let t=e.current;return t===F.BRUSH?M():t===F.POLYGON||t===F.PATH?P():!1},ne=()=>ee()!==`none`,L=(0,t.useCallback)(()=>{let e=ee();g.current?.({active:e!==`none`,kind:e,canUndo:I(),canRedo:te(),brush:e===`brush`?{mode:O.current,editing:T.current.length>0,editTargetIds:[...T.current]}:void 0})},[]),R=(0,t.useCallback)(()=>{E.current=[[]],D.current=0},[]),z=(0,t.useCallback)(()=>{let t=d.current;if(!t)return;let n=e.current;if(n===F.BRUSH){let e=[...C.current];if(v.current.length&&e.push({points:v.current,mode:k()}),!e.length&&!w.current.length){t.clearPreview();return}let n=nt(e,s.current,w.current);if(!n){t.clearPreview();return}let r=o.current?.color??`#00e5ff`;t.previewScalarMask(n,r);return}let r=v.current;if(!r.length){t.clearPreview();return}let i=o.current?.color??`#00e5ff`,a=Array.from(b.current),c=n!==F.PATH;t.previewPoly(r,y.current,i,!1,a,c)},[s,o,d,e]),re=(0,t.useCallback)(e=>{let t=it(e),n=E.current,r=D.current,i=n[r];i&&J(i,t)||(E.current=[...n.slice(0,r+1),t],D.current+=1,L())},[L]),ie=(0,t.useCallback)(e=>{let t=x.current,n=S.current,r=t[n];r&&ot(r,e)||(x.current=[...t.slice(0,n+1),at(e)],S.current+=1)},[]),B=(0,t.useCallback)(()=>{v.current=[],C.current=[],w.current=[],T.current=[],y.current=null,b.current=new Set,x.current=[[]],S.current=0,R(),d.current?.clearPreview(),L()},[d,L,R]),ae=(0,t.useCallback)((e,t)=>{v.current=e,b.current=new Set(Array.from(b.current).filter(t=>t>=0&&t<e.length)),t&&ie(e),z(),L()},[L,ie,z]),oe=(0,t.useCallback)(()=>at(v.current),[]),se=(0,t.useCallback)(()=>v.current.length>0,[]),ce=(0,t.useCallback)((t,n)=>{if(e.current!==F.POLYGON)return!1;let r=v.current;if(r.length<3)return!1;let i=r[0];return Math.hypot(t.x-i.x,t.y-i.y)>n?!1:(_.current(a.POLYGON,r),B(),!0)},[B,e]),le=(0,t.useCallback)(e=>{let t=v.current;return e<0||e>=t.length?!1:(ae(t.filter((t,n)=>n!==e),!0),!0)},[ae]),ue=(0,t.useCallback)((e,t)=>{let n=v.current;if(e<0||e>=n.length)return null;let r=new Set(b.current);return t?r.has(e)?r.delete(e):r.add(e):r.has(e)||(r.clear(),r.add(e)),b.current=r,y.current=null,z(),L(),{base:at(n),indices:Array.from(r)}},[L,z]),V=(0,t.useCallback)(e=>{b.current=new Set,y.current=e,ae([...v.current,e],!0)},[ae]),de=(0,t.useCallback)(e=>{y.current=null,b.current=new Set,v.current=[{...e}],z(),L()},[L,z]),fe=(0,t.useCallback)((e,t)=>{let n=v.current[v.current.length-1];return n&&Math.hypot(e.x-n.x,e.y-n.y)<t?!1:(v.current=[...v.current,{...e}],y.current=null,z(),L(),!0)},[L,z]),pe=(0,t.useCallback)((e,t,n,r)=>{let i=new Set(t);v.current=e.map((e,t)=>i.has(t)?{x:e.x+n,y:e.y+r}:{...e}),y.current=null,z(),L()},[L,z]),me=(0,t.useCallback)(e=>{e&&(ie(v.current),z(),L())},[L,ie,z]),he=(0,t.useCallback)(e=>{y.current=e?{...e}:null,z(),L()},[L,z]),ge=(0,t.useCallback)(()=>v.current.length>0?(v.current=[],z(),L(),!0):D.current<=0?!1:(--D.current,C.current=it(E.current[D.current]),z(),L(),!0),[L,z]),_e=(0,t.useCallback)(()=>v.current.length>0||D.current>=E.current.length-1?!1:(D.current+=1,C.current=it(E.current[D.current]),z(),L(),!0),[L,z]),ve=(0,t.useCallback)(()=>S.current<=0?!1:(--S.current,v.current=at(x.current[S.current]),b.current=new Set,z(),L(),!0),[L,z]),ye=(0,t.useCallback)(()=>S.current>=x.current.length-1?!1:(S.current+=1,v.current=at(x.current[S.current]),b.current=new Set,z(),L(),!0),[L,z]),be=(0,t.useCallback)(()=>{let t=e.current;return t===F.BRUSH?ge():t===F.POLYGON||t===F.PATH?ve():!1},[e,ge,ve]),xe=(0,t.useCallback)(()=>{let t=e.current;return t===F.BRUSH?_e():t===F.POLYGON||t===F.PATH?ye():!1},[_e,ye,e]),Se=(0,t.useCallback)(()=>{let e=n.current;if(!e.length)return T.current.length>0;let t=r.current.getShapes().filter(t=>e.includes(t.id)&&l(t)),i=tt(t);return i.length?(T.current=t.map(e=>e.id),w.current=i,!0):(T.current=[],w.current=[],!1)},[r,n]),Ce=(0,t.useCallback)(()=>{if(i.current)return!1;let e=[...C.current];v.current.length&&e.push({points:at(v.current),mode:k()});let t=w.current,n=[...T.current];if(!e.length&&!t.length)return!1;let l=nt(e,s.current,t);if(!l)return B(),!1;let d=q(l,c.current);if(n.length){let e=r.current.getShapes().filter(e=>n.includes(e.id));if(!d.length)return r.current.remove(n),B(),m([]),!0;d.sort((e,t)=>Je(t)-Je(e));let t=[],i=[],o=[];for(let n=0;n<d.length;n++){let r=d[n];if(n<e.length){let i=e[n];t.push({...i,type:a.POLYGON,points:r}),o.push(i.id)}else{let t=e[0],n=f();i.push({...t,id:n,type:a.POLYGON,points:r}),o.push(n)}}let s=e.slice(d.length).map(e=>e.id);return t.length&&r.current.update(t),i.length&&r.current.create(i),s.length&&r.current.remove(s),B(),m(o),!0}if(!d.length)return B(),!1;let p=o.current;if(!p)return!1;let h=d.map(e=>({id:f(),type:a.POLYGON,points:e,style:p,meta:u}));return r.current.create(h),m(h.map(e=>e.id)),B(),!0},[s,m,r,u,o,i,B]),we=(0,t.useCallback)(()=>{let t=e.current;if(t===F.BRUSH)return Ce();let n=v.current;return t===F.POLYGON&&n.length>=3?(_.current(a.POLYGON,n),B(),!0):!1},[Ce,B,e]),Te=(0,t.useCallback)(()=>{let t=v.current;if(e.current===F.PATH&&t.length>=3){let e=Ge(t,c.current);e.length>=3&&_.current(a.POLYGON,e)}B()},[B,e]),Ee=(0,t.useCallback)(e=>{O.current=e,L(),z()},[L,z]),H=(0,t.useCallback)(()=>{if(i.current||e.current!==F.BRUSH)return!1;C.current=[],v.current=[],R();let t=Se();return L(),z(),t},[L,i,z,R,Se,e]),De=(0,t.useCallback)(()=>{let e=b.current;if(!e.size)return!1;let t=v.current.filter((t,n)=>!e.has(n));return b.current=new Set,ae(t,!0),!0},[ae]),Oe=(0,t.useCallback)(e=>{let t=d.current,n=v.current;if(!t||!n.length)return-1;let r=st/(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]),ke=(0,t.useCallback)(()=>{v.current.length>=1&&(C.current.push({points:at(v.current),mode:k()}),v.current=[],re(C.current)),z(),L()},[L,re,z]);return{reset:B,undoSession:be,redoSession:xe,canUndoSession:I,canRedoSession:te,hasDraftSession:ne,hasDraftPoints:se,commitDraftSession:we,completeFreehandStroke:Te,setBrushScalarMode:Ee,getBrushScalarMode:()=>O.current,hasBrushSession:A,commitBrush:Ce,cancelBrush:(0,t.useCallback)(()=>{e.current===F.BRUSH&&B()},[B,e]),beginBrushEditFromSelection:H,deleteDraftSelectedPoints:De,hitDraftPoint:Oe,getDraftPointsSnapshot:oe,tryClosePolygon:ce,removeDraftPoint:le,selectDraftPointForDrag:ue,appendPolygonPoint:V,beginStroke:de,appendStrokePoint:fe,moveDraftPoints:pe,commitDraftPointDrag:me,setDraftCursor:he,finishScalarStroke:ke,handleToolChange:(0,t.useCallback)((e,t)=>{if(t){B(),O.current=`draw`;return}if(e!==F.BRUSH){B(),O.current=`draw`;return}O.current=`draw`,C.current=[],v.current=[],R(),Se(),L(),z()},[L,z,B,R,Se]),handleBrushSelectionChange:(0,t.useCallback)((t,n)=>{if(!(e.current!==F.BRUSH||n)){if(!t.length){L();return}[...t].sort().join(`,`)!==[...T.current].sort().join(`,`)&&(C.current.length||v.current.length||(C.current=[],v.current=[],R(),Se(),L(),z()))}},[L,z,R,Se,e])}}function lt(e,t){return{shapes:t,past:[...e.past,e.shapes],future:[]}}function ut(e,t){switch(t.type){case`CREATE`:return lt(e,[...e.shapes,...t.shapes]);case`UPDATE`:{let n=new Map(t.shapes.map(e=>[e.id,e]));return lt(e,e.shapes.map(e=>n.get(e.id)??e))}case`DELETE`:{let n=new Set(t.ids);return lt(e,e.shapes.filter(e=>!n.has(e.id)))}case`REPLACE`:{let n=new Set(t.removeIds);return lt(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:lt(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 dt(e){let{onShapesCreated:n,onShapesUpdated:r,onShapesDeleted:i}=e,[a,o]=(0,t.useReducer)(ut,{shapes:[],past:[],future:[]}),s=(0,t.useRef)(a);s.current=a;let c=(0,t.useCallback)(e=>{s.current=ut(s.current,e),o(e)},[]),l=(0,t.useCallback)((e,t)=>{let a=new Map(e.map(e=>[e.id,e])),o=new Map(t.map(e=>[e.id,e])),s=t.filter(e=>!a.has(e.id));s.length&&n?.(s);let c=e.filter(e=>!o.has(e.id)).map(e=>e.id);c.length&&i?.(c);let l=t.filter(e=>a.has(e.id)&&a.get(e.id)!==e);l.length&&r?.(l)},[n,r,i]),u=(0,t.useCallback)(e=>{let t=Array.isArray(e)?e:[e];t.length&&(c({type:`CREATE`,shapes:t}),n?.(t))},[n]),d=(0,t.useCallback)(e=>{c({type:`UPDATE`,shapes:e}),r?.(e)},[r]),f=(0,t.useCallback)(e=>{e.length!==0&&(c({type:`DELETE`,ids:e}),i?.(e))},[i]),p=(0,t.useCallback)((e,t)=>{!e.length&&!t.length||(c({type:`REPLACE`,removeIds:e,shapes:t}),e.length&&i?.(e),t.length&&n?.(t))},[n,i]),m=(0,t.useCallback)((e,t)=>{e.length!==0&&c({type:`REORDER`,ids:e,edge:t})},[]),h=(0,t.useCallback)(e=>{c({type:`RESET`,shapes:e})},[]),g=(0,t.useCallback)(()=>{let e=s.current;e.past.length!==0&&(l(e.shapes,e.past[e.past.length-1]),c({type:`UNDO`}))},[l]),_=(0,t.useCallback)(()=>{let e=s.current;e.future.length!==0&&(l(e.shapes,e.future[0]),c({type:`REDO`}))},[l]),v=(0,t.useCallback)(()=>s.current.past.length>0,[]),y=(0,t.useCallback)(()=>s.current.future.length>0,[]),b=(0,t.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 ft={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+[`],flipHorizontal:[`shift+h`],flipVertical:[`shift+v`],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`]},pt={Equal:`=`,Minus:`-`,BracketLeft:`[`,BracketRight:`]`,Semicolon:`;`,Period:`.`,Comma:`,`,Slash:`/`,Backquote:"`"},mt={Escape:`escape`,Enter:`enter`,Backspace:`backspace`,Delete:`delete`,Tab:`tab`,ArrowUp:`arrowup`,ArrowDown:`arrowdown`,ArrowLeft:`arrowleft`,ArrowRight:`arrowright`};function ht(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]:pt[t]?pt[t]:mt[e.key]?mt[e.key]:null}function gt(e){let t=ht(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 _t(e){let t=new Map;for(let n of Object.keys(ft)){let r=e?.[n],i=r===void 0?ft[n]:r===null?[]:Array.isArray(r)?r:[r];for(let e of i)t.set(e.toLowerCase(),n)}return t}var vt={ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0]};function yt(){let e=document.activeElement;return!!e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable)}function bt(e){let{spaceRef:n,shiftRef:r}=e,i=(0,t.useMemo)(()=>_t(e.keymap),[e.keymap]),a=(0,t.useRef)(e);a.current=e;let o=(0,t.useRef)(i);o.current=i,(0,t.useEffect)(()=>{let e=e=>{if(e.code===`Space`&&(n.current=!0,a.current.onSpaceDown()),e.key===`Shift`&&(r.current=!0),yt())return;let t=vt[e.key];if(t){e.preventDefault();let n=e.shiftKey?10:1;a.current.nudge(t[0]*n,t[1]*n);return}let i=gt(e);if(!i)return;let s=o.current.get(i);s&&a.current.actions[s]?.()!==!1&&e.preventDefault()},t=e=>{e.code===`Space`&&(n.current=!1,a.current.onSpaceUp()),e.key===`Shift`&&(r.current=!1)};return window.addEventListener(`keydown`,e),window.addEventListener(`keyup`,t),()=>{window.removeEventListener(`keydown`,e),window.removeEventListener(`keyup`,t)}},[n,r])}var xt=4e3;function Y(e,t,n=xt){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 St(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 Ct(e,t,n){if(t===a.POINT){e.setAttrs({x:n[0].x,y:n[0].y});return}if(t===a.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===a.ELLIPSE){let t=m(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 wt=`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`,Tt=`#ffffff`,X=1.5;function Et(e){return`<svg width="16" height="22" viewBox="0 0 16 22" xmlns="http://www.w3.org/2000/svg"><path d="${wt}" fill="${e}" stroke="${Tt}" stroke-width="${X}"/></svg>`}var Dt=Math.PI/12;function Ot(e,t){return t.kind!==`resize`&&t.kind!==`move`||t.shapes.length!==1?!1:e.find(e=>e.id===t.shapes[0].id)?.type===a.ROTATED_RECTANGLE}function kt(e,t,n){if(e.kind===`resize`){let r=n?e.box:g(e.anchor,e.box,t.x,t.y);return{updates:e.shapes.map(i=>({id:i.id,points:n?j(i.points,e.anchor,t):M(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/Dt)*Dt),{updates:[{id:e.id,points:e.points.map(t=>v(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:m(a)}}function Z(e,t,n){let r=e.filter(e=>t.includes(e.id)&&u(e)).map(e=>({id:e.id,points:e.points}));return r.length?{kind:`move`,start:n,box:m(r.flatMap(e=>e.points)),shapes:r}:null}function At(e){return e.map(e=>({...e,points:e.points.map(e=>({...e}))}))}function jt(e,t){let n=new Set(t);return e.filter(e=>n.has(e.id)&&l(e))}function Mt(e,t){return e.filter(e=>{if(!c(e))return!1;let n=m(e.points);return n.minX<=t.maxX&&n.maxX>=t.minX&&n.minY<=t.maxY&&n.maxY>=t.minY}).map(e=>e.id)}function Q(e,t,n){return(e?V(e,{strokeWidth:t}).pointRadius:5)/(n||1)}function Nt(e,t){return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}function Pt(e,t,n){if(e.type===a.ROTATED_RECTANGLE)return t;let r=e.type===a.POINT?Nt(t[0],n):m(t);return y([{x:r.minX,y:r.minY},{x:r.maxX,y:r.maxY}])}function Ft(e){return 24/(e||1)}function It(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}var Lt=2,Rt=`#1e88e5`,zt=`#669def`,Bt=class{constructor(e,t){this.layer=new r.default.Layer,this.world=new r.default.Group,this.bgGroup=new r.default.Group,this.overlayGroup=new r.default.Group({listening:!1}),this.shapeGroup=new r.default.Group,this.selGroup=new r.default.Group,this.previewGroup=new r.default.Group,this.handleGroup=new r.default.Group,this.baseCursor=`default`,this.strokeSize=Lt,this.imageSmoothing=!0,this.imageWidth=0,this.imageHeight=0,this.shapes=[],this.selected=[],this.nodes=new Map,this.lastAppliedScale=-1,this.imageLoadToken=0,this.transformEnabled=!1,this.handleNodes=[],this.vertexNodes=[],this.lastImg={x:0,y:0},this.lastDragImg=null,this.ro=null,this.activeDrag=null,this.midNodes=[],this.selectedVertices=new Set,this.vertexPolygonId=null,this.editingId=null,this.rotNode=null,this.rotLineNode=null,this.transformerOutline=null,this.selectionBorders=[],this.upCleanup=null,this.preview=null,this.marquee=null,this.host=e,this.cb=t,this.stage=new r.default.Stage({container:e,width:e.clientWidth||1,height:e.clientHeight||1}),this.world.add(this.bgGroup,this.overlayGroup,this.shapeGroup,this.selGroup,this.previewGroup),this.layer.add(this.world,this.handleGroup),this.world.visible(!1),this.stage.add(this.layer)}async init(){let e=e=>({button:e.evt.button,shiftKey:e.evt.shiftKey,altKey:e.evt.altKey,ctrlKey:e.evt.ctrlKey,metaKey:e.evt.metaKey,global:this.stage.getPointerPosition()??{x:0,y:0}});this.stage.on(`mousedown`,t=>{let n=t.target===this.stage?null:t.target.id()||null;this.cb.onPointerDown(this.toImage(),n,e(t))}),this.stage.on(`mousemove`,()=>{if(this.lastImg=this.toImage(),this.activeDrag){this.dragTransform(this.lastImg);return}this.cb.onPointerMove(this.lastImg,{global:this.stage.getPointerPosition()??{x:0,y:0}})});let t=()=>{if(this.activeDrag){this.endTransform();return}this.cb.onPointerUp(this.lastImg)};this.stage.on(`mouseup`,t),window.addEventListener(`mouseup`,t),this.upCleanup=()=>window.removeEventListener(`mouseup`,t),this.ro=new ResizeObserver(()=>{this.stage.size({width:this.host.clientWidth||1,height:this.host.clientHeight||1}),this.layer.batchDraw()}),this.ro.observe(this.host)}destroy(){this.ro?.disconnect(),this.upCleanup?.(),this.stage.destroy()}get dom(){return this.stage.container()}get screenSize(){return{w:this.stage.width(),h:this.stage.height()}}setCursor(e){this.baseCursor=e,this.applyCursor()}emitCursorHint(e){this.cb.onCursorHint?.(e)}emitInteractionMode(e){this.cb.onInteractionModeChange?.(e)}applyCursor(){this.stage.container().style.cursor=this.baseCursor;for(let e of this.stage.container().querySelectorAll(`canvas`))e.style.cursor=this.baseCursor}bindCursor(e,t){let n=()=>{this.activeDrag||t===`pointer`&&!this.transformEnabled||this.emitCursorHint(t)},r=()=>{this.activeDrag||this.emitCursorHint(null)};e.on(`mouseenter`,n),e.on(`mouseover`,n),e.on(`mouseleave`,r),e.on(`mouseout`,r)}toImage(){let e=this.world.getRelativePointerPosition();return e?{x:e.x,y:e.y}:this.lastImg}imgToScreen(e){return this.world.getAbsoluteTransform().point(e)}async setImage(e){let t=++this.imageLoadToken,n=null;try{let t=await fetch(e,{mode:`cors`,credentials:`omit`,cache:`no-store`});t.ok&&(n=URL.createObjectURL(await t.blob()))}catch{n=null}await new Promise(i=>{let a=new Image;n||(a.crossOrigin=`anonymous`),a.onload=()=>{if(n&&URL.revokeObjectURL(n),t!==this.imageLoadToken)return i();this.imageWidth=a.naturalWidth,this.imageHeight=a.naturalHeight,this.bgGroup.destroyChildren();for(let e of Y(this.imageWidth,this.imageHeight))this.bgGroup.add(new r.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}));this.layer.batchDraw(),i()},a.onerror=()=>{n&&URL.revokeObjectURL(n),this.imageWidth||=800,this.imageHeight||=600,i()},a.src=n??e})}clearImage(){this.imageLoadToken++,this.bgGroup.destroyChildren(),this.layer.batchDraw()}setFilter(e,t){let n=e!==1||t!==1?`brightness(${e}) contrast(${t})`:``,r=this.stage.container().querySelector(`canvas`);r&&(r.style.filter=n)}setStrokeSize(e){this.strokeSize!==e&&(this.strokeSize=e,this.setShapes(this.shapes,this.selected))}setImageSmoothing(e){this.imageSmoothing!==e&&(this.imageSmoothing=e,this.layer.imageSmoothingEnabled(e),this.layer.batchDraw())}setOverlays(e,t,n){if(this.overlayGroup.destroyChildren(),e&&this.overlayGroup.add(new r.default.Image({image:e,opacity:.55,imageSmoothingEnabled:!1,listening:!1})),t){this.overlayGroup.add(new r.default.Image({image:t.dimCanvas,listening:!1}));let e={stroke:se,strokeWidth:2,dash:ce,strokeScaleEnabled:!1,listening:!1};for(let n of t.rects)this.overlayGroup.add(new r.default.Rect({x:n.x,y:n.y,width:n.w,height:n.h,...e}));for(let n of t.zones)this.overlayGroup.add(new r.default.Line({points:n.points.flatMap(e=>[e.x,e.y]),closed:!0,...e}))}n&&this.imageWidth&&this.overlayGroup.add(new r.default.Rect({x:0,y:0,width:this.imageWidth,height:this.imageHeight,fill:`#0d0d12`,opacity:.3,listening:!1})),this.layer.batchDraw()}get viewport(){return{scale:this.world.scaleX(),x:this.world.x(),y:this.world.y()}}applyViewport(e){let t=e.scale!==this.lastAppliedScale;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)),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=At(e),this.selected=t,!this.activeDrag){this.shapeGroup.destroyChildren(),this.nodes.clear();for(let t of d(e).filter(o)){let e=this.makeNode(t);this.nodes.set(t.id,e),this.shapeGroup.add(e)}this.drawSelectionBorders(),this.drawTransformer(),this.layer.batchDraw()}}setSelection(e){this.selected=e,(e.length!==1||e[0]!==this.vertexPolygonId)&&(this.vertexPolygonId=null,this.selectedVertices.clear()),this.editingId&&(e.length!==1||e[0]!==this.editingId)&&(this.editingId=null),!this.activeDrag&&(this.drawSelectionBorders(),this.drawTransformer(),this.layer.batchDraw())}setEditing(e){this.editingId!==e&&(this.editingId=e,this.selectedVertices.clear(),this.activeDrag||(this.drawTransformer(),this.layer.batchDraw()))}makeNode(e){let{type:t,points:n}=e,i=V(e,{strokeWidth:this.strokeSize}),o=c(e),s={id:e.id,stroke:i.color,strokeWidth:i.strokeWidth,dash:this.scaledDash(i.dash),opacity:i.opacity,strokeScaleEnabled:!1,listening:o},l=i.fillVisible?de(i.color,i.fillAlpha):void 0;if(t===a.POINT){let t=1/(this.world.scaleX()||1),a=new r.default.Path({id:e.id,data:wt,x:n[0].x,y:n[0].y,offsetX:16/2,offsetY:22,scaleX:t,scaleY:t,fill:i.color,stroke:Tt,strokeWidth:X,strokeScaleEnabled:!1,shadowColor:`#000`,shadowBlur:2,shadowOpacity:.3,shadowForStrokeEnabled:!1,opacity:i.opacity,listening:o});return this.bindCursor(a,u(e)?`grab`:`default`),a}if(t===a.RECTANGLE){let t=m(n),i=new r.default.Rect({x:t.minX,y:t.minY,width:t.maxX-t.minX,height:t.maxY-t.minY,fill:l,...s});return this.bindCursor(i,u(e)?`grab`:`default`),i}if(t===a.ELLIPSE){let t=m(n),i=new r.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:l,...s});return this.bindCursor(i,u(e)?`grab`:`default`),i}let d=n.flatMap(e=>[e.x,e.y]),f=t!==a.LINE,p=new r.default.Line({points:d,closed:f,fill:f?l:void 0,lineJoin:`round`,...s});return this.bindCursor(p,u(e)?`grab`:`default`),p}liveUpdateShape(e,t){let n=this.nodes.get(e),i=this.shapes.find(t=>t.id===e);n&&i&&(Ct(n,i.type,t),i.type===a.POINT&&n instanceof r.default.Circle&&n.radius(this.pointRadius(i)),this.layer.batchDraw())}pointRadius(e){return Q(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===a.POINT){n?.scale({x:e,y:e});continue}n?.dash(this.scaledDash(V(t,{strokeWidth:this.strokeSize}).dash))}}shapesIntersecting(e){return Mt(this.shapes,e)}drawSelectionBorders(){let e=new Set(this.selected),t=this.selected.length?this.shapes.filter(t=>e.has(t.id)&&c(t)):[];if(this.selectionBorders.length!==t.length){for(let e of this.selectionBorders)e.destroy();this.selectionBorders=t.map(()=>{let e=new r.default.Line({closed:!0,stroke:zt,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)||!c(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 Pt(e,t,this.pointRadius(e))}clearPreview(){this.previewGroup.destroyChildren(),this.layer.batchDraw()}clearMarquee(){this.marquee?.destroy(),this.marquee=null,this.layer.batchDraw()}previewBox(e,t,n,i){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);this.preview=e===`ellipse`?new r.default.Ellipse({x:a+s/2,y:o+c/2,radiusX:s/2,radiusY:c/2,stroke:i,strokeWidth:this.strokeSize,strokeScaleEnabled:!1}):new r.default.Rect({x:a,y:o,width:s,height:c,stroke:i,strokeWidth:this.strokeSize,strokeScaleEnabled:!1}),this.previewGroup.add(this.preview),this.layer.batchDraw()}previewPoly(e,t,n,i,a=[],o=!0){if(this.previewGroup.destroyChildren(),!e.length)return;let s=e.flatMap(e=>[e.x,e.y]);if(t&&s.push(t.x,t.y),this.previewGroup.add(new r.default.Line({points:s,closed:i,stroke:n,strokeWidth:this.strokeSize,strokeScaleEnabled:!1,lineCap:`round`,lineJoin:`round`})),!o){this.layer.batchDraw();return}let c=new Set(a),l=this.world.scaleX()||1;for(let t=0;t<e.length;t++){let n=e[t],i=c.has(t);this.previewGroup.add(new r.default.Circle({x:n.x,y:n.y,radius:(i?6:5)/l,fill:i?Rt:`#ffffff`,stroke:i?`#ffffff`:Rt,strokeWidth:1.5,strokeScaleEnabled:!1,listening:!1}))}this.layer.batchDraw()}previewScalarMask(e,t){this.previewGroup.destroyChildren();let n=rt(e,t.length===7?`${t}99`:t);this.previewGroup.add(new r.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 r.default.Rect({fill:de(ae,oe),stroke:ae,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(y([{x:e.minX,y:e.minY},{x:e.maxX,y:e.maxY}]))}setTransformerOutlinePoints(e){e.length<2||(this.transformerOutline||(this.transformerOutline=new r.default.Line({closed:!0,stroke:Rt,strokeWidth:1,strokeScaleEnabled:!1,listening:!1}),this.selGroup.add(this.transformerOutline)),this.transformerOutline.points(e.flatMap(e=>[e.x,e.y])))}rotationHandleGap(){return Ft(this.viewport.scale)}rotationHandleScreenPoint(e){return this.imgToScreen(A(e,this.rotationHandleGap()))}setRotationConnector(e){let t=this.imgToScreen(D(e[0],e[1])),n=this.rotationHandleScreenPoint(e);this.rotLineNode?this.rotLineNode.points([t.x,t.y,n.x,n.y]):(this.rotLineNode=new r.default.Line({points:[t.x,t.y,n.x,n.y],stroke:Rt,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 It(this.imgToScreen(e[0]),this.imgToScreen(e[1]))}repositionOrientedHandles(e){let t=this.orientedHandleAngle(e);if(k(e).forEach((e,n)=>{let r=this.imgToScreen(e),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,t)}),this.setTransformerOutlinePoints(e),this.rotNode){let t=this.rotationHandleScreenPoint(e);this.rotNode.position({x:t.x,y:t.y})}this.rotLineNode&&this.setRotationConnector(e)}drawTransformer(){if(this.activeDrag)return;for(let e of this.handleNodes)e.destroy();for(let e of this.vertexNodes)e.destroy();for(let e of this.midNodes)e.destroy();if(this.rotNode?.destroy(),this.rotNode=null,this.rotLineNode?.destroy(),this.rotLineNode=null,this.transformerOutline?.destroy(),this.transformerOutline=null,this.handleNodes=[],this.vertexNodes=[],this.midNodes=[],!this.transformEnabled)return;let e=jt(this.shapes,this.selected);if(!e.length||e.length===1&&e[0].type===a.POINT)return;let t=e.length===1&&(e[0].type===a.POLYGON||e[0].type===a.LINE)&&this.editingId===e[0].id?e[0]:null,n=m(e.flatMap(e=>e.points)),i=e.length===1&&e[0].type===a.ROTATED_RECTANGLE?e[0]:null,o=i?k(i.points):p.map(e=>h(e,n));i?this.setTransformerOutlinePoints(i.points):this.setTransformerOutline(n),i&&this.setRotationConnector(i.points);let s=i?this.orientedHandleAngle(i.points):0;for(let e of t?[]:p){let t=this.imgToScreen(o[p.indexOf(e)]),n=new r.default.Rect({x:t.x,y:t.y,width:8,height:8,offsetX:4,offsetY:4,rotation:s*180/Math.PI,fill:`#ffffff`,stroke:Rt,strokeWidth:1}),i=De(e,s);this.bindCursor(n,i),n.on(`mousedown`,t=>{t.cancelBubble=!0,this.emitCursorHint(i),this.emitInteractionMode(`resizing`);let n=jt(this.shapes,this.selected);this.activeDrag={kind:`resize`,anchor:e,box:m(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,i=e.type===a.POLYGON?n.length:n.length-1;for(let t=0;t<i;t++){let i=n[t],a=n[(t+1)%n.length],o={x:(i.x+a.x)/2,y:(i.y+a.y)/2},s=this.imgToScreen(o),c=new r.default.Circle({x:s.x,y:s.y,radius:4,fill:`#ffffff`,opacity:.6,stroke:Rt,strokeWidth:1});this.bindCursor(c,`copy`),c.on(`mousedown`,r=>{r.cancelBubble=!0;let i=[...n.slice(0,t+1),o,...n.slice(t+1)];this.cb.onTransformCommit?.([{id:e.id,points:i}])}),this.handleGroup.add(c),this.midNodes.push(c)}this.vertexPolygonId!==e.id&&(this.vertexPolygonId=e.id,this.selectedVertices.clear()),n.forEach((t,i)=>{let a=this.imgToScreen(t),o=this.selectedVertices.has(i),s=new r.default.Circle({x:a.x,y:a.y,radius:5,fill:o?Rt:`#ffffff`,stroke:o?`#ffffff`:Rt,strokeWidth:1.5});this.bindCursor(s,`pointer`),s.on(`mousedown`,t=>{if(t.cancelBubble=!0,t.evt.shiftKey||t.evt.ctrlKey||t.evt.metaKey){this.selectedVertices.has(i)?this.selectedVertices.delete(i):this.selectedVertices.add(i),this.drawTransformer();return}let r=this.selectedVertices.has(i)&&this.selectedVertices.size>1?[...this.selectedVertices]:[i];r.length===1&&(this.selectedVertices.clear(),this.selectedVertices.add(i)),this.activeDrag={kind:`vertex`,id:e.id,indices:r,base:n,start:this.toImage()},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`vertexDragging`)}),this.handleGroup.add(s),this.vertexNodes.push(s)})}if(e.length===1&&e[0].type===a.ROTATED_RECTANGLE){let t=e[0],n=O(t.points),i=this.rotationHandleScreenPoint(t.points),a=new r.default.Circle({x:i.x,y:i.y,radius:6,fill:`#ffffff`,stroke:Rt,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=Z(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===a.ROTATED_RECTANGLE?this.setTransformerOutlinePoints(n.shapes[0].points):this.setTransformerOutline(n.box),this.updateSelectionBordersLive(e=>e.points))}repositionHandles(e){p.forEach((t,n)=>{let r=this.imgToScreen(h(t,e)),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,0)}),this.setTransformerOutline(e)}repositionPolygonHandles(e,t){if(!this.vertexNodes.length)return;e.forEach((e,t)=>{let n=this.imgToScreen(e);this.vertexNodes[t]?.position({x:n.x,y:n.y})});let n=t?e.length:e.length-1;for(let t=0;t<n;t++){let n=e[t],r=e[(t+1)%e.length],i=this.imgToScreen({x:(n.x+r.x)/2,y:(n.y+r.y)/2});this.midNodes[t]?.position({x:i.x,y:i.y})}}commitTransformUpdates(e){if(e.length){for(let t of e){let e=this.shapes.find(e=>e.id===t.id);e&&(e.points=t.points,this.liveUpdateShape(t.id,t.points))}this.cb.onTransformCommit?.(e),this.drawTransformer(),this.layer.batchDraw()}}dragTransform(e){let t=this.activeDrag;if(!t)return;this.applyCursor(),this.lastDragImg=e;let n=Ot(this.shapes,t),{updates:r,box:i}=kt(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,o=e?.type===a.POLYGON||e?.type===a.LINE;(t.kind===`resize`?o:this.vertexNodes.length>0&&t.shapes.length===1)&&this.repositionPolygonHandles(r[0].points,e?.type===a.POLYGON)}else if(t.kind===`rotate`){this.repositionOrientedHandles(r[0].points);let e=this.shapes.find(e=>e.id===t.id);e&&(e.type===a.POLYGON||e.type===a.LINE)&&this.repositionPolygonHandles(r[0].points,e.type===a.POLYGON)}else{i&&this.repositionHandles(i);let e=this.shapes.find(e=>e.id===t.id);this.repositionPolygonHandles(r[0].points,e?.type===a.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}=kt(e,t,Ot(this.shapes,e));this.commitTransformUpdates(n)}},Vt=2,Ht=58879,Ut=6725103;function Wt(e){if(!e)return Ht;let t=e.replace(`#`,``);return Number.parseInt(t.length===3?t.replace(/./g,`$&$&`):t,16)}var Gt=class{constructor(e,t){this.app=new i.Application,this.world=new i.Container,this.bgLayer=new i.Container,this.overlayLayer=new i.Container,this.shapeLayer=new i.Container,this.selLayer=new i.Container,this.previewLayer=new i.Container,this.handleLayer=new i.Container,this.filter=new i.ColorMatrixFilter,this.imageWidth=0,this.imageHeight=0,this.imageTileTextures=[],this.imageLoadToken=0,this.overlayTextures=[],this.roi=null,this.roiBorderG=null,this.baseCursor=`default`,this.strokeSize=Vt,this.shapes=[],this.selected=[],this.nodes=new Map,this.lastAppliedScale=-1,this.brightness=1,this.contrast=1,this.imageSmoothing=!0,this.destroyed=!1,this.transformEnabled=!1,this.handleNodes=[],this.vertexNodes=[],this.lastDragImg=null,this.activeDrag=null,this.midNodes=[],this.selectedVertices=new Set,this.vertexPolygonId=null,this.editingId=null,this.rotNode=null,this.rotLineNode=null,this.transformerOutline=null,this.selectionBorderGfx=[],this.previewG=new i.Graphics,this.marqueeG=new i.Graphics,this.previewMaskSprite=null,this.previewMaskTexture=null,this.previewReady=!1,this.host=e,this.cb=t}ev(e){return{button:e.button,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,global:{x:e.global.x,y:e.global.y}}}async init(){if(await this.app.init({resizeTo:this.host,background:`#111111`,antialias:!0,autoDensity:!0,resolution:window.devicePixelRatio||1,preference:`webgl`}),this.destroyed){this.app.destroy(!0);return}this.host.appendChild(this.app.canvas),this.applyCursor(),this.world.addChild(this.bgLayer,this.overlayLayer,this.shapeLayer,this.selLayer,this.previewLayer),this.app.stage.addChild(this.world,this.handleLayer),this.world.visible=!1,this.app.stage.eventMode=`static`,this.syncHitArea(),this.app.stage.on(`pointerdown`,e=>{this.cb.onPointerDown(this.toImage(e),null,this.ev(e))}),this.app.stage.on(`pointermove`,e=>{if(this.activeDrag){this.dragTransform(this.toImage(e));return}this.cb.onPointerMove(this.toImage(e),this.ev(e))});let e=e=>{if(this.activeDrag){this.endTransform();return}this.cb.onPointerUp(this.toImage(e))};this.app.stage.on(`pointerup`,e),this.app.stage.on(`pointerupoutside`,e),this.app.renderer.on(`resize`,()=>this.syncHitArea())}syncHitArea(){let{w:e,h:t}=this.screenSize;this.app.stage.hitArea=new i.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){let t=++this.imageLoadToken,n=null;try{let t=await fetch(e,{mode:`cors`,credentials:`omit`,cache:`no-store`});t.ok&&(n=URL.createObjectURL(await t.blob()))}catch{n=null}if(this.destroyed){n&&URL.revokeObjectURL(n);return}await new Promise(r=>{let a=new Image;n||(a.crossOrigin=`anonymous`),a.onload=()=>{if(n&&URL.revokeObjectURL(n),this.destroyed||t!==this.imageLoadToken)return r();this.imageWidth=a.naturalWidth,this.imageHeight=a.naturalHeight,this.clearImageTiles();for(let e of Y(this.imageWidth,this.imageHeight)){let t=i.Texture.from(St(a,e));t.source.scaleMode=this.imageSmoothing?`linear`:`nearest`,this.imageTileTextures.push(t);let n=new i.Sprite(t);n.x=e.x,n.y=e.y,n.width=e.width,n.height=e.height,this.bgLayer.addChild(n)}this.applySpriteFilter(),r()},a.onerror=()=>{n&&URL.revokeObjectURL(n),this.imageWidth||=800,this.imageHeight||=600,r()},a.src=n??e})}setFilter(e,t){this.brightness=e,this.contrast=t,this.applySpriteFilter()}setStrokeSize(e){this.strokeSize!==e&&(this.strokeSize=e,this.setShapes(this.shapes,this.selected))}applySpriteFilter(){if(!(this.destroyed||!this.app.renderer)){if(!(this.brightness!==1||this.contrast!==1)){this.filter.reset(),this.bgLayer.filters=void 0;return}this.filter.brightness(this.brightness,!1),this.filter.contrast(this.contrast-1,!0),this.bgLayer.filters=[this.filter]}}clearImage(){this.destroyed||(this.imageLoadToken++,this.clearImageTiles())}clearImageTiles(){for(let e of this.bgLayer.removeChildren())e.destroy();for(let e of this.imageTileTextures)e.destroy(!0);this.imageTileTextures=[]}setImageSmoothing(e){if(this.imageSmoothing===e)return;this.imageSmoothing=e;let t=e?`linear`:`nearest`;for(let e of this.imageTileTextures)e.source.scaleMode=t,e.source.style.update();!this.destroyed&&this.app.renderer&&this.app.render()}setOverlays(e,t,n){for(let e of this.overlayLayer.removeChildren())e.destroy();this.roiBorderG=null,this.roi=t;for(let e of this.overlayTextures)e.destroy(!0);if(this.overlayTextures=[],e){let t=i.Texture.from(e);t.source.scaleMode=`nearest`,this.overlayTextures.push(t);let n=new i.Sprite(t);n.alpha=.55,this.overlayLayer.addChild(n)}if(t){let e=i.Texture.from(t.dimCanvas);this.overlayTextures.push(e),this.overlayLayer.addChild(new i.Sprite(e)),this.roiBorderG=this.overlayLayer.addChild(new i.Graphics),this.redrawRoiBorder()}n&&this.imageWidth&&this.overlayLayer.addChild(new i.Graphics().rect(0,0,this.imageWidth,this.imageHeight).fill({color:855314,alpha:.3})),!this.destroyed&&this.app.renderer&&this.app.render()}get viewport(){return{scale:this.world.scale.x,x:this.world.x,y:this.world.y}}applyViewport(e){let t=e.scale!==this.lastAppliedScale;this.lastAppliedScale=e.scale,this.world.scale.set(e.scale),this.world.position.set(e.x,e.y),this.world.visible=!0,t&&this.restrokeShapes(),this.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=At(e),this.selected=t,!this.activeDrag&&(this.drawShapes(),this.drawSelectionBorders(),this.drawTransformer())}setSelection(e){this.selected=e,(e.length!==1||e[0]!==this.vertexPolygonId)&&(this.vertexPolygonId=null,this.selectedVertices.clear()),this.editingId&&(e.length!==1||e[0]!==this.editingId)&&(this.editingId=null),!this.activeDrag&&(this.drawSelectionBorders(),this.drawTransformer())}setEditing(e){this.editingId!==e&&(this.editingId=e,this.selectedVertices.clear(),this.activeDrag||this.drawTransformer())}setTransformEnabled(e){this.transformEnabled=e,this.syncShapeCursors(),this.drawTransformer()}setPanMode(e){this.handleLayer.interactiveChildren=!e}strokeW(e){return(e?V(e,{strokeWidth:this.strokeSize}).strokeWidth:Vt)/this.world.scale.x}pointRadius(e){return Q(e,this.strokeSize,this.world.scale.x)}dashForShape(e){let t=V(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 d(this.shapes).filter(o)){let t=new i.Graphics;this.paintShape(t,e),t.eventMode=c(e)?`static`:`none`,t.cursor=void 0,c(e)&&u(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=V(t,{strokeWidth:this.strokeSize}),r=Wt(n.color),i=this.strokeW(t),o=n.opacity,s=this.dashForShape(t);if(t.type===a.POINT){e.svg(Et(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=o;return}if(n.fillVisible&&t.type!==a.LINE?(this.path(e,t),e.fill({color:r,alpha:n.fillAlpha*o})):t.type!==a.LINE&&(this.path(e,t),e.fill({color:r,alpha:0})),s){this.dashedStrokeShape(e,t,i,r,o,s);return}this.path(e,t),e.stroke({width:i,color:r,alpha:o})}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 Mt(this.shapes,e)}shapesAt(e){return this.shapes.filter(t=>{let n=m(t.points);return e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY}).map(e=>e.id)}ensurePreview(){this.previewReady||=(this.previewLayer.addChild(this.previewG,this.marqueeG),!0)}clearPreview(){this.previewG.clear(),this.previewMaskSprite&&(this.previewMaskSprite.visible=!1)}clearMarquee(){this.marqueeG.clear()}previewBox(e,t,n,r){this.ensurePreview(),this.previewG.clear();let i=Math.min(t.x,n.x),a=Math.min(t.y,n.y),o=Math.abs(n.x-t.x),s=Math.abs(n.y-t.y);e===`ellipse`?this.previewG.ellipse(i+o/2,a+s/2,o/2,s/2):this.previewG.rect(i,a,o,s),this.previewG.stroke({width:this.strokeW(),color:Wt(r)})}previewPoly(e,t,n,r,i=[],a=!0){if(this.ensurePreview(),this.previewG.clear(),!e.length)return;let o=e.flatMap(e=>[e.x,e.y]);if(t&&o.push(t.x,t.y),this.previewG.poly(o,r),this.previewG.stroke({width:this.strokeW(),color:Wt(n)}),!a)return;let s=new Set(i),c=5/this.world.scale.x,l=6/this.world.scale.x;for(let t=0;t<e.length;t++){let n=e[t],r=s.has(t);this.previewG.circle(n.x,n.y,r?l:c).fill({color:r?2001125:16777215}).stroke({width:1.5/this.world.scale.x,color:r?16777215:2001125})}}previewScalarMask(e,t){this.ensurePreview(),this.previewG.clear();let n=rt(e,t.length===7?`${t}99`:t);this.previewMaskTexture&&this.previewMaskTexture.destroy(!0),this.previewMaskTexture=i.Texture.from(n),this.previewMaskSprite?(this.previewMaskSprite.texture=this.previewMaskTexture,this.previewMaskSprite.visible=!0):(this.previewMaskSprite=new i.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=Wt(ae);this.marqueeG.rect(n,r,i,a).fill({color:o,alpha:oe}).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.redrawRoiBorder()}redrawRoiBorder(){let e=this.roiBorderG;if(!e||(e.clear(),!this.roi))return;let t=this.world.scale.x||1,n=2/t,r=[ce[0]/t,ce[1]/t];for(let t of this.roi.rects)this.strokeDashedPolyline(e,[{x:t.x,y:t.y},{x:t.x+t.w,y:t.y},{x:t.x+t.w,y:t.y+t.h},{x:t.x,y:t.y+t.h}],!0,n,16777215,1,r);for(let t of this.roi.zones)this.strokeDashedPolyline(e,t.points,!0,n,16777215,1,r)}path(e,t){let{type:n,points:r}=t;if(n===a.POINT){e.circle(r[0].x,r[0].y,this.pointRadius(t));return}if(n===a.RECTANGLE){let t=m(r);e.rect(t.minX,t.minY,t.maxX-t.minX,t.maxY-t.minY);return}if(n===a.ELLIPSE){let t=m(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!==a.LINE)}dashedStrokeShape(e,t,n,r,i,o){let{type:s,points:c}=t;if(s===a.RECTANGLE){let t=m(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,o);return}if(s===a.ELLIPSE){let t=m(c),a=(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:a+Math.cos(n)*l,y:s+Math.sin(n)*u}});this.strokeDashedPolyline(e,d,!0,n,r,i,o);return}this.strokeDashedPolyline(e,c,s!==a.LINE,n,r,i,o)}strokeDashedPolyline(e,t,n,r,i,a,o){if(t.length<2)return;let[s,c]=o,l=!0,u=0,d=n?t.length:t.length-1;for(let n=0;n<d;n++){let o=t[n],d=t[(n+1)%t.length],f=d.x-o.x,p=d.y-o.y,m=Math.hypot(f,p);if(!m)continue;let h=0;for(;h<m;){let t=l?s:c,n=Math.min(t-u,m-h);if(l){let t=h/m,s=(h+n)/m;e.moveTo(o.x+f*t,o.y+p*t).lineTo(o.x+f*s,o.y+p*s).stroke({width:r,color:i,alpha:a})}h+=n,u+=n,u>=t-1e-4&&(u=0,l=!l)}}}drawSelectionBorders(){this.selLayer.position.set(0,0);let e=new Set(this.selected),t=this.selected.length?this.shapes.filter(t=>e.has(t.id)&&c(t)):[];if(this.selectionBorderGfx.length!==t.length){for(let e of this.selectionBorderGfx)e.destroy();this.selectionBorderGfx=t.map(()=>{let e=new i.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:Ut})})}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)||!c(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:Ut}))}}selectionOutlinePoints(e,t){return Pt(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(y([{x:e.minX,y:e.minY},{x:e.maxX,y:e.maxY}]))}setTransformerOutlinePoints(e){e.length<2||(this.transformerOutline||(this.transformerOutline=new i.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 Ft(this.viewport.scale)}rotationHandleScreenPoint(e){return this.imgToScreen(A(e,this.rotationHandleGap()))}setRotationConnector(e){let t=this.imgToScreen(D(e[0],e[1])),n=this.rotationHandleScreenPoint(e);this.rotLineNode||(this.rotLineNode=new i.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 It(this.imgToScreen(e[0]),this.imgToScreen(e[1]))}drawTransformer(){if(this.activeDrag)return;for(let e of this.handleNodes)e.destroy();for(let e of this.vertexNodes)e.destroy();for(let e of this.midNodes)e.destroy();if(this.rotNode?.destroy(),this.rotNode=null,this.rotLineNode?.destroy(),this.rotLineNode=null,this.transformerOutline?.destroy(),this.transformerOutline=null,this.handleNodes=[],this.vertexNodes=[],this.midNodes=[],!this.transformEnabled)return;let e=jt(this.shapes,this.selected);if(e.length===0||e.length===1&&e[0].type===a.POINT)return;let t=e.length===1&&(e[0].type===a.POLYGON||e[0].type===a.LINE)&&this.editingId===e[0].id?e[0]:null,n=m(e.flatMap(e=>e.points)),r=e.length===1&&e[0].type===a.ROTATED_RECTANGLE?e[0]:null,o=r?k(r.points):p.map(e=>h(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?[]:p){let t=this.imgToScreen(o[p.indexOf(e)]),n=new i.Graphics;n.rect(-4,-4,8,8).fill({color:16777215}).stroke({width:1,color:2001125}),this.layoutResizeHandle(n,t,s),n.eventMode=`static`;let r=De(e,s);this.bindCursor(n,r),n.on(`pointerdown`,t=>{t.stopPropagation(),this.emitCursorHint(r),this.emitInteractionMode(`resizing`);let n=jt(this.shapes,this.selected);this.activeDrag={kind:`resize`,anchor:e,box:m(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===a.POLYGON?n.length:n.length-1;for(let t=0;t<r;t++){let r=n[t],a=n[(t+1)%n.length],o={x:(r.x+a.x)/2,y:(r.y+a.y)/2},s=this.imgToScreen(o),c=new i.Graphics;c.circle(0,0,4).fill({color:16777215,alpha:.6}).stroke({width:1,color:2001125}),c.position.set(s.x,s.y),c.eventMode=`static`,this.bindCursor(c,`copy`),c.on(`pointerdown`,r=>{r.stopPropagation();let i=[...n.slice(0,t+1),o,...n.slice(t+1)];this.cb.onTransformCommit?.([{id:e.id,points:i}])}),this.handleLayer.addChild(c),this.midNodes.push(c)}this.vertexPolygonId!==e.id&&(this.vertexPolygonId=e.id,this.selectedVertices.clear()),n.forEach((t,r)=>{let a=this.imgToScreen(t),o=this.selectedVertices.has(r),s=new i.Graphics;s.circle(0,0,5).fill({color:o?2001125:16777215}).stroke({width:1.5,color:o?16777215:2001125}),s.position.set(a.x,a.y),s.eventMode=`static`,this.bindCursor(s,`pointer`),s.on(`pointerdown`,t=>{if(t.stopPropagation(),t.shiftKey||t.ctrlKey||t.metaKey){this.selectedVertices.has(r)?this.selectedVertices.delete(r):this.selectedVertices.add(r),this.drawTransformer();return}let i=this.selectedVertices.has(r)&&this.selectedVertices.size>1?[...this.selectedVertices]:[r];i.length===1&&(this.selectedVertices.clear(),this.selectedVertices.add(r)),this.activeDrag={kind:`vertex`,id:e.id,indices:i,base:n,start:this.toImage(t)},this.lastDragImg=null,this.emitCursorHint(`grabbing`),this.emitInteractionMode(`vertexDragging`)}),this.handleLayer.addChild(s),this.vertexNodes.push(s)})}if(e.length===1&&e[0].type===a.ROTATED_RECTANGLE){let t=e[0],n=O(t.points),r=this.rotationHandleScreenPoint(t.points),a=new i.Graphics;a.circle(0,0,6).fill({color:16777215}).stroke({width:1.5,color:2001125}),a.position.set(r.x,r.y),a.eventMode=`static`,this.bindCursor(a,`grab`),a.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(a),this.rotNode=a}}beginMove(e,t){let n=Z(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===a.ROTATED_RECTANGLE?this.setTransformerOutlinePoints(n.shapes[0].points):this.setTransformerOutline(n.box),this.updateSelectionBordersLive(e=>e.points))}repositionHandlesForBox(e){p.forEach((t,n)=>{let r=this.imgToScreen(h(t,e)),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,0)}),this.setTransformerOutline(e)}repositionOrientedHandles(e){let t=this.orientedHandleAngle(e);if(k(e).forEach((e,n)=>{let r=this.imgToScreen(e),i=this.handleNodes[n];i&&this.layoutResizeHandle(i,r,t)}),this.setTransformerOutlinePoints(e),this.rotNode){let t=this.rotationHandleScreenPoint(e);this.rotNode.position.set(t.x,t.y)}this.rotLineNode&&this.setRotationConnector(e)}repositionPolygonHandles(e,t){if(!this.vertexNodes.length)return;e.forEach((e,t)=>{let n=this.imgToScreen(e);this.vertexNodes[t]?.position.set(n.x,n.y)});let n=t?e.length:e.length-1;for(let t=0;t<n;t++){let n=e[t],r=e[(t+1)%e.length],i=this.imgToScreen({x:(n.x+r.x)/2,y:(n.y+r.y)/2});this.midNodes[t]?.position.set(i.x,i.y)}}resetMoveOffsets(){for(let[e,t]of this.nodes)this.shapes.find(t=>t.id===e)?.type!==a.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(),this.lastDragImg=e;let n=Ot(this.shapes,t),{updates:r,box:i}=kt(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===a.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,o=e?.type===a.POLYGON||e?.type===a.LINE;(t.kind===`resize`?o:this.vertexNodes.length>0&&t.shapes.length===1)&&this.repositionPolygonHandles(r[0].points,e?.type===a.POLYGON)}else if(t.kind===`rotate`){this.repositionOrientedHandles(r[0].points);let e=this.shapes.find(e=>e.id===t.id);e&&(e.type===a.POLYGON||e.type===a.LINE)&&this.repositionPolygonHandles(r[0].points,e.type===a.POLYGON)}else{i&&this.repositionHandlesForBox(i);let e=this.shapes.find(e=>e.id===t.id);this.repositionPolygonHandles(r[0].points,e?.type===a.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}=kt(e,t,Ot(this.shapes,e));e.kind===`move`&&this.resetMoveOffsets(),this.commitTransformUpdates(n)}};function Kt({backend:e,hostRef:n,engineRef:r,imageUrl:i,renderedImageUrl:a,makeCallbacks:o,viewRef:s,readOnlyRef:c,toolRef:l,docRef:u,selRef:d,maskCanvasRef:f,roiOverlayRef:p,dimmedRef:m,syncMinimap:h,setImage:g,setImageVisible:_,setReady:v,setImageStatus:y,onContextMenuRequest:b}){let x=(0,t.useRef)(a);x.current=a;let S=(0,t.useRef)(i);S.current=i;let C=(0,t.useRef)(null),w=(0,t.useRef)(null),T=(0,t.useRef)(!1),E=(0,t.useRef)(null),D=(0,t.useRef)(o);D.current=o;let O=(0,t.useRef)(b);O.current=b,(0,t.useEffect)(()=>{let t=n.current;if(!t)return;let i=!1,a=null,o=null,y=D.current(),b=e===`konva`?new Bt(t,y):new Gt(t,y);return r.current=b,(async()=>{if(await b.init(),!i){if(b.setFilter(s.current.brightness,s.current.contrast),b.setStrokeSize(s.current.strokeSize),b.setImageSmoothing(s.current.imageSmoothing),b.setTransformEnabled(!c.current),T.current=!0,x.current){if(await b.setImage(x.current),i)return;C.current=x.current,w.current=S.current,g({w:b.imageWidth,h:b.imageHeight}),_(!0),b.setShapes(u.current.getShapes(),d.current),b.setOverlays(s.current.showGuide?f.current:null,s.current.showRoi?p.current:null,m.current);let e=E.current;e?.viewport&&(e.imageUrl===C.current||s.current.keepZoomOnImageChange)?b.applyViewport(e.viewport):b.fit(),h(),v(!0)}a=e=>{e.preventDefault();let t=b.dom.getBoundingClientRect();if(e.ctrlKey||e.metaKey){b.zoomAt(e.clientX-t.left,e.clientY-t.top,Math.exp(-e.deltaY*.01));return}if(!s.current.wheelZoom){let t=b.viewport;b.applyViewport({scale:t.scale,x:t.x-e.deltaX,y:t.y-e.deltaY});return}b.zoomAt(e.clientX-t.left,e.clientY-t.top,e.deltaY<0?1.1:1/1.1)},b.dom.addEventListener(`wheel`,a,{passive:!1}),o=e=>{if(e.preventDefault(),l.current===F.ASSISTANT_POINT&&e.altKey)return;let n=t.getBoundingClientRect(),r=e.clientX-n.left,i=e.clientY-n.top,a=b.viewport;O.current({x:r,y:i,img:{x:(r-a.x)/a.scale,y:(i-a.y)/a.scale}})},b.dom.addEventListener(`contextmenu`,o)}})(),()=>{i=!0,T.current=!1,E.current={imageUrl:C.current??``,viewport:b.viewport},r.current=null,a&&b.dom&&b.dom.removeEventListener(`wheel`,a),o&&b.dom&&b.dom.removeEventListener(`contextmenu`,o),b.destroy()}},[e]),(0,t.useEffect)(()=>{let e=r.current;if(!e||!T.current||!a||C.current===a)return;let t=a,n=w.current!==i;n&&(e.clearImage(),e.setShapes([],[]),e.setOverlays(null,null,!1),_(!1));let o=!1;return(async()=>{await e.setImage(t),!(o||r.current!==e)&&(C.current=t,n&&(w.current=i,g({w:e.imageWidth,h:e.imageHeight}),_(!0),e.setShapes(u.current.getShapes(),d.current),e.setOverlays(s.current.showGuide?f.current:null,s.current.showRoi?p.current:null,m.current),s.current.keepZoomOnImageChange||e.fit(),h(),v(!0)))})(),()=>{o=!0}},[a]),(0,t.useEffect)(()=>{let e=!1;if(!a){y(`loading`);return}y(`loading`);let t=new Image;return t.onload=()=>{e||y(`ready`)},t.onerror=()=>{e||y(`error`)},t.src=a,()=>{e=!0}},[a])}var qt=.05,Jt=20;function Yt(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 Xt({engineRef:e,image:n,wheelZoom:r,minimapSize:i}){let a=(0,t.useRef)(null),o=!!n&&n.w>0&&n.h>0,s=o?Math.min(i/n.w,i/n.h):1,c=o?n.w*s:0,l=o?n.h*s:0,u=o?(i-c)/2:0,d=o?(i-l)/2:0,f=e=>{let t=e.currentTarget.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}},p=()=>{let t=e.current;if(!t)return null;let n=t.viewport;return{x:-n.x/n.scale*s+u,y:-n.y/n.scale*s+d,width:t.screenSize.w/n.scale*s,height:t.screenSize.h/n.scale*s}},m=(t,r,i)=>{let a=e.current;if(!a||!n)return;let o=p();if(!o)return;let c=i?.offsetX??o.width/2,l=i?.offsetY??o.height/2,f=t.x-c+o.width/2,m=t.y-l+o.height/2,h=(f-u)/s,g=(m-d)/s;a.applyViewport({scale:r,x:a.screenSize.w/2-h*r,y:a.screenSize.h/2-g*r})};return{mm:s,offX:u,offY:d,dispW:c,dispH:l,handleMinimapPointerDown:t=>{let n=e.current,r=p();if(!n||!r)return;t.preventDefault(),t.stopPropagation();let i=f(t),o=i.x>=r.x&&i.x<=r.x+r.width&&i.y>=r.y&&i.y<=r.y+r.height?{offsetX:i.x-r.x,offsetY:i.y-r.y}:{offsetX:r.width/2,offsetY:r.height/2};a.current={pointerId:t.pointerId,...o},t.currentTarget.setPointerCapture(t.pointerId),m(i,n.viewport.scale,o)},handleMinimapPointerMove:t=>{let n=a.current,r=e.current;!n||!r||n.pointerId!==t.pointerId||(t.preventDefault(),t.stopPropagation(),m(f(t),r.viewport.scale,n))},endMinimapDrag:e=>{let t=a.current;!t||t.pointerId!==e.pointerId||(a.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))},handleMinimapWheel:t=>{let n=e.current;if(!n||!r)return;t.preventDefault(),t.stopPropagation();let i=Yt(t.nativeEvent)?2.5:1,a=t.deltaY*i,o=1.05,s=a>0?n.viewport.scale/o:n.viewport.scale*o,c=Math.max(qt,Math.min(Jt,s));m(f(t),c)},zoomCentered:t=>{let n=e.current;if(!n)return;let{w:r,h:i}=n.screenSize;n.zoomAt(r/2,i/2,t)}}}function Zt(e,t,n){if(!(!e||!n.length)){if(t.type===a.POINT){e.setAttribute(`cx`,String(n[0].x)),e.setAttribute(`cy`,String(n[0].y));return}if(t.type===a.RECTANGLE||t.type===a.ELLIPSE){let r=m(n);if(t.type===a.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 Qt({engineRef:e,docRef:n,overlayRef:r,zoomLabelRef:i,minimapRectRef:a,minimapSize:o,onViewportChangeRef:s}){let c=(0,t.useRef)(new Map);return{registerMinimapShape:(0,t.useCallback)((e,t)=>{t?c.current.set(e,t):c.current.delete(e)},[]),applyMinimapPreview:(0,t.useCallback)(e=>{let t=n.current.getShapes();if(!e.length){for(let e of t)Zt(c.current.get(e.id),e,e.points);return}let r=new Map(t.map(e=>[e.id,e]));for(let t of e){let e=r.get(t.id);e&&Zt(c.current.get(e.id),e,t.points)}},[n]),syncMinimap:(0,t.useCallback)(()=>{let t=e.current;if(!t?.imageWidth)return;let n=t.viewport;if(s.current?.(n),r.current){r.current.style.transform=`translate(${n.x}px, ${n.y}px) scale(${n.scale})`;let e=1/(n.scale||1);r.current.style.setProperty(`--editor-overlay-stroke`,`${e}`),r.current.style.setProperty(`--editor-overlay-dash`,`${4*e}`),r.current.style.setProperty(`--editor-overlay-inverse-scale`,`${e}`)}i.current&&(i.current.textContent=`${Math.round(n.scale*100)}%`);let c=a.current;if(!c)return;let l=Math.min(o/t.imageWidth,o/t.imageHeight),u=(o-t.imageWidth*l)/2,d=(o-t.imageHeight*l)/2,{w:f,h:p}=t.screenSize;c.style.left=`${-n.x/n.scale*l+u}px`,c.style.top=`${-n.y/n.scale*l+d}px`,c.style.width=`${f/n.scale*l}px`,c.style.height=`${p/n.scale*l}px`},[e,r,i,a,o,s])}}var $t=12;function en({doc:e,selRef:n,effectiveReadOnly:r,changeSelection:i,canMergeSelection:o}){let s=(0,t.useRef)([]),u=(0,t.useRef)(0),d=(0,t.useCallback)(()=>i(e.getShapes().filter(e=>c(e)).map(e=>e.id)),[e,i]),p=(0,t.useCallback)(()=>i([]),[i]),h=(0,t.useCallback)(()=>e.getShapes().filter(e=>n.current.includes(e.id)&&l(e)),[e,n]),g=(0,t.useCallback)(()=>{if(r||!n.current.length)return;let t=h().map(e=>e.id);t.length&&(e.remove(t),i([]))},[e,r,i,h,n]),_=(0,t.useCallback)(()=>{s.current=h(),u.current=0},[h]),v=(0,t.useCallback)(()=>s.current.length>0,[]),y=(0,t.useCallback)(()=>{if(r||!s.current.length)return;u.current+=1;let t=$t*u.current,n=s.current.map(e=>({...e,id:f(),points:e.points.map(e=>({x:e.x+t,y:e.y+t}))}));e.create(n),i(n.map(e=>e.id))},[e,r,i]),b=(0,t.useCallback)(()=>{if(r||!n.current.length)return;let t=h().map(e=>({...e,id:f(),points:e.points.map(e=>({x:e.x+$t,y:e.y+$t}))}));t.length&&(e.create(t),i(t.map(e=>e.id)))},[e,r,i,h,n]),x=(0,t.useCallback)(()=>{if(r)return;let t=h().map(e=>e.id);t.length&&e.reorder(t,`front`)},[e,r,h]),S=(0,t.useCallback)(()=>{if(r)return;let t=h().map(e=>e.id);t.length&&e.reorder(t,`back`)},[e,r,h]),C=(0,t.useCallback)(t=>{if(r||!n.current.length)return;let i=h();if(!i.length)return;let a=m(i.flatMap(e=>e.points)),o=(a.minX+a.maxX)/2,s=(a.minY+a.maxY)/2;e.update(i.map(e=>({...e,points:e.points.map(e=>({x:t?2*o-e.x:e.x,y:t?e.y:2*s-e.y}))})))},[e,r,h,n]),w=(0,t.useCallback)((t,i)=>{if(r||!n.current.length)return;let a=e.getShapes().filter(e=>n.current.includes(e.id));a.length&&e.update(a.map(e=>({...e,points:e.points.map(e=>({x:e.x+t,y:e.y+i}))})))},[e,r,n]),T=(0,t.useCallback)(()=>h().filter(e=>e.type===a.POLYGON||e.type===a.RECTANGLE||e.type===a.ROTATED_RECTANGLE||e.type===a.ELLIPSE),[h]);return{selectAll:d,clearSelection:p,getEditableSelection:h,deleteSelection:g,copySelection:_,canPaste:v,paste:y,duplicate:b,bringToFront:x,sendToBack:S,flip:C,nudgeSelection:w,getMergeTargets:T,mergeSelection:(0,t.useCallback)(()=>{if(r)return;let t=T();if(t.length<2||o&&!o(t))return;let n=nt([],1,tt(t));if(!n)return;let s=q(n,1);if(!s.length)return;let c=t[0],l=s.map(e=>({id:f(),type:a.POLYGON,points:e,style:c.style,meta:c.meta}));e.replace(t.map(e=>e.id),l),i(l.map(e=>e.id))},[e,r,T,o,i])}}function tn({engineRef:e,doc:n,selRef:r,zoomAnimationDuration:i,zoomBound:a,ready:o}){let s=(0,t.useRef)(null),c=(0,t.useRef)(null),l=(0,t.useCallback)(()=>{s.current?.(),s.current=null},[]),u=(0,t.useCallback)((t,n=i)=>{let r=e.current;r&&(l(),s.current=Ve(r.viewport,t,e=>r.applyViewport(e),n))},[l,i,e]),d=(0,t.useCallback)((t,n=i)=>{let r=e.current;if(!r)return;let a=ze(t,r.screenSize.w,r.screenSize.h);a&&u(a,n)},[u,i,e]),f=(0,t.useCallback)((e,t=i)=>{let r=Re(n.getShapes().filter(t=>e.includes(t.id)));r&&d(r,t)},[n,d,i]),p=(0,t.useCallback)(()=>{let t=n.getShapes().filter(e=>r.current.includes(e.id));if(!t.length)return;let i=e.current;if(!i)return;let a=Be(m(t.flatMap(e=>e.points)),i.screenSize.w,i.screenSize.h,80);a&&u(a)},[n,u,e,r]),h=(0,t.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,t.useEffect)(()=>()=>l(),[l]),(0,t.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:h}}var nn=180,rn=`__draft_preview__`;function an(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function on({imageUrl:r,displayImageUrl:i,renderImageState:s,dimmed:u=!1,initialShapes:d,selectedIds:p,activeTool:h,draftStyle:g,draftMeta:_,readOnly:v,locked:y,onLockedInteraction:b,onIdleEscape:x,overrideShapeInteraction:S,defaultViewSettings:C,viewSettings:w,onViewSettingsChange:T,showMinimap:E=!0,showViewSettings:D=!0,getContextMenuItems:O,strings:k,canMergeSelection:A,brushSize:ee=20,zoomBound:j,zoomAnimationDuration:M=300,rois:N,excludedZones:te,guideMask:ne,maskPalette:L,overlayMarkers:R,renderOverlayMarker:ae,onOverlayMarkerClick:oe,renderImageOverlay:se,getSelectionLabel:ce,formatSelectionInfo:le,externalTools:ue,assistant:V,keymap:de,handleRef:fe,backend:pe=`pixi`,onActiveToolChange:me,onSelectionChange:he,onEditingChange:ge,onShapesCreated:ve,onShapesUpdated:ye,onShapesDeleted:be,onDrawSessionChange:Ce,onViewportChange:Te}){let Ee=(0,t.useRef)(null),H=(0,t.useRef)(null),De=(0,t.useRef)(null),Oe=(0,t.useRef)(null),Ae=(0,t.useRef)(null),je=`${(0,t.useId)()}-minimap`,[U,Pe]=(0,t.useState)(null),[Fe,Ie]=(0,t.useState)(!1),[W,Le]=(0,t.useState)(!1),[Re,ze]=(0,t.useState)(null),[Be,Ve]=(0,t.useState)({active:!1,kind:`none`,canUndo:!1,canRedo:!1}),[We,Ge]=(0,t.useState)(!0),[Ke,qe]=(0,t.useState)(!1),Je=i??r,[Ye,Xe]=(0,t.useState)(`loading`),G=dt({onShapesCreated:ve,onShapesUpdated:ye,onShapesDeleted:be}),[Ze,Qe]=(0,t.useState)([]),K=p??Ze,$e=p!==void 0,et=(0,t.useMemo)(()=>new Map((ue??[]).map(e=>[e.id,e])),[ue]),tt=(0,t.useRef)(et);tt.current=et;let nt=(0,t.useRef)(Be);nt.current=Be;let[q,rt]=(0,t.useState)(()=>{let e=Object.fromEntries(Object.entries(C??{}).filter(([,e])=>e!==void 0));return{...I,...e}}),it=(0,t.useCallback)(e=>rt(t=>({...t,...e})),[]),J=(0,t.useMemo)(()=>P(k),[k]);(0,t.useEffect)(()=>{w&&rt(e=>{let t=Object.entries(w).filter(([t,n])=>n!==void 0&&e[t]!==n);return t.length?{...e,...Object.fromEntries(t)}:e})},[w]);let at=(0,t.useRef)(T);at.current=T;let ot=(0,t.useRef)(!1);(0,t.useEffect)(()=>{if(!ot.current){ot.current=!0;return}at.current?.(q)},[q]);let st=(0,t.useMemo)(()=>!ne||!L?null:Me(ne,L),[ne,L]),lt=(0,t.useMemo)(()=>st?.toDataURL()??null,[st]),ut=(0,t.useMemo)(()=>!U||!N?.length?null:Ne(N,te,U.w,U.h),[U,N,te]),ft=(0,t.useRef)(st);ft.current=st;let pt=(0,t.useRef)(ut);pt.current=ut;let mt=(0,t.useRef)(u);mt.current=u;let ht=(0,t.useRef)([]);ht.current=K;let gt=(0,t.useRef)(h);gt.current=h;let _t=(0,t.useRef)(g);_t.current=g;let vt=(0,t.useRef)(_);vt.current=_;let yt=(0,t.useRef)(ee);yt.current=ee;let xt=(0,t.useRef)(q.simplifyStrength);xt.current=q.simplifyStrength;let Y=!!v||!!y,St=(0,t.useRef)(Y);St.current=Y;let Ct=(0,t.useRef)(y);Ct.current=y;let wt=(0,t.useRef)(b);wt.current=b;let Tt=(0,t.useRef)(S);Tt.current=S;let X=(0,t.useRef)(G);X.current=G;let Et=(0,t.useRef)(!1),Dt=(0,t.useRef)(!1),Ot=(0,t.useRef)(`idle`),kt=(0,t.useRef)(null),Z=(0,t.useCallback)(()=>{let e=H.current;if(!e)return;let t=gt.current,n=tt.current.get(t),r=nt.current;e.setCursor(ke({tool:t,externalToolCursor:n?.cursor,isSpacePressed:Et.current,interactionMode:Ot.current,rendererCursorHint:kt.current,isPolygonDrawing:r.kind===`polygon`&&r.active}))},[]),At=(0,t.useCallback)(e=>{Ot.current!==e&&(Ot.current=e,Z())},[Z]),jt=(0,t.useCallback)(e=>{kt.current!==e&&(kt.current=e,Z())},[Z]),Mt=(0,t.useCallback)(e=>{let t=new Set,n=new Map(X.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=Tt.current?.(r);return c(i?{...r,interaction:{...r.interaction,...i}}:r)})},[]),Q=(0,t.useCallback)(e=>{let t=Mt(e);an(ht.current,t)||($e||Qe(t),H.current?.setSelection(t),he?.(t))},[Mt,he,$e]),Nt=(0,t.useRef)(Q);Nt.current=Q;let[Pt,Ft]=(0,t.useState)(null),It=(0,t.useCallback)(e=>Ft(e),[]),Lt=(0,t.useRef)(It);Lt.current=It,(0,t.useEffect)(()=>{if(!$e)return;let e=Mt(p);an(p,e)||he?.(e)},[p,G.shapes,Mt,he,$e]);let Rt=(0,t.useRef)(Te);Rt.current=Te;let{registerMinimapShape:zt,applyMinimapPreview:Bt,syncMinimap:Vt}=Qt({engineRef:H,docRef:X,overlayRef:Oe,zoomLabelRef:Ae,minimapRectRef:De,minimapSize:nn,onViewportChangeRef:Rt}),Ht=(0,t.useRef)(new Map),Ut=(0,t.useRef)(le);Ut.current=le;let Wt=(0,t.useCallback)((e,t)=>{t?Ht.current.set(e,t):Ht.current.delete(e)},[]),Gt=(0,t.useRef)(null),[qt,Jt]=(0,t.useState)(null),Yt=(0,t.useCallback)(e=>{if(!e.length)return;let t=new Map(X.current.getShapes().map(e=>[e.id,e]));Gt.current&&t.set(Gt.current.id,Gt.current);for(let{id:n,points:r}of e){let e=Ht.current.get(n),i=t.get(n);if(!e||!i)continue;let a=m(r);e.style.left=`${a.minX}px`,e.style.top=`${a.minY}px`,e.style.width=`${a.maxX-a.minX}px`,e.style.height=`${a.maxY-a.minY}px`;let o=e.querySelector(`[data-selinfo-dim]`);if(o){let e=xe(i,r);o.textContent=Ut.current?.(e)??Se(e)}}},[]),Zt=(0,t.useCallback)(e=>{Bt(e),Yt(e)},[Bt,Yt]),$t=(0,t.useCallback)(e=>{if(!e||!_t.current){Gt.current&&(Gt.current=null,Jt(null));return}let t={id:rn,type:e.type,points:e.points,style:_t.current,meta:vt.current},n=Gt.current!==null;Gt.current=t,n?Yt([{id:rn,points:e.points}]):Jt(t)},[Yt]),on=(0,t.useCallback)((e,t)=>{let n=_t.current;if(!n||St.current)return;let r=f();X.current.create({id:r,type:e,points:t,style:n,meta:_}),Nt.current([r])},[_]),sn=(0,t.useRef)(on);sn.current=on;let cn=ct({toolRef:gt,selRef:ht,docRef:X,readOnlyRef:St,draftRef:_t,brushSizeRef:yt,simplifyEpsilonRef:xt,draftMeta:_,engineRef:H,onDrawSessionChange:(0,t.useCallback)(e=>{Ve(e),Ce?.(e)},[Ce]),changeSelection:Q,createShape:on}),ln=(0,t.useRef)(cn);ln.current=cn;let{reset:un,undoSession:dn,redoSession:fn,canUndoSession:pn,canRedoSession:mn,hasDraftSession:hn,hasDraftPoints:gn,commitDraftSession:_n,setBrushScalarMode:vn,getBrushScalarMode:yn,hasBrushSession:bn,commitBrush:xn,cancelBrush:Sn,beginBrushEditFromSelection:Cn,deleteDraftSelectedPoints:wn,handleToolChange:Tn,handleBrushSelectionChange:En}=cn,Dn=(0,t.useRef)(V);Dn.current=V;let $=Ue({docRef:X,draftRef:_t,draftMeta:_,changeSelection:Q,assistantRef:Dn}),On=(0,t.useRef)($);On.current=$;let{selectAll:kn,clearSelection:An,deleteSelection:jn,copySelection:Mn,canPaste:Nn,paste:Pn,duplicate:Fn,bringToFront:In,sendToBack:Ln,flip:Rn,nudgeSelection:zn,getMergeTargets:Bn,mergeSelection:Vn}=en({doc:G,selRef:ht,effectiveReadOnly:Y,changeSelection:Q,canMergeSelection:A}),{zoomToBounds:Hn,zoomToShapes:Un,zoomToSelection:Wn,zoomAtCenter:Gn}=tn({engineRef:H,doc:G,selRef:ht,zoomAnimationDuration:M,zoomBound:j,ready:W});(0,t.useImperativeHandle)(fe,()=>({undo:()=>{dn()||G.undo()},redo:()=>{fn()||G.redo()},canUndo:()=>pn()||G.canUndo(),canRedo:()=>mn()||G.canRedo(),undoSession:dn,redoSession:fn,canUndoSession:pn,canRedoSession:mn,hasDraftSession:hn,cancelDraftSession:un,commitDraftSession:_n,setSelection:Q,createShapes:e=>{e.length&&(G.create(e),Q(e.map(e=>e.id)))},updateShapes:G.update,deleteShapes:G.remove,getShapes:G.getShapes,selectAll:kn,clearSelection:An,deleteSelection:jn,copySelection:Mn,paste:Pn,duplicate:Fn,bringToFront:In,sendToBack:Ln,flipHorizontal:()=>Rn(!0),flipVertical:()=>Rn(!1),zoomFit:()=>H.current?.fit(),zoom100:()=>H.current?.zoom100(),zoomIn:()=>{let e=H.current;if(!e)return;let{w:t,h:n}=e.screenSize;e.zoomAt(t/2,n/2,1.2)},zoomOut:()=>{let e=H.current;if(!e)return;let{w:t,h:n}=e.screenSize;e.zoomAt(t/2,n/2,1/1.2)},zoomToSelection:Wn,zoomToShapes:Un,zoomToBounds:Hn,brush:{setScalarMode:vn,getScalarMode:yn,hasSession:bn,commit:xn,cancel:Sn,beginEditFromSelection:Cn}}),[G,Q,dn,fn,_n,un,xn,Sn,kn,An,jn,Mn,Pn,Fn,In,Ln,Rn,Wn,Un,Hn,vn,yn,bn,Cn]);let Kn=(0,t.useRef)(q);Kn.current=q,Kt({backend:pe,hostRef:Ee,engineRef:H,imageUrl:r,renderedImageUrl:Je,makeCallbacks:(0,t.useCallback)(()=>He({engineRef:H,toolRef:gt,externalToolMapRef:tt,spaceRef:Et,shiftRef:Dt,docRef:X,selRef:ht,draftRef:_t,readOnlyRef:St,lockedRef:Ct,onLockedInteraction:()=>wt.current?.(),createRef:sn,selectRef:Nt,enterEditRef:Lt,drawSessionRef:ln,assistantRef:On,setCursorHint:jt,setInteractionMode:At,syncMinimap:Vt,onTransformPreview:Zt,onDrawPreview:$t}),[jt,At,Vt,Zt,$t]),viewRef:Kn,readOnlyRef:St,toolRef:gt,docRef:X,selRef:ht,maskCanvasRef:ft,roiOverlayRef:pt,dimmedRef:mt,syncMinimap:Vt,setImage:Pe,setImageVisible:Ie,setReady:Le,setImageStatus:Xe,onContextMenuRequest:ze});let qn=(0,t.useMemo)(()=>S?G.shapes.map(e=>{let t=S(e);return t?{...e,interaction:{...e.interaction,...t}}:e}):G.shapes,[G.shapes,S]);(0,t.useEffect)(()=>{H.current?.setShapes(qn,K),Vt()},[qn,K,Vt]),(0,t.useEffect)(()=>{H.current?.setEditing(Pt)},[Pt,W]);let Jn=(0,t.useRef)(ge);Jn.current=ge,(0,t.useEffect)(()=>{Jn.current?.(Pt)},[Pt]),(0,t.useEffect)(()=>{Ft(null)},[h]),(0,t.useEffect)(()=>{Pt&&(K.length!==1||K[0]!==Pt)&&Ft(null)},[K,Pt]),(0,t.useEffect)(()=>{let e=H.current;e&&(e.setFilter(q.brightness,q.contrast),e.setStrokeSize(q.strokeSize),e.setImageSmoothing(q.imageSmoothing),Vt())},[q.brightness,q.contrast,q.strokeSize,q.imageSmoothing,Vt]),(0,t.useEffect)(()=>{W&&H.current?.setOverlays(q.showGuide?st:null,q.showRoi?ut:null,u)},[W,st,ut,q.showGuide,q.showRoi,u]),(0,t.useEffect)(()=>{!W||!U||Vt()},[W,U,lt,q.showGuide,q.showRoi,N,te,Vt]),(0,t.useEffect)(()=>{W&&H.current?.setTransformEnabled(!Y&&h!==F.BRUSH)},[Y,W,h]),(0,t.useEffect)(()=>{Tn(h,et.has(h))},[h,et,Tn]);let Yn=$.finalize;(0,t.useEffect)(()=>{Yn()},[h,Yn]),(0,t.useEffect)(()=>{Ot.current=`idle`,kt.current=null,Z()},[h,pe,Z]),(0,t.useEffect)(()=>{En(K,Y)},[K,h,Y,En]),(0,t.useEffect)(()=>{W&&Z()},[h,Be,et,W,Z]);let Xn=(0,t.useRef)(null);(0,t.useEffect)(()=>{Xn.current!==r&&(Xn.current=r,G.reset(d??[]),Q([]),un(),Yn())},[r,d,G.reset,Q,un,Yn]),bt({keymap:de,actions:{undo:()=>{Y||dn()||G.undo()},redo:()=>{Y||fn()||G.redo()},selectAll:kn,copy:Mn,cut:()=>{Mn(),jn()},paste:Pn,duplicate:Fn,delete:()=>{gn()?wn():jn()},cancel:()=>{let e=tt.current.get(gt.current);if(!(e?.onCancel&&e.onCancel()!==!1)){if($.isActive()){$.cancel();return}if(hn()){un();return}if(Pt){Ft(null);return}if(ht.current.length){An();return}x?.()}},commitDraft:()=>{if($.isActive()){$.finalize();return}if(hn()){_n();return}if(Y)return;if(Pt){Ft(null);return}let e=ht.current;if(e.length!==1)return;let t=X.current.getShapes().find(t=>t.id===e[0]);t&&(t.type===a.POLYGON||t.type===a.LINE)&&t.interaction?.editable!==!1&&!t.readOnly&&Ft(e[0])},bringToFront:In,sendToBack:Ln,flipHorizontal:()=>Rn(!0),flipVertical:()=>Rn(!1),zoomIn:()=>Gn(1.2),zoomOut:()=>Gn(1/1.2),zoom100:()=>H.current?.zoom100(),zoomFit:()=>H.current?.fit(),toggleMinimap:()=>Ge(e=>!e),toggleCursorGuide:()=>rt(e=>({...e,showCursorGuide:!e.showCursorGuide})),togglePixelation:()=>rt(e=>({...e,imageSmoothing:!e.imageSmoothing})),selectTool:()=>me?.(F.SELECT),rectangleTool:()=>me?.(F.RECTANGLE),rotatedRectangleTool:()=>me?.(F.ROTATED_RECTANGLE),circleTool:()=>me?.(F.CIRCLE),polygonTool:()=>me?.(F.POLYGON),pathTool:()=>me?.(F.PATH),brushTool:()=>me?.(F.BRUSH),pointTool:()=>me?.(F.POINT)},spaceRef:Et,shiftRef:Dt,onSpaceDown:()=>{H.current?.setPanMode(!0),Z()},onSpaceUp:()=>{H.current?.setPanMode(!1),Ot.current===`panning`?At(`idle`):Z()},nudge:zn});let Zn=(0,t.useMemo)(()=>qn.filter(e=>K.includes(e.id)&&o(e)),[qn,K]),Qn=(0,t.useMemo)(()=>qt?[...Zn,qt]:Zn,[Zn,qt]),$n=K.length>0,er=G.shapes.some(e=>K.includes(e.id)&&l(e)),tr=!Y&&K.length===1&&(()=>{let e=G.shapes.find(e=>e.id===K[0]);return!!e&&(e.type===a.POLYGON||e.type===a.LINE)&&e.interaction?.editable!==!1&&!e.readOnly})(),nr=Bn(),rr=Y||nr.length<2||(A?!A(nr):!1),ir=V&&!Y&&K.length===1?(()=>{let e=G.shapes.find(e=>e.id===K[0]);return e&&e.type===a.POLYGON&&e.interaction?.editable!==!1&&!e.readOnly?e:null})():null,ar=[{label:J.contextMenu.copy,shortcut:`⌘C`,disabled:!$n,onClick:Mn},{label:J.contextMenu.paste,shortcut:`⌘V`,disabled:Y||!Nn(),onClick:Pn},{label:J.contextMenu.duplicate,shortcut:`⌘D`,disabled:!er||Y,onClick:Fn},{label:J.contextMenu.delete,shortcut:`Del`,danger:!0,disabled:!er||Y,onClick:jn},{separator:!0},{label:J.contextMenu.editVertices,shortcut:`Enter`,disabled:!tr,onClick:()=>Ft(K[0])},{label:J.contextMenu.merge,disabled:rr,onClick:Vn},{label:J.contextMenu.assistExpand,icon:(0,n.jsx)(e.mr,{size:14}),disabled:!ir,onClick:()=>{Re&&ir&&$.refineShape(ir,Re.img,!0)}},{label:J.contextMenu.assistExclude,icon:(0,n.jsx)(e.mr,{size:14}),disabled:!ir,onClick:()=>{Re&&ir&&$.refineShape(ir,Re.img,!1)}},{label:J.contextMenu.bringToFront,disabled:!er||Y,onClick:In},{label:J.contextMenu.sendToBack,disabled:!er||Y,onClick:Ln},{label:J.contextMenu.flipHorizontal,disabled:!er||Y,onClick:()=>Rn(!0)},{label:J.contextMenu.flipVertical,disabled:!er||Y,onClick:()=>Rn(!1)},{separator:!0},{label:J.contextMenu.undo,shortcut:`⌘Z`,disabled:Y||!pn()&&!G.canUndo(),onClick:()=>{dn()||G.undo()}},{label:J.contextMenu.redo,shortcut:`⇧⌘Z`,disabled:Y||!mn()&&!G.canRedo(),onClick:()=>{fn()||G.redo()}},{separator:!0},{label:J.contextMenu.selectAll,shortcut:`⌘A`,onClick:kn},{label:J.contextMenu.clearSelection,disabled:!$n,onClick:An},{label:J.contextMenu.zoomToSelection,disabled:!$n,onClick:Wn}],or=O?O(ar,{selectedIds:K,readOnly:Y}):ar,sr=Xt({engineRef:H,image:U,wheelZoom:q.wheelZoom,minimapSize:nn});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:Ee,className:`aivex:h-full aivex:w-full`,style:{opacity:+!!Fe,transition:Fe?`opacity 0.3s ease`:`none`}}),Ye!==`ready`&&(0,n.jsx)(B,{status:Ye,render:s,loadingLabel:J.imageLoading,errorLabel:J.imageLoadError}),W&&U&&(0,n.jsx)(`div`,{className:`aivex:pointer-events-none aivex:absolute aivex:inset-0 aivex:overflow-hidden`,children:(0,n.jsxs)(`div`,{ref:Oe,style:{position:`absolute`,top:0,left:0,width:U.w,height:U.h,transformOrigin:`0 0`},children:[!!R?.length&&ae&&(0,n.jsx)(`div`,{style:{position:`absolute`,left:0,top:0,width:U.w,height:U.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||oe?.(e)},onKeyDown:t=>{e.disabled||t.key!==`Enter`&&t.key!==` `||(t.preventDefault(),t.stopPropagation(),oe?.(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:ae(e)},e.id))}),se?.({image:U,viewport:H.current?.viewport??{scale:1,x:0,y:0}}),Qn.length>0&&(0,n.jsx)(we,{shapes:Qn,getLabel:ce,formatInfo:le,register:Wt}),V&&($.status===`loading`||$.boxes.length>0)&&(0,n.jsx)(z,{image:U,points:$.points,boxes:$.boxes,status:$.status})]})}),W&&q.showCursorGuide&&(0,n.jsx)(ie,{color:`#1e88e5`}),W&&U&&E&&(0,n.jsx)(_e,{image:U,imageUrl:Je,imageVisible:Fe,maskDataUrl:lt,rois:N,excludedZones:te,roiMaskId:je,shapes:qn,view:q,onChangeView:it,nav:sr,registerShape:zt,rectRef:De,zoomLabelRef:Ae,onZoom100:()=>H.current?.zoom100(),open:We,onToggleOpen:()=>Ge(e=>!e),labels:J.minimap,settingsLabels:J.viewSettings,showSettings:D,settingsOpen:Ke,onToggleSettings:()=>qe(e=>!e),onCloseSettings:()=>qe(!1)}),Re&&(0,n.jsx)(re,{x:Re.x,y:Re.y,items:or,onClose:()=>ze(null)})]})}exports.DEFAULT_EDITOR_STRINGS=N,exports.DEFAULT_VIEW_SETTINGS=I,exports.SHAPE_TYPE=a,exports.ShapeEditor=on,exports.default=on,exports.TOOL=F,exports.generateId=f;
|
|
2
|
+
//# sourceMappingURL=shape-editor.cjs.map
|