ima2-gen 2.0.3 → 2.0.4
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/CHANGELOG.md +20 -0
- package/docs/IMAGE_RESOLUTION.md +29 -0
- package/lib/oauthProxy/prompts.js +15 -1
- package/package.json +1 -1
- package/ui/dist/.vite/manifest.json +13 -13
- package/ui/dist/assets/{AgentWorkspace-qEMrATBP.js → AgentWorkspace-CMP9XZrL.js} +1 -1
- package/ui/dist/assets/{CardNewsWorkspace-DoJnVHmn.js → CardNewsWorkspace-DtOwgYzf.js} +1 -1
- package/ui/dist/assets/{GenerationRequestLogPanel-BDWRRLNV.js → GenerationRequestLogPanel-CB1i5dWd.js} +1 -1
- package/ui/dist/assets/{NodeCanvas-DIMo45sp.js → NodeCanvas-DwX2jRHf.js} +1 -1
- package/ui/dist/assets/{PromptBuilderPanel-BF3lcSJD.js → PromptBuilderPanel-B3VhUc5u.js} +1 -1
- package/ui/dist/assets/{PromptImportDialog-Cy6ZymKG.js → PromptImportDialog-4FQd2YVS.js} +2 -2
- package/ui/dist/assets/{PromptImportDiscoverySection-CzuW-8P2.js → PromptImportDiscoverySection-CTNr6ft3.js} +1 -1
- package/ui/dist/assets/{PromptImportFolderSection-DP5ywnsv.js → PromptImportFolderSection-zCJ1lBH8.js} +1 -1
- package/ui/dist/assets/{PromptLibraryPanel-CAsKr7CV.js → PromptLibraryPanel-B784T1KR.js} +2 -2
- package/ui/dist/assets/{SettingsWorkspace-_PdPVsxi.js → SettingsWorkspace-BpM6lWH-.js} +1 -1
- package/ui/dist/assets/index-2oG6in1i.css +1 -0
- package/ui/dist/assets/index-BzjrmmIG.js +23 -0
- package/ui/dist/assets/{index-BUinlX2n.js → index-CwAzer33.js} +1 -1
- package/ui/dist/index.html +2 -2
- package/ui/dist/assets/index-CX3fge8X.css +0 -1
- package/ui/dist/assets/index-ygo6nfqx.js +0 -23
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as c,j as o,u as ye,f as on,w as sn,x as ln,y as cn,z as Bt,B as me,C as un,D as jt,E as dn,b as j,F as hn,c as fn,G as pn,H as mn,J as vn}from"./index-ygo6nfqx.js";const De=2,Le=1e-6;function bn({paths:e,points:t,radius:n,makeId:a=()=>crypto.randomUUID()}){if(e.length===0||t.length===0||n<=0)return{paths:e,changed:!1};let r=!1;const l=[];for(const s of e){const i=gn(s,t,n,a);(i.length!==1||i[0]!==s)&&(r=!0),l.push(...i)}return{paths:l,changed:r}}function gn(e,t,n,a=()=>crypto.randomUUID()){if(e.points.length<De||t.length===0||n<=0)return[e];const r=[];let l=je(e.points[0],t,n)?[]:[e.points[0]];for(let i=1;i<e.points.length;i+=1){const d=e.points[i-1],u=e.points[i],b=je(u,t,n),f=xn(d,u,t,n);if(f){l.length===0&&!je(d,t,n)&&(l=[d]),l.length>0&&f.leftT>Le&&ft(l,Te(d,u,f.leftT)),l.length>=De&&r.push(l),l=[],f.rightT<1-Le&&!b&&(l=[Te(d,u,f.rightT),u]);continue}if(b){l.length>=De&&r.push(l),l=[];continue}l.length===0&&!je(d,t,n)&&(l=[d]),ft(l,u)}if(l.length>=De&&r.push(l),r.length===0)return[];if(r.length===1&&r[0].length===e.points.length)return[e];const s=e.tool==="arrow"?r.length-1:-1;return r.map((i,d)=>({...e,id:d===0?e.id:a(),tool:e.tool==="arrow"&&d!==s?"pen":e.tool,points:i}))}function je(e,t,n){if(t.length===1)return xe(e,t[0])<=n;for(let a=1;a<t.length;a+=1)if(yn(e,t[a-1],t[a])<=n)return!0;return!1}function xe(e,t){const n=e.x-t.x,a=e.y-t.y;return Math.sqrt(n*n+a*a)}function xn(e,t,n,a){const r=xe(e,t);if(r<=Le)return je(e,n,a)?{leftT:0,rightT:1}:null;let l=null,s=Number.POSITIVE_INFINITY;for(const d of n){const u=ht(d,e,t),b=Te(e,t,u),f=xe(d,b);f<s&&(s=f,l=u)}for(let d=1;d<n.length;d+=1){const u=[0,.25,.5,.75,1];for(const b of u){const f=Te(n[d-1],n[d],b),_=ht(f,e,t),B=Te(e,t,_),A=xe(f,B);A<s&&(s=A,l=_)}}if(l===null||s>a)return null;const i=Math.max(a/r,.01);return{leftT:Math.max(0,l-i),rightT:Math.min(1,l+i)}}function ht(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,i=a*a+r*r;return i===0?0:Math.max(0,Math.min(1,(l*a+s*r)/i))}function Te(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function ft(e,t){const n=e.at(-1);(!n||xe(n,t)>Le)&&e.push(t)}function yn(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,i=a*a+r*r;if(i===0)return xe(e,t);const d=Math.max(0,Math.min(1,(l*a+s*r)/i));return xe(e,{x:t.x+d*a,y:t.y+d*r})}function st(e,t){return`${e}:${t}`}function lt(e){const t=e.indexOf(":");if(t<=0)return null;const n=e.slice(0,t),a=e.slice(t+1);return!a||n!=="path"&&n!=="box"&&n!=="memo"?null:{kind:n,id:a}}function Tt(e){return st("path",e.id)}function Pt(e){return st("box",e.id)}function Dt(e){return st("memo",e.id)}function pe(e,t,n){const a=lt(e);return a?.kind===t&&a.id===n}const At="ima2.canvas.annotationStyle.v1",It=["#ef4444","#f97316","#eab308","#22c55e","#38bdf8","#6366f1","#a855f7","#111827","#ffffff"],Nt=[2,3,5,8],Ee={color:"#ef4444",strokeWidth:3};function kn(){if(typeof window>"u")return Ee;try{const e=window.localStorage.getItem(At);if(!e)return Ee;const t=JSON.parse(e),n=typeof t.color=="string"&&It.includes(t.color)?t.color:Ee.color,a=typeof t.strokeWidth=="number"&&Nt.includes(t.strokeWidth)?t.strokeWidth:Ee.strokeWidth;return{color:n,strokeWidth:a}}catch{return Ee}}function wn(e){if(!(typeof window>"u"))try{window.localStorage.setItem(At,JSON.stringify(e))}catch{}}const pt=kn(),tt={activeTool:"select",toolColor:pt.color,strokeWidth:pt.strokeWidth,paths:[],boxes:[],memos:[],activeMemoId:null,activePath:null,activeBox:null,eraserMode:"object",activeEraserStroke:null,eraserBaseline:null,selectionBox:null,selectedIds:[],past:[],future:[],memoBaseline:null,moveBaseline:null,isDirty:!1};function ge(e){return{paths:e.paths,boxes:e.boxes,memos:e.memos}}function be(e){return{...e,past:[...e.past.slice(-49),ge(e)],future:[]}}function Ge(e,t){return{...e,past:[...e.past.slice(-49),t],future:[]}}function Cn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function mt(e,t){return{...e,...t,activeMemoId:null,activePath:null,activeBox:null,selectionBox:null,selectedIds:[],isDirty:!0}}function _n(e,t,n){const{start:a,current:r}=e,l=Math.min(a.x,r.x),s=Math.min(a.y,r.y),i=Math.abs(r.x-a.x),d=Math.abs(r.y-a.y);return i<.01||d<.01?null:{id:crypto.randomUUID(),x:l,y:s,width:i,height:d,color:t,strokeWidth:n}}function Mn(e,t){return{...e,x:Math.min(1-e.width,Math.max(0,e.x+t.x)),y:Math.min(1-e.height,Math.max(0,e.y+t.y))}}function Ze(e,t){return{x:Math.min(1,Math.max(0,e.x+t.x)),y:Math.min(1,Math.max(0,e.y+t.y))}}function En(e,t){switch(t.type){case"SET_TOOL":return{...e,activeTool:t.tool};case"SET_ERASER_MODE":return{...e,eraserMode:t.mode};case"SET_STYLE":return{...e,toolColor:t.style.color,strokeWidth:t.style.strokeWidth};case"START_PATH":return{...e,isDirty:!0,activePath:{id:crypto.randomUUID(),tool:e.activeTool,points:[t.point],color:e.toolColor,strokeWidth:e.strokeWidth}};case"ADD_POINT":return e.activePath?{...e,activePath:{...e.activePath,points:[...e.activePath.points,t.point]}}:e;case"END_PATH":return!e.activePath||e.activePath.points.length<2?{...e,activePath:null}:{...be(e),isDirty:!0,paths:[...e.paths,e.activePath],activePath:null};case"START_BOX":return{...e,isDirty:!0,activeBox:{start:t.point,current:t.point}};case"UPDATE_BOX":return e.activeBox?{...e,activeBox:{...e.activeBox,current:t.point}}:e;case"END_BOX":{if(!e.activeBox)return e;const n=_n(e.activeBox,e.toolColor,e.strokeWidth);return n?{...be(e),isDirty:!0,boxes:[...e.boxes,n],activeBox:null}:{...e,activeBox:null}}case"CREATE_MEMO":{const n=crypto.randomUUID(),a={id:n,x:t.point.x,y:t.point.y,text:"",color:e.toolColor};return{...be(e),isDirty:!0,memos:[...e.memos,a],activeMemoId:n}}case"UPDATE_MEMO":return{...e,isDirty:!0,memos:e.memos.map(n=>n.id===t.id?{...n,text:t.text}:n)};case"COMMIT_MEMO_EDIT":return e.memoBaseline?Cn(e.memoBaseline,ge(e))?{...e,memoBaseline:null,activeMemoId:null}:{...Ge(e,e.memoBaseline),memoBaseline:null,activeMemoId:null,isDirty:!0}:{...e,activeMemoId:null};case"DELETE_MEMO":return{...be(e),isDirty:!0,memos:e.memos.filter(n=>n.id!==t.id),activeMemoId:e.activeMemoId===t.id?null:e.activeMemoId,selectedIds:e.selectedIds.filter(n=>!pe(n,"memo",t.id))};case"FOCUS_MEMO":return{...e,activeMemoId:t.id,memoBaseline:t.id&&e.activeMemoId!==t.id&&!e.memoBaseline?ge(e):e.memoBaseline};case"CLEAR":return{...be(e),isDirty:!0,paths:[],boxes:[],memos:[],activeMemoId:null,activePath:null,activeBox:null,selectionBox:null,selectedIds:[]};case"LOAD":return{...tt,activeTool:e.activeTool,eraserMode:e.eraserMode,toolColor:e.toolColor,strokeWidth:e.strokeWidth,...t.payload};case"MARK_SAVED":return{...e,isDirty:!1};case"RESET_LOCAL":return{...tt,activeTool:e.activeTool,eraserMode:e.eraserMode,toolColor:e.toolColor,strokeWidth:e.strokeWidth};case"UNDO":{const n=e.past.at(-1);return n?{...mt(e,n),past:e.past.slice(0,-1),future:[ge(e),...e.future]}:e}case"REDO":{const n=e.future[0];return n?{...mt(e,n),past:[...e.past.slice(-49),ge(e)],future:e.future.slice(1)}:e}case"SELECT_ONE":return{...e,selectedIds:[t.id],selectionBox:null};case"TOGGLE_SELECTED":return{...e,selectedIds:e.selectedIds.includes(t.id)?e.selectedIds.filter(n=>n!==t.id):[...e.selectedIds,t.id],selectionBox:null};case"CLEAR_SELECTION":return{...e,selectedIds:[],selectionBox:null};case"DELETE_SELECTED":return e.selectedIds.length===0?e:{...be(e),isDirty:!0,paths:e.paths.filter(n=>!e.selectedIds.some(a=>pe(a,"path",n.id))),boxes:e.boxes.filter(n=>!e.selectedIds.some(a=>pe(a,"box",n.id))),memos:e.memos.filter(n=>!e.selectedIds.some(a=>pe(a,"memo",n.id))),selectedIds:[]};case"MOVE_SELECTED":return e.selectedIds.length===0?e:{...e,isDirty:!0,paths:e.paths.map(n=>e.selectedIds.some(a=>pe(a,"path",n.id))?{...n,points:n.points.map(a=>Ze(a,t.delta))}:n),boxes:e.boxes.map(n=>e.selectedIds.some(a=>pe(a,"box",n.id))?Mn(n,t.delta):n),memos:e.memos.map(n=>e.selectedIds.some(a=>pe(a,"memo",n.id))?{...n,x:Ze(n,t.delta).x,y:Ze(n,t.delta).y}:n)};case"START_SELECTED_MOVE":return{...e,moveBaseline:ge(e)};case"COMMIT_SELECTED_MOVE":return e.moveBaseline?{...Ge(e,e.moveBaseline),moveBaseline:null,isDirty:!0}:e;case"START_SELECTION_BOX":return{...e,selectionBox:{start:t.point,current:t.point},selectedIds:[]};case"UPDATE_SELECTION_BOX":return e.selectionBox?{...e,selectionBox:{...e.selectionBox,current:t.point}}:e;case"END_SELECTION_BOX":return{...e,selectionBox:null,selectedIds:t.ids};case"ERASE_OBJECT":{const n=lt(t.id);return!n||!(n.kind==="path"?e.paths.some(r=>r.id===n.id):n.kind==="box"?e.boxes.some(r=>r.id===n.id):e.memos.some(r=>r.id===n.id))?e:{...be(e),isDirty:!0,paths:n.kind==="path"?e.paths.filter(r=>r.id!==n.id):e.paths,boxes:n.kind==="box"?e.boxes.filter(r=>r.id!==n.id):e.boxes,memos:n.kind==="memo"?e.memos.filter(r=>r.id!==n.id):e.memos,selectedIds:e.selectedIds.filter(r=>r!==t.id)}}case"START_ERASER_STROKE":return{...e,activeEraserStroke:{points:[t.point],radius:.018},eraserBaseline:ge(e)};case"UPDATE_ERASER_STROKE":return e.activeEraserStroke?{...e,activeEraserStroke:{...e.activeEraserStroke,points:[...e.activeEraserStroke.points,t.point]}}:e;case"END_ERASER_STROKE":{if(!e.activeEraserStroke||!e.eraserBaseline)return{...e,activeEraserStroke:null,eraserBaseline:null};const n=bn({paths:e.paths,points:e.activeEraserStroke.points,radius:e.activeEraserStroke.radius});return n.changed?{...Ge(e,e.eraserBaseline),paths:n.paths,activeEraserStroke:null,eraserBaseline:null,selectedIds:[],isDirty:!0}:{...e,activeEraserStroke:null,eraserBaseline:null}}default:return e}}function Sn(){const[e,t]=c.useReducer(En,tt),n=c.useMemo(()=>e.paths.length>0||e.boxes.length>0||e.memos.length>0,[e.paths.length,e.boxes.length,e.memos.length]),a=e.past.length>0,r=e.future.length>0,l=c.useCallback(p=>t({type:"SET_TOOL",tool:p}),[]),s=c.useCallback(p=>{wn(p),t({type:"SET_STYLE",style:p})},[]),i=c.useCallback(()=>t({type:"CLEAR"}),[]),d=c.useCallback(p=>t({type:"LOAD",payload:p}),[]),u=c.useCallback(()=>t({type:"MARK_SAVED"}),[]),b=c.useCallback(()=>t({type:"RESET_LOCAL"}),[]),f=c.useCallback(()=>t({type:"UNDO"}),[]),_=c.useCallback(()=>t({type:"REDO"}),[]),B=c.useCallback(()=>t({type:"COMMIT_MEMO_EDIT"}),[]),A=c.useCallback(()=>t({type:"START_SELECTED_MOVE"}),[]),O=c.useCallback(()=>t({type:"COMMIT_SELECTED_MOVE"}),[]),T=c.useCallback(p=>{e.activeTool==="pen"||e.activeTool==="arrow"?t({type:"START_PATH",point:p}):e.activeTool==="box"&&t({type:"START_BOX",point:p})},[e.activeTool]),N=c.useCallback(p=>{e.activePath?t({type:"ADD_POINT",point:p}):e.activeBox&&t({type:"UPDATE_BOX",point:p})},[e.activePath,e.activeBox]),m=c.useCallback(()=>{e.activePath?t({type:"END_PATH"}):e.activeBox&&t({type:"END_BOX"})},[e.activePath,e.activeBox]),C=c.useCallback(p=>t({type:"CREATE_MEMO",point:p}),[]),E=c.useCallback((p,R)=>t({type:"UPDATE_MEMO",id:p,text:R}),[]),y=c.useCallback(p=>t({type:"DELETE_MEMO",id:p}),[]),v=c.useCallback(p=>t({type:"FOCUS_MEMO",id:p}),[]),Z=c.useCallback(p=>t({type:"SET_ERASER_MODE",mode:p}),[]),I=c.useCallback(p=>t({type:"SELECT_ONE",id:p}),[]),U=c.useCallback(p=>t({type:"TOGGLE_SELECTED",id:p}),[]),g=c.useCallback(()=>t({type:"CLEAR_SELECTION"}),[]),S=c.useCallback(()=>t({type:"DELETE_SELECTED"}),[]),D=c.useCallback(p=>t({type:"MOVE_SELECTED",delta:p}),[]),P=c.useCallback(p=>t({type:"START_SELECTION_BOX",point:p}),[]),V=c.useCallback(p=>t({type:"UPDATE_SELECTION_BOX",point:p}),[]),Y=c.useCallback(p=>t({type:"END_SELECTION_BOX",ids:p}),[]),te=c.useCallback(p=>t({type:"ERASE_OBJECT",id:p}),[]),ne=c.useCallback(p=>t({type:"START_ERASER_STROKE",point:p}),[]),se=c.useCallback(p=>t({type:"UPDATE_ERASER_STROKE",point:p}),[]),ue=c.useCallback(()=>t({type:"END_ERASER_STROKE"}),[]),L=c.useCallback(()=>({paths:e.paths,boxes:e.boxes,memos:e.memos}),[e.paths,e.boxes,e.memos]);return{...e,canUndo:a,canRedo:r,hasAnnotations:n,setTool:l,setStyle:s,setEraserMode:Z,startDrawing:T,moveDrawing:N,endDrawing:m,createMemo:C,updateMemo:E,commitMemoEdit:B,deleteMemo:y,focusMemo:v,clear:i,load:d,toPayload:L,markSaved:u,resetLocal:b,undo:f,redo:_,selectOne:I,toggleSelected:U,clearSelection:g,deleteSelected:S,moveSelected:D,startSelectedMove:A,commitSelectedMove:O,startSelectionBox:P,updateSelectionBox:V,endSelectionBox:Y,eraseObjectAtPoint:te,startEraserStroke:ne,updateEraserStroke:se,endEraserStroke:ue}}function Ae(e,t){return{x:e.x*t.width,y:e.y*t.height}}function nt(e,t,n){if(t.points.length<2)return;const a=Ae(t.points[0],n);e.save(),e.beginPath(),e.strokeStyle=t.color,e.lineWidth=t.strokeWidth,e.lineCap="round",e.lineJoin="round",e.moveTo(a.x,a.y);for(const r of t.points.slice(1)){const l=Ae(r,n);e.lineTo(l.x,l.y)}if(e.stroke(),t.tool==="arrow"){const r=Ae(t.points[t.points.length-1],n),l=Ae(t.points[t.points.length-2],n);Tn(e,l,r,t.color,t.strokeWidth)}e.restore()}function at(e,t,n,a){const r="start"in t?{x:Math.min(t.start.x,t.current.x),y:Math.min(t.start.y,t.current.y),width:Math.abs(t.current.x-t.start.x),height:Math.abs(t.current.y-t.start.y),color:"#64c8ff",strokeWidth:2}:t;e.save(),e.strokeStyle=r.color,e.lineWidth=a==="active"?Math.max(2,r.strokeWidth):r.strokeWidth,a==="active"&&e.setLineDash([8,6]),e.strokeRect(r.x*n.width,r.y*n.height,r.width*n.width,r.height*n.height),e.restore()}function Bn(e,t,n){const a=t.x*n.width,r=t.y*n.height,l=Math.min(260,Math.max(150,n.width*.22)),s=12,i=18;e.save(),e.font="14px sans-serif";const d=Pn(e,t.text.trim()||" ",l-s*2),u=Math.max(52,s*2+d.length*i);e.fillStyle="rgba(255, 246, 179, 0.96)",e.strokeStyle="rgba(44, 37, 12, 0.28)",e.lineWidth=1,Dn(e,a,r,l,u,8),e.fill(),e.stroke(),e.fillStyle="#2f2a13",e.textBaseline="top",d.forEach((b,f)=>{e.fillText(b,a+s,r+s+f*i)}),e.restore()}function jn(e,t){const n=lt(e);if(!n)return null;if(n.kind==="box")return t.boxes.find(u=>u.id===n.id)??null;const a=n.kind==="memo"?t.memos.find(u=>u.id===n.id):null;if(a)return{id:a.id,x:a.x,y:a.y,width:.18,height:.12,color:a.color,strokeWidth:1};if(n.kind!=="path")return null;const r=t.paths.find(u=>u.id===n.id);if(!r||r.points.length===0)return null;const l=r.points.map(u=>u.x),s=r.points.map(u=>u.y),i=Math.min(...l),d=Math.min(...s);return{id:r.id,x:i,y:d,width:Math.max(.01,Math.max(...l)-i),height:Math.max(.01,Math.max(...s)-d),color:r.color,strokeWidth:r.strokeWidth}}function vt(e,t,n){const a="start"in t?{x:Math.min(t.start.x,t.current.x),y:Math.min(t.start.y,t.current.y),width:Math.abs(t.current.x-t.start.x),height:Math.abs(t.current.y-t.start.y)}:t;e.save(),e.strokeStyle="#64c8ff",e.lineWidth=2,e.setLineDash([5,5]),e.strokeRect(a.x*n.width,a.y*n.height,a.width*n.width,a.height*n.height),e.restore()}function Tn(e,t,n,a,r){const l=Math.atan2(n.y-t.y,n.x-t.x),s=Math.max(12,r*4),i=Math.PI/7;e.save(),e.fillStyle=a,e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x-s*Math.cos(l-i),n.y-s*Math.sin(l-i)),e.lineTo(n.x-s*Math.cos(l+i),n.y-s*Math.sin(l+i)),e.closePath(),e.fill(),e.restore()}function Pn(e,t,n){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const r=[];let l="";for(const s of a){const i=l?`${l} ${s}`:s;if(e.measureText(i).width<=n||l===""){l=i;continue}r.push(l),l=s}return l&&r.push(l),r}function Dn(e,t,n,a,r,l){const s=Math.min(l,a/2,r/2);e.beginPath(),e.moveTo(t+s,n),e.lineTo(t+a-s,n),e.quadraticCurveTo(t+a,n,t+a,n+s),e.lineTo(t+a,n+r-s),e.quadraticCurveTo(t+a,n+r,t+a-s,n+r),e.lineTo(t+s,n+r),e.quadraticCurveTo(t,n+r,t,n+r-s),e.lineTo(t,n+s),e.quadraticCurveTo(t,n,t+s,n),e.closePath()}function An({paths:e,boxes:t,memos:n=[],selectedIds:a=[],selectionBox:r=null,activePath:l,activeBox:s}){const i=c.useRef(null);return c.useEffect(()=>{const d=i.current;if(!d)return;const u=d.getBoundingClientRect(),b=window.devicePixelRatio||1;d.width=Math.max(1,Math.round(u.width*b)),d.height=Math.max(1,Math.round(u.height*b));const f=d.getContext("2d");if(!f)return;f.setTransform(b,0,0,b,0,0),f.clearRect(0,0,u.width,u.height);const _={width:u.width,height:u.height};for(const B of e)nt(f,B,_);for(const B of t)at(f,B,_,"committed");for(const B of a){const A=jn(B,{paths:e,boxes:t,memos:n});A&&vt(f,A,_)}r&&vt(f,r,_),l&&nt(f,l,_),s&&at(f,s,_,"active")},[e,t,n,a,r,l,s]),o.jsx("canvas",{ref:i,className:"canvas-annotation-layer","aria-hidden":"true"})}function Ie(e){e.stopPropagation()}function In({memos:e,activeMemoId:t,onUpdate:n,onDelete:a,onFocus:r,onCommit:l}){return o.jsx("div",{className:"canvas-memo-overlay",children:e.map(s=>o.jsx("textarea",{className:`canvas-memo${t===s.id?" canvas-memo--active":""}`,value:s.text,style:{left:`${s.x*100}%`,top:`${s.y*100}%`},autoFocus:t===s.id,onFocus:()=>r(s.id),onPointerDown:Ie,onPointerMove:Ie,onPointerUp:Ie,onPointerCancel:Ie,onChange:i=>n(s.id,i.currentTarget.value),onBlur:()=>{l?.(),s.text.trim()===""&&a(s.id)},"aria-label":"Canvas memo"},s.id))})}function Nn({annotationFrameRef:e,imageElementRef:t,frameClassName:n,frameStyle:a,imageKey:r,imageSrc:l,fallbackImage:s,alt:i,canvasOpen:d,maskOverlayUrl:u,cleanupLayer:b,annotations:f,onOpenCanvas:_,onPointerDown:B,onPointerMove:A,onPointerUp:O,onPointerLeave:T}){return o.jsxs("div",{ref:e,className:n,onPointerDown:B,onPointerMove:A,onPointerUp:O,onPointerCancel:O,onPointerLeave:T,style:a,children:[o.jsx("img",{ref:t,className:"result-img",src:l??s,alt:i,decoding:"async",onDoubleClick:N=>{N.stopPropagation(),_()}},r),d&&u?o.jsx("img",{className:"canvas-background-cleanup-mask",src:u,alt:"","aria-hidden":"true",decoding:"async"}):null,d?b:null,d&&o.jsxs(o.Fragment,{children:[o.jsx(An,{paths:f.paths,boxes:f.boxes,memos:f.memos,selectedIds:f.selectedIds,selectionBox:f.selectionBox,activePath:f.activePath,activeBox:f.activeBox}),o.jsx(In,{memos:f.memos,activeMemoId:f.activeMemoId,onUpdate:f.updateMemo,onDelete:f.deleteMemo,onFocus:f.focusMemo,onCommit:f.commitMemoEdit})]})]})}function Rn(e){return`${e.x*100} ${e.y*100}`}function Ln(e){return e.map(Rn).join(" ")}function On({seeds:e,brushStrokes:t,brushCursor:n,brushRadius:a,active:r}){if(!r&&e.length===0&&t.length===0)return null;const l=a*100;return o.jsxs("svg",{className:"canvas-cleanup-overlay",viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",children:[t.map(s=>o.jsx("polyline",{className:`canvas-cleanup-overlay__stroke canvas-cleanup-overlay__stroke--${s.intent}`,points:Ln(s.points),strokeWidth:Math.max(.3,s.radius*200),vectorEffect:"non-scaling-stroke"},s.id)),r&&n?o.jsx("circle",{className:"canvas-cleanup-cursor",cx:n.x*100,cy:n.y*100,r:Math.max(.6,l),vectorEffect:"non-scaling-stroke"}):null]})}function $n({mode:e,matteColor:t,onModeChange:n,onMatteColorChange:a}){const{t:r}=ye();return o.jsxs("div",{className:"canvas-toolbar__bg",role:"group","aria-label":r("canvas.toolbar.bgGroup"),children:[o.jsx("button",{type:"button",className:`canvas-toolbar__bg-tab${e==="alpha"?" active":""}`,onClick:()=>n("alpha"),children:r("canvas.toolbar.bgAlpha")}),o.jsx("button",{type:"button",className:`canvas-toolbar__bg-tab${e==="matte"?" active":""}`,onClick:()=>n("matte"),children:r("canvas.toolbar.bgMatte")}),e==="matte"?o.jsx("input",{type:"color","aria-label":r("canvas.toolbar.bgMatteColor"),value:t,onChange:l=>a(l.target.value)}):null]})}function bt({label:e,value:t,options:n,onChange:a}){return o.jsxs("div",{className:"canvas-toolbar__segmented-row",children:[o.jsx("span",{className:"canvas-toolbar__segmented-label",children:e}),o.jsx("div",{className:"canvas-toolbar__segmented",role:"group","aria-label":e,children:n.map(r=>o.jsx("button",{type:"button",className:"canvas-toolbar__segmented-button","data-value":r.value,"aria-pressed":t===r.value,onClick:()=>a(r.value),children:r.label},r.value))})]})}function Un({seedCount:e,tolerance:t,stats:n,hasPreview:a,isPickingSeed:r,intent:l,tool:s,brushRadius:i,isPreviewing:d,isApplying:u,keepOpen:b,disabled:f,onAutoSample:_,onPickSeed:B,onIntentChange:A,onToolChange:O,onBrushRadiusChange:T,onToleranceChange:N,onPreview:m,onApply:C,onReset:E}){const{t:y}=ye(),[v,Z]=c.useState(!1),I=c.useRef(null),U=n?Math.round(n.removedPercent*1e3)/10:0,g=r||s==="brush";return c.useEffect(()=>{if(!v)return;const S=D=>{b||I.current?.contains(D.target)||Z(!1)};return window.addEventListener("pointerdown",S),()=>window.removeEventListener("pointerdown",S)},[b,v]),o.jsxs("div",{className:"canvas-toolbar__cleanup",ref:I,children:[o.jsx("button",{type:"button",className:`canvas-toolbar__button${v||a?" canvas-toolbar__button--active":""}`,onClick:()=>Z(S=>!S),disabled:f,"aria-expanded":v,"aria-label":y("canvas.toolbar.cleanup"),title:y("canvas.toolbar.cleanup"),children:o.jsx(Wn,{})}),v?o.jsxs("div",{className:"canvas-toolbar__cleanup-panel",role:"group","aria-label":y("canvas.toolbar.cleanup"),children:[o.jsxs("div",{className:"canvas-toolbar__cleanup-row",children:[o.jsx("span",{className:"canvas-toolbar__cleanup-title",children:y("canvas.toolbar.cleanup")}),o.jsx("span",{className:"canvas-toolbar__cleanup-meta",children:y("canvas.toolbar.cleanupSeedCount",{n:e})})]}),o.jsx(bt,{label:y("canvas.toolbar.cleanupMark"),value:l,options:[{value:"remove",label:y("canvas.toolbar.cleanupRemove")},{value:"preserve",label:y("canvas.toolbar.cleanupPreserve")}],onChange:A}),o.jsx(bt,{label:y("canvas.toolbar.cleanupInput"),value:s,options:[{value:"click",label:y("canvas.toolbar.cleanupClick")},{value:"brush",label:y("canvas.toolbar.cleanupBrush")}],onChange:O}),o.jsxs("label",{className:"canvas-toolbar__cleanup-slider",children:[o.jsx("span",{children:y("canvas.toolbar.cleanupTolerance")}),o.jsx("input",{type:"range",min:"0",max:"96",value:t,onChange:S=>N(Number(S.target.value))}),o.jsx("output",{children:t})]}),s==="brush"?o.jsxs("label",{className:"canvas-toolbar__cleanup-slider",children:[o.jsx("span",{children:y("canvas.toolbar.cleanupBrushSize")}),o.jsx("input",{type:"range",min:"0.006",max:"0.06",step:"0.002",value:i,onChange:S=>T(Number(S.target.value))}),o.jsx("output",{children:Math.round(i*1e3)})]}):null,o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:_,children:y("canvas.toolbar.cleanupAutoSample")}),o.jsx("button",{type:"button",className:r?"active":"",onClick:B,children:y(g?"canvas.toolbar.cleanupActive":"canvas.toolbar.cleanupPickSeed")})]}),o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:m,disabled:d||e===0,children:y(d?"canvas.toolbar.cleanupPreviewing":"canvas.toolbar.cleanupPreview")}),o.jsx("button",{type:"button",onClick:C,disabled:u||!a&&e===0,children:y(u?"canvas.toolbar.cleanupApplying":"canvas.toolbar.cleanupApply")}),o.jsx("button",{type:"button",onClick:E,disabled:!a&&e===0,children:y("canvas.toolbar.cleanupReset")})]}),g?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:y(s==="brush"?"canvas.toolbar.cleanupBrushHint":"canvas.toolbar.cleanupPickHint")}):n&&!a?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:y("canvas.toolbar.cleanupMaskHint")}):null,n?o.jsx("div",{className:"canvas-toolbar__cleanup-status",children:y("canvas.toolbar.cleanupRemoved",{n:U})}):null]}):null]})}function Wn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M5 7.5h14"}),o.jsx("path",{d:"M7 12h10"}),o.jsx("path",{d:"M10 16.5h4"}),o.jsx("path",{d:"M7.5 5.5 9 4l1.5 1.5L9 7 7.5 5.5Z"}),o.jsx("path",{d:"M13.5 11 15 9.5l1.5 1.5L15 12.5 13.5 11Z"}),o.jsx("path",{d:"M4.5 15.5 6 14l1.5 1.5L6 17 4.5 15.5Z"})]})}function Hn({style:e,onStyleChange:t}){const{t:n}=ye(),[a,r]=c.useState(!1),l=c.useRef(null);return c.useEffect(()=>{if(!a)return;const s=i=>{l.current?.contains(i.target)||r(!1)};return window.addEventListener("pointerdown",s),()=>window.removeEventListener("pointerdown",s)},[a]),o.jsxs("div",{ref:l,className:`canvas-toolbar__split-button${a?" canvas-toolbar__split-button--active":""}`,onKeyDown:s=>{s.key==="Escape"&&a&&(s.preventDefault(),s.stopPropagation(),r(!1))},children:[o.jsxs("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__style-trigger",onClick:()=>r(s=>!s),"aria-haspopup":"dialog","aria-expanded":a,"aria-label":n("canvas.toolbar.style"),title:n("canvas.toolbar.style"),children:[o.jsx("span",{className:"canvas-style-trigger__swatch",style:{background:e.color},"aria-hidden":"true"}),o.jsx("span",{className:"canvas-style-trigger__width",style:{height:`${Math.min(8,Math.max(2,e.strokeWidth))}px`},"aria-hidden":"true"})]}),a?o.jsxs("div",{className:"canvas-style-popover",role:"dialog","aria-label":n("canvas.toolbar.style"),children:[o.jsx("div",{className:"canvas-style-popover__row",role:"group","aria-label":n("canvas.toolbar.color"),children:It.map(s=>o.jsx("button",{type:"button",className:`canvas-style-swatch${e.color===s?" canvas-style-swatch--active":""}`,style:{background:s},onClick:()=>t({...e,color:s}),"aria-pressed":e.color===s,"aria-label":s,title:s},s))}),o.jsx("div",{className:"canvas-style-popover__row",role:"group","aria-label":n("canvas.toolbar.strokeWidth"),children:Nt.map(s=>o.jsx("button",{type:"button",className:`canvas-style-width${e.strokeWidth===s?" canvas-style-width--active":""}`,onClick:()=>t({...e,strokeWidth:s}),"aria-pressed":e.strokeWidth===s,"aria-label":`${s}px`,title:`${s}px`,children:o.jsx("span",{style:{height:`${s}px`,background:e.color}})},s))})]}):null]})}function Fn({tools:e,activeTool:t,onToolChange:n}){const[a,r]=c.useState(!1),l=c.useRef(null),s=e.find(d=>d.id===t)??e[0],i=s.icon;return c.useEffect(()=>{if(!a)return;const d=u=>{l.current?.contains(u.target)||r(!1)};return window.addEventListener("pointerdown",d),()=>window.removeEventListener("pointerdown",d)},[a]),o.jsxs("div",{ref:l,className:"canvas-tool-picker",children:[o.jsxs("button",{type:"button",className:`canvas-toolbar__button canvas-tool-picker__trigger${t!=="eraser"?" canvas-toolbar__button--active":""}`,onClick:()=>r(d=>!d),"aria-label":`${s.label} (${s.shortcut})`,"aria-pressed":t===s.id,"aria-haspopup":"menu","aria-expanded":a,title:`${s.label} (${s.shortcut})`,children:[o.jsx(i,{}),o.jsx("span",{className:"canvas-toolbar__shortcut","aria-hidden":"true",children:s.shortcut})]}),a?o.jsx("div",{className:"canvas-tool-picker__menu",role:"menu",children:e.map(d=>{const u=d.icon,b=t===d.id;return o.jsxs("button",{type:"button",className:`canvas-tool-picker__item${b?" active":""}`,role:"menuitemradio","aria-checked":b,onClick:()=>{n(d.id),r(!1)},children:[o.jsx(u,{}),o.jsx("span",{children:d.label}),o.jsx("kbd",{children:d.shortcut})]},d.id)})}):null]})}function Vn({activeTool:e,hasAnnotations:t,hasExportableContent:n,onToolChange:a,eraserMode:r="object",onEraserModeChange:l,style:s,onStyleChange:i,onClear:d,onApply:u,onExport:b,onUndo:f,onRedo:_,canUndo:B,canRedo:A,onDeleteSelected:O,selectedCount:T=0,onEditWithMask:N,canEditWithMask:m,isEditingWithMask:C,isApplying:E,isExporting:y,exportBackground:v="alpha",exportMatteColor:Z="#ffffff",onExportBackgroundChange:I,onExportMatteColorChange:U,cleanupTolerance:g=28,cleanupSeedCount:S=0,cleanupStats:D=null,cleanupHasPreview:P=!1,isCleanupPickingSeed:V=!1,isCleanupActive:Y=!1,cleanupIntent:te="remove",cleanupTool:ne="click",cleanupBrushRadius:se=.018,isCleanupPreviewing:ue=!1,isCleanupApplying:L=!1,onCleanupAutoSample:p,onCleanupPickSeed:R,onCleanupIntentChange:J,onCleanupToolChange:ae,onCleanupBrushRadiusChange:le,onCleanupToleranceChange:K,onCleanupPreview:q,onCleanupApply:G,onCleanupReset:z}){const{t:w}=ye(),[$,ee]=c.useState(!1),W=c.useRef(null),ce=n??t??!1,X=w(r==="object"?"canvas.toolbar.objectEraser":"canvas.toolbar.brushEraser"),F=[{id:"select",shortcut:"1",label:w("canvas.toolbar.select"),icon:Kn},{id:"pen",shortcut:"2",label:w("canvas.toolbar.pen"),icon:zn},{id:"box",shortcut:"3",label:w("canvas.toolbar.box"),icon:Xn},{id:"arrow",shortcut:"4",label:w("canvas.toolbar.arrow"),icon:qn},{id:"memo",shortcut:"5",label:w("canvas.toolbar.memo"),icon:Yn}];c.useEffect(()=>{if(!$)return;const re=we=>{W.current?.contains(we.target)||ee(!1)};return window.addEventListener("pointerdown",re),()=>window.removeEventListener("pointerdown",re)},[$]);const de=re=>{l?.(re),a("eraser"),ee(!1)};return o.jsxs("div",{className:"canvas-toolbar","aria-label":w("canvas.toolbar.label"),children:[o.jsx(Fn,{tools:F,activeTool:e,onToolChange:a}),o.jsx(Hn,{style:s,onStyleChange:i}),o.jsxs("div",{ref:W,className:`canvas-toolbar__split-button${e==="eraser"?" canvas-toolbar__split-button--active":""}`,onKeyDown:re=>{re.key==="Escape"&&$&&(re.preventDefault(),ee(!1))},children:[o.jsxs("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--split-main${e==="eraser"?" canvas-toolbar__button--active":""}`,onClick:()=>a("eraser"),"aria-label":`${X} (6)`,"aria-pressed":e==="eraser",title:`${X} (6)`,children:[o.jsx(Gn,{}),o.jsx("span",{className:"canvas-toolbar__shortcut","aria-hidden":"true",children:"6"})]}),o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--split-menu",onClick:()=>ee(re=>!re),"aria-label":w("canvas.toolbar.eraserMenu"),"aria-haspopup":"menu","aria-expanded":$,"aria-controls":"canvas-eraser-menu",title:w("canvas.toolbar.eraserMenu"),children:o.jsx(Zn,{})}),$?o.jsxs("div",{id:"canvas-eraser-menu",className:"canvas-toolbar__eraser-menu",role:"menu",children:[o.jsx("button",{type:"button",className:`canvas-toolbar__eraser-menu-item${r==="object"?" canvas-toolbar__eraser-menu-item--active":""}`,role:"menuitemradio","aria-checked":r==="object",onClick:()=>de("object"),children:w("canvas.toolbar.objectEraser")}),o.jsx("button",{type:"button",className:`canvas-toolbar__eraser-menu-item${r==="brush"?" canvas-toolbar__eraser-menu-item--active":""}`,role:"menuitemradio","aria-checked":r==="brush",onClick:()=>de("brush"),children:w("canvas.toolbar.brushEraser")})]}):null]}),o.jsx("span",{className:"canvas-toolbar__divider","aria-hidden":"true"}),u?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--primary${E?" canvas-toolbar__button--busy":""}`,onClick:u,disabled:!ce||E,"aria-label":w("canvas.toolbar.apply"),title:w("canvas.toolbar.apply"),children:o.jsx(Jn,{})}):null,N?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--primary canvas-toolbar__button--mask${C?" canvas-toolbar__button--busy":""}`,onClick:N,disabled:!m||C,"aria-label":w(m?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),title:w(m?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),children:o.jsx(na,{})}):null,f?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:f,disabled:!B,"aria-label":w("canvas.toolbar.undo"),title:w("canvas.toolbar.undo"),children:o.jsx(ea,{})}):null,_?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:_,disabled:!A,"aria-label":w("canvas.toolbar.redo"),title:w("canvas.toolbar.redo"),children:o.jsx(ta,{})}):null,O?o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:O,disabled:T===0,"aria-label":w("canvas.toolbar.deleteSelected"),title:w("canvas.toolbar.deleteSelected"),children:o.jsx(gt,{})}):null,b&&I&&U?o.jsx($n,{mode:v,matteColor:Z,onModeChange:I,onMatteColorChange:U}):null,p&&R&&J&&ae&&le&&K&&q&&G&&z?o.jsx(Un,{seedCount:S,tolerance:g,stats:D,hasPreview:P,isPickingSeed:V,intent:te,tool:ne,brushRadius:se,isPreviewing:ue,isApplying:L,keepOpen:Y,disabled:E||y,onAutoSample:p,onPickSeed:R,onIntentChange:J,onToolChange:ae,onBrushRadiusChange:le,onToleranceChange:K,onPreview:q,onApply:G,onReset:z}):null,b?o.jsx("button",{type:"button",className:`canvas-toolbar__button${y?" canvas-toolbar__button--busy":""}`,onClick:b,disabled:!ce||y,"aria-label":w("canvas.toolbar.export"),title:w("canvas.toolbar.export"),children:o.jsx(Qn,{})}):null,o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:d,disabled:!ce,"aria-label":w("canvas.toolbar.clear"),title:w("canvas.toolbar.clear"),children:o.jsx(gt,{})})]})}function Kn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M8 12.5V7a2 2 0 0 1 4 0v4"}),o.jsx("path",{d:"M12 11V5a2 2 0 0 1 4 0v7"}),o.jsx("path",{d:"M16 12V8a2 2 0 0 1 4 0v5.5A6.5 6.5 0 0 1 13.5 20H12a6 6 0 0 1-4.24-1.76L4.7 15.18a1.7 1.7 0 0 1 2.4-2.4L9 14.68"})]})}function zn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"m4 20 4.2-1.1L19.5 7.6a2.2 2.2 0 0 0-3.1-3.1L5.1 15.8 4 20Z"}),o.jsx("path",{d:"m14.5 6.5 3 3"})]})}function Xn(){return o.jsx("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:o.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"2"})})}function qn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M5 19 19 5"}),o.jsx("path",{d:"M10 5h9v9"})]})}function Yn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M6 4h12v16H6z"}),o.jsx("path",{d:"M9 8h6"}),o.jsx("path",{d:"M9 12h5"}),o.jsx("path",{d:"M9 16h3"})]})}function Gn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"m4 15 8.5-8.5a2.1 2.1 0 0 1 3 0l2 2a2.1 2.1 0 0 1 0 3L10 19H6.5L4 16.5V15Z"}),o.jsx("path",{d:"M10 19h10"}),o.jsx("path",{d:"m8.5 10.5 5 5"})]})}function Zn(){return o.jsx("svg",{className:"canvas-toolbar__icon canvas-toolbar__icon--small",viewBox:"0 0 24 24","aria-hidden":"true",children:o.jsx("path",{d:"m7 14 5-5 5 5"})})}function Jn(){return o.jsx("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:o.jsx("path",{d:"M5 12.5 10 17 19 7"})})}function Qn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M12 4v11"}),o.jsx("path",{d:"m8 11 4 4 4-4"}),o.jsx("path",{d:"M5 20h14"})]})}function gt(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M4 7h16"}),o.jsx("path",{d:"M9 7V5h6v2"}),o.jsx("path",{d:"M7 7l1 13h8l1-13"}),o.jsx("path",{d:"M10 11v5"}),o.jsx("path",{d:"M14 11v5"})]})}function ea(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M9 7 5 11l4 4"}),o.jsx("path",{d:"M5 11h9a5 5 0 0 1 0 10h-2"})]})}function ta(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"m15 7 4 4-4 4"}),o.jsx("path",{d:"M19 11h-9a5 5 0 0 0 0 10h2"})]})}function na(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"2"}),o.jsx("path",{d:"M9 9h6v6H9z"})]})}function aa({annotations:e,backgroundCleanup:t,backgroundCleanupPreview:n,canvasState:a,actions:r}){return o.jsx(Vn,{activeTool:e.activeTool,eraserMode:e.eraserMode,onEraserModeChange:e.setEraserMode,style:{color:e.toolColor,strokeWidth:e.strokeWidth},onStyleChange:e.setStyle,hasExportableContent:e.hasAnnotations,onToolChange:e.setTool,onClear:e.clear,onApply:()=>{r.handleApplyCanvas()},onExport:()=>{r.handleExportCanvas()},onUndo:e.undo,onRedo:e.redo,canUndo:e.canUndo,canRedo:e.canRedo,onDeleteSelected:e.deleteSelected,selectedCount:e.selectedIds.length,onEditWithMask:()=>{r.handleEditWithMask()},canEditWithMask:e.boxes.length>0,isEditingWithMask:a.isEditingWithMask,isApplying:a.isApplying,isExporting:a.isExporting,exportBackground:a.exportBackground,exportMatteColor:a.exportMatteColor,onExportBackgroundChange:r.setExportBackground,onExportMatteColorChange:r.setExportMatteColor,cleanupTolerance:t.backgroundCleanupTolerance,cleanupSeedCount:t.backgroundCleanupSeeds.length,cleanupStats:t.backgroundCleanupStats,cleanupHasPreview:!!n,isCleanupPickingSeed:t.isBackgroundCleanupPickingSeed,isCleanupActive:t.isBackgroundCleanupActive,cleanupIntent:t.cleanupIntent,cleanupTool:t.cleanupTool,cleanupBrushRadius:t.cleanupBrushRadius,isCleanupPreviewing:t.isBackgroundCleanupPreviewing,isCleanupApplying:t.isBackgroundCleanupApplying,onCleanupAutoSample:t.handleBackgroundCleanupAutoSample,onCleanupPickSeed:t.handleBackgroundCleanupPickSeed,onCleanupIntentChange:t.setCleanupIntent,onCleanupToolChange:l=>{t.setCleanupTool(l),t.setIsBackgroundCleanupActive(!0)},onCleanupBrushRadiusChange:t.setCleanupBrushRadius,onCleanupToleranceChange:t.handleBackgroundCleanupToleranceChange,onCleanupPreview:()=>{t.runBackgroundCleanupPreview()},onCleanupApply:()=>{t.handleBackgroundCleanupApply()},onCleanupReset:t.handleBackgroundCleanupReset})}function ra({currentImage:e,canvasDisplayImage:t,canvasOpen:n,displayQuality:a,displaySize:r,displayModel:l,onAfterDeleteFocus:s,onCopyPrompt:i}){const{t:d}=ye(),u=[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?d("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,on(e.reasoningEffort),a,r,l].filter(b=>!!b).join(" · ");return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"result-meta",children:u}),o.jsx(sn,{imageOverride:n?t:null,onAfterDeleteFocus:s}),e.prompt?o.jsx(ln,{prompt:e.prompt,onCopy:i}):null]})}function oa({zoom:e,onZoomIn:t,onZoomOut:n,onZoomReset:a}){const{t:r}=ye(),l=Math.round(e*100);return o.jsxs("div",{className:"canvas-toolbar__zoom",role:"group","aria-label":r("canvas.toolbar.zoomGroup"),children:[o.jsx("button",{type:"button",className:"canvas-toolbar__zoom-button",onClick:n,"aria-label":r("canvas.toolbar.zoomOut"),title:r("canvas.toolbar.zoomOut"),children:o.jsx(sa,{})}),o.jsxs("button",{type:"button",className:"canvas-toolbar__zoom-value",onClick:a,"aria-label":r("canvas.toolbar.zoomReset"),title:r("canvas.toolbar.zoomReset"),children:[l,"%"]}),o.jsx("button",{type:"button",className:"canvas-toolbar__zoom-button",onClick:t,"aria-label":r("canvas.toolbar.zoomIn"),title:r("canvas.toolbar.zoomIn"),children:o.jsx(la,{})})]})}function sa(){return o.jsx("svg",{className:"canvas-toolbar__icon canvas-toolbar__icon--small",viewBox:"0 0 24 24","aria-hidden":"true",children:o.jsx("path",{d:"M5 12h14"})})}function la(){return o.jsxs("svg",{className:"canvas-toolbar__icon canvas-toolbar__icon--small",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M12 5v14"}),o.jsx("path",{d:"M5 12h14"})]})}function ca({zoom:e,closeLabel:t,blankCanvasLabel:n,blankCanvasAriaLabel:a,blankCanvasShortcut:r,blankCanvasBusy:l,shortcutHint:s,onZoomIn:i,onZoomOut:d,onZoomReset:u,onCreateBlankCanvas:b,onClose:f}){return o.jsxs("div",{className:"canvas-mode-topbar",children:[o.jsxs("div",{className:"canvas-mode-topbar__stack",children:[o.jsx("span",{className:"canvas-mode-topbar__label",children:"Canvas Mode"}),o.jsx(oa,{zoom:e,onZoomIn:i,onZoomOut:d,onZoomReset:u}),o.jsx("span",{className:"canvas-mode-topbar__shortcuts",children:s})]}),o.jsx("div",{className:"canvas-mode-topbar__center",children:o.jsxs("button",{type:"button",className:"canvas-mode-blank",onClick:b,disabled:l,"aria-label":a,title:a,children:[o.jsx("span",{"aria-hidden":"true",children:"+"}),o.jsx("span",{children:n}),o.jsx("kbd",{children:r})]})}),o.jsxs("button",{type:"button",className:"canvas-mode-close",onClick:f,"aria-label":t,children:[o.jsx("kbd",{children:"ESC"}),o.jsx("span",{children:t})]})]})}function Je(e,t,n){return Math.max(t,Math.min(n,e))}function ia({zoom:e,panX:t,panY:n}){const a=Je(100/Math.max(1,e),18,100),r=a/2,l=Je(50-t/40,r,100-r),s=Je(50-n/40,r,100-r);return{width:`${a}%`,height:`${a}%`,left:`${l}%`,top:`${s}%`}}function ua({imageSrc:e,zoom:t,panX:n,panY:a,resetLabel:r,onReset:l}){return o.jsxs("button",{type:"button",className:"canvas-viewport-minimap",onClick:l,"aria-label":r,title:r,children:[o.jsx("img",{src:e,alt:"","aria-hidden":"true"}),o.jsx("span",{className:"canvas-viewport-minimap__window",style:ia({zoom:t,panX:n,panY:a}),"aria-hidden":"true"})]})}function Ne(e){return Math.min(1,Math.max(0,e))}function da(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("mask_blob_unavailable"))},"image/png")})}async function ha(e){const t=e.imageElement.naturalWidth,n=e.imageElement.naturalHeight;if(!t||!n)throw new Error("mask_source_size_unavailable");if(e.boxes.length===0)throw new Error("mask_boxes_required");const a=document.createElement("canvas");a.width=t,a.height=n;const r=a.getContext("2d");if(!r)throw new Error("mask_context_unavailable");r.fillStyle="rgba(0, 0, 0, 1)",r.fillRect(0,0,t,n),r.globalCompositeOperation="destination-out";for(const l of e.boxes){const s=Ne(l.x)*t,i=Ne(l.y)*n,d=Ne(l.width)*t,u=Ne(l.height)*n;d>0&&u>0&&r.fillRect(s,i,d,u)}return da(a)}async function fa(e){const t=e.naturalWidth,n=e.naturalHeight;if(!t||!n)throw new Error("image_source_size_unavailable");const a=document.createElement("canvas");a.width=t,a.height=n;const r=a.getContext("2d");if(!r)throw new Error("image_context_unavailable");return r.drawImage(e,0,0,t,n),a.toDataURL("image/png")}function ct(e){return new Promise((t,n)=>{const a=new FileReader;a.onerror=()=>n(new Error("mask_blob_read_failed")),a.onload=()=>t(String(a.result)),a.readAsDataURL(e)})}const pa=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='28' height='28' viewBox='0 0 28 28'%3E%3Ccircle cx='14' cy='14' r='8' fill='white' fill-opacity='0.16' stroke='black' stroke-width='3'/%3E%3Ccircle cx='14' cy='14' r='8' fill='none' stroke='white' stroke-width='1.5'/%3E%3Ccircle cx='14' cy='14' r='2' fill='white' stroke='black' stroke-width='1'/%3E%3C/svg%3E") 14 14, auto`,ma=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='28' height='28' viewBox='0 0 28 28'%3E%3Ccircle cx='14' cy='14' r='8' fill='white' fill-opacity='0.18' stroke='black' stroke-width='3'/%3E%3Ccircle cx='14' cy='14' r='8' fill='none' stroke='white' stroke-width='1.5'/%3E%3C/svg%3E") 14 14, auto`;function va(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function ba(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function ga(e){const t=e.url??e.image;if(!e.canvasVersion||!e.canvasMergedAt||t.startsWith("data:"))return t;const n=t.includes("?")?"&":"?";return`${t}${n}canvasMergedAt=${e.canvasMergedAt}`}function xa(e){const t=e.canvasSourceFilename??e.filename;return t?`/generated/${encodeURIComponent(t)}`:e.url??e.image}async function xt(e){const t=xa(e);if(t.startsWith("data:image/png;"))return t;const n=new Image;return await new Promise((a,r)=>{n.onload=()=>a(),n.onerror=()=>r(new Error("clean_source_load_failed")),n.src=t}),fa(n)}function it(e,t){return!e.canvasVersion||e.prompt||!t?.prompt?e:{...e,prompt:t.prompt}}function ya(e,t){if(!t?.filename)return null;const n=e.find(a=>a.canvasVersion&&(a.canvasSourceFilename===t.filename||a.canvasEditableFilename===t.filename))??null;return n?it(n,t):null}function ka(e,t){if(cn(e)){const n=e.images[0];if(!n)throw new Error("edit_empty_response");return{...n,prompt:t,reasoningEffort:e.reasoningEffort,provider:e.provider,quality:e.quality,size:e.size,moderation:e.moderation,model:e.model,usage:e.usage,kind:"edit",createdAt:Date.now()}}return{image:e.image,url:e.filename?`/generated/${e.filename}`:e.image,thumb:e.image,filename:e.filename,prompt:t,elapsed:e.elapsed,reasoningEffort:e.reasoningEffort,provider:e.provider,quality:e.quality,size:e.size,moderation:e.moderation,model:e.model,usage:e.usage,revisedPrompt:e.revisedPrompt??null,promptMode:e.promptMode??null,kind:"edit",createdAt:Date.now()}}const Qe=new WeakMap;function wa(e){if(!e.complete||!e.naturalWidth||!e.naturalHeight)return!1;const t=Qe.get(e);if(t&&t.src===e.currentSrc&&t.width===e.naturalWidth&&t.height===e.naturalHeight)return t.result;const n=64,a=Math.min(n,e.naturalWidth),r=Math.min(n,e.naturalHeight),l=document.createElement("canvas");l.width=a,l.height=r;const s=l.getContext("2d",{willReadFrequently:!0});if(!s)return!1;try{s.drawImage(e,0,0,a,r);const i=s.getImageData(0,0,a,r).data;for(let d=3;d<i.length;d+=4)if(i[d]<250)return Qe.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!0}),!0;return Qe.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!1}),!1}catch{return!1}}function Ca(e,t){if(e.width!==t.width||e.height!==t.height||e.data.length!==t.data.length)throw new Error("cleanup_mask_size_mismatch")}function yt(e,t){return{width:e,height:t,data:new Uint8Array(e*t)}}function rt(e){return{width:e.width,height:e.height,data:new Uint8Array(e.data)}}function _a(e,t){Ca(e,t);for(let n=0;n<e.data.length;n+=1)(t.data[n]??0)>0&&(e.data[n]=0)}function Se(e,t){if(!e)return null;const n=rt(e);return t&&_a(n,t),n}function Ma(e,t){if(e.width!==t.width||e.height!==t.height)throw new Error("cleanup_mask_size_mismatch");const n=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);for(let a=0;a<t.data.length;a+=1)(t.data[a]??0)>0&&(n.data[a*4+3]=0);return n}const ut=[{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}],Ea=1024;function Sa(e){return Math.max(0,Math.min(255,Math.round(e)))}function Rt(e,t,n){const a=Math.max(0,Math.min(t-1,Math.round(e.x*(t-1))));return Math.max(0,Math.min(n-1,Math.round(e.y*(n-1))))*t+a}function Ba(e,t){return(t.length>0?t:ut).map(a=>{const r=Rt(a,e.width,e.height)*4;return{r:e.data[r]??0,g:e.data[r+1]??0,b:e.data[r+2]??0}})}function ja(e,t,n,a){for(const r of n)if(Math.max(Math.abs((e[t]??0)-r.r),Math.abs((e[t+1]??0)-r.g),Math.abs((e[t+2]??0)-r.b))<=a)return!0;return!1}function Be(e,t,n,a,r,l,s){if(e<0||e>=a.length||a[e])return r;const i=e*4;return(t.data[i+3]??0)===0?(a[e]=1,r):ja(t.data,i,l,s)?(a[e]=1,n[r]=e,r+1):r}function et(){return ut.map(e=>({...e}))}function kt(e,t,n,a){if(e.width!==t.width||e.height!==t.height)throw new Error("cleanup_mask_size_mismatch");const{width:r,height:l}=t,s=r*l,i=new Uint8Array(s),d=new Int32Array(s),u=Ba(t,n),b=Sa(a);let f=0;for(const _ of n.length>0?n:ut)f=Be(Rt(_,r,l),t,d,i,f,u,b);for(;f>0;){const _=d[--f];e.data[_]=255;const B=_%r;B>0&&(f=Be(_-1,t,d,i,f,u,b)),B<r-1&&(f=Be(_+1,t,d,i,f,u,b)),_>=r&&(f=Be(_-r,t,d,i,f,u,b)),_<s-r&&(f=Be(_+r,t,d,i,f,u,b))}}function Ta(e,t){const n=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),a=Ma(n,t),r=t.data.reduce((l,s)=>l+(s>0?1:0),0);return{imageData:{width:e.width,height:e.height,data:a.data},stats:{width:e.width,height:e.height,removedPixels:r,removedPercent:t.data.length>0?r/t.data.length:0}}}function Lt(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("background_cleanup_blob_failed"))},"image/png")})}function Ot(e,t){const n=e.naturalWidth,a=e.naturalHeight;if(n<=0||a<=0)throw new Error("background_cleanup_image_not_ready");const r=t&&t>0?Math.min(1,t/Math.max(n,a)):1,l=Math.max(1,Math.round(n*r)),s=Math.max(1,Math.round(a*r)),i=document.createElement("canvas");i.width=l,i.height=s;const d=i.getContext("2d",{willReadFrequently:!0});if(!d)throw new Error("background_cleanup_context_failed");return d.drawImage(e,0,0,l,s),{canvas:i,context:d,width:l,height:s}}async function wt({imageElement:e,mask:t}){try{const{canvas:n,context:a,width:r,height:l}=Ot(e),s=a.getImageData(0,0,r,l),i=Ta({width:r,height:l,data:s.data},t),d=a.createImageData(r,l);d.data.set(i.imageData.data),a.putImageData(d,0,0);const u=await Lt(n);return{blob:u,dataUrl:await ct(u),stats:i.stats}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}async function Pa({imageElement:e,mask:t}){try{const{width:n,height:a}=Ot(e,Ea),r=document.createElement("canvas");r.width=n,r.height=a;const l=r.getContext("2d");if(!l)throw new Error("background_cleanup_context_failed");const s=l.createImageData(n,a);let i=0;for(let u=0;u<a;u+=1)for(let b=0;b<n;b+=1){const f=Math.min(t.width-1,Math.floor(b/n*t.width)),_=Math.min(t.height-1,Math.floor(u/a*t.height));if((t.data[_*t.width+f]??0)===0)continue;const B=(u*n+b)*4;s.data[B]=168,s.data[B+1]=85,s.data[B+2]=247,s.data[B+3]=150,i+=1}l.putImageData(s,0,0);const d=await Lt(r);return{dataUrl:await ct(d),stats:{width:t.width,height:t.height,removedPixels:t.data.reduce((u,b)=>u+(b>0?1:0),0),removedPercent:t.data.length>0?i/(n*a):0}}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}function Ct(e){return{...e,seeds:e.seeds.map(t=>({intent:t.intent,point:{...t.point}})),brushStrokes:e.brushStrokes.map(t=>({...t,points:t.points.map(n=>({...n}))})),brushCursor:e.brushCursor?{...e.brushCursor}:null,removeMask:e.removeMask?rt(e.removeMask):null,preserveMask:e.preserveMask?rt(e.preserveMask):null}}function Da(){return`cleanup_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function Re(e){return Math.max(0,Math.min(1,e))}function Aa(e){const t=[],n=Math.max(0,e.radius*.55);for(const a of e.points)t.push({...a}),!(n<=0)&&t.push({x:Re(a.x-n),y:a.y},{x:Re(a.x+n),y:a.y},{x:a.x,y:Re(a.y-n)},{x:a.x,y:Re(a.y+n)});return t}function Ia(e){const t=e.naturalWidth,n=e.naturalHeight;if(t<=0||n<=0)throw new Error("background_cleanup_image_not_ready");const a=document.createElement("canvas");a.width=t,a.height=n;const r=a.getContext("2d",{willReadFrequently:!0});if(!r)throw new Error("background_cleanup_context_failed");r.drawImage(e,0,0,t,n);const l=r.getImageData(0,0,t,n);return{width:t,height:n,data:l.data}}function Na({canvasOpen:e,currentImage:t,canvasDisplayImage:n,imageElementRef:a,canvasSourceImageRef:r,lastMergedDataUrlRef:l,setCanvasSaveState:s,setCanvasVersionItem:i,applyMergedCanvasImage:d,attachCanvasVersionReference:u,showToast:b,t:f}){const[_,B]=c.useState(!1),[A,O]=c.useState("remove"),[T,N]=c.useState("click"),[m,C]=c.useState("flat-flood-fill"),[E,y]=c.useState([]),[v,Z]=c.useState([]),[I,U]=c.useState(28),[g,S]=c.useState(null),[D,P]=c.useState(null),[V,Y]=c.useState(null),[te,ne]=c.useState(!1),[se,ue]=c.useState(.018),[L,p]=c.useState(null),[R,J]=c.useState(!1),[ae,le]=c.useState(!1),K=c.useRef(null),q=c.useRef(null),G=c.useRef(null),z=c.useRef({past:[],future:[]}),w=c.useRef(0),$=c.useRef(null),ee=c.useCallback(()=>Ct({intent:A,tool:T,engine:m,seeds:E,brushStrokes:v,brushRadius:se,tolerance:I,removeMask:K.current,preserveMask:q.current,preview:g,maskOverlay:D,stats:V,active:te,brushCursor:L}),[v,D,g,E,V,I,L,se,m,A,T,te]),W=c.useCallback(()=>{z.current={past:[...z.current.past.slice(-19),ee()],future:[]}},[ee]),ce=c.useCallback(x=>{const k=Ct(x);K.current=k.removeMask,q.current=k.preserveMask,G.current=null,O(k.intent),N(k.tool),C(k.engine),y(k.seeds),Z(k.brushStrokes),ue(k.brushRadius),U(k.tolerance),S(k.preview),P(k.maskOverlay),Y(k.stats),ne(k.active),p(k.brushCursor),J(!1),le(!1)},[]),X=c.useCallback(async()=>{if(!a.current||!t)return;const x=Se(K.current,q.current);if(!x){P(null),Y(null);return}const k=w.current+1;w.current=k,J(!0);try{const M=await Pa({imageElement:a.current,mask:x});if(w.current!==k)return;P(M),Y(M.stats)}catch{if(w.current!==k)return;b(f("canvas.toolbar.cleanupFailed"),!0)}finally{w.current===k&&J(!1)}},[t,a,b,f]),F=c.useCallback(async(x,k,M)=>{if(!a.current)return;const Q=Ia(a.current),ie=yt(Q.width,Q.height),ke=yt(Q.width,Q.height);for(const fe of x){const Ce=fe.intent==="remove"?ie:ke;kt(Ce,Q,[fe.point],M)}for(const fe of k){const Ce=fe.intent==="remove"?ie:ke;kt(Ce,Q,Aa(fe),M)}K.current=ie,q.current=ke},[a]),de=c.useCallback(()=>{w.current+=1,$.current!=null&&(window.clearTimeout($.current),$.current=null),K.current=null,q.current=null,G.current=null,z.current={past:[],future:[]},y([]),Z([]),S(null),P(null),Y(null),ne(!1),p(null),J(!1),le(!1)},[]),re=c.useCallback(()=>{const x=z.current.past.pop();return x?(z.current.future=[ee(),...z.current.future.slice(0,19)],ce(x),!0):!1},[ee,ce]),we=c.useCallback(()=>{const x=z.current.future.shift();return x?(z.current.past=[...z.current.past.slice(-19),ee()],ce(x),!0):!1},[ee,ce]),Pe=c.useCallback(x=>{W();const k=[...E,{point:x,intent:A}];y(k),S(null),F(k,v,I).then(X)},[v,E,I,A,W,F,X]),Oe=c.useCallback(()=>{W();const x=et().map(k=>({point:k,intent:"remove"}));y(x),S(null),ne(!1),F(x,v,I).then(X)},[v,I,W,F,X]),$e=c.useCallback(()=>{W(),N("click"),ne(x=>!x)},[W]),Ue=c.useCallback(x=>{W(),$.current!=null&&window.clearTimeout($.current),U(x),S(null),$.current=window.setTimeout(()=>{$.current=null,F(E,v,x).then(X)},180)},[v,E,W,F,X]),H=c.useCallback(async()=>{if(!a.current||!t)return null;let x=Se(K.current,q.current);if(!x){const M=et().map(Q=>({point:Q,intent:"remove"}));y(M),await F(M,v,I),x=Se(K.current,q.current)}if(!x)return null;W();const k=w.current+1;w.current=k,J(!0);try{const M=await wt({imageElement:a.current,mask:x});return w.current!==k?null:(S(M),P(null),Y(M.stats),M)}catch{return w.current!==k||b(f("canvas.toolbar.cleanupFailed"),!0),null}finally{w.current===k&&J(!1)}},[v,I,t,a,W,F,b,f]),We=c.useCallback(()=>{W(),de()},[W,de]),He=c.useCallback(x=>{W();const k={id:Da(),intent:A,points:[{...x}],radius:se};G.current=k,p(x),Z(M=>[...M,k])},[se,A,W]),Fe=c.useCallback(x=>{const k=G.current;if(!k){p(x);return}k.points=[...k.points,{...x}],p(x),Z(M=>M.map(Q=>Q.id===k.id?{...k,points:k.points.map(ie=>({...ie}))}:Q)),F(E,v.map(M=>M.id===k.id?k:M),I).then(X)},[v,E,I,F,X]),Ve=c.useCallback(()=>{G.current=null,F(E,v,I).then(X)},[v,E,I,F,X]),ve=c.useCallback(async()=>{if(!t||!a.current)return;const x=r.current??t;if(!x?.filename){b(f("canvas.toolbar.cleanupFailed"),!0);return}let k=Se(K.current,q.current);if(!k){const M=et().map(Q=>({point:Q,intent:"remove"}));y(M),await F(M,v,I),k=Se(K.current,q.current)}if(k){le(!0),s("saving");try{W();const M=await wt({imageElement:a.current,mask:k}),Q=await Bt({sourceFilename:x.canvasSourceFilename??x.filename,image:M.blob,prompt:x.prompt}),ie=it(Q.item,x);l.current=M.dataUrl,i(ie),d(ie),await u(ie),s("saved"),S(null),P(null),Y(M.stats),ne(!1),b(f("canvas.toolbar.cleanupApplied"))}catch{s("error"),b(f("canvas.toolbar.cleanupFailed"),!0)}finally{le(!1)}}},[d,u,v,I,r,t,a,l,W,F,s,i,b,f]),he=c.useCallback(()=>te?(G.current=null,ne(!1),p(null),!0):!1,[te]);return c.useEffect(()=>{const x=a.current;if(!x||!e){B(!1);return}const k=()=>B(wa(x));if(x.complete)k();else return x.addEventListener("load",k),()=>x.removeEventListener("load",k)},[e,n?.canvasMergedAt,n?.filename,n?.image,n?.url,g?.dataUrl,a]),{imageHasAlpha:_,backgroundCleanupSeeds:E,backgroundCleanupBrushStrokes:v,backgroundCleanupTolerance:I,backgroundCleanupPreview:g,backgroundCleanupMaskOverlay:D,backgroundCleanupStats:V,cleanupIntent:A,setCleanupIntent:O,cleanupTool:T,setCleanupTool:N,cleanupClickEngine:m,setCleanupClickEngine:C,cleanupBrushRadius:se,setCleanupBrushRadius:ue,cleanupBrushCursor:L,setCleanupBrushCursor:p,isBackgroundCleanupActive:te,setIsBackgroundCleanupActive:ne,isBackgroundCleanupPickingSeed:te&&T==="click",isBackgroundCleanupPreviewing:R,isBackgroundCleanupApplying:ae,hasActiveCleanupStroke:!!G.current,canUndoBackgroundCleanup:z.current.past.length>0,canRedoBackgroundCleanup:z.current.future.length>0,resetBackgroundCleanup:de,undoBackgroundCleanup:re,redoBackgroundCleanup:we,addBackgroundCleanupClick:Pe,addBackgroundCleanupSeed:Pe,runBackgroundCleanupPreview:H,handleBackgroundCleanupAutoSample:Oe,handleBackgroundCleanupPickSeed:$e,handleBackgroundCleanupToleranceChange:Ue,handleBackgroundCleanupReset:We,handleBackgroundCleanupApply:ve,handleBackgroundCleanupEscape:he,startBackgroundCleanupBrushStroke:He,updateBackgroundCleanupBrushStroke:Fe,endBackgroundCleanupBrushStroke:Ve}}function _t(e){return Math.min(1,Math.max(0,e))}function Mt(e,t){const n=t.getBoundingClientRect();return{x:_t((e.clientX-n.left)/n.width),y:_t((e.clientY-n.top)/n.height)}}const Ra=.18,La=.12;function Oa(e){return{id:"selection-box",x:Math.min(e.start.x,e.current.x),y:Math.min(e.start.y,e.current.y),width:Math.abs(e.current.x-e.start.x),height:Math.abs(e.current.y-e.start.y),color:"#64c8ff",strokeWidth:2}}function ot(e,t,n=0){return e.x>=t.x-n&&e.x<=t.x+t.width+n&&e.y>=t.y-n&&e.y<=t.y+t.height+n}function $t(e){return{id:e.id,x:e.x,y:e.y,width:Ra,height:La,color:e.color,strokeWidth:1}}function $a(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,i=a*a+r*r;if(i===0)return Math.hypot(e.x-t.x,e.y-t.y);const d=Math.max(0,Math.min(1,(l*a+s*r)/i));return Math.hypot(e.x-(t.x+d*a),e.y-(t.y+d*r))}function Ua(e,t,n){for(let a=1;a<t.points.length;a+=1)if($a(e,t.points[a-1],t.points[a])<=n)return!0;return!1}function Et(e,t){return e.x<=t.x+t.width&&e.x+e.width>=t.x&&e.y<=t.y+t.height&&e.y+e.height>=t.y}function Wa(e,t){return e.points.some(n=>ot(n,t))}function St(e){const t=e.tolerance??.015;for(const n of[...e.memos].reverse())if(ot(e.point,$t(n),t))return Dt(n);for(const n of[...e.boxes].reverse())if(ot(e.point,n,t))return Pt(n);for(const n of[...e.paths].reverse())if(Ua(e.point,n,t))return Tt(n);return null}function Ha(e){const t=[];for(const n of e.annotations.paths)Wa(n,e.box)&&t.push(Tt(n));for(const n of e.annotations.boxes)Et(n,e.box)&&t.push(Pt(n));for(const n of e.annotations.memos)Et($t(n),e.box)&&t.push(Dt(n));return t}function Fa({canvasOpen:e,canvasZoom:t,canvasPanX:n,canvasPanY:a,spaceHeld:r,canDragViewportWithSelect:l,isBackgroundCleanupActive:s,cleanupTool:i,annotationFrameRef:d,annotations:u,setCanvasPan:b,addBackgroundCleanupClick:f,startBackgroundCleanupBrushStroke:_,updateBackgroundCleanupBrushStroke:B,endBackgroundCleanupBrushStroke:A,setCleanupBrushCursor:O}){const T=c.useRef({mode:null,lastPoint:null,didMove:!1}),N=c.useRef({active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null}),[m,C]=c.useState(!1),E=g=>{g.currentTarget.setPointerCapture(g.pointerId),N.current={active:!0,startX:g.clientX,startY:g.clientY,basePanX:n,basePanY:a,pointerId:g.pointerId},C(!0)};return{viewportPanActive:m,resetPointerSession:()=>{T.current={mode:null,lastPoint:null,didMove:!1},N.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},C(!1)},handleAnnotationPointerDown:g=>{if(!e||me(g.target)||!d.current)return;const S=g.button===1;if(r||S){g.preventDefault(),E(g);return}g.preventDefault();const D=Mt(g,d.current);if(s){i==="click"?f(D):(g.currentTarget.setPointerCapture(g.pointerId),_(D));return}if(u.activeTool==="select"){const P=St({point:D,paths:u.paths,boxes:u.boxes,memos:u.memos});if(P)g.shiftKey?u.toggleSelected(P):u.selectOne(P),u.startSelectedMove(),T.current={mode:"move",lastPoint:D,didMove:!1};else if(l&&t>1.01){E(g);return}else u.clearSelection(),u.startSelectionBox(D),T.current={mode:"box",lastPoint:D,didMove:!1};g.currentTarget.setPointerCapture(g.pointerId);return}if(u.activeTool==="memo"){u.createMemo(D),requestAnimationFrame(()=>{d.current?.querySelector(".canvas-memo--active")?.focus()});return}if(u.activeTool==="eraser"){if(u.eraserMode==="object"){const P=St({point:D,paths:u.paths,boxes:u.boxes,memos:u.memos});P&&u.eraseObjectAtPoint(P);return}g.currentTarget.setPointerCapture(g.pointerId),u.startEraserStroke(D);return}g.currentTarget.setPointerCapture(g.pointerId),u.startDrawing(D)},handleAnnotationPointerMove:g=>{if(!e||me(g.target)||!d.current)return;if(N.current.active){const D=g.clientX-N.current.startX,P=g.clientY-N.current.startY;b(N.current.basePanX+D,N.current.basePanY+P);return}const S=Mt(g,d.current);if(s){i==="brush"?B(S):O(S);return}if(u.activeTool==="select"){if(T.current.mode==="move"&&T.current.lastPoint){const D={x:S.x-T.current.lastPoint.x,y:S.y-T.current.lastPoint.y};(Math.abs(D.x)>5e-4||Math.abs(D.y)>5e-4)&&(u.moveSelected(D),T.current.didMove=!0),T.current.lastPoint=S}else T.current.mode==="box"&&u.updateSelectionBox(S);return}if(u.activeTool!=="memo"){if(u.activeTool==="eraser"){u.eraserMode==="brush"&&u.updateEraserStroke(S);return}u.moveDrawing(S)}},handleAnnotationPointerUp:g=>{if(e&&!me(g.target)){if(N.current.active&&N.current.pointerId===g.pointerId){g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),N.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},C(!1);return}if(g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),s){i==="brush"&&A();return}if(u.activeTool==="select"){T.current.mode==="move"&&T.current.didMove&&u.commitSelectedMove(),T.current.mode==="box"&&u.selectionBox&&u.endSelectionBox(Ha({box:Oa(u.selectionBox),annotations:u.toPayload()})),T.current={mode:null,lastPoint:null,didMove:!1};return}if(u.activeTool!=="memo"){if(u.activeTool==="eraser"){u.eraserMode==="brush"&&u.endEraserStroke();return}u.endDrawing()}}},handleAnnotationPointerLeave:()=>{s&&O(null)}}}function Va({canvasOpen:e,canvasZoom:t,currentImage:n,annotations:a,undoBackgroundCleanup:r,redoBackgroundCleanup:l,handleBackgroundCleanupEscape:s,handleCloseCanvas:i,selectHistoryShortcutTarget:d,trashHistoryItem:u,permanentlyDeleteHistoryItemByShortcut:b,setCanvasZoom:f,resetCanvasZoom:_,onCreateBlankCanvas:B,isCreatingBlankCanvas:A}){const[O,T]=c.useState(!1);return c.useEffect(()=>{if(!e)return;const m=v=>{v.preventDefault()},C=v=>{v.ctrlKey&&v.preventDefault()},E={passive:!1,capture:!0},y={passive:!1};return window.addEventListener("wheel",C,E),window.addEventListener("gesturestart",m,y),window.addEventListener("gesturechange",m,y),window.addEventListener("gestureend",m,y),()=>{window.removeEventListener("wheel",C,E),window.removeEventListener("gesturestart",m,y),window.removeEventListener("gesturechange",m,y),window.removeEventListener("gestureend",m,y)}},[e]),c.useEffect(()=>{if(!e)return;const m=E=>{E.code==="Space"&&(me(E.target)||(O||T(!0),E.preventDefault()))},C=E=>{E.code==="Space"&&T(!1)};return window.addEventListener("keydown",m),window.addEventListener("keyup",C),()=>{window.removeEventListener("keydown",m),window.removeEventListener("keyup",C)}},[e,O]),c.useEffect(()=>{if(!e)return;const m=C=>{if(!C.defaultPrevented){if(me(C.target)){C.key==="Escape"&&(C.preventDefault(),C.target.blur(),a.focusMemo(null));return}if(C.key==="Escape"){if(C.preventDefault(),s())return;i();return}if(C.shiftKey&&!C.metaKey&&!C.ctrlKey&&!C.altKey&&C.key.toLowerCase()==="b"){C.preventDefault(),!A&&!C.repeat&&B();return}if((C.metaKey||C.ctrlKey)&&C.key.toLowerCase()==="z"){if(C.preventDefault(),C.shiftKey){if(l())return;a.redo();return}if(r())return;a.undo()}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[a,a.focusMemo,a.redo,a.undo,e,i,s,A,B,l,r]),{spaceHeld:O,handleViewerKeyDown:m=>{if(me(m.target)){m.key==="Escape"&&(m.preventDefault(),m.target.blur(),a.focusMemo(null));return}if(e&&["1","2","3","4","5","6"].includes(m.key)){m.preventDefault();const C=["select","pen","box","arrow","memo","eraser"];a.setTool(C[Number(m.key)-1]);return}if(e&&m.key==="Escape"){if(m.preventDefault(),m.stopPropagation(),s())return;i();return}if(e&&m.key==="]"){m.preventDefault(),f(t+.1);return}if(e&&m.key==="["){m.preventDefault(),f(t-.1);return}if(e&&m.key==="0"){m.preventDefault(),_();return}if(m.key==="Delete"||m.key==="Backspace"){if(!n||m.target!==m.currentTarget)return;if(m.preventDefault(),m.shiftKey){b(n);return}u(n);return}m.key!=="ArrowLeft"&&m.key!=="ArrowRight"&&m.key!=="Home"&&m.key!=="End"||m.target===m.currentTarget&&(me(m.target)||(m.preventDefault(),m.key==="ArrowLeft"?d("previous"):m.key==="ArrowRight"?d("next"):m.key==="Home"?d("first"):m.key==="End"&&d("last")))}}}function Ka(e,t){return new Promise((n,a)=>{e.toBlob(r=>{if(r){n(r);return}a(new Error("canvas_blob_unavailable"))},t)})}async function Ut(e){const t=document.createElement("canvas");t.width=e.imageElement.naturalWidth,t.height=e.imageElement.naturalHeight;const n=t.getContext("2d");if(!n)throw new Error("canvas_context_unavailable");e.background?.mode==="matte"&&(n.fillStyle=e.background.color,n.fillRect(0,0,t.width,t.height)),n.drawImage(e.imageElement,0,0,t.width,t.height);const a={width:t.width,height:t.height};for(const l of e.paths)nt(n,l,a);for(const l of e.boxes)at(n,l,a,"committed");for(const l of e.memos)Bn(n,l,a);return{blob:await Ka(t,"image/png"),dataUrl:t.toDataURL("image/png")}}const za=["left","center","right"],Xa=["top","middle","bottom"];function qa(e,t){const n=za[Math.min(2,Math.max(0,Math.floor(e*3)))],a=Xa[Math.min(2,Math.max(0,Math.floor(t*3)))];return`${a==="middle"&&n==="center"?"center":`${a} ${n}`} area (x: ${Math.round(e*100)}%, y: ${Math.round(t*100)}% from top-left)`}function Ya(e){const t=e.map(n=>({...n,text:n.text.trim()})).filter(n=>n.text.length>0);return t.length===0?"":["Apply the following annotation instructions at the specified image locations (percentages are relative to image width and height):",...t.map((n,a)=>`${a+1}. At the ${qa(n.x,n.y)}: ${n.text}`),"Do not render any annotation text, sticky notes, boxes, arrows, or markup in the output image."].join(`
|
|
1
|
+
import{a as c,j as o,u as ye,f as on,w as sn,x as ln,y as cn,z as Bt,B as me,C as un,D as jt,E as dn,b as j,F as hn,c as fn,G as pn,H as mn,J as vn}from"./index-BzjrmmIG.js";const De=2,Le=1e-6;function bn({paths:e,points:t,radius:n,makeId:a=()=>crypto.randomUUID()}){if(e.length===0||t.length===0||n<=0)return{paths:e,changed:!1};let r=!1;const l=[];for(const s of e){const i=gn(s,t,n,a);(i.length!==1||i[0]!==s)&&(r=!0),l.push(...i)}return{paths:l,changed:r}}function gn(e,t,n,a=()=>crypto.randomUUID()){if(e.points.length<De||t.length===0||n<=0)return[e];const r=[];let l=je(e.points[0],t,n)?[]:[e.points[0]];for(let i=1;i<e.points.length;i+=1){const d=e.points[i-1],u=e.points[i],b=je(u,t,n),f=xn(d,u,t,n);if(f){l.length===0&&!je(d,t,n)&&(l=[d]),l.length>0&&f.leftT>Le&&ft(l,Te(d,u,f.leftT)),l.length>=De&&r.push(l),l=[],f.rightT<1-Le&&!b&&(l=[Te(d,u,f.rightT),u]);continue}if(b){l.length>=De&&r.push(l),l=[];continue}l.length===0&&!je(d,t,n)&&(l=[d]),ft(l,u)}if(l.length>=De&&r.push(l),r.length===0)return[];if(r.length===1&&r[0].length===e.points.length)return[e];const s=e.tool==="arrow"?r.length-1:-1;return r.map((i,d)=>({...e,id:d===0?e.id:a(),tool:e.tool==="arrow"&&d!==s?"pen":e.tool,points:i}))}function je(e,t,n){if(t.length===1)return xe(e,t[0])<=n;for(let a=1;a<t.length;a+=1)if(yn(e,t[a-1],t[a])<=n)return!0;return!1}function xe(e,t){const n=e.x-t.x,a=e.y-t.y;return Math.sqrt(n*n+a*a)}function xn(e,t,n,a){const r=xe(e,t);if(r<=Le)return je(e,n,a)?{leftT:0,rightT:1}:null;let l=null,s=Number.POSITIVE_INFINITY;for(const d of n){const u=ht(d,e,t),b=Te(e,t,u),f=xe(d,b);f<s&&(s=f,l=u)}for(let d=1;d<n.length;d+=1){const u=[0,.25,.5,.75,1];for(const b of u){const f=Te(n[d-1],n[d],b),_=ht(f,e,t),B=Te(e,t,_),A=xe(f,B);A<s&&(s=A,l=_)}}if(l===null||s>a)return null;const i=Math.max(a/r,.01);return{leftT:Math.max(0,l-i),rightT:Math.min(1,l+i)}}function ht(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,i=a*a+r*r;return i===0?0:Math.max(0,Math.min(1,(l*a+s*r)/i))}function Te(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function ft(e,t){const n=e.at(-1);(!n||xe(n,t)>Le)&&e.push(t)}function yn(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,i=a*a+r*r;if(i===0)return xe(e,t);const d=Math.max(0,Math.min(1,(l*a+s*r)/i));return xe(e,{x:t.x+d*a,y:t.y+d*r})}function st(e,t){return`${e}:${t}`}function lt(e){const t=e.indexOf(":");if(t<=0)return null;const n=e.slice(0,t),a=e.slice(t+1);return!a||n!=="path"&&n!=="box"&&n!=="memo"?null:{kind:n,id:a}}function Tt(e){return st("path",e.id)}function Pt(e){return st("box",e.id)}function Dt(e){return st("memo",e.id)}function pe(e,t,n){const a=lt(e);return a?.kind===t&&a.id===n}const At="ima2.canvas.annotationStyle.v1",It=["#ef4444","#f97316","#eab308","#22c55e","#38bdf8","#6366f1","#a855f7","#111827","#ffffff"],Nt=[2,3,5,8],Ee={color:"#ef4444",strokeWidth:3};function kn(){if(typeof window>"u")return Ee;try{const e=window.localStorage.getItem(At);if(!e)return Ee;const t=JSON.parse(e),n=typeof t.color=="string"&&It.includes(t.color)?t.color:Ee.color,a=typeof t.strokeWidth=="number"&&Nt.includes(t.strokeWidth)?t.strokeWidth:Ee.strokeWidth;return{color:n,strokeWidth:a}}catch{return Ee}}function wn(e){if(!(typeof window>"u"))try{window.localStorage.setItem(At,JSON.stringify(e))}catch{}}const pt=kn(),tt={activeTool:"select",toolColor:pt.color,strokeWidth:pt.strokeWidth,paths:[],boxes:[],memos:[],activeMemoId:null,activePath:null,activeBox:null,eraserMode:"object",activeEraserStroke:null,eraserBaseline:null,selectionBox:null,selectedIds:[],past:[],future:[],memoBaseline:null,moveBaseline:null,isDirty:!1};function ge(e){return{paths:e.paths,boxes:e.boxes,memos:e.memos}}function be(e){return{...e,past:[...e.past.slice(-49),ge(e)],future:[]}}function Ge(e,t){return{...e,past:[...e.past.slice(-49),t],future:[]}}function Cn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function mt(e,t){return{...e,...t,activeMemoId:null,activePath:null,activeBox:null,selectionBox:null,selectedIds:[],isDirty:!0}}function _n(e,t,n){const{start:a,current:r}=e,l=Math.min(a.x,r.x),s=Math.min(a.y,r.y),i=Math.abs(r.x-a.x),d=Math.abs(r.y-a.y);return i<.01||d<.01?null:{id:crypto.randomUUID(),x:l,y:s,width:i,height:d,color:t,strokeWidth:n}}function Mn(e,t){return{...e,x:Math.min(1-e.width,Math.max(0,e.x+t.x)),y:Math.min(1-e.height,Math.max(0,e.y+t.y))}}function Ze(e,t){return{x:Math.min(1,Math.max(0,e.x+t.x)),y:Math.min(1,Math.max(0,e.y+t.y))}}function En(e,t){switch(t.type){case"SET_TOOL":return{...e,activeTool:t.tool};case"SET_ERASER_MODE":return{...e,eraserMode:t.mode};case"SET_STYLE":return{...e,toolColor:t.style.color,strokeWidth:t.style.strokeWidth};case"START_PATH":return{...e,isDirty:!0,activePath:{id:crypto.randomUUID(),tool:e.activeTool,points:[t.point],color:e.toolColor,strokeWidth:e.strokeWidth}};case"ADD_POINT":return e.activePath?{...e,activePath:{...e.activePath,points:[...e.activePath.points,t.point]}}:e;case"END_PATH":return!e.activePath||e.activePath.points.length<2?{...e,activePath:null}:{...be(e),isDirty:!0,paths:[...e.paths,e.activePath],activePath:null};case"START_BOX":return{...e,isDirty:!0,activeBox:{start:t.point,current:t.point}};case"UPDATE_BOX":return e.activeBox?{...e,activeBox:{...e.activeBox,current:t.point}}:e;case"END_BOX":{if(!e.activeBox)return e;const n=_n(e.activeBox,e.toolColor,e.strokeWidth);return n?{...be(e),isDirty:!0,boxes:[...e.boxes,n],activeBox:null}:{...e,activeBox:null}}case"CREATE_MEMO":{const n=crypto.randomUUID(),a={id:n,x:t.point.x,y:t.point.y,text:"",color:e.toolColor};return{...be(e),isDirty:!0,memos:[...e.memos,a],activeMemoId:n}}case"UPDATE_MEMO":return{...e,isDirty:!0,memos:e.memos.map(n=>n.id===t.id?{...n,text:t.text}:n)};case"COMMIT_MEMO_EDIT":return e.memoBaseline?Cn(e.memoBaseline,ge(e))?{...e,memoBaseline:null,activeMemoId:null}:{...Ge(e,e.memoBaseline),memoBaseline:null,activeMemoId:null,isDirty:!0}:{...e,activeMemoId:null};case"DELETE_MEMO":return{...be(e),isDirty:!0,memos:e.memos.filter(n=>n.id!==t.id),activeMemoId:e.activeMemoId===t.id?null:e.activeMemoId,selectedIds:e.selectedIds.filter(n=>!pe(n,"memo",t.id))};case"FOCUS_MEMO":return{...e,activeMemoId:t.id,memoBaseline:t.id&&e.activeMemoId!==t.id&&!e.memoBaseline?ge(e):e.memoBaseline};case"CLEAR":return{...be(e),isDirty:!0,paths:[],boxes:[],memos:[],activeMemoId:null,activePath:null,activeBox:null,selectionBox:null,selectedIds:[]};case"LOAD":return{...tt,activeTool:e.activeTool,eraserMode:e.eraserMode,toolColor:e.toolColor,strokeWidth:e.strokeWidth,...t.payload};case"MARK_SAVED":return{...e,isDirty:!1};case"RESET_LOCAL":return{...tt,activeTool:e.activeTool,eraserMode:e.eraserMode,toolColor:e.toolColor,strokeWidth:e.strokeWidth};case"UNDO":{const n=e.past.at(-1);return n?{...mt(e,n),past:e.past.slice(0,-1),future:[ge(e),...e.future]}:e}case"REDO":{const n=e.future[0];return n?{...mt(e,n),past:[...e.past.slice(-49),ge(e)],future:e.future.slice(1)}:e}case"SELECT_ONE":return{...e,selectedIds:[t.id],selectionBox:null};case"TOGGLE_SELECTED":return{...e,selectedIds:e.selectedIds.includes(t.id)?e.selectedIds.filter(n=>n!==t.id):[...e.selectedIds,t.id],selectionBox:null};case"CLEAR_SELECTION":return{...e,selectedIds:[],selectionBox:null};case"DELETE_SELECTED":return e.selectedIds.length===0?e:{...be(e),isDirty:!0,paths:e.paths.filter(n=>!e.selectedIds.some(a=>pe(a,"path",n.id))),boxes:e.boxes.filter(n=>!e.selectedIds.some(a=>pe(a,"box",n.id))),memos:e.memos.filter(n=>!e.selectedIds.some(a=>pe(a,"memo",n.id))),selectedIds:[]};case"MOVE_SELECTED":return e.selectedIds.length===0?e:{...e,isDirty:!0,paths:e.paths.map(n=>e.selectedIds.some(a=>pe(a,"path",n.id))?{...n,points:n.points.map(a=>Ze(a,t.delta))}:n),boxes:e.boxes.map(n=>e.selectedIds.some(a=>pe(a,"box",n.id))?Mn(n,t.delta):n),memos:e.memos.map(n=>e.selectedIds.some(a=>pe(a,"memo",n.id))?{...n,x:Ze(n,t.delta).x,y:Ze(n,t.delta).y}:n)};case"START_SELECTED_MOVE":return{...e,moveBaseline:ge(e)};case"COMMIT_SELECTED_MOVE":return e.moveBaseline?{...Ge(e,e.moveBaseline),moveBaseline:null,isDirty:!0}:e;case"START_SELECTION_BOX":return{...e,selectionBox:{start:t.point,current:t.point},selectedIds:[]};case"UPDATE_SELECTION_BOX":return e.selectionBox?{...e,selectionBox:{...e.selectionBox,current:t.point}}:e;case"END_SELECTION_BOX":return{...e,selectionBox:null,selectedIds:t.ids};case"ERASE_OBJECT":{const n=lt(t.id);return!n||!(n.kind==="path"?e.paths.some(r=>r.id===n.id):n.kind==="box"?e.boxes.some(r=>r.id===n.id):e.memos.some(r=>r.id===n.id))?e:{...be(e),isDirty:!0,paths:n.kind==="path"?e.paths.filter(r=>r.id!==n.id):e.paths,boxes:n.kind==="box"?e.boxes.filter(r=>r.id!==n.id):e.boxes,memos:n.kind==="memo"?e.memos.filter(r=>r.id!==n.id):e.memos,selectedIds:e.selectedIds.filter(r=>r!==t.id)}}case"START_ERASER_STROKE":return{...e,activeEraserStroke:{points:[t.point],radius:.018},eraserBaseline:ge(e)};case"UPDATE_ERASER_STROKE":return e.activeEraserStroke?{...e,activeEraserStroke:{...e.activeEraserStroke,points:[...e.activeEraserStroke.points,t.point]}}:e;case"END_ERASER_STROKE":{if(!e.activeEraserStroke||!e.eraserBaseline)return{...e,activeEraserStroke:null,eraserBaseline:null};const n=bn({paths:e.paths,points:e.activeEraserStroke.points,radius:e.activeEraserStroke.radius});return n.changed?{...Ge(e,e.eraserBaseline),paths:n.paths,activeEraserStroke:null,eraserBaseline:null,selectedIds:[],isDirty:!0}:{...e,activeEraserStroke:null,eraserBaseline:null}}default:return e}}function Sn(){const[e,t]=c.useReducer(En,tt),n=c.useMemo(()=>e.paths.length>0||e.boxes.length>0||e.memos.length>0,[e.paths.length,e.boxes.length,e.memos.length]),a=e.past.length>0,r=e.future.length>0,l=c.useCallback(p=>t({type:"SET_TOOL",tool:p}),[]),s=c.useCallback(p=>{wn(p),t({type:"SET_STYLE",style:p})},[]),i=c.useCallback(()=>t({type:"CLEAR"}),[]),d=c.useCallback(p=>t({type:"LOAD",payload:p}),[]),u=c.useCallback(()=>t({type:"MARK_SAVED"}),[]),b=c.useCallback(()=>t({type:"RESET_LOCAL"}),[]),f=c.useCallback(()=>t({type:"UNDO"}),[]),_=c.useCallback(()=>t({type:"REDO"}),[]),B=c.useCallback(()=>t({type:"COMMIT_MEMO_EDIT"}),[]),A=c.useCallback(()=>t({type:"START_SELECTED_MOVE"}),[]),O=c.useCallback(()=>t({type:"COMMIT_SELECTED_MOVE"}),[]),T=c.useCallback(p=>{e.activeTool==="pen"||e.activeTool==="arrow"?t({type:"START_PATH",point:p}):e.activeTool==="box"&&t({type:"START_BOX",point:p})},[e.activeTool]),N=c.useCallback(p=>{e.activePath?t({type:"ADD_POINT",point:p}):e.activeBox&&t({type:"UPDATE_BOX",point:p})},[e.activePath,e.activeBox]),m=c.useCallback(()=>{e.activePath?t({type:"END_PATH"}):e.activeBox&&t({type:"END_BOX"})},[e.activePath,e.activeBox]),C=c.useCallback(p=>t({type:"CREATE_MEMO",point:p}),[]),E=c.useCallback((p,R)=>t({type:"UPDATE_MEMO",id:p,text:R}),[]),y=c.useCallback(p=>t({type:"DELETE_MEMO",id:p}),[]),v=c.useCallback(p=>t({type:"FOCUS_MEMO",id:p}),[]),Z=c.useCallback(p=>t({type:"SET_ERASER_MODE",mode:p}),[]),I=c.useCallback(p=>t({type:"SELECT_ONE",id:p}),[]),U=c.useCallback(p=>t({type:"TOGGLE_SELECTED",id:p}),[]),g=c.useCallback(()=>t({type:"CLEAR_SELECTION"}),[]),S=c.useCallback(()=>t({type:"DELETE_SELECTED"}),[]),D=c.useCallback(p=>t({type:"MOVE_SELECTED",delta:p}),[]),P=c.useCallback(p=>t({type:"START_SELECTION_BOX",point:p}),[]),V=c.useCallback(p=>t({type:"UPDATE_SELECTION_BOX",point:p}),[]),Y=c.useCallback(p=>t({type:"END_SELECTION_BOX",ids:p}),[]),te=c.useCallback(p=>t({type:"ERASE_OBJECT",id:p}),[]),ne=c.useCallback(p=>t({type:"START_ERASER_STROKE",point:p}),[]),se=c.useCallback(p=>t({type:"UPDATE_ERASER_STROKE",point:p}),[]),ue=c.useCallback(()=>t({type:"END_ERASER_STROKE"}),[]),L=c.useCallback(()=>({paths:e.paths,boxes:e.boxes,memos:e.memos}),[e.paths,e.boxes,e.memos]);return{...e,canUndo:a,canRedo:r,hasAnnotations:n,setTool:l,setStyle:s,setEraserMode:Z,startDrawing:T,moveDrawing:N,endDrawing:m,createMemo:C,updateMemo:E,commitMemoEdit:B,deleteMemo:y,focusMemo:v,clear:i,load:d,toPayload:L,markSaved:u,resetLocal:b,undo:f,redo:_,selectOne:I,toggleSelected:U,clearSelection:g,deleteSelected:S,moveSelected:D,startSelectedMove:A,commitSelectedMove:O,startSelectionBox:P,updateSelectionBox:V,endSelectionBox:Y,eraseObjectAtPoint:te,startEraserStroke:ne,updateEraserStroke:se,endEraserStroke:ue}}function Ae(e,t){return{x:e.x*t.width,y:e.y*t.height}}function nt(e,t,n){if(t.points.length<2)return;const a=Ae(t.points[0],n);e.save(),e.beginPath(),e.strokeStyle=t.color,e.lineWidth=t.strokeWidth,e.lineCap="round",e.lineJoin="round",e.moveTo(a.x,a.y);for(const r of t.points.slice(1)){const l=Ae(r,n);e.lineTo(l.x,l.y)}if(e.stroke(),t.tool==="arrow"){const r=Ae(t.points[t.points.length-1],n),l=Ae(t.points[t.points.length-2],n);Tn(e,l,r,t.color,t.strokeWidth)}e.restore()}function at(e,t,n,a){const r="start"in t?{x:Math.min(t.start.x,t.current.x),y:Math.min(t.start.y,t.current.y),width:Math.abs(t.current.x-t.start.x),height:Math.abs(t.current.y-t.start.y),color:"#64c8ff",strokeWidth:2}:t;e.save(),e.strokeStyle=r.color,e.lineWidth=a==="active"?Math.max(2,r.strokeWidth):r.strokeWidth,a==="active"&&e.setLineDash([8,6]),e.strokeRect(r.x*n.width,r.y*n.height,r.width*n.width,r.height*n.height),e.restore()}function Bn(e,t,n){const a=t.x*n.width,r=t.y*n.height,l=Math.min(260,Math.max(150,n.width*.22)),s=12,i=18;e.save(),e.font="14px sans-serif";const d=Pn(e,t.text.trim()||" ",l-s*2),u=Math.max(52,s*2+d.length*i);e.fillStyle="rgba(255, 246, 179, 0.96)",e.strokeStyle="rgba(44, 37, 12, 0.28)",e.lineWidth=1,Dn(e,a,r,l,u,8),e.fill(),e.stroke(),e.fillStyle="#2f2a13",e.textBaseline="top",d.forEach((b,f)=>{e.fillText(b,a+s,r+s+f*i)}),e.restore()}function jn(e,t){const n=lt(e);if(!n)return null;if(n.kind==="box")return t.boxes.find(u=>u.id===n.id)??null;const a=n.kind==="memo"?t.memos.find(u=>u.id===n.id):null;if(a)return{id:a.id,x:a.x,y:a.y,width:.18,height:.12,color:a.color,strokeWidth:1};if(n.kind!=="path")return null;const r=t.paths.find(u=>u.id===n.id);if(!r||r.points.length===0)return null;const l=r.points.map(u=>u.x),s=r.points.map(u=>u.y),i=Math.min(...l),d=Math.min(...s);return{id:r.id,x:i,y:d,width:Math.max(.01,Math.max(...l)-i),height:Math.max(.01,Math.max(...s)-d),color:r.color,strokeWidth:r.strokeWidth}}function vt(e,t,n){const a="start"in t?{x:Math.min(t.start.x,t.current.x),y:Math.min(t.start.y,t.current.y),width:Math.abs(t.current.x-t.start.x),height:Math.abs(t.current.y-t.start.y)}:t;e.save(),e.strokeStyle="#64c8ff",e.lineWidth=2,e.setLineDash([5,5]),e.strokeRect(a.x*n.width,a.y*n.height,a.width*n.width,a.height*n.height),e.restore()}function Tn(e,t,n,a,r){const l=Math.atan2(n.y-t.y,n.x-t.x),s=Math.max(12,r*4),i=Math.PI/7;e.save(),e.fillStyle=a,e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x-s*Math.cos(l-i),n.y-s*Math.sin(l-i)),e.lineTo(n.x-s*Math.cos(l+i),n.y-s*Math.sin(l+i)),e.closePath(),e.fill(),e.restore()}function Pn(e,t,n){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const r=[];let l="";for(const s of a){const i=l?`${l} ${s}`:s;if(e.measureText(i).width<=n||l===""){l=i;continue}r.push(l),l=s}return l&&r.push(l),r}function Dn(e,t,n,a,r,l){const s=Math.min(l,a/2,r/2);e.beginPath(),e.moveTo(t+s,n),e.lineTo(t+a-s,n),e.quadraticCurveTo(t+a,n,t+a,n+s),e.lineTo(t+a,n+r-s),e.quadraticCurveTo(t+a,n+r,t+a-s,n+r),e.lineTo(t+s,n+r),e.quadraticCurveTo(t,n+r,t,n+r-s),e.lineTo(t,n+s),e.quadraticCurveTo(t,n,t+s,n),e.closePath()}function An({paths:e,boxes:t,memos:n=[],selectedIds:a=[],selectionBox:r=null,activePath:l,activeBox:s}){const i=c.useRef(null);return c.useEffect(()=>{const d=i.current;if(!d)return;const u=d.getBoundingClientRect(),b=window.devicePixelRatio||1;d.width=Math.max(1,Math.round(u.width*b)),d.height=Math.max(1,Math.round(u.height*b));const f=d.getContext("2d");if(!f)return;f.setTransform(b,0,0,b,0,0),f.clearRect(0,0,u.width,u.height);const _={width:u.width,height:u.height};for(const B of e)nt(f,B,_);for(const B of t)at(f,B,_,"committed");for(const B of a){const A=jn(B,{paths:e,boxes:t,memos:n});A&&vt(f,A,_)}r&&vt(f,r,_),l&&nt(f,l,_),s&&at(f,s,_,"active")},[e,t,n,a,r,l,s]),o.jsx("canvas",{ref:i,className:"canvas-annotation-layer","aria-hidden":"true"})}function Ie(e){e.stopPropagation()}function In({memos:e,activeMemoId:t,onUpdate:n,onDelete:a,onFocus:r,onCommit:l}){return o.jsx("div",{className:"canvas-memo-overlay",children:e.map(s=>o.jsx("textarea",{className:`canvas-memo${t===s.id?" canvas-memo--active":""}`,value:s.text,style:{left:`${s.x*100}%`,top:`${s.y*100}%`},autoFocus:t===s.id,onFocus:()=>r(s.id),onPointerDown:Ie,onPointerMove:Ie,onPointerUp:Ie,onPointerCancel:Ie,onChange:i=>n(s.id,i.currentTarget.value),onBlur:()=>{l?.(),s.text.trim()===""&&a(s.id)},"aria-label":"Canvas memo"},s.id))})}function Nn({annotationFrameRef:e,imageElementRef:t,frameClassName:n,frameStyle:a,imageKey:r,imageSrc:l,fallbackImage:s,alt:i,canvasOpen:d,maskOverlayUrl:u,cleanupLayer:b,annotations:f,onOpenCanvas:_,onPointerDown:B,onPointerMove:A,onPointerUp:O,onPointerLeave:T}){return o.jsxs("div",{ref:e,className:n,onPointerDown:B,onPointerMove:A,onPointerUp:O,onPointerCancel:O,onPointerLeave:T,style:a,children:[o.jsx("img",{ref:t,className:"result-img",src:l??s,alt:i,decoding:"async",onDoubleClick:N=>{N.stopPropagation(),_()}},r),d&&u?o.jsx("img",{className:"canvas-background-cleanup-mask",src:u,alt:"","aria-hidden":"true",decoding:"async"}):null,d?b:null,d&&o.jsxs(o.Fragment,{children:[o.jsx(An,{paths:f.paths,boxes:f.boxes,memos:f.memos,selectedIds:f.selectedIds,selectionBox:f.selectionBox,activePath:f.activePath,activeBox:f.activeBox}),o.jsx(In,{memos:f.memos,activeMemoId:f.activeMemoId,onUpdate:f.updateMemo,onDelete:f.deleteMemo,onFocus:f.focusMemo,onCommit:f.commitMemoEdit})]})]})}function Rn(e){return`${e.x*100} ${e.y*100}`}function Ln(e){return e.map(Rn).join(" ")}function On({seeds:e,brushStrokes:t,brushCursor:n,brushRadius:a,active:r}){if(!r&&e.length===0&&t.length===0)return null;const l=a*100;return o.jsxs("svg",{className:"canvas-cleanup-overlay",viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",children:[t.map(s=>o.jsx("polyline",{className:`canvas-cleanup-overlay__stroke canvas-cleanup-overlay__stroke--${s.intent}`,points:Ln(s.points),strokeWidth:Math.max(.3,s.radius*200),vectorEffect:"non-scaling-stroke"},s.id)),r&&n?o.jsx("circle",{className:"canvas-cleanup-cursor",cx:n.x*100,cy:n.y*100,r:Math.max(.6,l),vectorEffect:"non-scaling-stroke"}):null]})}function $n({mode:e,matteColor:t,onModeChange:n,onMatteColorChange:a}){const{t:r}=ye();return o.jsxs("div",{className:"canvas-toolbar__bg",role:"group","aria-label":r("canvas.toolbar.bgGroup"),children:[o.jsx("button",{type:"button",className:`canvas-toolbar__bg-tab${e==="alpha"?" active":""}`,onClick:()=>n("alpha"),children:r("canvas.toolbar.bgAlpha")}),o.jsx("button",{type:"button",className:`canvas-toolbar__bg-tab${e==="matte"?" active":""}`,onClick:()=>n("matte"),children:r("canvas.toolbar.bgMatte")}),e==="matte"?o.jsx("input",{type:"color","aria-label":r("canvas.toolbar.bgMatteColor"),value:t,onChange:l=>a(l.target.value)}):null]})}function bt({label:e,value:t,options:n,onChange:a}){return o.jsxs("div",{className:"canvas-toolbar__segmented-row",children:[o.jsx("span",{className:"canvas-toolbar__segmented-label",children:e}),o.jsx("div",{className:"canvas-toolbar__segmented",role:"group","aria-label":e,children:n.map(r=>o.jsx("button",{type:"button",className:"canvas-toolbar__segmented-button","data-value":r.value,"aria-pressed":t===r.value,onClick:()=>a(r.value),children:r.label},r.value))})]})}function Un({seedCount:e,tolerance:t,stats:n,hasPreview:a,isPickingSeed:r,intent:l,tool:s,brushRadius:i,isPreviewing:d,isApplying:u,keepOpen:b,disabled:f,onAutoSample:_,onPickSeed:B,onIntentChange:A,onToolChange:O,onBrushRadiusChange:T,onToleranceChange:N,onPreview:m,onApply:C,onReset:E}){const{t:y}=ye(),[v,Z]=c.useState(!1),I=c.useRef(null),U=n?Math.round(n.removedPercent*1e3)/10:0,g=r||s==="brush";return c.useEffect(()=>{if(!v)return;const S=D=>{b||I.current?.contains(D.target)||Z(!1)};return window.addEventListener("pointerdown",S),()=>window.removeEventListener("pointerdown",S)},[b,v]),o.jsxs("div",{className:"canvas-toolbar__cleanup",ref:I,children:[o.jsx("button",{type:"button",className:`canvas-toolbar__button${v||a?" canvas-toolbar__button--active":""}`,onClick:()=>Z(S=>!S),disabled:f,"aria-expanded":v,"aria-label":y("canvas.toolbar.cleanup"),title:y("canvas.toolbar.cleanup"),children:o.jsx(Wn,{})}),v?o.jsxs("div",{className:"canvas-toolbar__cleanup-panel",role:"group","aria-label":y("canvas.toolbar.cleanup"),children:[o.jsxs("div",{className:"canvas-toolbar__cleanup-row",children:[o.jsx("span",{className:"canvas-toolbar__cleanup-title",children:y("canvas.toolbar.cleanup")}),o.jsx("span",{className:"canvas-toolbar__cleanup-meta",children:y("canvas.toolbar.cleanupSeedCount",{n:e})})]}),o.jsx(bt,{label:y("canvas.toolbar.cleanupMark"),value:l,options:[{value:"remove",label:y("canvas.toolbar.cleanupRemove")},{value:"preserve",label:y("canvas.toolbar.cleanupPreserve")}],onChange:A}),o.jsx(bt,{label:y("canvas.toolbar.cleanupInput"),value:s,options:[{value:"click",label:y("canvas.toolbar.cleanupClick")},{value:"brush",label:y("canvas.toolbar.cleanupBrush")}],onChange:O}),o.jsxs("label",{className:"canvas-toolbar__cleanup-slider",children:[o.jsx("span",{children:y("canvas.toolbar.cleanupTolerance")}),o.jsx("input",{type:"range",min:"0",max:"96",value:t,onChange:S=>N(Number(S.target.value))}),o.jsx("output",{children:t})]}),s==="brush"?o.jsxs("label",{className:"canvas-toolbar__cleanup-slider",children:[o.jsx("span",{children:y("canvas.toolbar.cleanupBrushSize")}),o.jsx("input",{type:"range",min:"0.006",max:"0.06",step:"0.002",value:i,onChange:S=>T(Number(S.target.value))}),o.jsx("output",{children:Math.round(i*1e3)})]}):null,o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:_,children:y("canvas.toolbar.cleanupAutoSample")}),o.jsx("button",{type:"button",className:r?"active":"",onClick:B,children:y(g?"canvas.toolbar.cleanupActive":"canvas.toolbar.cleanupPickSeed")})]}),o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:m,disabled:d||e===0,children:y(d?"canvas.toolbar.cleanupPreviewing":"canvas.toolbar.cleanupPreview")}),o.jsx("button",{type:"button",onClick:C,disabled:u||!a&&e===0,children:y(u?"canvas.toolbar.cleanupApplying":"canvas.toolbar.cleanupApply")}),o.jsx("button",{type:"button",onClick:E,disabled:!a&&e===0,children:y("canvas.toolbar.cleanupReset")})]}),g?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:y(s==="brush"?"canvas.toolbar.cleanupBrushHint":"canvas.toolbar.cleanupPickHint")}):n&&!a?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:y("canvas.toolbar.cleanupMaskHint")}):null,n?o.jsx("div",{className:"canvas-toolbar__cleanup-status",children:y("canvas.toolbar.cleanupRemoved",{n:U})}):null]}):null]})}function Wn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M5 7.5h14"}),o.jsx("path",{d:"M7 12h10"}),o.jsx("path",{d:"M10 16.5h4"}),o.jsx("path",{d:"M7.5 5.5 9 4l1.5 1.5L9 7 7.5 5.5Z"}),o.jsx("path",{d:"M13.5 11 15 9.5l1.5 1.5L15 12.5 13.5 11Z"}),o.jsx("path",{d:"M4.5 15.5 6 14l1.5 1.5L6 17 4.5 15.5Z"})]})}function Hn({style:e,onStyleChange:t}){const{t:n}=ye(),[a,r]=c.useState(!1),l=c.useRef(null);return c.useEffect(()=>{if(!a)return;const s=i=>{l.current?.contains(i.target)||r(!1)};return window.addEventListener("pointerdown",s),()=>window.removeEventListener("pointerdown",s)},[a]),o.jsxs("div",{ref:l,className:`canvas-toolbar__split-button${a?" canvas-toolbar__split-button--active":""}`,onKeyDown:s=>{s.key==="Escape"&&a&&(s.preventDefault(),s.stopPropagation(),r(!1))},children:[o.jsxs("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__style-trigger",onClick:()=>r(s=>!s),"aria-haspopup":"dialog","aria-expanded":a,"aria-label":n("canvas.toolbar.style"),title:n("canvas.toolbar.style"),children:[o.jsx("span",{className:"canvas-style-trigger__swatch",style:{background:e.color},"aria-hidden":"true"}),o.jsx("span",{className:"canvas-style-trigger__width",style:{height:`${Math.min(8,Math.max(2,e.strokeWidth))}px`},"aria-hidden":"true"})]}),a?o.jsxs("div",{className:"canvas-style-popover",role:"dialog","aria-label":n("canvas.toolbar.style"),children:[o.jsx("div",{className:"canvas-style-popover__row",role:"group","aria-label":n("canvas.toolbar.color"),children:It.map(s=>o.jsx("button",{type:"button",className:`canvas-style-swatch${e.color===s?" canvas-style-swatch--active":""}`,style:{background:s},onClick:()=>t({...e,color:s}),"aria-pressed":e.color===s,"aria-label":s,title:s},s))}),o.jsx("div",{className:"canvas-style-popover__row",role:"group","aria-label":n("canvas.toolbar.strokeWidth"),children:Nt.map(s=>o.jsx("button",{type:"button",className:`canvas-style-width${e.strokeWidth===s?" canvas-style-width--active":""}`,onClick:()=>t({...e,strokeWidth:s}),"aria-pressed":e.strokeWidth===s,"aria-label":`${s}px`,title:`${s}px`,children:o.jsx("span",{style:{height:`${s}px`,background:e.color}})},s))})]}):null]})}function Fn({tools:e,activeTool:t,onToolChange:n}){const[a,r]=c.useState(!1),l=c.useRef(null),s=e.find(d=>d.id===t)??e[0],i=s.icon;return c.useEffect(()=>{if(!a)return;const d=u=>{l.current?.contains(u.target)||r(!1)};return window.addEventListener("pointerdown",d),()=>window.removeEventListener("pointerdown",d)},[a]),o.jsxs("div",{ref:l,className:"canvas-tool-picker",children:[o.jsxs("button",{type:"button",className:`canvas-toolbar__button canvas-tool-picker__trigger${t!=="eraser"?" canvas-toolbar__button--active":""}`,onClick:()=>r(d=>!d),"aria-label":`${s.label} (${s.shortcut})`,"aria-pressed":t===s.id,"aria-haspopup":"menu","aria-expanded":a,title:`${s.label} (${s.shortcut})`,children:[o.jsx(i,{}),o.jsx("span",{className:"canvas-toolbar__shortcut","aria-hidden":"true",children:s.shortcut})]}),a?o.jsx("div",{className:"canvas-tool-picker__menu",role:"menu",children:e.map(d=>{const u=d.icon,b=t===d.id;return o.jsxs("button",{type:"button",className:`canvas-tool-picker__item${b?" active":""}`,role:"menuitemradio","aria-checked":b,onClick:()=>{n(d.id),r(!1)},children:[o.jsx(u,{}),o.jsx("span",{children:d.label}),o.jsx("kbd",{children:d.shortcut})]},d.id)})}):null]})}function Vn({activeTool:e,hasAnnotations:t,hasExportableContent:n,onToolChange:a,eraserMode:r="object",onEraserModeChange:l,style:s,onStyleChange:i,onClear:d,onApply:u,onExport:b,onUndo:f,onRedo:_,canUndo:B,canRedo:A,onDeleteSelected:O,selectedCount:T=0,onEditWithMask:N,canEditWithMask:m,isEditingWithMask:C,isApplying:E,isExporting:y,exportBackground:v="alpha",exportMatteColor:Z="#ffffff",onExportBackgroundChange:I,onExportMatteColorChange:U,cleanupTolerance:g=28,cleanupSeedCount:S=0,cleanupStats:D=null,cleanupHasPreview:P=!1,isCleanupPickingSeed:V=!1,isCleanupActive:Y=!1,cleanupIntent:te="remove",cleanupTool:ne="click",cleanupBrushRadius:se=.018,isCleanupPreviewing:ue=!1,isCleanupApplying:L=!1,onCleanupAutoSample:p,onCleanupPickSeed:R,onCleanupIntentChange:J,onCleanupToolChange:ae,onCleanupBrushRadiusChange:le,onCleanupToleranceChange:K,onCleanupPreview:q,onCleanupApply:G,onCleanupReset:z}){const{t:w}=ye(),[$,ee]=c.useState(!1),W=c.useRef(null),ce=n??t??!1,X=w(r==="object"?"canvas.toolbar.objectEraser":"canvas.toolbar.brushEraser"),F=[{id:"select",shortcut:"1",label:w("canvas.toolbar.select"),icon:Kn},{id:"pen",shortcut:"2",label:w("canvas.toolbar.pen"),icon:zn},{id:"box",shortcut:"3",label:w("canvas.toolbar.box"),icon:Xn},{id:"arrow",shortcut:"4",label:w("canvas.toolbar.arrow"),icon:qn},{id:"memo",shortcut:"5",label:w("canvas.toolbar.memo"),icon:Yn}];c.useEffect(()=>{if(!$)return;const re=we=>{W.current?.contains(we.target)||ee(!1)};return window.addEventListener("pointerdown",re),()=>window.removeEventListener("pointerdown",re)},[$]);const de=re=>{l?.(re),a("eraser"),ee(!1)};return o.jsxs("div",{className:"canvas-toolbar","aria-label":w("canvas.toolbar.label"),children:[o.jsx(Fn,{tools:F,activeTool:e,onToolChange:a}),o.jsx(Hn,{style:s,onStyleChange:i}),o.jsxs("div",{ref:W,className:`canvas-toolbar__split-button${e==="eraser"?" canvas-toolbar__split-button--active":""}`,onKeyDown:re=>{re.key==="Escape"&&$&&(re.preventDefault(),ee(!1))},children:[o.jsxs("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--split-main${e==="eraser"?" canvas-toolbar__button--active":""}`,onClick:()=>a("eraser"),"aria-label":`${X} (6)`,"aria-pressed":e==="eraser",title:`${X} (6)`,children:[o.jsx(Gn,{}),o.jsx("span",{className:"canvas-toolbar__shortcut","aria-hidden":"true",children:"6"})]}),o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--split-menu",onClick:()=>ee(re=>!re),"aria-label":w("canvas.toolbar.eraserMenu"),"aria-haspopup":"menu","aria-expanded":$,"aria-controls":"canvas-eraser-menu",title:w("canvas.toolbar.eraserMenu"),children:o.jsx(Zn,{})}),$?o.jsxs("div",{id:"canvas-eraser-menu",className:"canvas-toolbar__eraser-menu",role:"menu",children:[o.jsx("button",{type:"button",className:`canvas-toolbar__eraser-menu-item${r==="object"?" canvas-toolbar__eraser-menu-item--active":""}`,role:"menuitemradio","aria-checked":r==="object",onClick:()=>de("object"),children:w("canvas.toolbar.objectEraser")}),o.jsx("button",{type:"button",className:`canvas-toolbar__eraser-menu-item${r==="brush"?" canvas-toolbar__eraser-menu-item--active":""}`,role:"menuitemradio","aria-checked":r==="brush",onClick:()=>de("brush"),children:w("canvas.toolbar.brushEraser")})]}):null]}),o.jsx("span",{className:"canvas-toolbar__divider","aria-hidden":"true"}),u?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--primary${E?" canvas-toolbar__button--busy":""}`,onClick:u,disabled:!ce||E,"aria-label":w("canvas.toolbar.apply"),title:w("canvas.toolbar.apply"),children:o.jsx(Jn,{})}):null,N?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--primary canvas-toolbar__button--mask${C?" canvas-toolbar__button--busy":""}`,onClick:N,disabled:!m||C,"aria-label":w(m?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),title:w(m?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),children:o.jsx(na,{})}):null,f?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:f,disabled:!B,"aria-label":w("canvas.toolbar.undo"),title:w("canvas.toolbar.undo"),children:o.jsx(ea,{})}):null,_?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:_,disabled:!A,"aria-label":w("canvas.toolbar.redo"),title:w("canvas.toolbar.redo"),children:o.jsx(ta,{})}):null,O?o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:O,disabled:T===0,"aria-label":w("canvas.toolbar.deleteSelected"),title:w("canvas.toolbar.deleteSelected"),children:o.jsx(gt,{})}):null,b&&I&&U?o.jsx($n,{mode:v,matteColor:Z,onModeChange:I,onMatteColorChange:U}):null,p&&R&&J&&ae&&le&&K&&q&&G&&z?o.jsx(Un,{seedCount:S,tolerance:g,stats:D,hasPreview:P,isPickingSeed:V,intent:te,tool:ne,brushRadius:se,isPreviewing:ue,isApplying:L,keepOpen:Y,disabled:E||y,onAutoSample:p,onPickSeed:R,onIntentChange:J,onToolChange:ae,onBrushRadiusChange:le,onToleranceChange:K,onPreview:q,onApply:G,onReset:z}):null,b?o.jsx("button",{type:"button",className:`canvas-toolbar__button${y?" canvas-toolbar__button--busy":""}`,onClick:b,disabled:!ce||y,"aria-label":w("canvas.toolbar.export"),title:w("canvas.toolbar.export"),children:o.jsx(Qn,{})}):null,o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:d,disabled:!ce,"aria-label":w("canvas.toolbar.clear"),title:w("canvas.toolbar.clear"),children:o.jsx(gt,{})})]})}function Kn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M8 12.5V7a2 2 0 0 1 4 0v4"}),o.jsx("path",{d:"M12 11V5a2 2 0 0 1 4 0v7"}),o.jsx("path",{d:"M16 12V8a2 2 0 0 1 4 0v5.5A6.5 6.5 0 0 1 13.5 20H12a6 6 0 0 1-4.24-1.76L4.7 15.18a1.7 1.7 0 0 1 2.4-2.4L9 14.68"})]})}function zn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"m4 20 4.2-1.1L19.5 7.6a2.2 2.2 0 0 0-3.1-3.1L5.1 15.8 4 20Z"}),o.jsx("path",{d:"m14.5 6.5 3 3"})]})}function Xn(){return o.jsx("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:o.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"2"})})}function qn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M5 19 19 5"}),o.jsx("path",{d:"M10 5h9v9"})]})}function Yn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M6 4h12v16H6z"}),o.jsx("path",{d:"M9 8h6"}),o.jsx("path",{d:"M9 12h5"}),o.jsx("path",{d:"M9 16h3"})]})}function Gn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"m4 15 8.5-8.5a2.1 2.1 0 0 1 3 0l2 2a2.1 2.1 0 0 1 0 3L10 19H6.5L4 16.5V15Z"}),o.jsx("path",{d:"M10 19h10"}),o.jsx("path",{d:"m8.5 10.5 5 5"})]})}function Zn(){return o.jsx("svg",{className:"canvas-toolbar__icon canvas-toolbar__icon--small",viewBox:"0 0 24 24","aria-hidden":"true",children:o.jsx("path",{d:"m7 14 5-5 5 5"})})}function Jn(){return o.jsx("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:o.jsx("path",{d:"M5 12.5 10 17 19 7"})})}function Qn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M12 4v11"}),o.jsx("path",{d:"m8 11 4 4 4-4"}),o.jsx("path",{d:"M5 20h14"})]})}function gt(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M4 7h16"}),o.jsx("path",{d:"M9 7V5h6v2"}),o.jsx("path",{d:"M7 7l1 13h8l1-13"}),o.jsx("path",{d:"M10 11v5"}),o.jsx("path",{d:"M14 11v5"})]})}function ea(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M9 7 5 11l4 4"}),o.jsx("path",{d:"M5 11h9a5 5 0 0 1 0 10h-2"})]})}function ta(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"m15 7 4 4-4 4"}),o.jsx("path",{d:"M19 11h-9a5 5 0 0 0 0 10h2"})]})}function na(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"2"}),o.jsx("path",{d:"M9 9h6v6H9z"})]})}function aa({annotations:e,backgroundCleanup:t,backgroundCleanupPreview:n,canvasState:a,actions:r}){return o.jsx(Vn,{activeTool:e.activeTool,eraserMode:e.eraserMode,onEraserModeChange:e.setEraserMode,style:{color:e.toolColor,strokeWidth:e.strokeWidth},onStyleChange:e.setStyle,hasExportableContent:e.hasAnnotations,onToolChange:e.setTool,onClear:e.clear,onApply:()=>{r.handleApplyCanvas()},onExport:()=>{r.handleExportCanvas()},onUndo:e.undo,onRedo:e.redo,canUndo:e.canUndo,canRedo:e.canRedo,onDeleteSelected:e.deleteSelected,selectedCount:e.selectedIds.length,onEditWithMask:()=>{r.handleEditWithMask()},canEditWithMask:e.boxes.length>0,isEditingWithMask:a.isEditingWithMask,isApplying:a.isApplying,isExporting:a.isExporting,exportBackground:a.exportBackground,exportMatteColor:a.exportMatteColor,onExportBackgroundChange:r.setExportBackground,onExportMatteColorChange:r.setExportMatteColor,cleanupTolerance:t.backgroundCleanupTolerance,cleanupSeedCount:t.backgroundCleanupSeeds.length,cleanupStats:t.backgroundCleanupStats,cleanupHasPreview:!!n,isCleanupPickingSeed:t.isBackgroundCleanupPickingSeed,isCleanupActive:t.isBackgroundCleanupActive,cleanupIntent:t.cleanupIntent,cleanupTool:t.cleanupTool,cleanupBrushRadius:t.cleanupBrushRadius,isCleanupPreviewing:t.isBackgroundCleanupPreviewing,isCleanupApplying:t.isBackgroundCleanupApplying,onCleanupAutoSample:t.handleBackgroundCleanupAutoSample,onCleanupPickSeed:t.handleBackgroundCleanupPickSeed,onCleanupIntentChange:t.setCleanupIntent,onCleanupToolChange:l=>{t.setCleanupTool(l),t.setIsBackgroundCleanupActive(!0)},onCleanupBrushRadiusChange:t.setCleanupBrushRadius,onCleanupToleranceChange:t.handleBackgroundCleanupToleranceChange,onCleanupPreview:()=>{t.runBackgroundCleanupPreview()},onCleanupApply:()=>{t.handleBackgroundCleanupApply()},onCleanupReset:t.handleBackgroundCleanupReset})}function ra({currentImage:e,canvasDisplayImage:t,canvasOpen:n,displayQuality:a,displaySize:r,displayModel:l,onAfterDeleteFocus:s,onCopyPrompt:i}){const{t:d}=ye(),u=[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?d("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,on(e.reasoningEffort),a,r,l].filter(b=>!!b).join(" · ");return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"result-meta",children:u}),o.jsx(sn,{imageOverride:n?t:null,onAfterDeleteFocus:s}),e.prompt?o.jsx(ln,{prompt:e.prompt,onCopy:i}):null]})}function oa({zoom:e,onZoomIn:t,onZoomOut:n,onZoomReset:a}){const{t:r}=ye(),l=Math.round(e*100);return o.jsxs("div",{className:"canvas-toolbar__zoom",role:"group","aria-label":r("canvas.toolbar.zoomGroup"),children:[o.jsx("button",{type:"button",className:"canvas-toolbar__zoom-button",onClick:n,"aria-label":r("canvas.toolbar.zoomOut"),title:r("canvas.toolbar.zoomOut"),children:o.jsx(sa,{})}),o.jsxs("button",{type:"button",className:"canvas-toolbar__zoom-value",onClick:a,"aria-label":r("canvas.toolbar.zoomReset"),title:r("canvas.toolbar.zoomReset"),children:[l,"%"]}),o.jsx("button",{type:"button",className:"canvas-toolbar__zoom-button",onClick:t,"aria-label":r("canvas.toolbar.zoomIn"),title:r("canvas.toolbar.zoomIn"),children:o.jsx(la,{})})]})}function sa(){return o.jsx("svg",{className:"canvas-toolbar__icon canvas-toolbar__icon--small",viewBox:"0 0 24 24","aria-hidden":"true",children:o.jsx("path",{d:"M5 12h14"})})}function la(){return o.jsxs("svg",{className:"canvas-toolbar__icon canvas-toolbar__icon--small",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M12 5v14"}),o.jsx("path",{d:"M5 12h14"})]})}function ca({zoom:e,closeLabel:t,blankCanvasLabel:n,blankCanvasAriaLabel:a,blankCanvasShortcut:r,blankCanvasBusy:l,shortcutHint:s,onZoomIn:i,onZoomOut:d,onZoomReset:u,onCreateBlankCanvas:b,onClose:f}){return o.jsxs("div",{className:"canvas-mode-topbar",children:[o.jsxs("div",{className:"canvas-mode-topbar__stack",children:[o.jsx("span",{className:"canvas-mode-topbar__label",children:"Canvas Mode"}),o.jsx(oa,{zoom:e,onZoomIn:i,onZoomOut:d,onZoomReset:u}),o.jsx("span",{className:"canvas-mode-topbar__shortcuts",children:s})]}),o.jsx("div",{className:"canvas-mode-topbar__center",children:o.jsxs("button",{type:"button",className:"canvas-mode-blank",onClick:b,disabled:l,"aria-label":a,title:a,children:[o.jsx("span",{"aria-hidden":"true",children:"+"}),o.jsx("span",{children:n}),o.jsx("kbd",{children:r})]})}),o.jsxs("button",{type:"button",className:"canvas-mode-close",onClick:f,"aria-label":t,children:[o.jsx("kbd",{children:"ESC"}),o.jsx("span",{children:t})]})]})}function Je(e,t,n){return Math.max(t,Math.min(n,e))}function ia({zoom:e,panX:t,panY:n}){const a=Je(100/Math.max(1,e),18,100),r=a/2,l=Je(50-t/40,r,100-r),s=Je(50-n/40,r,100-r);return{width:`${a}%`,height:`${a}%`,left:`${l}%`,top:`${s}%`}}function ua({imageSrc:e,zoom:t,panX:n,panY:a,resetLabel:r,onReset:l}){return o.jsxs("button",{type:"button",className:"canvas-viewport-minimap",onClick:l,"aria-label":r,title:r,children:[o.jsx("img",{src:e,alt:"","aria-hidden":"true"}),o.jsx("span",{className:"canvas-viewport-minimap__window",style:ia({zoom:t,panX:n,panY:a}),"aria-hidden":"true"})]})}function Ne(e){return Math.min(1,Math.max(0,e))}function da(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("mask_blob_unavailable"))},"image/png")})}async function ha(e){const t=e.imageElement.naturalWidth,n=e.imageElement.naturalHeight;if(!t||!n)throw new Error("mask_source_size_unavailable");if(e.boxes.length===0)throw new Error("mask_boxes_required");const a=document.createElement("canvas");a.width=t,a.height=n;const r=a.getContext("2d");if(!r)throw new Error("mask_context_unavailable");r.fillStyle="rgba(0, 0, 0, 1)",r.fillRect(0,0,t,n),r.globalCompositeOperation="destination-out";for(const l of e.boxes){const s=Ne(l.x)*t,i=Ne(l.y)*n,d=Ne(l.width)*t,u=Ne(l.height)*n;d>0&&u>0&&r.fillRect(s,i,d,u)}return da(a)}async function fa(e){const t=e.naturalWidth,n=e.naturalHeight;if(!t||!n)throw new Error("image_source_size_unavailable");const a=document.createElement("canvas");a.width=t,a.height=n;const r=a.getContext("2d");if(!r)throw new Error("image_context_unavailable");return r.drawImage(e,0,0,t,n),a.toDataURL("image/png")}function ct(e){return new Promise((t,n)=>{const a=new FileReader;a.onerror=()=>n(new Error("mask_blob_read_failed")),a.onload=()=>t(String(a.result)),a.readAsDataURL(e)})}const pa=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='28' height='28' viewBox='0 0 28 28'%3E%3Ccircle cx='14' cy='14' r='8' fill='white' fill-opacity='0.16' stroke='black' stroke-width='3'/%3E%3Ccircle cx='14' cy='14' r='8' fill='none' stroke='white' stroke-width='1.5'/%3E%3Ccircle cx='14' cy='14' r='2' fill='white' stroke='black' stroke-width='1'/%3E%3C/svg%3E") 14 14, auto`,ma=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='28' height='28' viewBox='0 0 28 28'%3E%3Ccircle cx='14' cy='14' r='8' fill='white' fill-opacity='0.18' stroke='black' stroke-width='3'/%3E%3Ccircle cx='14' cy='14' r='8' fill='none' stroke='white' stroke-width='1.5'/%3E%3C/svg%3E") 14 14, auto`;function va(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function ba(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function ga(e){const t=e.url??e.image;if(!e.canvasVersion||!e.canvasMergedAt||t.startsWith("data:"))return t;const n=t.includes("?")?"&":"?";return`${t}${n}canvasMergedAt=${e.canvasMergedAt}`}function xa(e){const t=e.canvasSourceFilename??e.filename;return t?`/generated/${encodeURIComponent(t)}`:e.url??e.image}async function xt(e){const t=xa(e);if(t.startsWith("data:image/png;"))return t;const n=new Image;return await new Promise((a,r)=>{n.onload=()=>a(),n.onerror=()=>r(new Error("clean_source_load_failed")),n.src=t}),fa(n)}function it(e,t){return!e.canvasVersion||e.prompt||!t?.prompt?e:{...e,prompt:t.prompt}}function ya(e,t){if(!t?.filename)return null;const n=e.find(a=>a.canvasVersion&&(a.canvasSourceFilename===t.filename||a.canvasEditableFilename===t.filename))??null;return n?it(n,t):null}function ka(e,t){if(cn(e)){const n=e.images[0];if(!n)throw new Error("edit_empty_response");return{...n,prompt:t,reasoningEffort:e.reasoningEffort,provider:e.provider,quality:e.quality,size:e.size,moderation:e.moderation,model:e.model,usage:e.usage,kind:"edit",createdAt:Date.now()}}return{image:e.image,url:e.filename?`/generated/${e.filename}`:e.image,thumb:e.image,filename:e.filename,prompt:t,elapsed:e.elapsed,reasoningEffort:e.reasoningEffort,provider:e.provider,quality:e.quality,size:e.size,moderation:e.moderation,model:e.model,usage:e.usage,revisedPrompt:e.revisedPrompt??null,promptMode:e.promptMode??null,kind:"edit",createdAt:Date.now()}}const Qe=new WeakMap;function wa(e){if(!e.complete||!e.naturalWidth||!e.naturalHeight)return!1;const t=Qe.get(e);if(t&&t.src===e.currentSrc&&t.width===e.naturalWidth&&t.height===e.naturalHeight)return t.result;const n=64,a=Math.min(n,e.naturalWidth),r=Math.min(n,e.naturalHeight),l=document.createElement("canvas");l.width=a,l.height=r;const s=l.getContext("2d",{willReadFrequently:!0});if(!s)return!1;try{s.drawImage(e,0,0,a,r);const i=s.getImageData(0,0,a,r).data;for(let d=3;d<i.length;d+=4)if(i[d]<250)return Qe.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!0}),!0;return Qe.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!1}),!1}catch{return!1}}function Ca(e,t){if(e.width!==t.width||e.height!==t.height||e.data.length!==t.data.length)throw new Error("cleanup_mask_size_mismatch")}function yt(e,t){return{width:e,height:t,data:new Uint8Array(e*t)}}function rt(e){return{width:e.width,height:e.height,data:new Uint8Array(e.data)}}function _a(e,t){Ca(e,t);for(let n=0;n<e.data.length;n+=1)(t.data[n]??0)>0&&(e.data[n]=0)}function Se(e,t){if(!e)return null;const n=rt(e);return t&&_a(n,t),n}function Ma(e,t){if(e.width!==t.width||e.height!==t.height)throw new Error("cleanup_mask_size_mismatch");const n=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);for(let a=0;a<t.data.length;a+=1)(t.data[a]??0)>0&&(n.data[a*4+3]=0);return n}const ut=[{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}],Ea=1024;function Sa(e){return Math.max(0,Math.min(255,Math.round(e)))}function Rt(e,t,n){const a=Math.max(0,Math.min(t-1,Math.round(e.x*(t-1))));return Math.max(0,Math.min(n-1,Math.round(e.y*(n-1))))*t+a}function Ba(e,t){return(t.length>0?t:ut).map(a=>{const r=Rt(a,e.width,e.height)*4;return{r:e.data[r]??0,g:e.data[r+1]??0,b:e.data[r+2]??0}})}function ja(e,t,n,a){for(const r of n)if(Math.max(Math.abs((e[t]??0)-r.r),Math.abs((e[t+1]??0)-r.g),Math.abs((e[t+2]??0)-r.b))<=a)return!0;return!1}function Be(e,t,n,a,r,l,s){if(e<0||e>=a.length||a[e])return r;const i=e*4;return(t.data[i+3]??0)===0?(a[e]=1,r):ja(t.data,i,l,s)?(a[e]=1,n[r]=e,r+1):r}function et(){return ut.map(e=>({...e}))}function kt(e,t,n,a){if(e.width!==t.width||e.height!==t.height)throw new Error("cleanup_mask_size_mismatch");const{width:r,height:l}=t,s=r*l,i=new Uint8Array(s),d=new Int32Array(s),u=Ba(t,n),b=Sa(a);let f=0;for(const _ of n.length>0?n:ut)f=Be(Rt(_,r,l),t,d,i,f,u,b);for(;f>0;){const _=d[--f];e.data[_]=255;const B=_%r;B>0&&(f=Be(_-1,t,d,i,f,u,b)),B<r-1&&(f=Be(_+1,t,d,i,f,u,b)),_>=r&&(f=Be(_-r,t,d,i,f,u,b)),_<s-r&&(f=Be(_+r,t,d,i,f,u,b))}}function Ta(e,t){const n=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),a=Ma(n,t),r=t.data.reduce((l,s)=>l+(s>0?1:0),0);return{imageData:{width:e.width,height:e.height,data:a.data},stats:{width:e.width,height:e.height,removedPixels:r,removedPercent:t.data.length>0?r/t.data.length:0}}}function Lt(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("background_cleanup_blob_failed"))},"image/png")})}function Ot(e,t){const n=e.naturalWidth,a=e.naturalHeight;if(n<=0||a<=0)throw new Error("background_cleanup_image_not_ready");const r=t&&t>0?Math.min(1,t/Math.max(n,a)):1,l=Math.max(1,Math.round(n*r)),s=Math.max(1,Math.round(a*r)),i=document.createElement("canvas");i.width=l,i.height=s;const d=i.getContext("2d",{willReadFrequently:!0});if(!d)throw new Error("background_cleanup_context_failed");return d.drawImage(e,0,0,l,s),{canvas:i,context:d,width:l,height:s}}async function wt({imageElement:e,mask:t}){try{const{canvas:n,context:a,width:r,height:l}=Ot(e),s=a.getImageData(0,0,r,l),i=Ta({width:r,height:l,data:s.data},t),d=a.createImageData(r,l);d.data.set(i.imageData.data),a.putImageData(d,0,0);const u=await Lt(n);return{blob:u,dataUrl:await ct(u),stats:i.stats}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}async function Pa({imageElement:e,mask:t}){try{const{width:n,height:a}=Ot(e,Ea),r=document.createElement("canvas");r.width=n,r.height=a;const l=r.getContext("2d");if(!l)throw new Error("background_cleanup_context_failed");const s=l.createImageData(n,a);let i=0;for(let u=0;u<a;u+=1)for(let b=0;b<n;b+=1){const f=Math.min(t.width-1,Math.floor(b/n*t.width)),_=Math.min(t.height-1,Math.floor(u/a*t.height));if((t.data[_*t.width+f]??0)===0)continue;const B=(u*n+b)*4;s.data[B]=168,s.data[B+1]=85,s.data[B+2]=247,s.data[B+3]=150,i+=1}l.putImageData(s,0,0);const d=await Lt(r);return{dataUrl:await ct(d),stats:{width:t.width,height:t.height,removedPixels:t.data.reduce((u,b)=>u+(b>0?1:0),0),removedPercent:t.data.length>0?i/(n*a):0}}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}function Ct(e){return{...e,seeds:e.seeds.map(t=>({intent:t.intent,point:{...t.point}})),brushStrokes:e.brushStrokes.map(t=>({...t,points:t.points.map(n=>({...n}))})),brushCursor:e.brushCursor?{...e.brushCursor}:null,removeMask:e.removeMask?rt(e.removeMask):null,preserveMask:e.preserveMask?rt(e.preserveMask):null}}function Da(){return`cleanup_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function Re(e){return Math.max(0,Math.min(1,e))}function Aa(e){const t=[],n=Math.max(0,e.radius*.55);for(const a of e.points)t.push({...a}),!(n<=0)&&t.push({x:Re(a.x-n),y:a.y},{x:Re(a.x+n),y:a.y},{x:a.x,y:Re(a.y-n)},{x:a.x,y:Re(a.y+n)});return t}function Ia(e){const t=e.naturalWidth,n=e.naturalHeight;if(t<=0||n<=0)throw new Error("background_cleanup_image_not_ready");const a=document.createElement("canvas");a.width=t,a.height=n;const r=a.getContext("2d",{willReadFrequently:!0});if(!r)throw new Error("background_cleanup_context_failed");r.drawImage(e,0,0,t,n);const l=r.getImageData(0,0,t,n);return{width:t,height:n,data:l.data}}function Na({canvasOpen:e,currentImage:t,canvasDisplayImage:n,imageElementRef:a,canvasSourceImageRef:r,lastMergedDataUrlRef:l,setCanvasSaveState:s,setCanvasVersionItem:i,applyMergedCanvasImage:d,attachCanvasVersionReference:u,showToast:b,t:f}){const[_,B]=c.useState(!1),[A,O]=c.useState("remove"),[T,N]=c.useState("click"),[m,C]=c.useState("flat-flood-fill"),[E,y]=c.useState([]),[v,Z]=c.useState([]),[I,U]=c.useState(28),[g,S]=c.useState(null),[D,P]=c.useState(null),[V,Y]=c.useState(null),[te,ne]=c.useState(!1),[se,ue]=c.useState(.018),[L,p]=c.useState(null),[R,J]=c.useState(!1),[ae,le]=c.useState(!1),K=c.useRef(null),q=c.useRef(null),G=c.useRef(null),z=c.useRef({past:[],future:[]}),w=c.useRef(0),$=c.useRef(null),ee=c.useCallback(()=>Ct({intent:A,tool:T,engine:m,seeds:E,brushStrokes:v,brushRadius:se,tolerance:I,removeMask:K.current,preserveMask:q.current,preview:g,maskOverlay:D,stats:V,active:te,brushCursor:L}),[v,D,g,E,V,I,L,se,m,A,T,te]),W=c.useCallback(()=>{z.current={past:[...z.current.past.slice(-19),ee()],future:[]}},[ee]),ce=c.useCallback(x=>{const k=Ct(x);K.current=k.removeMask,q.current=k.preserveMask,G.current=null,O(k.intent),N(k.tool),C(k.engine),y(k.seeds),Z(k.brushStrokes),ue(k.brushRadius),U(k.tolerance),S(k.preview),P(k.maskOverlay),Y(k.stats),ne(k.active),p(k.brushCursor),J(!1),le(!1)},[]),X=c.useCallback(async()=>{if(!a.current||!t)return;const x=Se(K.current,q.current);if(!x){P(null),Y(null);return}const k=w.current+1;w.current=k,J(!0);try{const M=await Pa({imageElement:a.current,mask:x});if(w.current!==k)return;P(M),Y(M.stats)}catch{if(w.current!==k)return;b(f("canvas.toolbar.cleanupFailed"),!0)}finally{w.current===k&&J(!1)}},[t,a,b,f]),F=c.useCallback(async(x,k,M)=>{if(!a.current)return;const Q=Ia(a.current),ie=yt(Q.width,Q.height),ke=yt(Q.width,Q.height);for(const fe of x){const Ce=fe.intent==="remove"?ie:ke;kt(Ce,Q,[fe.point],M)}for(const fe of k){const Ce=fe.intent==="remove"?ie:ke;kt(Ce,Q,Aa(fe),M)}K.current=ie,q.current=ke},[a]),de=c.useCallback(()=>{w.current+=1,$.current!=null&&(window.clearTimeout($.current),$.current=null),K.current=null,q.current=null,G.current=null,z.current={past:[],future:[]},y([]),Z([]),S(null),P(null),Y(null),ne(!1),p(null),J(!1),le(!1)},[]),re=c.useCallback(()=>{const x=z.current.past.pop();return x?(z.current.future=[ee(),...z.current.future.slice(0,19)],ce(x),!0):!1},[ee,ce]),we=c.useCallback(()=>{const x=z.current.future.shift();return x?(z.current.past=[...z.current.past.slice(-19),ee()],ce(x),!0):!1},[ee,ce]),Pe=c.useCallback(x=>{W();const k=[...E,{point:x,intent:A}];y(k),S(null),F(k,v,I).then(X)},[v,E,I,A,W,F,X]),Oe=c.useCallback(()=>{W();const x=et().map(k=>({point:k,intent:"remove"}));y(x),S(null),ne(!1),F(x,v,I).then(X)},[v,I,W,F,X]),$e=c.useCallback(()=>{W(),N("click"),ne(x=>!x)},[W]),Ue=c.useCallback(x=>{W(),$.current!=null&&window.clearTimeout($.current),U(x),S(null),$.current=window.setTimeout(()=>{$.current=null,F(E,v,x).then(X)},180)},[v,E,W,F,X]),H=c.useCallback(async()=>{if(!a.current||!t)return null;let x=Se(K.current,q.current);if(!x){const M=et().map(Q=>({point:Q,intent:"remove"}));y(M),await F(M,v,I),x=Se(K.current,q.current)}if(!x)return null;W();const k=w.current+1;w.current=k,J(!0);try{const M=await wt({imageElement:a.current,mask:x});return w.current!==k?null:(S(M),P(null),Y(M.stats),M)}catch{return w.current!==k||b(f("canvas.toolbar.cleanupFailed"),!0),null}finally{w.current===k&&J(!1)}},[v,I,t,a,W,F,b,f]),We=c.useCallback(()=>{W(),de()},[W,de]),He=c.useCallback(x=>{W();const k={id:Da(),intent:A,points:[{...x}],radius:se};G.current=k,p(x),Z(M=>[...M,k])},[se,A,W]),Fe=c.useCallback(x=>{const k=G.current;if(!k){p(x);return}k.points=[...k.points,{...x}],p(x),Z(M=>M.map(Q=>Q.id===k.id?{...k,points:k.points.map(ie=>({...ie}))}:Q)),F(E,v.map(M=>M.id===k.id?k:M),I).then(X)},[v,E,I,F,X]),Ve=c.useCallback(()=>{G.current=null,F(E,v,I).then(X)},[v,E,I,F,X]),ve=c.useCallback(async()=>{if(!t||!a.current)return;const x=r.current??t;if(!x?.filename){b(f("canvas.toolbar.cleanupFailed"),!0);return}let k=Se(K.current,q.current);if(!k){const M=et().map(Q=>({point:Q,intent:"remove"}));y(M),await F(M,v,I),k=Se(K.current,q.current)}if(k){le(!0),s("saving");try{W();const M=await wt({imageElement:a.current,mask:k}),Q=await Bt({sourceFilename:x.canvasSourceFilename??x.filename,image:M.blob,prompt:x.prompt}),ie=it(Q.item,x);l.current=M.dataUrl,i(ie),d(ie),await u(ie),s("saved"),S(null),P(null),Y(M.stats),ne(!1),b(f("canvas.toolbar.cleanupApplied"))}catch{s("error"),b(f("canvas.toolbar.cleanupFailed"),!0)}finally{le(!1)}}},[d,u,v,I,r,t,a,l,W,F,s,i,b,f]),he=c.useCallback(()=>te?(G.current=null,ne(!1),p(null),!0):!1,[te]);return c.useEffect(()=>{const x=a.current;if(!x||!e){B(!1);return}const k=()=>B(wa(x));if(x.complete)k();else return x.addEventListener("load",k),()=>x.removeEventListener("load",k)},[e,n?.canvasMergedAt,n?.filename,n?.image,n?.url,g?.dataUrl,a]),{imageHasAlpha:_,backgroundCleanupSeeds:E,backgroundCleanupBrushStrokes:v,backgroundCleanupTolerance:I,backgroundCleanupPreview:g,backgroundCleanupMaskOverlay:D,backgroundCleanupStats:V,cleanupIntent:A,setCleanupIntent:O,cleanupTool:T,setCleanupTool:N,cleanupClickEngine:m,setCleanupClickEngine:C,cleanupBrushRadius:se,setCleanupBrushRadius:ue,cleanupBrushCursor:L,setCleanupBrushCursor:p,isBackgroundCleanupActive:te,setIsBackgroundCleanupActive:ne,isBackgroundCleanupPickingSeed:te&&T==="click",isBackgroundCleanupPreviewing:R,isBackgroundCleanupApplying:ae,hasActiveCleanupStroke:!!G.current,canUndoBackgroundCleanup:z.current.past.length>0,canRedoBackgroundCleanup:z.current.future.length>0,resetBackgroundCleanup:de,undoBackgroundCleanup:re,redoBackgroundCleanup:we,addBackgroundCleanupClick:Pe,addBackgroundCleanupSeed:Pe,runBackgroundCleanupPreview:H,handleBackgroundCleanupAutoSample:Oe,handleBackgroundCleanupPickSeed:$e,handleBackgroundCleanupToleranceChange:Ue,handleBackgroundCleanupReset:We,handleBackgroundCleanupApply:ve,handleBackgroundCleanupEscape:he,startBackgroundCleanupBrushStroke:He,updateBackgroundCleanupBrushStroke:Fe,endBackgroundCleanupBrushStroke:Ve}}function _t(e){return Math.min(1,Math.max(0,e))}function Mt(e,t){const n=t.getBoundingClientRect();return{x:_t((e.clientX-n.left)/n.width),y:_t((e.clientY-n.top)/n.height)}}const Ra=.18,La=.12;function Oa(e){return{id:"selection-box",x:Math.min(e.start.x,e.current.x),y:Math.min(e.start.y,e.current.y),width:Math.abs(e.current.x-e.start.x),height:Math.abs(e.current.y-e.start.y),color:"#64c8ff",strokeWidth:2}}function ot(e,t,n=0){return e.x>=t.x-n&&e.x<=t.x+t.width+n&&e.y>=t.y-n&&e.y<=t.y+t.height+n}function $t(e){return{id:e.id,x:e.x,y:e.y,width:Ra,height:La,color:e.color,strokeWidth:1}}function $a(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,i=a*a+r*r;if(i===0)return Math.hypot(e.x-t.x,e.y-t.y);const d=Math.max(0,Math.min(1,(l*a+s*r)/i));return Math.hypot(e.x-(t.x+d*a),e.y-(t.y+d*r))}function Ua(e,t,n){for(let a=1;a<t.points.length;a+=1)if($a(e,t.points[a-1],t.points[a])<=n)return!0;return!1}function Et(e,t){return e.x<=t.x+t.width&&e.x+e.width>=t.x&&e.y<=t.y+t.height&&e.y+e.height>=t.y}function Wa(e,t){return e.points.some(n=>ot(n,t))}function St(e){const t=e.tolerance??.015;for(const n of[...e.memos].reverse())if(ot(e.point,$t(n),t))return Dt(n);for(const n of[...e.boxes].reverse())if(ot(e.point,n,t))return Pt(n);for(const n of[...e.paths].reverse())if(Ua(e.point,n,t))return Tt(n);return null}function Ha(e){const t=[];for(const n of e.annotations.paths)Wa(n,e.box)&&t.push(Tt(n));for(const n of e.annotations.boxes)Et(n,e.box)&&t.push(Pt(n));for(const n of e.annotations.memos)Et($t(n),e.box)&&t.push(Dt(n));return t}function Fa({canvasOpen:e,canvasZoom:t,canvasPanX:n,canvasPanY:a,spaceHeld:r,canDragViewportWithSelect:l,isBackgroundCleanupActive:s,cleanupTool:i,annotationFrameRef:d,annotations:u,setCanvasPan:b,addBackgroundCleanupClick:f,startBackgroundCleanupBrushStroke:_,updateBackgroundCleanupBrushStroke:B,endBackgroundCleanupBrushStroke:A,setCleanupBrushCursor:O}){const T=c.useRef({mode:null,lastPoint:null,didMove:!1}),N=c.useRef({active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null}),[m,C]=c.useState(!1),E=g=>{g.currentTarget.setPointerCapture(g.pointerId),N.current={active:!0,startX:g.clientX,startY:g.clientY,basePanX:n,basePanY:a,pointerId:g.pointerId},C(!0)};return{viewportPanActive:m,resetPointerSession:()=>{T.current={mode:null,lastPoint:null,didMove:!1},N.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},C(!1)},handleAnnotationPointerDown:g=>{if(!e||me(g.target)||!d.current)return;const S=g.button===1;if(r||S){g.preventDefault(),E(g);return}g.preventDefault();const D=Mt(g,d.current);if(s){i==="click"?f(D):(g.currentTarget.setPointerCapture(g.pointerId),_(D));return}if(u.activeTool==="select"){const P=St({point:D,paths:u.paths,boxes:u.boxes,memos:u.memos});if(P)g.shiftKey?u.toggleSelected(P):u.selectOne(P),u.startSelectedMove(),T.current={mode:"move",lastPoint:D,didMove:!1};else if(l&&t>1.01){E(g);return}else u.clearSelection(),u.startSelectionBox(D),T.current={mode:"box",lastPoint:D,didMove:!1};g.currentTarget.setPointerCapture(g.pointerId);return}if(u.activeTool==="memo"){u.createMemo(D),requestAnimationFrame(()=>{d.current?.querySelector(".canvas-memo--active")?.focus()});return}if(u.activeTool==="eraser"){if(u.eraserMode==="object"){const P=St({point:D,paths:u.paths,boxes:u.boxes,memos:u.memos});P&&u.eraseObjectAtPoint(P);return}g.currentTarget.setPointerCapture(g.pointerId),u.startEraserStroke(D);return}g.currentTarget.setPointerCapture(g.pointerId),u.startDrawing(D)},handleAnnotationPointerMove:g=>{if(!e||me(g.target)||!d.current)return;if(N.current.active){const D=g.clientX-N.current.startX,P=g.clientY-N.current.startY;b(N.current.basePanX+D,N.current.basePanY+P);return}const S=Mt(g,d.current);if(s){i==="brush"?B(S):O(S);return}if(u.activeTool==="select"){if(T.current.mode==="move"&&T.current.lastPoint){const D={x:S.x-T.current.lastPoint.x,y:S.y-T.current.lastPoint.y};(Math.abs(D.x)>5e-4||Math.abs(D.y)>5e-4)&&(u.moveSelected(D),T.current.didMove=!0),T.current.lastPoint=S}else T.current.mode==="box"&&u.updateSelectionBox(S);return}if(u.activeTool!=="memo"){if(u.activeTool==="eraser"){u.eraserMode==="brush"&&u.updateEraserStroke(S);return}u.moveDrawing(S)}},handleAnnotationPointerUp:g=>{if(e&&!me(g.target)){if(N.current.active&&N.current.pointerId===g.pointerId){g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),N.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},C(!1);return}if(g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),s){i==="brush"&&A();return}if(u.activeTool==="select"){T.current.mode==="move"&&T.current.didMove&&u.commitSelectedMove(),T.current.mode==="box"&&u.selectionBox&&u.endSelectionBox(Ha({box:Oa(u.selectionBox),annotations:u.toPayload()})),T.current={mode:null,lastPoint:null,didMove:!1};return}if(u.activeTool!=="memo"){if(u.activeTool==="eraser"){u.eraserMode==="brush"&&u.endEraserStroke();return}u.endDrawing()}}},handleAnnotationPointerLeave:()=>{s&&O(null)}}}function Va({canvasOpen:e,canvasZoom:t,currentImage:n,annotations:a,undoBackgroundCleanup:r,redoBackgroundCleanup:l,handleBackgroundCleanupEscape:s,handleCloseCanvas:i,selectHistoryShortcutTarget:d,trashHistoryItem:u,permanentlyDeleteHistoryItemByShortcut:b,setCanvasZoom:f,resetCanvasZoom:_,onCreateBlankCanvas:B,isCreatingBlankCanvas:A}){const[O,T]=c.useState(!1);return c.useEffect(()=>{if(!e)return;const m=v=>{v.preventDefault()},C=v=>{v.ctrlKey&&v.preventDefault()},E={passive:!1,capture:!0},y={passive:!1};return window.addEventListener("wheel",C,E),window.addEventListener("gesturestart",m,y),window.addEventListener("gesturechange",m,y),window.addEventListener("gestureend",m,y),()=>{window.removeEventListener("wheel",C,E),window.removeEventListener("gesturestart",m,y),window.removeEventListener("gesturechange",m,y),window.removeEventListener("gestureend",m,y)}},[e]),c.useEffect(()=>{if(!e)return;const m=E=>{E.code==="Space"&&(me(E.target)||(O||T(!0),E.preventDefault()))},C=E=>{E.code==="Space"&&T(!1)};return window.addEventListener("keydown",m),window.addEventListener("keyup",C),()=>{window.removeEventListener("keydown",m),window.removeEventListener("keyup",C)}},[e,O]),c.useEffect(()=>{if(!e)return;const m=C=>{if(!C.defaultPrevented){if(me(C.target)){C.key==="Escape"&&(C.preventDefault(),C.target.blur(),a.focusMemo(null));return}if(C.key==="Escape"){if(C.preventDefault(),s())return;i();return}if(C.shiftKey&&!C.metaKey&&!C.ctrlKey&&!C.altKey&&C.key.toLowerCase()==="b"){C.preventDefault(),!A&&!C.repeat&&B();return}if((C.metaKey||C.ctrlKey)&&C.key.toLowerCase()==="z"){if(C.preventDefault(),C.shiftKey){if(l())return;a.redo();return}if(r())return;a.undo()}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[a,a.focusMemo,a.redo,a.undo,e,i,s,A,B,l,r]),{spaceHeld:O,handleViewerKeyDown:m=>{if(me(m.target)){m.key==="Escape"&&(m.preventDefault(),m.target.blur(),a.focusMemo(null));return}if(e&&["1","2","3","4","5","6"].includes(m.key)){m.preventDefault();const C=["select","pen","box","arrow","memo","eraser"];a.setTool(C[Number(m.key)-1]);return}if(e&&m.key==="Escape"){if(m.preventDefault(),m.stopPropagation(),s())return;i();return}if(e&&m.key==="]"){m.preventDefault(),f(t+.1);return}if(e&&m.key==="["){m.preventDefault(),f(t-.1);return}if(e&&m.key==="0"){m.preventDefault(),_();return}if(m.key==="Delete"||m.key==="Backspace"){if(!n||m.target!==m.currentTarget)return;if(m.preventDefault(),m.shiftKey){b(n);return}u(n);return}m.key!=="ArrowLeft"&&m.key!=="ArrowRight"&&m.key!=="Home"&&m.key!=="End"||m.target===m.currentTarget&&(me(m.target)||(m.preventDefault(),m.key==="ArrowLeft"?d("previous"):m.key==="ArrowRight"?d("next"):m.key==="Home"?d("first"):m.key==="End"&&d("last")))}}}function Ka(e,t){return new Promise((n,a)=>{e.toBlob(r=>{if(r){n(r);return}a(new Error("canvas_blob_unavailable"))},t)})}async function Ut(e){const t=document.createElement("canvas");t.width=e.imageElement.naturalWidth,t.height=e.imageElement.naturalHeight;const n=t.getContext("2d");if(!n)throw new Error("canvas_context_unavailable");e.background?.mode==="matte"&&(n.fillStyle=e.background.color,n.fillRect(0,0,t.width,t.height)),n.drawImage(e.imageElement,0,0,t.width,t.height);const a={width:t.width,height:t.height};for(const l of e.paths)nt(n,l,a);for(const l of e.boxes)at(n,l,a,"committed");for(const l of e.memos)Bn(n,l,a);return{blob:await Ka(t,"image/png"),dataUrl:t.toDataURL("image/png")}}const za=["left","center","right"],Xa=["top","middle","bottom"];function qa(e,t){const n=za[Math.min(2,Math.max(0,Math.floor(e*3)))],a=Xa[Math.min(2,Math.max(0,Math.floor(t*3)))];return`${a==="middle"&&n==="center"?"center":`${a} ${n}`} area (x: ${Math.round(e*100)}%, y: ${Math.round(t*100)}% from top-left)`}function Ya(e){const t=e.map(n=>({...n,text:n.text.trim()})).filter(n=>n.text.length>0);return t.length===0?"":["Apply the following annotation instructions at the specified image locations (percentages are relative to image width and height):",...t.map((n,a)=>`${a+1}. At the ${qa(n.x,n.y)}: ${n.text}`),"Do not render any annotation text, sticky notes, boxes, arrows, or markup in the output image."].join(`
|
|
2
2
|
`)}async function Ga(e){return(await Ut(e)).blob}function Za(e={},t=new Date){const n=t.toISOString().slice(0,19).replace(/[-:T]/g,""),a=e.matte?"-flat":"";return`canvas-export-${n}${a}.png`}function Ja(e,t){const n=URL.createObjectURL(e);try{const a=document.createElement("a");a.href=n,a.download=t,a.click()}finally{URL.revokeObjectURL(n)}}function Qa({imageElementRef:e,currentImage:t,canvasDisplayImage:n,canvasSourceImageRef:a,lastMergedDataUrlRef:r,lastCleanDataUrlRef:l,canvasVersionItem:s,annotations:i,exportBackground:d,exportMatteColor:u,quality:b,format:f,moderation:_,provider:B,imageModel:A,reasoningEffort:O,promptMode:T,webSearchEnabled:N,getResolvedSize:m,setCanvasVersionItem:C,setCanvasSaveState:E,setIsApplying:y,setIsExporting:v,setIsEditingWithMask:Z,applyMergedCanvasImage:I,addGeneratedHistoryItem:U,attachCanvasVersionReference:g,closeCanvas:S,resetCanvasSession:D,showToast:P,t:V}){const Y=c.useCallback(async()=>{if(!e.current||!t)return null;const L=a.current??t;if(!L?.filename)return P(V("canvas.version.failed"),!0),null;y(!0),E("saving");try{const p=await Ut({imageElement:e.current,paths:i.paths,boxes:i.boxes,memos:i.memos});r.current=p.dataUrl;const R=await xt(L);l.current=R;const J=s?.filename?await un(s.filename,{image:p.blob,sourceFilename:L.canvasSourceFilename??L.filename,prompt:L.prompt}):await Bt({sourceFilename:L.filename,image:p.blob,prompt:L.prompt}),ae=it(J.item,L);return C(ae),I(ae),await g(ae,R),await jt(L.filename).catch(()=>{}),i.resetLocal(),i.markSaved(),E("saved"),P(V("canvas.version.saved")),ae}catch{return E("error"),P(V("canvas.version.failed"),!0),null}finally{y(!1)}},[i,I,g,a,s?.filename,t,e,r,l,E,C,y,P,V]);return{saveCanvasVersionAndUseReference:Y,handleApplyCanvas:async()=>{await Y()},handleCloseCanvas:async()=>{(i.hasAnnotations||i.isDirty)&&!await Y()||(S(),D())},handleExportCanvas:async()=>{if(!(!e.current||!t)){v(!0);try{const L=d==="matte",p=await Ga({imageElement:e.current,paths:i.paths,boxes:i.boxes,memos:i.memos,background:L?{mode:"matte",color:u}:{mode:"alpha"}});Ja(p,Za({matte:L}))}catch{P(V("canvas.toolbar.exportFailed"),!0)}finally{v(!1)}}},handleEditWithMask:async()=>{if(!(!e.current||!n||i.boxes.length===0)){Z(!0);try{const L=i.memos;let p=l.current;if(i.isDirty||i.hasAnnotations){if(!await Y())return;p=l.current}p||(p=await xt(a.current??n));const R=i.boxes.filter(w=>i.selectedIds.some($=>pe($,"box",w.id))),J=await ha({imageElement:e.current,boxes:R.length>0?R:i.boxes}),ae=Ya(L),K=[(n.prompt??t?.prompt??"").trim(),ae].filter(Boolean).join(`
|
|
3
3
|
|
|
4
4
|
`);if(!K.trim()){P(V("toast.noPromptToFork"),!0);return}const q=n.size??t?.size??null,G=q&&/^\d+x\d+$/.test(q)?q:m(),z=await dn({image:p,mask:await ct(J),prompt:K,quality:b,size:G,format:f,moderation:_,provider:B,n:1,model:A,reasoningEffort:O,mode:T,webSearchEnabled:N});await U(ka(z,K))}catch(L){const p=L.code;P(V(p==="EDIT_MASK_NOT_SUPPORTED"?"canvas.toolbar.editMaskUnsupported":"canvas.toolbar.editMaskFailed"),!0)}finally{Z(!1)}}}}}function tr(e){const t=j(h=>h.currentImage),n=j(h=>h.history),a=j(h=>h.importLocalImageToHistory),[r,l]=c.useState(!1),s=j(h=>{const oe=h.multimodePreviewFlightId;return oe?h.multimodeSequences[oe]??null:null}),i=j(h=>h.selectHistoryShortcutTarget),d=j(h=>h.trashHistoryItem),u=j(h=>h.permanentlyDeleteHistoryItemByShortcut),b=j(h=>h.markGeneratedResultsSeen),f=j(h=>h.activeGenerations),_=j(h=>h.quality),B=j(h=>h.format),A=j(h=>h.moderation),O=j(h=>h.provider),T=j(h=>h.imageModel),N=j(h=>h.reasoningEffort),m=j(h=>h.promptMode),C=j(h=>h.webSearchEnabled),E=j(h=>h.getResolvedSize),y=j(h=>h.showToast),v=j(h=>h.canvasOpen),Z=j(h=>h.openCanvas),I=j(h=>h.closeCanvas),U=j(h=>h.canvasZoom),g=j(h=>h.canvasPanX),S=j(h=>h.canvasPanY),D=j(h=>h.setCanvasPan),P=j(h=>h.setCanvasZoom),V=j(h=>h.resetCanvasZoom),Y=j(h=>h.canvasExportBackground),te=j(h=>h.canvasExportMatteColor),ne=j(h=>h.setCanvasExportBackground),se=j(h=>h.setCanvasExportMatteColor),ue=j(h=>h.applyMergedCanvasImage),L=j(h=>h.addGeneratedHistoryItem),p=j(h=>h.attachCanvasVersionReference),{t:R}=ye(),{creatingBlankCanvas:J,createBlankCanvas:ae}=hn(),le=c.useRef(null),K=c.useRef(null),q=c.useRef(null),G=c.useRef(null),z=c.useRef(null),w=c.useRef(null),$=c.useRef(null),ee=c.useRef(null),W=c.useRef(null),[ce,X]=c.useState(null),[F,de]=c.useState("idle"),[re,we]=c.useState(!1),[Pe,Oe]=c.useState(!1),[$e,Ue]=c.useState(!1),H=Sn(),We=()=>{t?.prompt&&(navigator.clipboard.writeText(t.prompt),y(R("toast.promptCopied")))},He=va(t?.quality),Fe=ba(t?.size),Ve=fn(t?.model),ve=t?.filename??t?.url??t?.image??null,he=ya(n,t),x=v?ce??he??t:t,k=x?ga(x):null,M=Na({canvasOpen:v,currentImage:t,canvasDisplayImage:x,imageElementRef:K,canvasSourceImageRef:$,lastMergedDataUrlRef:ee,setCanvasSaveState:de,setCanvasVersionItem:X,applyMergedCanvasImage:ue,attachCanvasVersionReference:p,showToast:y,t:R}),{imageHasAlpha:Q,backgroundCleanupSeeds:ie,backgroundCleanupPreview:ke,backgroundCleanupMaskOverlay:fe,backgroundCleanupBrushStrokes:Ce,cleanupTool:Wt,cleanupBrushRadius:Ht,cleanupBrushCursor:Ft,isBackgroundCleanupActive:_e}=M,Ke=M.backgroundCleanupPreview?.dataUrl??k,ze=()=>{$.current=null,z.current=null,w.current!=null&&(window.clearTimeout(w.current),w.current=null),X(null),de("idle"),M.resetBackgroundCleanup(),ee.current=null,W.current=null,en()};c.useEffect(()=>{if(!v){G.current=ve,ze();return}if(G.current===null){G.current=ve,$.current=t,X(he);return}G.current!==ve&&(H.resetLocal(),ze(),$.current=t,X(he),G.current=ve)},[H.resetLocal,v,t,ve,he]),c.useEffect(()=>{!v||!t||$.current||($.current=t,X(he))},[v,t,he]),c.useEffect(()=>{if(!v||!t?.filename||t.canvasVersion)return;const h=t.filename;if(z.current===h)return;z.current=h;let oe=!1;return pn(h).then(Me=>{!oe&&Me.annotations&&H.load(Me.annotations)}).catch(()=>{}),()=>{oe=!0}},[H.load,v,t?.canvasVersion,t?.filename]),c.useEffect(()=>{if(!v||!t?.filename||t.canvasVersion||!H.isDirty)return;const h=t.filename;return w.current!=null&&window.clearTimeout(w.current),w.current=window.setTimeout(()=>{const oe=H.toPayload();(H.hasAnnotations?mn(h,oe):jt(h)).then(()=>H.markSaved()).catch(()=>{})},500),()=>{w.current!=null&&(window.clearTimeout(w.current),w.current=null)}},[H,H.hasAnnotations,H.isDirty,v,t?.canvasVersion,t?.filename]);const Vt=h=>{me(h.target)||(b(),h.currentTarget.focus())},Kt=c.useCallback(()=>{window.requestAnimationFrame(()=>q.current?.focus())},[]),zt=h=>{if(v){if(h.preventDefault(),h.ctrlKey){P(U-h.deltaY*.01);return}D(g-h.deltaX,S-h.deltaY)}},Xt=c.useCallback(h=>{Array.from(h.dataTransfer.types).includes("Files")&&(h.preventDefault(),l(oe=>oe||!0))},[]),qt=c.useCallback(h=>{h.currentTarget.contains(h.relatedTarget)||l(!1)},[]),Yt=c.useCallback(async h=>{if(!Array.from(h.dataTransfer.types).includes("Files"))return;h.preventDefault(),l(!1);const oe=Array.from(h.dataTransfer.files).filter(Me=>/^image\/(png|jpeg|webp)$/.test(Me.type));oe.length!==0&&await a(oe[0])},[a]),{handleApplyCanvas:Gt,handleCloseCanvas:dt,handleExportCanvas:Zt,handleEditWithMask:Jt}=Qa({imageElementRef:K,currentImage:t,canvasDisplayImage:x,canvasSourceImageRef:$,lastMergedDataUrlRef:ee,lastCleanDataUrlRef:W,canvasVersionItem:ce,annotations:H,exportBackground:Y,exportMatteColor:te,quality:_,format:B,moderation:A,provider:O,imageModel:T,reasoningEffort:N,promptMode:m,webSearchEnabled:C,getResolvedSize:E,setCanvasVersionItem:X,setCanvasSaveState:de,setIsApplying:we,setIsExporting:Oe,setIsEditingWithMask:Ue,applyMergedCanvasImage:ue,addGeneratedHistoryItem:L,attachCanvasVersionReference:p,closeCanvas:I,resetCanvasSession:ze,showToast:y,t:R}),{spaceHeld:Xe,handleViewerKeyDown:Qt}=Va({canvasOpen:v,canvasZoom:U,currentImage:t,annotations:H,undoBackgroundCleanup:M.undoBackgroundCleanup,redoBackgroundCleanup:M.redoBackgroundCleanup,handleBackgroundCleanupEscape:M.handleBackgroundCleanupEscape,handleCloseCanvas:dt,selectHistoryShortcutTarget:i,trashHistoryItem:d,permanentlyDeleteHistoryItemByShortcut:u,setCanvasZoom:P,resetCanvasZoom:V,onCreateBlankCanvas:ae,isCreatingBlankCanvas:J}),qe=v&&U>1.01&&H.activeTool==="select"&&!_e,{viewportPanActive:Ye,resetPointerSession:en,handleAnnotationPointerDown:tn,handleAnnotationPointerMove:nn,handleAnnotationPointerUp:an,handleAnnotationPointerLeave:rn}=Fa({canvasOpen:v,canvasZoom:U,canvasPanX:g,canvasPanY:S,spaceHeld:Xe,canDragViewportWithSelect:qe,isBackgroundCleanupActive:_e,cleanupTool:Wt,annotationFrameRef:le,annotations:H,setCanvasPan:D,addBackgroundCleanupClick:M.addBackgroundCleanupClick,startBackgroundCleanupBrushStroke:M.startBackgroundCleanupBrushStroke,updateBackgroundCleanupBrushStroke:M.updateBackgroundCleanupBrushStroke,endBackgroundCleanupBrushStroke:M.endBackgroundCleanupBrushStroke,setCleanupBrushCursor:M.setCleanupBrushCursor});return o.jsxs("main",{className:`canvas${v?" canvas--mode-open":""}${r?" canvas--drop-active":""}${Xe?" canvas--space-held":""}${Ye?" canvas--pan-active":""}${qe?" canvas--zoom-hand":""}`,onDragOver:Xt,onDragLeave:qt,onDrop:Yt,children:[r?o.jsx("div",{className:"canvas__drop-overlay","aria-hidden":!0,children:o.jsx("span",{className:"canvas__drop-hint",children:R("canvas.drop.hint")})}):null,v&&o.jsx(ca,{zoom:U,closeLabel:R("canvas.close"),blankCanvasLabel:R("canvas.blank.title"),blankCanvasAriaLabel:`${R(J?"canvas.blank.creating":"canvas.blank.create")} (Shift+B)`,blankCanvasShortcut:"Shift+B",blankCanvasBusy:J,shortcutHint:R("canvas.toolbar.zoomShortcutHint"),onZoomIn:()=>P(U+.1),onZoomOut:()=>P(U-.1),onZoomReset:V,onCreateBlankCanvas:()=>{ae()},onClose:()=>{dt()}}),o.jsx("div",{className:`progress-bar${f>0?" active":""}`}),s?o.jsx(vn,{}):t?o.jsxs("div",{ref:q,className:"result-container visible",tabIndex:0,onMouseDown:Vt,onWheel:zt,onKeyDown:Qt,"aria-label":R("canvas.imageViewerAria"),children:[o.jsx(Nn,{annotationFrameRef:le,imageElementRef:K,frameClassName:`canvas-annotation-frame${(Q||ke)&&v?" canvas-annotation-frame--alpha":""}${_e&&v?" canvas-annotation-frame--cleanup-picking":""}${fe&&v?" canvas-annotation-frame--cleanup-mask":""}`,frameStyle:{cursor:Ye?"grabbing":Xe||qe?"grab":v?_e?"crosshair":H.activeTool==="select"?"default":H.activeTool==="eraser"?H.eraserMode==="object"?pa:ma:"crosshair":"zoom-in",transform:v?`translate(${g}px, ${S}px) scale(${U})`:void 0,transition:v&&!Ye?"transform 0.2s ease":void 0},imageKey:`${x?.filename??x?.url??x?.image}:${x?.canvasMergedAt??""}`,imageSrc:Ke??t.image,fallbackImage:t.image,alt:R("canvas.resultAlt"),canvasOpen:v,maskOverlayUrl:fe?.dataUrl??null,cleanupLayer:o.jsx(On,{seeds:ie,brushStrokes:Ce,brushCursor:Ft,brushRadius:Ht,active:_e}),annotations:H,onOpenCanvas:Z,onPointerDown:tn,onPointerMove:nn,onPointerUp:an,onPointerLeave:rn}),v&&Ke?o.jsx(ua,{imageSrc:Ke,zoom:U,panX:g,panY:S,resetLabel:R("canvas.toolbar.zoomReset"),onReset:V}):null,v&&o.jsx(aa,{annotations:H,backgroundCleanup:M,backgroundCleanupPreview:ke,canvasState:{exportBackground:Y,exportMatteColor:te,isApplying:re,isExporting:Pe,isEditingWithMask:$e},actions:{handleApplyCanvas:Gt,handleExportCanvas:Zt,handleEditWithMask:Jt,setExportBackground:ne,setExportMatteColor:se}}),v&&F!=="idle"?o.jsx("div",{className:`canvas-save-state canvas-save-state--${F}`,children:R(F==="saving"?"canvas.version.saving":F==="saved"?"canvas.version.saved":"canvas.version.failed")}):null,o.jsx(ra,{currentImage:t,canvasDisplayImage:x,canvasOpen:v,displayQuality:He,displaySize:Fe,displayModel:Ve,onAfterDeleteFocus:Kt,onCopyPrompt:We})]}):null]})}export{tr as CanvasModeWorkspace};
|
package/ui/dist/index.html
CHANGED
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
}
|
|
35
35
|
})();
|
|
36
36
|
</script>
|
|
37
|
-
<script type="module" crossorigin src="/assets/index-
|
|
38
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
37
|
+
<script type="module" crossorigin src="/assets/index-BzjrmmIG.js"></script>
|
|
38
|
+
<link rel="stylesheet" crossorigin href="/assets/index-2oG6in1i.css">
|
|
39
39
|
</head>
|
|
40
40
|
<body>
|
|
41
41
|
<div id="root"></div>
|