ima2-gen 1.1.13 → 1.1.14

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.
Files changed (53) hide show
  1. package/README.md +10 -1
  2. package/bin/commands/doctor.js +195 -0
  3. package/bin/commands/doctor.ts +202 -0
  4. package/bin/ima2.js +3 -105
  5. package/bin/ima2.ts +3 -109
  6. package/config.js +1 -0
  7. package/config.ts +5 -0
  8. package/docs/CLI.md +36 -0
  9. package/docs/FAQ.ko.md +82 -2
  10. package/docs/FAQ.md +85 -2
  11. package/docs/PROMPT_STUDIO.ko.md +111 -0
  12. package/docs/PROMPT_STUDIO.md +115 -0
  13. package/docs/README.ko.md +8 -1
  14. package/docs/migration/runtime-test-inventory.md +6 -1
  15. package/lib/agentRuntime.js +9 -2
  16. package/lib/agentRuntime.ts +8 -2
  17. package/lib/errorClassify.js +1 -1
  18. package/lib/errorClassify.ts +1 -1
  19. package/lib/generationErrors.js +121 -23
  20. package/lib/generationErrors.ts +100 -13
  21. package/lib/responsesDoctor.js +386 -0
  22. package/lib/responsesDoctor.ts +456 -0
  23. package/lib/responsesErrors.js +57 -0
  24. package/lib/responsesErrors.ts +83 -0
  25. package/lib/responsesFallback.js +72 -0
  26. package/lib/responsesFallback.ts +114 -0
  27. package/lib/responsesImageAdapter.js +121 -174
  28. package/lib/responsesImageAdapter.ts +136 -211
  29. package/lib/responsesParse.js +324 -0
  30. package/lib/responsesParse.ts +452 -0
  31. package/lib/responsesTools.js +15 -0
  32. package/lib/responsesTools.ts +28 -0
  33. package/package.json +1 -1
  34. package/routes/edit.js +26 -1
  35. package/routes/edit.ts +26 -1
  36. package/routes/generate.js +40 -0
  37. package/routes/generate.ts +47 -0
  38. package/ui/dist/.vite/manifest.json +12 -12
  39. package/ui/dist/assets/{AgentWorkspace-BJe9yxPA.js → AgentWorkspace-B6YNOZHi.js} +1 -1
  40. package/ui/dist/assets/{CardNewsWorkspace-BBLdwzYU.js → CardNewsWorkspace-EFVeg4l_.js} +1 -1
  41. package/ui/dist/assets/{NodeCanvas-BSZ527J4.js → NodeCanvas-iM6yjHvO.js} +1 -1
  42. package/ui/dist/assets/{PromptBuilderPanel-Y2VygFc0.js → PromptBuilderPanel-C3GdLDCl.js} +1 -1
  43. package/ui/dist/assets/{PromptImportDialog-C6lFV-LL.js → PromptImportDialog-DS9vrc_w.js} +2 -2
  44. package/ui/dist/assets/{PromptImportDiscoverySection-D8YJFhND.js → PromptImportDiscoverySection-DHFEt_FA.js} +1 -1
  45. package/ui/dist/assets/{PromptImportFolderSection-ywfcQolW.js → PromptImportFolderSection-BQxb1zs5.js} +1 -1
  46. package/ui/dist/assets/{PromptLibraryPanel-fk4KmrGy.js → PromptLibraryPanel-NhMKVGfU.js} +2 -2
  47. package/ui/dist/assets/{SettingsWorkspace-DL5vhAHQ.js → SettingsWorkspace-FjKjaDqj.js} +1 -1
  48. package/ui/dist/assets/index-BAN6lKgf.js +28 -0
  49. package/ui/dist/assets/{index-BLx55BOg.js → index-BbFZyM92.js} +1 -1
  50. package/ui/dist/assets/index-DK1faG9Z.css +1 -0
  51. package/ui/dist/index.html +2 -2
  52. package/ui/dist/assets/index-ByViUJfx.css +0 -1
  53. package/ui/dist/assets/index-Ci36vcFD.js +0 -28
@@ -1 +1 @@
1
- import{a as c,j as o,u as ke,p as an,q as rn,s as St,t as me,v as on,w as Bt,x as sn,b as j,y as ln,c as cn,z as un,A as dn,M as hn}from"./index-Ci36vcFD.js";const Ae=2,Oe=1e-6;function fn({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 d=pn(s,t,n,a);(d.length!==1||d[0]!==s)&&(r=!0),l.push(...d)}return{paths:l,changed:r}}function pn(e,t,n,a=()=>crypto.randomUUID()){if(e.points.length<Ae||t.length===0||n<=0)return[e];const r=[];let l=Te(e.points[0],t,n)?[]:[e.points[0]];for(let d=1;d<e.points.length;d+=1){const u=e.points[d-1],i=e.points[d],b=Te(i,t,n),f=mn(u,i,t,n);if(f){l.length===0&&!Te(u,t,n)&&(l=[u]),l.length>0&&f.leftT>Oe&&ft(l,Pe(u,i,f.leftT)),l.length>=Ae&&r.push(l),l=[],f.rightT<1-Oe&&!b&&(l=[Pe(u,i,f.rightT),i]);continue}if(b){l.length>=Ae&&r.push(l),l=[];continue}l.length===0&&!Te(u,t,n)&&(l=[u]),ft(l,i)}if(l.length>=Ae&&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((d,u)=>({...e,id:u===0?e.id:a(),tool:e.tool==="arrow"&&u!==s?"pen":e.tool,points:d}))}function Te(e,t,n){if(t.length===1)return ye(e,t[0])<=n;for(let a=1;a<t.length;a+=1)if(vn(e,t[a-1],t[a])<=n)return!0;return!1}function ye(e,t){const n=e.x-t.x,a=e.y-t.y;return Math.sqrt(n*n+a*a)}function mn(e,t,n,a){const r=ye(e,t);if(r<=Oe)return Te(e,n,a)?{leftT:0,rightT:1}:null;let l=null,s=Number.POSITIVE_INFINITY;for(const u of n){const i=ht(u,e,t),b=Pe(e,t,i),f=ye(u,b);f<s&&(s=f,l=i)}for(let u=1;u<n.length;u+=1){const i=[0,.25,.5,.75,1];for(const b of i){const f=Pe(n[u-1],n[u],b),_=ht(f,e,t),B=Pe(e,t,_),A=ye(f,B);A<s&&(s=A,l=_)}}if(l===null||s>a)return null;const d=Math.max(a/r,.01);return{leftT:Math.max(0,l-d),rightT:Math.min(1,l+d)}}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,d=a*a+r*r;return d===0?0:Math.max(0,Math.min(1,(l*a+s*r)/d))}function Pe(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||ye(n,t)>Oe)&&e.push(t)}function vn(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,d=a*a+r*r;if(d===0)return ye(e,t);const u=Math.max(0,Math.min(1,(l*a+s*r)/d));return ye(e,{x:t.x+u*a,y:t.y+u*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 jt(e){return st("path",e.id)}function Tt(e){return st("box",e.id)}function Pt(e){return st("memo",e.id)}function pe(e,t,n){const a=lt(e);return a?.kind===t&&a.id===n}const Dt="ima2.canvas.annotationStyle.v1",At=["#ef4444","#f97316","#eab308","#22c55e","#38bdf8","#6366f1","#a855f7","#111827","#ffffff"],It=[2,3,5,8],Se={color:"#ef4444",strokeWidth:3};function bn(){if(typeof window>"u")return Se;try{const e=window.localStorage.getItem(Dt);if(!e)return Se;const t=JSON.parse(e),n=typeof t.color=="string"&&At.includes(t.color)?t.color:Se.color,a=typeof t.strokeWidth=="number"&&It.includes(t.strokeWidth)?t.strokeWidth:Se.strokeWidth;return{color:n,strokeWidth:a}}catch{return Se}}function gn(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Dt,JSON.stringify(e))}catch{}}const pt=bn(),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 xe(e){return{paths:e.paths,boxes:e.boxes,memos:e.memos}}function ge(e){return{...e,past:[...e.past.slice(-49),xe(e)],future:[]}}function Ge(e,t){return{...e,past:[...e.past.slice(-49),t],future:[]}}function xn(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 yn(e,t,n){const{start:a,current:r}=e,l=Math.min(a.x,r.x),s=Math.min(a.y,r.y),d=Math.abs(r.x-a.x),u=Math.abs(r.y-a.y);return d<.01||u<.01?null:{id:crypto.randomUUID(),x:l,y:s,width:d,height:u,color:t,strokeWidth:n}}function kn(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 Cn(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}:{...ge(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=yn(e.activeBox,e.toolColor,e.strokeWidth);return n?{...ge(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{...ge(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?xn(e.memoBaseline,xe(e))?{...e,memoBaseline:null,activeMemoId:null}:{...Ge(e,e.memoBaseline),memoBaseline:null,activeMemoId:null,isDirty:!0}:{...e,activeMemoId:null};case"DELETE_MEMO":return{...ge(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?xe(e):e.memoBaseline};case"CLEAR":return{...ge(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:[xe(e),...e.future]}:e}case"REDO":{const n=e.future[0];return n?{...mt(e,n),past:[...e.past.slice(-49),xe(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:{...ge(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))?kn(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:xe(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:{...ge(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:xe(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=fn({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 wn(){const[e,t]=c.useReducer(Cn,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(g=>t({type:"SET_TOOL",tool:g}),[]),s=c.useCallback(g=>{gn(g),t({type:"SET_STYLE",style:g})},[]),d=c.useCallback(()=>t({type:"CLEAR"}),[]),u=c.useCallback(g=>t({type:"LOAD",payload:g}),[]),i=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(g=>{e.activeTool==="pen"||e.activeTool==="arrow"?t({type:"START_PATH",point:g}):e.activeTool==="box"&&t({type:"START_BOX",point:g})},[e.activeTool]),N=c.useCallback(g=>{e.activePath?t({type:"ADD_POINT",point:g}):e.activeBox&&t({type:"UPDATE_BOX",point:g})},[e.activePath,e.activeBox]),p=c.useCallback(()=>{e.activePath?t({type:"END_PATH"}):e.activeBox&&t({type:"END_BOX"})},[e.activePath,e.activeBox]),C=c.useCallback(g=>t({type:"CREATE_MEMO",point:g}),[]),M=c.useCallback((g,D)=>t({type:"UPDATE_MEMO",id:g,text:D}),[]),y=c.useCallback(g=>t({type:"DELETE_MEMO",id:g}),[]),v=c.useCallback(g=>t({type:"FOCUS_MEMO",id:g}),[]),X=c.useCallback(g=>t({type:"SET_ERASER_MODE",mode:g}),[]),R=c.useCallback(g=>t({type:"SELECT_ONE",id:g}),[]),$=c.useCallback(g=>t({type:"TOGGLE_SELECTED",id:g}),[]),x=c.useCallback(()=>t({type:"CLEAR_SELECTION"}),[]),E=c.useCallback(()=>t({type:"DELETE_SELECTED"}),[]),S=c.useCallback(g=>t({type:"MOVE_SELECTED",delta:g}),[]),P=c.useCallback(g=>t({type:"START_SELECTION_BOX",point:g}),[]),Y=c.useCallback(g=>t({type:"UPDATE_SELECTION_BOX",point:g}),[]),ne=c.useCallback(g=>t({type:"END_SELECTION_BOX",ids:g}),[]),ae=c.useCallback(g=>t({type:"ERASE_OBJECT",id:g}),[]),re=c.useCallback(g=>t({type:"START_ERASER_STROKE",point:g}),[]),le=c.useCallback(g=>t({type:"UPDATE_ERASER_STROKE",point:g}),[]),I=c.useCallback(()=>t({type:"END_ERASER_STROKE"}),[]),F=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:X,startDrawing:T,moveDrawing:N,endDrawing:p,createMemo:C,updateMemo:M,commitMemoEdit:B,deleteMemo:y,focusMemo:v,clear:d,load:u,toPayload:F,markSaved:i,resetLocal:b,undo:f,redo:_,selectOne:R,toggleSelected:$,clearSelection:x,deleteSelected:E,moveSelected:S,startSelectedMove:A,commitSelectedMove:O,startSelectionBox:P,updateSelectionBox:Y,endSelectionBox:ne,eraseObjectAtPoint:ae,startEraserStroke:re,updateEraserStroke:le,endEraserStroke:I}}function Ie(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=Ie(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=Ie(r,n);e.lineTo(l.x,l.y)}if(e.stroke(),t.tool==="arrow"){const r=Ie(t.points[t.points.length-1],n),l=Ie(t.points[t.points.length-2],n);En(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 _n(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,d=18;e.save(),e.font="14px sans-serif";const u=Sn(e,t.text.trim()||" ",l-s*2),i=Math.max(52,s*2+u.length*d);e.fillStyle="rgba(255, 246, 179, 0.96)",e.strokeStyle="rgba(44, 37, 12, 0.28)",e.lineWidth=1,Bn(e,a,r,l,i,8),e.fill(),e.stroke(),e.fillStyle="#2f2a13",e.textBaseline="top",u.forEach((b,f)=>{e.fillText(b,a+s,r+s+f*d)}),e.restore()}function Mn(e,t){const n=lt(e);if(!n)return null;if(n.kind==="box")return t.boxes.find(i=>i.id===n.id)??null;const a=n.kind==="memo"?t.memos.find(i=>i.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(i=>i.id===n.id);if(!r||r.points.length===0)return null;const l=r.points.map(i=>i.x),s=r.points.map(i=>i.y),d=Math.min(...l),u=Math.min(...s);return{id:r.id,x:d,y:u,width:Math.max(.01,Math.max(...l)-d),height:Math.max(.01,Math.max(...s)-u),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 En(e,t,n,a,r){const l=Math.atan2(n.y-t.y,n.x-t.x),s=Math.max(12,r*4),d=Math.PI/7;e.save(),e.fillStyle=a,e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x-s*Math.cos(l-d),n.y-s*Math.sin(l-d)),e.lineTo(n.x-s*Math.cos(l+d),n.y-s*Math.sin(l+d)),e.closePath(),e.fill(),e.restore()}function Sn(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 d=l?`${l} ${s}`:s;if(e.measureText(d).width<=n||l===""){l=d;continue}r.push(l),l=s}return l&&r.push(l),r}function Bn(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 jn({paths:e,boxes:t,memos:n=[],selectedIds:a=[],selectionBox:r=null,activePath:l,activeBox:s}){const d=c.useRef(null);return c.useEffect(()=>{const u=d.current;if(!u)return;const i=u.getBoundingClientRect(),b=window.devicePixelRatio||1;u.width=Math.max(1,Math.round(i.width*b)),u.height=Math.max(1,Math.round(i.height*b));const f=u.getContext("2d");if(!f)return;f.setTransform(b,0,0,b,0,0),f.clearRect(0,0,i.width,i.height);const _={width:i.width,height:i.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=Mn(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:d,className:"canvas-annotation-layer","aria-hidden":"true"})}function Ne(e){e.stopPropagation()}function Tn({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:Ne,onPointerMove:Ne,onPointerUp:Ne,onPointerCancel:Ne,onChange:d=>n(s.id,d.currentTarget.value),onBlur:()=>{l?.(),s.text.trim()===""&&a(s.id)},"aria-label":"Canvas memo"},s.id))})}function Pn({annotationFrameRef:e,imageElementRef:t,frameClassName:n,frameStyle:a,imageKey:r,imageSrc:l,fallbackImage:s,alt:d,canvasOpen:u,maskOverlayUrl:i,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:d,onDoubleClick:N=>{N.stopPropagation(),_()}},r),u&&i?o.jsx("img",{className:"canvas-background-cleanup-mask",src:i,alt:"","aria-hidden":"true"}):null,u?b:null,u&&o.jsxs(o.Fragment,{children:[o.jsx(jn,{paths:f.paths,boxes:f.boxes,memos:f.memos,selectedIds:f.selectedIds,selectionBox:f.selectionBox,activePath:f.activePath,activeBox:f.activeBox}),o.jsx(Tn,{memos:f.memos,activeMemoId:f.activeMemoId,onUpdate:f.updateMemo,onDelete:f.deleteMemo,onFocus:f.focusMemo,onCommit:f.commitMemoEdit})]})]})}function Dn(e){return`${e.x*100} ${e.y*100}`}function An(e){return e.map(Dn).join(" ")}function In({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:An(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 Nn({mode:e,matteColor:t,onModeChange:n,onMatteColorChange:a}){const{t:r}=ke();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 Rn({seedCount:e,tolerance:t,stats:n,hasPreview:a,isPickingSeed:r,intent:l,tool:s,brushRadius:d,isPreviewing:u,isApplying:i,keepOpen:b,disabled:f,onAutoSample:_,onPickSeed:B,onIntentChange:A,onToolChange:O,onBrushRadiusChange:T,onToleranceChange:N,onPreview:p,onApply:C,onReset:M}){const{t:y}=ke(),[v,X]=c.useState(!1),R=c.useRef(null),$=n?Math.round(n.removedPercent*1e3)/10:0,x=r||s==="brush";return c.useEffect(()=>{if(!v)return;const E=S=>{b||R.current?.contains(S.target)||X(!1)};return window.addEventListener("pointerdown",E),()=>window.removeEventListener("pointerdown",E)},[b,v]),o.jsxs("div",{className:"canvas-toolbar__cleanup",ref:R,children:[o.jsx("button",{type:"button",className:`canvas-toolbar__button${v||a?" canvas-toolbar__button--active":""}`,onClick:()=>X(E=>!E),disabled:f,"aria-expanded":v,"aria-label":y("canvas.toolbar.cleanup"),title:y("canvas.toolbar.cleanup"),children:o.jsx(Ln,{})}),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:E=>N(Number(E.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:d,onChange:E=>T(Number(E.target.value))}),o.jsx("output",{children:Math.round(d*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(x?"canvas.toolbar.cleanupActive":"canvas.toolbar.cleanupPickSeed")})]}),o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:p,disabled:u||e===0,children:y(u?"canvas.toolbar.cleanupPreviewing":"canvas.toolbar.cleanupPreview")}),o.jsx("button",{type:"button",onClick:C,disabled:i||!a&&e===0,children:y(i?"canvas.toolbar.cleanupApplying":"canvas.toolbar.cleanupApply")}),o.jsx("button",{type:"button",onClick:M,disabled:!a&&e===0,children:y("canvas.toolbar.cleanupReset")})]}),x?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:$})}):null]}):null]})}function Ln(){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 On({style:e,onStyleChange:t}){const{t:n}=ke(),[a,r]=c.useState(!1),l=c.useRef(null);return c.useEffect(()=>{if(!a)return;const s=d=>{l.current?.contains(d.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:At.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:It.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 $n({tools:e,activeTool:t,onToolChange:n}){const[a,r]=c.useState(!1),l=c.useRef(null),s=e.find(u=>u.id===t)??e[0],d=s.icon;return c.useEffect(()=>{if(!a)return;const u=i=>{l.current?.contains(i.target)||r(!1)};return window.addEventListener("pointerdown",u),()=>window.removeEventListener("pointerdown",u)},[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(u=>!u),"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(d,{}),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(u=>{const i=u.icon,b=t===u.id;return o.jsxs("button",{type:"button",className:`canvas-tool-picker__item${b?" active":""}`,role:"menuitemradio","aria-checked":b,onClick:()=>{n(u.id),r(!1)},children:[o.jsx(i,{}),o.jsx("span",{children:u.label}),o.jsx("kbd",{children:u.shortcut})]},u.id)})}):null]})}function Un({activeTool:e,hasAnnotations:t,hasExportableContent:n,onToolChange:a,eraserMode:r="object",onEraserModeChange:l,style:s,onStyleChange:d,onClear:u,onApply:i,onExport:b,onUndo:f,onRedo:_,canUndo:B,canRedo:A,onDeleteSelected:O,selectedCount:T=0,onEditWithMask:N,canEditWithMask:p,isEditingWithMask:C,isApplying:M,isExporting:y,exportBackground:v="alpha",exportMatteColor:X="#ffffff",onExportBackgroundChange:R,onExportMatteColorChange:$,cleanupTolerance:x=28,cleanupSeedCount:E=0,cleanupStats:S=null,cleanupHasPreview:P=!1,isCleanupPickingSeed:Y=!1,isCleanupActive:ne=!1,cleanupIntent:ae="remove",cleanupTool:re="click",cleanupBrushRadius:le=.018,isCleanupPreviewing:I=!1,isCleanupApplying:F=!1,onCleanupAutoSample:g,onCleanupPickSeed:D,onCleanupIntentChange:J,onCleanupToolChange:de,onCleanupBrushRadiusChange:ce,onCleanupToleranceChange:G,onCleanupPreview:Q,onCleanupApply:Z,onCleanupReset:K}){const{t:k}=ke(),[H,ee]=c.useState(!1),U=c.useRef(null),te=n??t??!1,z=k(r==="object"?"canvas.toolbar.objectEraser":"canvas.toolbar.brushEraser"),V=[{id:"select",shortcut:"1",label:k("canvas.toolbar.select"),icon:Wn},{id:"pen",shortcut:"2",label:k("canvas.toolbar.pen"),icon:Hn},{id:"box",shortcut:"3",label:k("canvas.toolbar.box"),icon:Fn},{id:"arrow",shortcut:"4",label:k("canvas.toolbar.arrow"),icon:Vn},{id:"memo",shortcut:"5",label:k("canvas.toolbar.memo"),icon:Kn}];c.useEffect(()=>{if(!H)return;const oe=we=>{U.current?.contains(we.target)||ee(!1)};return window.addEventListener("pointerdown",oe),()=>window.removeEventListener("pointerdown",oe)},[H]);const he=oe=>{l?.(oe),a("eraser"),ee(!1)};return o.jsxs("div",{className:"canvas-toolbar","aria-label":k("canvas.toolbar.label"),children:[o.jsx($n,{tools:V,activeTool:e,onToolChange:a}),o.jsx(On,{style:s,onStyleChange:d}),o.jsxs("div",{ref:U,className:`canvas-toolbar__split-button${e==="eraser"?" canvas-toolbar__split-button--active":""}`,onKeyDown:oe=>{oe.key==="Escape"&&H&&(oe.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":`${z} (6)`,"aria-pressed":e==="eraser",title:`${z} (6)`,children:[o.jsx(zn,{}),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(oe=>!oe),"aria-label":k("canvas.toolbar.eraserMenu"),"aria-haspopup":"menu","aria-expanded":H,"aria-controls":"canvas-eraser-menu",title:k("canvas.toolbar.eraserMenu"),children:o.jsx(Xn,{})}),H?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:()=>he("object"),children:k("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:()=>he("brush"),children:k("canvas.toolbar.brushEraser")})]}):null]}),o.jsx("span",{className:"canvas-toolbar__divider","aria-hidden":"true"}),i?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--primary${M?" canvas-toolbar__button--busy":""}`,onClick:i,disabled:!te||M,"aria-label":k("canvas.toolbar.apply"),title:k("canvas.toolbar.apply"),children:o.jsx(qn,{})}):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:!p||C,"aria-label":k(p?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),title:k(p?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),children:o.jsx(Jn,{})}):null,f?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:f,disabled:!B,"aria-label":k("canvas.toolbar.undo"),title:k("canvas.toolbar.undo"),children:o.jsx(Gn,{})}):null,_?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:_,disabled:!A,"aria-label":k("canvas.toolbar.redo"),title:k("canvas.toolbar.redo"),children:o.jsx(Zn,{})}):null,O?o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:O,disabled:T===0,"aria-label":k("canvas.toolbar.deleteSelected"),title:k("canvas.toolbar.deleteSelected"),children:o.jsx(gt,{})}):null,b&&R&&$?o.jsx(Nn,{mode:v,matteColor:X,onModeChange:R,onMatteColorChange:$}):null,g&&D&&J&&de&&ce&&G&&Q&&Z&&K?o.jsx(Rn,{seedCount:E,tolerance:x,stats:S,hasPreview:P,isPickingSeed:Y,intent:ae,tool:re,brushRadius:le,isPreviewing:I,isApplying:F,keepOpen:ne,disabled:M||y,onAutoSample:g,onPickSeed:D,onIntentChange:J,onToolChange:de,onBrushRadiusChange:ce,onToleranceChange:G,onPreview:Q,onApply:Z,onReset:K}):null,b?o.jsx("button",{type:"button",className:`canvas-toolbar__button${y?" canvas-toolbar__button--busy":""}`,onClick:b,disabled:!te||y,"aria-label":k("canvas.toolbar.export"),title:k("canvas.toolbar.export"),children:o.jsx(Yn,{})}):null,o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:u,disabled:!te,"aria-label":k("canvas.toolbar.clear"),title:k("canvas.toolbar.clear"),children:o.jsx(gt,{})})]})}function Wn(){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 Hn(){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 Fn(){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 Vn(){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 Kn(){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 zn(){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 Xn(){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 qn(){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 Yn(){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 Gn(){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 Zn(){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 Jn(){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 Qn({annotations:e,backgroundCleanup:t,backgroundCleanupPreview:n,canvasState:a,actions:r}){return o.jsx(Un,{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 ea({currentImage:e,canvasDisplayImage:t,canvasOpen:n,displayQuality:a,displaySize:r,displayModel:l,onAfterDeleteFocus:s,onCopyPrompt:d}){const{t:u}=ke(),i=[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?u("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,a,r,l,e.provider??null].filter(b=>!!b).join(" · ");return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"result-meta",children:i}),o.jsx(an,{imageOverride:n?t:null,onAfterDeleteFocus:s}),e.prompt?o.jsx("div",{className:"result-prompt",onClick:d,children:e.prompt}):null]})}function ta({zoom:e,onZoomIn:t,onZoomOut:n,onZoomReset:a}){const{t:r}=ke(),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(na,{})}),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(aa,{})})]})}function na(){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 aa(){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 ra({zoom:e,closeLabel:t,blankCanvasLabel:n,blankCanvasAriaLabel:a,blankCanvasShortcut:r,blankCanvasBusy:l,shortcutHint:s,onZoomIn:d,onZoomOut:u,onZoomReset:i,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(ta,{zoom:e,onZoomIn:d,onZoomOut:u,onZoomReset:i}),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 oa({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 sa({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:oa({zoom:t,panX:n,panY:a}),"aria-hidden":"true"})]})}const la=`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`,ca=`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 ia(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function ua(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function da(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 ct(e,t){return!e.canvasVersion||e.prompt||!t?.prompt?e:{...e,prompt:t.prompt}}function ha(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?ct(n,t):null}function fa(e,t){if(rn(e)){const n=e.images[0];if(!n)throw new Error("edit_empty_response");return{...n,prompt:t,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,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 pa(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 d=s.getImageData(0,0,a,r).data;for(let u=3;u<d.length;u+=4)if(d[u]<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 ma(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 xt(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 va(e,t){ma(e,t);for(let n=0;n<e.data.length;n+=1)(t.data[n]??0)>0&&(e.data[n]=0)}function Be(e,t){if(!e)return null;const n=rt(e);return t&&va(n,t),n}function ba(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}function Re(e){return Math.min(1,Math.max(0,e))}function ga(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("mask_blob_unavailable"))},"image/png")})}async function xa(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=Re(l.x)*t,d=Re(l.y)*n,u=Re(l.width)*t,i=Re(l.height)*n;u>0&&i>0&&r.fillRect(s,d,u,i)}return ga(a)}async function ya(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 it(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 ut=[{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}],ka=1024;function Ca(e){return Math.max(0,Math.min(255,Math.round(e)))}function Nt(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 wa(e,t){return(t.length>0?t:ut).map(a=>{const r=Nt(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 _a(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 je(e,t,n,a,r,l,s){if(e<0||e>=a.length||a[e])return r;const d=e*4;return(t.data[d+3]??0)===0?(a[e]=1,r):_a(t.data,d,l,s)?(a[e]=1,n[r]=e,r+1):r}function et(){return ut.map(e=>({...e}))}function yt(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,d=new Uint8Array(s),u=new Int32Array(s),i=wa(t,n),b=Ca(a);let f=0;for(const _ of n.length>0?n:ut)f=je(Nt(_,r,l),t,u,d,f,i,b);for(;f>0;){const _=u[--f];e.data[_]=255;const B=_%r;B>0&&(f=je(_-1,t,u,d,f,i,b)),B<r-1&&(f=je(_+1,t,u,d,f,i,b)),_>=r&&(f=je(_-r,t,u,d,f,i,b)),_<s-r&&(f=je(_+r,t,u,d,f,i,b))}}function Ma(e,t){const n=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),a=ba(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 Rt(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("background_cleanup_blob_failed"))},"image/png")})}function Lt(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)),d=document.createElement("canvas");d.width=l,d.height=s;const u=d.getContext("2d",{willReadFrequently:!0});if(!u)throw new Error("background_cleanup_context_failed");return u.drawImage(e,0,0,l,s),{canvas:d,context:u,width:l,height:s}}async function kt({imageElement:e,mask:t}){try{const{canvas:n,context:a,width:r,height:l}=Lt(e),s=a.getImageData(0,0,r,l),d=Ma({width:r,height:l,data:s.data},t),u=a.createImageData(r,l);u.data.set(d.imageData.data),a.putImageData(u,0,0);const i=await Rt(n);return{blob:i,dataUrl:await it(i),stats:d.stats}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}async function Ea({imageElement:e,mask:t}){try{const{width:n,height:a}=Lt(e,ka),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 d=0;for(let i=0;i<a;i+=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(i/a*t.height));if((t.data[_*t.width+f]??0)===0)continue;const B=(i*n+b)*4;s.data[B]=168,s.data[B+1]=85,s.data[B+2]=247,s.data[B+3]=150,d+=1}l.putImageData(s,0,0);const u=await Rt(r);return{dataUrl:await it(u),stats:{width:t.width,height:t.height,removedPixels:t.data.reduce((i,b)=>i+(b>0?1:0),0),removedPercent:t.data.length>0?d/(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 Sa(){return`cleanup_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function Le(e){return Math.max(0,Math.min(1,e))}function Ba(e){const t=[],n=Math.max(0,e.radius*.55);for(const a of e.points)t.push({...a}),!(n<=0)&&t.push({x:Le(a.x-n),y:a.y},{x:Le(a.x+n),y:a.y},{x:a.x,y:Le(a.y-n)},{x:a.x,y:Le(a.y+n)});return t}function ja(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 Ta({canvasOpen:e,currentImage:t,canvasDisplayImage:n,imageElementRef:a,canvasSourceImageRef:r,lastMergedDataUrlRef:l,setCanvasSaveState:s,setCanvasVersionItem:d,applyMergedCanvasImage:u,attachCanvasVersionReference:i,showToast:b,t:f}){const[_,B]=c.useState(!1),[A,O]=c.useState("remove"),[T,N]=c.useState("click"),[p,C]=c.useState("flat-flood-fill"),[M,y]=c.useState([]),[v,X]=c.useState([]),[R,$]=c.useState(28),[x,E]=c.useState(null),[S,P]=c.useState(null),[Y,ne]=c.useState(null),[ae,re]=c.useState(!1),[le,I]=c.useState(.018),[F,g]=c.useState(null),[D,J]=c.useState(!1),[de,ce]=c.useState(!1),G=c.useRef(null),Q=c.useRef(null),Z=c.useRef(null),K=c.useRef({past:[],future:[]}),k=c.useRef(0),H=c.useRef(null),ee=c.useCallback(()=>Ct({intent:A,tool:T,engine:p,seeds:M,brushStrokes:v,brushRadius:le,tolerance:R,removeMask:G.current,preserveMask:Q.current,preview:x,maskOverlay:S,stats:Y,active:ae,brushCursor:F}),[v,S,x,M,Y,R,F,le,p,A,T,ae]),U=c.useCallback(()=>{K.current={past:[...K.current.past.slice(-19),ee()],future:[]}},[ee]),te=c.useCallback(w=>{const m=Ct(w);G.current=m.removeMask,Q.current=m.preserveMask,Z.current=null,O(m.intent),N(m.tool),C(m.engine),y(m.seeds),X(m.brushStrokes),I(m.brushRadius),$(m.tolerance),E(m.preview),P(m.maskOverlay),ne(m.stats),re(m.active),g(m.brushCursor),J(!1),ce(!1)},[]),z=c.useCallback(async()=>{if(!a.current||!t)return;const w=Be(G.current,Q.current);if(!w){P(null),ne(null);return}const m=k.current+1;k.current=m,J(!0);try{const L=await Ea({imageElement:a.current,mask:w});if(k.current!==m)return;P(L),ne(L.stats)}catch{if(k.current!==m)return;b(f("canvas.toolbar.cleanupFailed"),!0)}finally{k.current===m&&J(!1)}},[t,a,b,f]),V=c.useCallback(async(w,m,L)=>{if(!a.current)return;const q=ja(a.current),ie=xt(q.width,q.height),Ce=xt(q.width,q.height);for(const be of w){const _e=be.intent==="remove"?ie:Ce;yt(_e,q,[be.point],L)}for(const be of m){const _e=be.intent==="remove"?ie:Ce;yt(_e,q,Ba(be),L)}G.current=ie,Q.current=Ce},[a]),he=c.useCallback(()=>{k.current+=1,H.current!=null&&(window.clearTimeout(H.current),H.current=null),G.current=null,Q.current=null,Z.current=null,K.current={past:[],future:[]},y([]),X([]),E(null),P(null),ne(null),re(!1),g(null),J(!1),ce(!1)},[]),oe=c.useCallback(()=>{const w=K.current.past.pop();return w?(K.current.future=[ee(),...K.current.future.slice(0,19)],te(w),!0):!1},[ee,te]),we=c.useCallback(()=>{const w=K.current.future.shift();return w?(K.current.past=[...K.current.past.slice(-19),ee()],te(w),!0):!1},[ee,te]),De=c.useCallback(w=>{U();const m=[...M,{point:w,intent:A}];y(m),E(null),V(m,v,R).then(z)},[v,M,R,A,U,V,z]),$e=c.useCallback(()=>{U();const w=et().map(m=>({point:m,intent:"remove"}));y(w),E(null),re(!1),V(w,v,R).then(z)},[v,R,U,V,z]),Ue=c.useCallback(()=>{U(),N("click"),re(w=>!w)},[U]),W=c.useCallback(w=>{U(),H.current!=null&&window.clearTimeout(H.current),$(w),E(null),H.current=window.setTimeout(()=>{H.current=null,V(M,v,w).then(z)},180)},[v,M,U,V,z]),We=c.useCallback(async()=>{if(!a.current||!t)return null;let w=Be(G.current,Q.current);if(!w){const L=et().map(q=>({point:q,intent:"remove"}));y(L),await V(L,v,R),w=Be(G.current,Q.current)}if(!w)return null;U();const m=k.current+1;k.current=m,J(!0);try{const L=await kt({imageElement:a.current,mask:w});return k.current!==m?null:(E(L),P(null),ne(L.stats),L)}catch{return k.current!==m||b(f("canvas.toolbar.cleanupFailed"),!0),null}finally{k.current===m&&J(!1)}},[v,R,t,a,U,V,b,f]),He=c.useCallback(()=>{U(),he()},[U,he]),Fe=c.useCallback(w=>{U();const m={id:Sa(),intent:A,points:[{...w}],radius:le};Z.current=m,g(w),X(L=>[...L,m])},[le,A,U]),Ve=c.useCallback(w=>{const m=Z.current;if(!m){g(w);return}m.points=[...m.points,{...w}],g(w),X(L=>L.map(q=>q.id===m.id?{...m,points:m.points.map(ie=>({...ie}))}:q)),V(M,v.map(L=>L.id===m.id?m:L),R).then(z)},[v,M,R,V,z]),ve=c.useCallback(()=>{Z.current=null,V(M,v,R).then(z)},[v,M,R,V,z]),fe=c.useCallback(async()=>{if(!t||!a.current)return;const w=r.current??t;if(!w?.filename){b(f("canvas.toolbar.cleanupFailed"),!0);return}let m=Be(G.current,Q.current);if(!m){const L=et().map(q=>({point:q,intent:"remove"}));y(L),await V(L,v,R),m=Be(G.current,Q.current)}if(m){ce(!0),s("saving");try{U();const L=await kt({imageElement:a.current,mask:m}),q=await St({sourceFilename:w.canvasSourceFilename??w.filename,image:L.blob,prompt:w.prompt}),ie=ct(q.item,w);l.current=L.dataUrl,d(ie),u(ie),await i(ie),s("saved"),E(null),P(null),ne(L.stats),re(!1),b(f("canvas.toolbar.cleanupApplied"))}catch{s("error"),b(f("canvas.toolbar.cleanupFailed"),!0)}finally{ce(!1)}}},[u,i,v,R,r,t,a,l,U,V,s,d,b,f]),ue=c.useCallback(()=>ae?(Z.current=null,re(!1),g(null),!0):!1,[ae]);return c.useEffect(()=>{const w=a.current;if(!w||!e){B(!1);return}const m=()=>B(pa(w));if(w.complete)m();else return w.addEventListener("load",m),()=>w.removeEventListener("load",m)},[e,n?.canvasMergedAt,n?.filename,n?.image,n?.url,x?.dataUrl,a]),{imageHasAlpha:_,backgroundCleanupSeeds:M,backgroundCleanupBrushStrokes:v,backgroundCleanupTolerance:R,backgroundCleanupPreview:x,backgroundCleanupMaskOverlay:S,backgroundCleanupStats:Y,cleanupIntent:A,setCleanupIntent:O,cleanupTool:T,setCleanupTool:N,cleanupClickEngine:p,setCleanupClickEngine:C,cleanupBrushRadius:le,setCleanupBrushRadius:I,cleanupBrushCursor:F,setCleanupBrushCursor:g,isBackgroundCleanupActive:ae,setIsBackgroundCleanupActive:re,isBackgroundCleanupPickingSeed:ae&&T==="click",isBackgroundCleanupPreviewing:D,isBackgroundCleanupApplying:de,hasActiveCleanupStroke:!!Z.current,canUndoBackgroundCleanup:K.current.past.length>0,canRedoBackgroundCleanup:K.current.future.length>0,resetBackgroundCleanup:he,undoBackgroundCleanup:oe,redoBackgroundCleanup:we,addBackgroundCleanupClick:De,addBackgroundCleanupSeed:De,runBackgroundCleanupPreview:We,handleBackgroundCleanupAutoSample:$e,handleBackgroundCleanupPickSeed:Ue,handleBackgroundCleanupToleranceChange:W,handleBackgroundCleanupReset:He,handleBackgroundCleanupApply:fe,handleBackgroundCleanupEscape:ue,startBackgroundCleanupBrushStroke:Fe,updateBackgroundCleanupBrushStroke:Ve,endBackgroundCleanupBrushStroke:ve}}function wt(e){return Math.min(1,Math.max(0,e))}function _t(e,t){const n=t.getBoundingClientRect();return{x:wt((e.clientX-n.left)/n.width),y:wt((e.clientY-n.top)/n.height)}}const Pa=.18,Da=.12;function Aa(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 Ot(e){return{id:e.id,x:e.x,y:e.y,width:Pa,height:Da,color:e.color,strokeWidth:1}}function Ia(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,d=a*a+r*r;if(d===0)return Math.hypot(e.x-t.x,e.y-t.y);const u=Math.max(0,Math.min(1,(l*a+s*r)/d));return Math.hypot(e.x-(t.x+u*a),e.y-(t.y+u*r))}function Na(e,t,n){for(let a=1;a<t.points.length;a+=1)if(Ia(e,t.points[a-1],t.points[a])<=n)return!0;return!1}function Mt(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 Ra(e,t){return e.points.some(n=>ot(n,t))}function Et(e){const t=e.tolerance??.015;for(const n of[...e.memos].reverse())if(ot(e.point,Ot(n),t))return Pt(n);for(const n of[...e.boxes].reverse())if(ot(e.point,n,t))return Tt(n);for(const n of[...e.paths].reverse())if(Na(e.point,n,t))return jt(n);return null}function La(e){const t=[];for(const n of e.annotations.paths)Ra(n,e.box)&&t.push(jt(n));for(const n of e.annotations.boxes)Mt(n,e.box)&&t.push(Tt(n));for(const n of e.annotations.memos)Mt(Ot(n),e.box)&&t.push(Pt(n));return t}function Oa({canvasOpen:e,canvasZoom:t,canvasPanX:n,canvasPanY:a,spaceHeld:r,canDragViewportWithSelect:l,isBackgroundCleanupActive:s,cleanupTool:d,annotationFrameRef:u,annotations:i,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}),[p,C]=c.useState(!1),M=x=>{x.currentTarget.setPointerCapture(x.pointerId),N.current={active:!0,startX:x.clientX,startY:x.clientY,basePanX:n,basePanY:a,pointerId:x.pointerId},C(!0)};return{viewportPanActive:p,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:x=>{if(!e||me(x.target)||!u.current)return;const E=x.button===1;if(r||E){x.preventDefault(),M(x);return}x.preventDefault();const S=_t(x,u.current);if(s){d==="click"?f(S):(x.currentTarget.setPointerCapture(x.pointerId),_(S));return}if(i.activeTool==="select"){const P=Et({point:S,paths:i.paths,boxes:i.boxes,memos:i.memos});if(P)x.shiftKey?i.toggleSelected(P):i.selectOne(P),i.startSelectedMove(),T.current={mode:"move",lastPoint:S,didMove:!1};else if(l&&t>1.01){M(x);return}else i.clearSelection(),i.startSelectionBox(S),T.current={mode:"box",lastPoint:S,didMove:!1};x.currentTarget.setPointerCapture(x.pointerId);return}if(i.activeTool==="memo"){i.createMemo(S),requestAnimationFrame(()=>{u.current?.querySelector(".canvas-memo--active")?.focus()});return}if(i.activeTool==="eraser"){if(i.eraserMode==="object"){const P=Et({point:S,paths:i.paths,boxes:i.boxes,memos:i.memos});P&&i.eraseObjectAtPoint(P);return}x.currentTarget.setPointerCapture(x.pointerId),i.startEraserStroke(S);return}x.currentTarget.setPointerCapture(x.pointerId),i.startDrawing(S)},handleAnnotationPointerMove:x=>{if(!e||me(x.target)||!u.current)return;if(N.current.active){const S=x.clientX-N.current.startX,P=x.clientY-N.current.startY;b(N.current.basePanX+S,N.current.basePanY+P);return}const E=_t(x,u.current);if(s){d==="brush"?B(E):O(E);return}if(i.activeTool==="select"){if(T.current.mode==="move"&&T.current.lastPoint){const S={x:E.x-T.current.lastPoint.x,y:E.y-T.current.lastPoint.y};(Math.abs(S.x)>5e-4||Math.abs(S.y)>5e-4)&&(i.moveSelected(S),T.current.didMove=!0),T.current.lastPoint=E}else T.current.mode==="box"&&i.updateSelectionBox(E);return}if(i.activeTool!=="memo"){if(i.activeTool==="eraser"){i.eraserMode==="brush"&&i.updateEraserStroke(E);return}i.moveDrawing(E)}},handleAnnotationPointerUp:x=>{if(e&&!me(x.target)){if(N.current.active&&N.current.pointerId===x.pointerId){x.currentTarget.hasPointerCapture(x.pointerId)&&x.currentTarget.releasePointerCapture(x.pointerId),N.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},C(!1);return}if(x.currentTarget.hasPointerCapture(x.pointerId)&&x.currentTarget.releasePointerCapture(x.pointerId),s){d==="brush"&&A();return}if(i.activeTool==="select"){T.current.mode==="move"&&T.current.didMove&&i.commitSelectedMove(),T.current.mode==="box"&&i.selectionBox&&i.endSelectionBox(La({box:Aa(i.selectionBox),annotations:i.toPayload()})),T.current={mode:null,lastPoint:null,didMove:!1};return}if(i.activeTool!=="memo"){if(i.activeTool==="eraser"){i.eraserMode==="brush"&&i.endEraserStroke();return}i.endDrawing()}}},handleAnnotationPointerLeave:()=>{s&&O(null)}}}function $a({canvasOpen:e,canvasZoom:t,currentImage:n,annotations:a,undoBackgroundCleanup:r,redoBackgroundCleanup:l,handleBackgroundCleanupEscape:s,handleCloseCanvas:d,selectHistoryShortcutTarget:u,trashHistoryItem:i,permanentlyDeleteHistoryItemByShortcut:b,setCanvasZoom:f,resetCanvasZoom:_,onCreateBlankCanvas:B,isCreatingBlankCanvas:A}){const[O,T]=c.useState(!1);return c.useEffect(()=>{if(!e)return;const p=v=>{v.preventDefault()},C=v=>{v.ctrlKey&&v.preventDefault()},M={passive:!1,capture:!0},y={passive:!1};return window.addEventListener("wheel",C,M),window.addEventListener("gesturestart",p,y),window.addEventListener("gesturechange",p,y),window.addEventListener("gestureend",p,y),()=>{window.removeEventListener("wheel",C,M),window.removeEventListener("gesturestart",p,y),window.removeEventListener("gesturechange",p,y),window.removeEventListener("gestureend",p,y)}},[e]),c.useEffect(()=>{if(!e)return;const p=M=>{M.code==="Space"&&(me(M.target)||(O||T(!0),M.preventDefault()))},C=M=>{M.code==="Space"&&T(!1)};return window.addEventListener("keydown",p),window.addEventListener("keyup",C),()=>{window.removeEventListener("keydown",p),window.removeEventListener("keyup",C)}},[e,O]),c.useEffect(()=>{if(!e)return;const p=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;d();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",p),()=>window.removeEventListener("keydown",p)},[a,a.focusMemo,a.redo,a.undo,e,d,s,A,B,l,r]),{spaceHeld:O,handleViewerKeyDown:p=>{if(me(p.target)){p.key==="Escape"&&(p.preventDefault(),p.target.blur(),a.focusMemo(null));return}if(e&&["1","2","3","4","5","6"].includes(p.key)){p.preventDefault();const C=["select","pen","box","arrow","memo","eraser"];a.setTool(C[Number(p.key)-1]);return}if(e&&p.key==="Escape"){if(p.preventDefault(),p.stopPropagation(),s())return;d();return}if(e&&p.key==="]"){p.preventDefault(),f(t+.1);return}if(e&&p.key==="["){p.preventDefault(),f(t-.1);return}if(e&&p.key==="0"){p.preventDefault(),_();return}if(p.key==="Delete"||p.key==="Backspace"){if(!n||p.target!==p.currentTarget)return;if(p.preventDefault(),p.shiftKey){b(n);return}i(n);return}p.key!=="ArrowLeft"&&p.key!=="ArrowRight"&&p.key!=="Home"&&p.key!=="End"||p.target===p.currentTarget&&(me(p.target)||(p.preventDefault(),p.key==="ArrowLeft"?u("previous"):p.key==="ArrowRight"?u("next"):p.key==="Home"?u("first"):p.key==="End"&&u("last")))}}}function Ua(e,t){return new Promise((n,a)=>{e.toBlob(r=>{if(r){n(r);return}a(new Error("canvas_blob_unavailable"))},t)})}async function $t(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)_n(n,l,a);return{blob:await Ua(t,"image/png"),dataUrl:t.toDataURL("image/png")}}async function Wa(e){return(await $t(e)).blob}function Ha(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 Fa(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 Va({imageElementRef:e,currentImage:t,canvasDisplayImage:n,canvasSourceImageRef:a,lastMergedDataUrlRef:r,canvasVersionItem:l,annotations:s,exportBackground:d,exportMatteColor:u,quality:i,format:b,moderation:f,provider:_,imageModel:B,reasoningEffort:A,promptMode:O,webSearchEnabled:T,getResolvedSize:N,setCanvasVersionItem:p,setCanvasSaveState:C,setIsApplying:M,setIsExporting:y,setIsEditingWithMask:v,applyMergedCanvasImage:X,addGeneratedHistoryItem:R,attachCanvasVersionReference:$,closeCanvas:x,resetCanvasSession:E,showToast:S,t:P}){const Y=c.useCallback(async()=>{if(!e.current||!t)return null;const I=a.current??t;if(!I?.filename)return S(P("canvas.version.failed"),!0),null;M(!0),C("saving");try{const F=await $t({imageElement:e.current,paths:s.paths,boxes:s.boxes,memos:s.memos});r.current=F.dataUrl;const g=l?.filename?await on(l.filename,{image:F.blob,sourceFilename:I.canvasSourceFilename??I.filename,prompt:I.prompt}):await St({sourceFilename:I.filename,image:F.blob,prompt:I.prompt}),D=ct(g.item,I);return p(D),X(D),await $(D),await Bt(I.filename).catch(()=>{}),s.resetLocal(),s.markSaved(),C("saved"),S(P("canvas.version.saved")),D}catch{return C("error"),S(P("canvas.version.failed"),!0),null}finally{M(!1)}},[s,X,$,a,l?.filename,t,e,r,C,p,M,S,P]);return{saveCanvasVersionAndUseReference:Y,handleApplyCanvas:async()=>{await Y()},handleCloseCanvas:async()=>{(s.hasAnnotations||s.isDirty)&&!await Y()||(x(),E())},handleExportCanvas:async()=>{if(!(!e.current||!t)){y(!0);try{const I=d==="matte",F=await Wa({imageElement:e.current,paths:s.paths,boxes:s.boxes,memos:s.memos,background:I?{mode:"matte",color:u}:{mode:"alpha"}});Fa(F,Ha({matte:I}))}catch{S(P("canvas.toolbar.exportFailed"),!0)}finally{y(!1)}}},handleEditWithMask:async()=>{if(!(!e.current||!n||s.boxes.length===0)){v(!0);try{let I=r.current;if(s.isDirty||s.hasAnnotations){if(!await Y())return;I=r.current}I||(I=await ya(e.current));const F=s.boxes.filter(de=>s.selectedIds.some(ce=>pe(ce,"box",de.id))),g=await xa({imageElement:e.current,boxes:F.length>0?F:s.boxes}),D=n.prompt??t?.prompt??"";if(!D.trim()){S(P("toast.noPromptToFork"),!0);return}const J=await sn({image:I,mask:await it(g),prompt:D,quality:i,size:n.size??t?.size??N(),format:b,moderation:f,provider:_,n:1,model:B,reasoningEffort:A,mode:O,webSearchEnabled:T});await R(fa(J,D))}catch(I){const F=I.code;S(P(F==="EDIT_MASK_NOT_SUPPORTED"?"canvas.toolbar.editMaskUnsupported":"canvas.toolbar.editMaskFailed"),!0)}finally{v(!1)}}}}}function za(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 se=h.multimodePreviewFlightId;return se?h.multimodeSequences[se]??null:null}),d=j(h=>h.selectHistoryShortcutTarget),u=j(h=>h.trashHistoryItem),i=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),p=j(h=>h.promptMode),C=j(h=>h.webSearchEnabled),M=j(h=>h.getResolvedSize),y=j(h=>h.showToast),v=j(h=>h.canvasOpen),X=j(h=>h.openCanvas),R=j(h=>h.closeCanvas),$=j(h=>h.canvasZoom),x=j(h=>h.canvasPanX),E=j(h=>h.canvasPanY),S=j(h=>h.setCanvasPan),P=j(h=>h.setCanvasZoom),Y=j(h=>h.resetCanvasZoom),ne=j(h=>h.canvasExportBackground),ae=j(h=>h.canvasExportMatteColor),re=j(h=>h.setCanvasExportBackground),le=j(h=>h.setCanvasExportMatteColor),I=j(h=>h.applyMergedCanvasImage),F=j(h=>h.addGeneratedHistoryItem),g=j(h=>h.attachCanvasVersionReference),{t:D}=ke(),{creatingBlankCanvas:J,createBlankCanvas:de}=ln(),ce=c.useRef(null),G=c.useRef(null),Q=c.useRef(null),Z=c.useRef(null),K=c.useRef(null),k=c.useRef(null),H=c.useRef(null),ee=c.useRef(null),[U,te]=c.useState(null),[z,V]=c.useState("idle"),[he,oe]=c.useState(!1),[we,De]=c.useState(!1),[$e,Ue]=c.useState(!1),W=wn(),We=()=>{t?.prompt&&(navigator.clipboard.writeText(t.prompt),y(D("toast.promptCopied")))},He=ia(t?.quality??_),Fe=ua(t?.size??M()),Ve=cn(t?.model),ve=t?.filename??t?.url??t?.image??null,fe=ha(n,t),ue=v?U??fe??t:t,w=ue?da(ue):null,m=Ta({canvasOpen:v,currentImage:t,canvasDisplayImage:ue,imageElementRef:G,canvasSourceImageRef:H,lastMergedDataUrlRef:ee,setCanvasSaveState:V,setCanvasVersionItem:te,applyMergedCanvasImage:I,attachCanvasVersionReference:g,showToast:y,t:D}),{imageHasAlpha:L,backgroundCleanupSeeds:q,backgroundCleanupPreview:ie,backgroundCleanupMaskOverlay:Ce,backgroundCleanupBrushStrokes:be,cleanupTool:_e,cleanupBrushRadius:Ut,cleanupBrushCursor:Wt,isBackgroundCleanupActive:Me}=m,Ke=m.backgroundCleanupPreview?.dataUrl??w,ze=()=>{H.current=null,K.current=null,k.current!=null&&(window.clearTimeout(k.current),k.current=null),te(null),V("idle"),m.resetBackgroundCleanup(),ee.current=null,Jt()};c.useEffect(()=>{if(!v){Z.current=ve,ze();return}if(Z.current===null){Z.current=ve,H.current=t,te(fe);return}Z.current!==ve&&(W.resetLocal(),ze(),H.current=t,te(fe),Z.current=ve)},[W.resetLocal,v,t,ve,fe]),c.useEffect(()=>{!v||!t||H.current||(H.current=t,te(fe))},[v,t,fe]),c.useEffect(()=>{if(!v||!t?.filename||t.canvasVersion)return;const h=t.filename;if(K.current===h)return;K.current=h;let se=!1;return un(h).then(Ee=>{!se&&Ee.annotations&&W.load(Ee.annotations)}).catch(()=>{}),()=>{se=!0}},[W.load,v,t?.canvasVersion,t?.filename]),c.useEffect(()=>{if(!v||!t?.filename||t.canvasVersion||!W.isDirty)return;const h=t.filename;return k.current!=null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{const se=W.toPayload();(W.hasAnnotations?dn(h,se):Bt(h)).then(()=>W.markSaved()).catch(()=>{})},500),()=>{k.current!=null&&(window.clearTimeout(k.current),k.current=null)}},[W,W.hasAnnotations,W.isDirty,v,t?.canvasVersion,t?.filename]);const Ht=h=>{me(h.target)||(b(),h.currentTarget.focus())},Ft=c.useCallback(()=>{window.requestAnimationFrame(()=>Q.current?.focus())},[]),Vt=h=>{if(v){if(h.preventDefault(),h.ctrlKey){P($-h.deltaY*.01);return}S(x-h.deltaX,E-h.deltaY)}},Kt=c.useCallback(h=>{Array.from(h.dataTransfer.types).includes("Files")&&(h.preventDefault(),l(se=>se||!0))},[]),zt=c.useCallback(h=>{h.currentTarget.contains(h.relatedTarget)||l(!1)},[]),Xt=c.useCallback(async h=>{if(!Array.from(h.dataTransfer.types).includes("Files"))return;h.preventDefault(),l(!1);const se=Array.from(h.dataTransfer.files).filter(Ee=>/^image\/(png|jpeg|webp)$/.test(Ee.type));se.length!==0&&await a(se[0])},[a]),{handleApplyCanvas:qt,handleCloseCanvas:dt,handleExportCanvas:Yt,handleEditWithMask:Gt}=Va({imageElementRef:G,currentImage:t,canvasDisplayImage:ue,canvasSourceImageRef:H,lastMergedDataUrlRef:ee,canvasVersionItem:U,annotations:W,exportBackground:ne,exportMatteColor:ae,quality:_,format:B,moderation:A,provider:O,imageModel:T,reasoningEffort:N,promptMode:p,webSearchEnabled:C,getResolvedSize:M,setCanvasVersionItem:te,setCanvasSaveState:V,setIsApplying:oe,setIsExporting:De,setIsEditingWithMask:Ue,applyMergedCanvasImage:I,addGeneratedHistoryItem:F,attachCanvasVersionReference:g,closeCanvas:R,resetCanvasSession:ze,showToast:y,t:D}),{spaceHeld:Xe,handleViewerKeyDown:Zt}=$a({canvasOpen:v,canvasZoom:$,currentImage:t,annotations:W,undoBackgroundCleanup:m.undoBackgroundCleanup,redoBackgroundCleanup:m.redoBackgroundCleanup,handleBackgroundCleanupEscape:m.handleBackgroundCleanupEscape,handleCloseCanvas:dt,selectHistoryShortcutTarget:d,trashHistoryItem:u,permanentlyDeleteHistoryItemByShortcut:i,setCanvasZoom:P,resetCanvasZoom:Y,onCreateBlankCanvas:de,isCreatingBlankCanvas:J}),qe=v&&$>1.01&&W.activeTool==="select"&&!Me,{viewportPanActive:Ye,resetPointerSession:Jt,handleAnnotationPointerDown:Qt,handleAnnotationPointerMove:en,handleAnnotationPointerUp:tn,handleAnnotationPointerLeave:nn}=Oa({canvasOpen:v,canvasZoom:$,canvasPanX:x,canvasPanY:E,spaceHeld:Xe,canDragViewportWithSelect:qe,isBackgroundCleanupActive:Me,cleanupTool:_e,annotationFrameRef:ce,annotations:W,setCanvasPan:S,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:Kt,onDragLeave:zt,onDrop:Xt,children:[r?o.jsx("div",{className:"canvas__drop-overlay","aria-hidden":!0,children:o.jsx("span",{className:"canvas__drop-hint",children:D("canvas.drop.hint")})}):null,v&&o.jsx(ra,{zoom:$,closeLabel:D("canvas.close"),blankCanvasLabel:D("canvas.blank.title"),blankCanvasAriaLabel:`${D(J?"canvas.blank.creating":"canvas.blank.create")} (Shift+B)`,blankCanvasShortcut:"Shift+B",blankCanvasBusy:J,shortcutHint:D("canvas.toolbar.zoomShortcutHint"),onZoomIn:()=>P($+.1),onZoomOut:()=>P($-.1),onZoomReset:Y,onCreateBlankCanvas:()=>{de()},onClose:()=>{dt()}}),o.jsx("div",{className:`progress-bar${f>0?" active":""}`}),s?o.jsx(hn,{}):t?o.jsxs("div",{ref:Q,className:"result-container visible",tabIndex:0,onMouseDown:Ht,onWheel:Vt,onKeyDown:Zt,"aria-label":D("canvas.imageViewerAria"),children:[o.jsx(Pn,{annotationFrameRef:ce,imageElementRef:G,frameClassName:`canvas-annotation-frame${(L||ie)&&v?" canvas-annotation-frame--alpha":""}${Me&&v?" canvas-annotation-frame--cleanup-picking":""}${Ce&&v?" canvas-annotation-frame--cleanup-mask":""}`,frameStyle:{cursor:Ye?"grabbing":Xe||qe?"grab":v?Me?"crosshair":W.activeTool==="select"?"default":W.activeTool==="eraser"?W.eraserMode==="object"?la:ca:"crosshair":"zoom-in",transform:v?`translate(${x}px, ${E}px) scale(${$})`:void 0,transition:v&&!Ye?"transform 0.2s ease":void 0},imageKey:`${ue?.filename??ue?.url??ue?.image}:${ue?.canvasMergedAt??""}`,imageSrc:Ke??t.image,fallbackImage:t.image,alt:D("canvas.resultAlt"),canvasOpen:v,maskOverlayUrl:Ce?.dataUrl??null,cleanupLayer:o.jsx(In,{seeds:q,brushStrokes:be,brushCursor:Wt,brushRadius:Ut,active:Me}),annotations:W,onOpenCanvas:X,onPointerDown:Qt,onPointerMove:en,onPointerUp:tn,onPointerLeave:nn}),v&&Ke?o.jsx(sa,{imageSrc:Ke,zoom:$,panX:x,panY:E,resetLabel:D("canvas.toolbar.zoomReset"),onReset:Y}):null,v&&o.jsx(Qn,{annotations:W,backgroundCleanup:m,backgroundCleanupPreview:ie,canvasState:{exportBackground:ne,exportMatteColor:ae,isApplying:he,isExporting:we,isEditingWithMask:$e},actions:{handleApplyCanvas:qt,handleExportCanvas:Yt,handleEditWithMask:Gt,setExportBackground:re,setExportMatteColor:le}}),v&&z!=="idle"?o.jsx("div",{className:`canvas-save-state canvas-save-state--${z}`,children:D(z==="saving"?"canvas.version.saving":z==="saved"?"canvas.version.saved":"canvas.version.failed")}):null,o.jsx(ea,{currentImage:t,canvasDisplayImage:ue,canvasOpen:v,displayQuality:He,displaySize:Fe,displayModel:Ve,onAfterDeleteFocus:Ft,onCopyPrompt:We})]}):null]})}export{za as CanvasModeWorkspace};
1
+ import{a as c,j as o,u as ke,p as an,q as rn,s as St,t as me,v as on,w as Bt,x as sn,b as j,y as ln,c as cn,z as un,A as dn,M as hn}from"./index-BAN6lKgf.js";const Ae=2,Oe=1e-6;function fn({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 d=pn(s,t,n,a);(d.length!==1||d[0]!==s)&&(r=!0),l.push(...d)}return{paths:l,changed:r}}function pn(e,t,n,a=()=>crypto.randomUUID()){if(e.points.length<Ae||t.length===0||n<=0)return[e];const r=[];let l=Te(e.points[0],t,n)?[]:[e.points[0]];for(let d=1;d<e.points.length;d+=1){const u=e.points[d-1],i=e.points[d],b=Te(i,t,n),f=mn(u,i,t,n);if(f){l.length===0&&!Te(u,t,n)&&(l=[u]),l.length>0&&f.leftT>Oe&&ft(l,Pe(u,i,f.leftT)),l.length>=Ae&&r.push(l),l=[],f.rightT<1-Oe&&!b&&(l=[Pe(u,i,f.rightT),i]);continue}if(b){l.length>=Ae&&r.push(l),l=[];continue}l.length===0&&!Te(u,t,n)&&(l=[u]),ft(l,i)}if(l.length>=Ae&&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((d,u)=>({...e,id:u===0?e.id:a(),tool:e.tool==="arrow"&&u!==s?"pen":e.tool,points:d}))}function Te(e,t,n){if(t.length===1)return ye(e,t[0])<=n;for(let a=1;a<t.length;a+=1)if(vn(e,t[a-1],t[a])<=n)return!0;return!1}function ye(e,t){const n=e.x-t.x,a=e.y-t.y;return Math.sqrt(n*n+a*a)}function mn(e,t,n,a){const r=ye(e,t);if(r<=Oe)return Te(e,n,a)?{leftT:0,rightT:1}:null;let l=null,s=Number.POSITIVE_INFINITY;for(const u of n){const i=ht(u,e,t),b=Pe(e,t,i),f=ye(u,b);f<s&&(s=f,l=i)}for(let u=1;u<n.length;u+=1){const i=[0,.25,.5,.75,1];for(const b of i){const f=Pe(n[u-1],n[u],b),_=ht(f,e,t),B=Pe(e,t,_),A=ye(f,B);A<s&&(s=A,l=_)}}if(l===null||s>a)return null;const d=Math.max(a/r,.01);return{leftT:Math.max(0,l-d),rightT:Math.min(1,l+d)}}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,d=a*a+r*r;return d===0?0:Math.max(0,Math.min(1,(l*a+s*r)/d))}function Pe(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||ye(n,t)>Oe)&&e.push(t)}function vn(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,d=a*a+r*r;if(d===0)return ye(e,t);const u=Math.max(0,Math.min(1,(l*a+s*r)/d));return ye(e,{x:t.x+u*a,y:t.y+u*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 jt(e){return st("path",e.id)}function Tt(e){return st("box",e.id)}function Pt(e){return st("memo",e.id)}function pe(e,t,n){const a=lt(e);return a?.kind===t&&a.id===n}const Dt="ima2.canvas.annotationStyle.v1",At=["#ef4444","#f97316","#eab308","#22c55e","#38bdf8","#6366f1","#a855f7","#111827","#ffffff"],It=[2,3,5,8],Se={color:"#ef4444",strokeWidth:3};function bn(){if(typeof window>"u")return Se;try{const e=window.localStorage.getItem(Dt);if(!e)return Se;const t=JSON.parse(e),n=typeof t.color=="string"&&At.includes(t.color)?t.color:Se.color,a=typeof t.strokeWidth=="number"&&It.includes(t.strokeWidth)?t.strokeWidth:Se.strokeWidth;return{color:n,strokeWidth:a}}catch{return Se}}function gn(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Dt,JSON.stringify(e))}catch{}}const pt=bn(),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 xe(e){return{paths:e.paths,boxes:e.boxes,memos:e.memos}}function ge(e){return{...e,past:[...e.past.slice(-49),xe(e)],future:[]}}function Ge(e,t){return{...e,past:[...e.past.slice(-49),t],future:[]}}function xn(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 yn(e,t,n){const{start:a,current:r}=e,l=Math.min(a.x,r.x),s=Math.min(a.y,r.y),d=Math.abs(r.x-a.x),u=Math.abs(r.y-a.y);return d<.01||u<.01?null:{id:crypto.randomUUID(),x:l,y:s,width:d,height:u,color:t,strokeWidth:n}}function kn(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 Cn(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}:{...ge(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=yn(e.activeBox,e.toolColor,e.strokeWidth);return n?{...ge(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{...ge(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?xn(e.memoBaseline,xe(e))?{...e,memoBaseline:null,activeMemoId:null}:{...Ge(e,e.memoBaseline),memoBaseline:null,activeMemoId:null,isDirty:!0}:{...e,activeMemoId:null};case"DELETE_MEMO":return{...ge(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?xe(e):e.memoBaseline};case"CLEAR":return{...ge(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:[xe(e),...e.future]}:e}case"REDO":{const n=e.future[0];return n?{...mt(e,n),past:[...e.past.slice(-49),xe(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:{...ge(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))?kn(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:xe(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:{...ge(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:xe(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=fn({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 wn(){const[e,t]=c.useReducer(Cn,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(g=>t({type:"SET_TOOL",tool:g}),[]),s=c.useCallback(g=>{gn(g),t({type:"SET_STYLE",style:g})},[]),d=c.useCallback(()=>t({type:"CLEAR"}),[]),u=c.useCallback(g=>t({type:"LOAD",payload:g}),[]),i=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(g=>{e.activeTool==="pen"||e.activeTool==="arrow"?t({type:"START_PATH",point:g}):e.activeTool==="box"&&t({type:"START_BOX",point:g})},[e.activeTool]),N=c.useCallback(g=>{e.activePath?t({type:"ADD_POINT",point:g}):e.activeBox&&t({type:"UPDATE_BOX",point:g})},[e.activePath,e.activeBox]),p=c.useCallback(()=>{e.activePath?t({type:"END_PATH"}):e.activeBox&&t({type:"END_BOX"})},[e.activePath,e.activeBox]),C=c.useCallback(g=>t({type:"CREATE_MEMO",point:g}),[]),M=c.useCallback((g,D)=>t({type:"UPDATE_MEMO",id:g,text:D}),[]),y=c.useCallback(g=>t({type:"DELETE_MEMO",id:g}),[]),v=c.useCallback(g=>t({type:"FOCUS_MEMO",id:g}),[]),X=c.useCallback(g=>t({type:"SET_ERASER_MODE",mode:g}),[]),R=c.useCallback(g=>t({type:"SELECT_ONE",id:g}),[]),$=c.useCallback(g=>t({type:"TOGGLE_SELECTED",id:g}),[]),x=c.useCallback(()=>t({type:"CLEAR_SELECTION"}),[]),E=c.useCallback(()=>t({type:"DELETE_SELECTED"}),[]),S=c.useCallback(g=>t({type:"MOVE_SELECTED",delta:g}),[]),P=c.useCallback(g=>t({type:"START_SELECTION_BOX",point:g}),[]),Y=c.useCallback(g=>t({type:"UPDATE_SELECTION_BOX",point:g}),[]),ne=c.useCallback(g=>t({type:"END_SELECTION_BOX",ids:g}),[]),ae=c.useCallback(g=>t({type:"ERASE_OBJECT",id:g}),[]),re=c.useCallback(g=>t({type:"START_ERASER_STROKE",point:g}),[]),le=c.useCallback(g=>t({type:"UPDATE_ERASER_STROKE",point:g}),[]),I=c.useCallback(()=>t({type:"END_ERASER_STROKE"}),[]),F=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:X,startDrawing:T,moveDrawing:N,endDrawing:p,createMemo:C,updateMemo:M,commitMemoEdit:B,deleteMemo:y,focusMemo:v,clear:d,load:u,toPayload:F,markSaved:i,resetLocal:b,undo:f,redo:_,selectOne:R,toggleSelected:$,clearSelection:x,deleteSelected:E,moveSelected:S,startSelectedMove:A,commitSelectedMove:O,startSelectionBox:P,updateSelectionBox:Y,endSelectionBox:ne,eraseObjectAtPoint:ae,startEraserStroke:re,updateEraserStroke:le,endEraserStroke:I}}function Ie(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=Ie(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=Ie(r,n);e.lineTo(l.x,l.y)}if(e.stroke(),t.tool==="arrow"){const r=Ie(t.points[t.points.length-1],n),l=Ie(t.points[t.points.length-2],n);En(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 _n(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,d=18;e.save(),e.font="14px sans-serif";const u=Sn(e,t.text.trim()||" ",l-s*2),i=Math.max(52,s*2+u.length*d);e.fillStyle="rgba(255, 246, 179, 0.96)",e.strokeStyle="rgba(44, 37, 12, 0.28)",e.lineWidth=1,Bn(e,a,r,l,i,8),e.fill(),e.stroke(),e.fillStyle="#2f2a13",e.textBaseline="top",u.forEach((b,f)=>{e.fillText(b,a+s,r+s+f*d)}),e.restore()}function Mn(e,t){const n=lt(e);if(!n)return null;if(n.kind==="box")return t.boxes.find(i=>i.id===n.id)??null;const a=n.kind==="memo"?t.memos.find(i=>i.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(i=>i.id===n.id);if(!r||r.points.length===0)return null;const l=r.points.map(i=>i.x),s=r.points.map(i=>i.y),d=Math.min(...l),u=Math.min(...s);return{id:r.id,x:d,y:u,width:Math.max(.01,Math.max(...l)-d),height:Math.max(.01,Math.max(...s)-u),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 En(e,t,n,a,r){const l=Math.atan2(n.y-t.y,n.x-t.x),s=Math.max(12,r*4),d=Math.PI/7;e.save(),e.fillStyle=a,e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x-s*Math.cos(l-d),n.y-s*Math.sin(l-d)),e.lineTo(n.x-s*Math.cos(l+d),n.y-s*Math.sin(l+d)),e.closePath(),e.fill(),e.restore()}function Sn(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 d=l?`${l} ${s}`:s;if(e.measureText(d).width<=n||l===""){l=d;continue}r.push(l),l=s}return l&&r.push(l),r}function Bn(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 jn({paths:e,boxes:t,memos:n=[],selectedIds:a=[],selectionBox:r=null,activePath:l,activeBox:s}){const d=c.useRef(null);return c.useEffect(()=>{const u=d.current;if(!u)return;const i=u.getBoundingClientRect(),b=window.devicePixelRatio||1;u.width=Math.max(1,Math.round(i.width*b)),u.height=Math.max(1,Math.round(i.height*b));const f=u.getContext("2d");if(!f)return;f.setTransform(b,0,0,b,0,0),f.clearRect(0,0,i.width,i.height);const _={width:i.width,height:i.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=Mn(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:d,className:"canvas-annotation-layer","aria-hidden":"true"})}function Ne(e){e.stopPropagation()}function Tn({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:Ne,onPointerMove:Ne,onPointerUp:Ne,onPointerCancel:Ne,onChange:d=>n(s.id,d.currentTarget.value),onBlur:()=>{l?.(),s.text.trim()===""&&a(s.id)},"aria-label":"Canvas memo"},s.id))})}function Pn({annotationFrameRef:e,imageElementRef:t,frameClassName:n,frameStyle:a,imageKey:r,imageSrc:l,fallbackImage:s,alt:d,canvasOpen:u,maskOverlayUrl:i,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:d,onDoubleClick:N=>{N.stopPropagation(),_()}},r),u&&i?o.jsx("img",{className:"canvas-background-cleanup-mask",src:i,alt:"","aria-hidden":"true"}):null,u?b:null,u&&o.jsxs(o.Fragment,{children:[o.jsx(jn,{paths:f.paths,boxes:f.boxes,memos:f.memos,selectedIds:f.selectedIds,selectionBox:f.selectionBox,activePath:f.activePath,activeBox:f.activeBox}),o.jsx(Tn,{memos:f.memos,activeMemoId:f.activeMemoId,onUpdate:f.updateMemo,onDelete:f.deleteMemo,onFocus:f.focusMemo,onCommit:f.commitMemoEdit})]})]})}function Dn(e){return`${e.x*100} ${e.y*100}`}function An(e){return e.map(Dn).join(" ")}function In({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:An(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 Nn({mode:e,matteColor:t,onModeChange:n,onMatteColorChange:a}){const{t:r}=ke();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 Rn({seedCount:e,tolerance:t,stats:n,hasPreview:a,isPickingSeed:r,intent:l,tool:s,brushRadius:d,isPreviewing:u,isApplying:i,keepOpen:b,disabled:f,onAutoSample:_,onPickSeed:B,onIntentChange:A,onToolChange:O,onBrushRadiusChange:T,onToleranceChange:N,onPreview:p,onApply:C,onReset:M}){const{t:y}=ke(),[v,X]=c.useState(!1),R=c.useRef(null),$=n?Math.round(n.removedPercent*1e3)/10:0,x=r||s==="brush";return c.useEffect(()=>{if(!v)return;const E=S=>{b||R.current?.contains(S.target)||X(!1)};return window.addEventListener("pointerdown",E),()=>window.removeEventListener("pointerdown",E)},[b,v]),o.jsxs("div",{className:"canvas-toolbar__cleanup",ref:R,children:[o.jsx("button",{type:"button",className:`canvas-toolbar__button${v||a?" canvas-toolbar__button--active":""}`,onClick:()=>X(E=>!E),disabled:f,"aria-expanded":v,"aria-label":y("canvas.toolbar.cleanup"),title:y("canvas.toolbar.cleanup"),children:o.jsx(Ln,{})}),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:E=>N(Number(E.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:d,onChange:E=>T(Number(E.target.value))}),o.jsx("output",{children:Math.round(d*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(x?"canvas.toolbar.cleanupActive":"canvas.toolbar.cleanupPickSeed")})]}),o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:p,disabled:u||e===0,children:y(u?"canvas.toolbar.cleanupPreviewing":"canvas.toolbar.cleanupPreview")}),o.jsx("button",{type:"button",onClick:C,disabled:i||!a&&e===0,children:y(i?"canvas.toolbar.cleanupApplying":"canvas.toolbar.cleanupApply")}),o.jsx("button",{type:"button",onClick:M,disabled:!a&&e===0,children:y("canvas.toolbar.cleanupReset")})]}),x?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:$})}):null]}):null]})}function Ln(){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 On({style:e,onStyleChange:t}){const{t:n}=ke(),[a,r]=c.useState(!1),l=c.useRef(null);return c.useEffect(()=>{if(!a)return;const s=d=>{l.current?.contains(d.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:At.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:It.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 $n({tools:e,activeTool:t,onToolChange:n}){const[a,r]=c.useState(!1),l=c.useRef(null),s=e.find(u=>u.id===t)??e[0],d=s.icon;return c.useEffect(()=>{if(!a)return;const u=i=>{l.current?.contains(i.target)||r(!1)};return window.addEventListener("pointerdown",u),()=>window.removeEventListener("pointerdown",u)},[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(u=>!u),"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(d,{}),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(u=>{const i=u.icon,b=t===u.id;return o.jsxs("button",{type:"button",className:`canvas-tool-picker__item${b?" active":""}`,role:"menuitemradio","aria-checked":b,onClick:()=>{n(u.id),r(!1)},children:[o.jsx(i,{}),o.jsx("span",{children:u.label}),o.jsx("kbd",{children:u.shortcut})]},u.id)})}):null]})}function Un({activeTool:e,hasAnnotations:t,hasExportableContent:n,onToolChange:a,eraserMode:r="object",onEraserModeChange:l,style:s,onStyleChange:d,onClear:u,onApply:i,onExport:b,onUndo:f,onRedo:_,canUndo:B,canRedo:A,onDeleteSelected:O,selectedCount:T=0,onEditWithMask:N,canEditWithMask:p,isEditingWithMask:C,isApplying:M,isExporting:y,exportBackground:v="alpha",exportMatteColor:X="#ffffff",onExportBackgroundChange:R,onExportMatteColorChange:$,cleanupTolerance:x=28,cleanupSeedCount:E=0,cleanupStats:S=null,cleanupHasPreview:P=!1,isCleanupPickingSeed:Y=!1,isCleanupActive:ne=!1,cleanupIntent:ae="remove",cleanupTool:re="click",cleanupBrushRadius:le=.018,isCleanupPreviewing:I=!1,isCleanupApplying:F=!1,onCleanupAutoSample:g,onCleanupPickSeed:D,onCleanupIntentChange:J,onCleanupToolChange:de,onCleanupBrushRadiusChange:ce,onCleanupToleranceChange:G,onCleanupPreview:Q,onCleanupApply:Z,onCleanupReset:K}){const{t:k}=ke(),[H,ee]=c.useState(!1),U=c.useRef(null),te=n??t??!1,z=k(r==="object"?"canvas.toolbar.objectEraser":"canvas.toolbar.brushEraser"),V=[{id:"select",shortcut:"1",label:k("canvas.toolbar.select"),icon:Wn},{id:"pen",shortcut:"2",label:k("canvas.toolbar.pen"),icon:Hn},{id:"box",shortcut:"3",label:k("canvas.toolbar.box"),icon:Fn},{id:"arrow",shortcut:"4",label:k("canvas.toolbar.arrow"),icon:Vn},{id:"memo",shortcut:"5",label:k("canvas.toolbar.memo"),icon:Kn}];c.useEffect(()=>{if(!H)return;const oe=we=>{U.current?.contains(we.target)||ee(!1)};return window.addEventListener("pointerdown",oe),()=>window.removeEventListener("pointerdown",oe)},[H]);const he=oe=>{l?.(oe),a("eraser"),ee(!1)};return o.jsxs("div",{className:"canvas-toolbar","aria-label":k("canvas.toolbar.label"),children:[o.jsx($n,{tools:V,activeTool:e,onToolChange:a}),o.jsx(On,{style:s,onStyleChange:d}),o.jsxs("div",{ref:U,className:`canvas-toolbar__split-button${e==="eraser"?" canvas-toolbar__split-button--active":""}`,onKeyDown:oe=>{oe.key==="Escape"&&H&&(oe.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":`${z} (6)`,"aria-pressed":e==="eraser",title:`${z} (6)`,children:[o.jsx(zn,{}),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(oe=>!oe),"aria-label":k("canvas.toolbar.eraserMenu"),"aria-haspopup":"menu","aria-expanded":H,"aria-controls":"canvas-eraser-menu",title:k("canvas.toolbar.eraserMenu"),children:o.jsx(Xn,{})}),H?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:()=>he("object"),children:k("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:()=>he("brush"),children:k("canvas.toolbar.brushEraser")})]}):null]}),o.jsx("span",{className:"canvas-toolbar__divider","aria-hidden":"true"}),i?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--primary${M?" canvas-toolbar__button--busy":""}`,onClick:i,disabled:!te||M,"aria-label":k("canvas.toolbar.apply"),title:k("canvas.toolbar.apply"),children:o.jsx(qn,{})}):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:!p||C,"aria-label":k(p?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),title:k(p?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),children:o.jsx(Jn,{})}):null,f?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:f,disabled:!B,"aria-label":k("canvas.toolbar.undo"),title:k("canvas.toolbar.undo"),children:o.jsx(Gn,{})}):null,_?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:_,disabled:!A,"aria-label":k("canvas.toolbar.redo"),title:k("canvas.toolbar.redo"),children:o.jsx(Zn,{})}):null,O?o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:O,disabled:T===0,"aria-label":k("canvas.toolbar.deleteSelected"),title:k("canvas.toolbar.deleteSelected"),children:o.jsx(gt,{})}):null,b&&R&&$?o.jsx(Nn,{mode:v,matteColor:X,onModeChange:R,onMatteColorChange:$}):null,g&&D&&J&&de&&ce&&G&&Q&&Z&&K?o.jsx(Rn,{seedCount:E,tolerance:x,stats:S,hasPreview:P,isPickingSeed:Y,intent:ae,tool:re,brushRadius:le,isPreviewing:I,isApplying:F,keepOpen:ne,disabled:M||y,onAutoSample:g,onPickSeed:D,onIntentChange:J,onToolChange:de,onBrushRadiusChange:ce,onToleranceChange:G,onPreview:Q,onApply:Z,onReset:K}):null,b?o.jsx("button",{type:"button",className:`canvas-toolbar__button${y?" canvas-toolbar__button--busy":""}`,onClick:b,disabled:!te||y,"aria-label":k("canvas.toolbar.export"),title:k("canvas.toolbar.export"),children:o.jsx(Yn,{})}):null,o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:u,disabled:!te,"aria-label":k("canvas.toolbar.clear"),title:k("canvas.toolbar.clear"),children:o.jsx(gt,{})})]})}function Wn(){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 Hn(){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 Fn(){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 Vn(){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 Kn(){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 zn(){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 Xn(){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 qn(){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 Yn(){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 Gn(){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 Zn(){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 Jn(){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 Qn({annotations:e,backgroundCleanup:t,backgroundCleanupPreview:n,canvasState:a,actions:r}){return o.jsx(Un,{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 ea({currentImage:e,canvasDisplayImage:t,canvasOpen:n,displayQuality:a,displaySize:r,displayModel:l,onAfterDeleteFocus:s,onCopyPrompt:d}){const{t:u}=ke(),i=[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?u("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,a,r,l,e.provider??null].filter(b=>!!b).join(" · ");return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"result-meta",children:i}),o.jsx(an,{imageOverride:n?t:null,onAfterDeleteFocus:s}),e.prompt?o.jsx("div",{className:"result-prompt",onClick:d,children:e.prompt}):null]})}function ta({zoom:e,onZoomIn:t,onZoomOut:n,onZoomReset:a}){const{t:r}=ke(),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(na,{})}),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(aa,{})})]})}function na(){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 aa(){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 ra({zoom:e,closeLabel:t,blankCanvasLabel:n,blankCanvasAriaLabel:a,blankCanvasShortcut:r,blankCanvasBusy:l,shortcutHint:s,onZoomIn:d,onZoomOut:u,onZoomReset:i,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(ta,{zoom:e,onZoomIn:d,onZoomOut:u,onZoomReset:i}),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 oa({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 sa({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:oa({zoom:t,panX:n,panY:a}),"aria-hidden":"true"})]})}const la=`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`,ca=`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 ia(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function ua(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function da(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 ct(e,t){return!e.canvasVersion||e.prompt||!t?.prompt?e:{...e,prompt:t.prompt}}function ha(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?ct(n,t):null}function fa(e,t){if(rn(e)){const n=e.images[0];if(!n)throw new Error("edit_empty_response");return{...n,prompt:t,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,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 pa(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 d=s.getImageData(0,0,a,r).data;for(let u=3;u<d.length;u+=4)if(d[u]<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 ma(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 xt(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 va(e,t){ma(e,t);for(let n=0;n<e.data.length;n+=1)(t.data[n]??0)>0&&(e.data[n]=0)}function Be(e,t){if(!e)return null;const n=rt(e);return t&&va(n,t),n}function ba(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}function Re(e){return Math.min(1,Math.max(0,e))}function ga(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("mask_blob_unavailable"))},"image/png")})}async function xa(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=Re(l.x)*t,d=Re(l.y)*n,u=Re(l.width)*t,i=Re(l.height)*n;u>0&&i>0&&r.fillRect(s,d,u,i)}return ga(a)}async function ya(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 it(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 ut=[{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}],ka=1024;function Ca(e){return Math.max(0,Math.min(255,Math.round(e)))}function Nt(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 wa(e,t){return(t.length>0?t:ut).map(a=>{const r=Nt(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 _a(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 je(e,t,n,a,r,l,s){if(e<0||e>=a.length||a[e])return r;const d=e*4;return(t.data[d+3]??0)===0?(a[e]=1,r):_a(t.data,d,l,s)?(a[e]=1,n[r]=e,r+1):r}function et(){return ut.map(e=>({...e}))}function yt(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,d=new Uint8Array(s),u=new Int32Array(s),i=wa(t,n),b=Ca(a);let f=0;for(const _ of n.length>0?n:ut)f=je(Nt(_,r,l),t,u,d,f,i,b);for(;f>0;){const _=u[--f];e.data[_]=255;const B=_%r;B>0&&(f=je(_-1,t,u,d,f,i,b)),B<r-1&&(f=je(_+1,t,u,d,f,i,b)),_>=r&&(f=je(_-r,t,u,d,f,i,b)),_<s-r&&(f=je(_+r,t,u,d,f,i,b))}}function Ma(e,t){const n=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),a=ba(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 Rt(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("background_cleanup_blob_failed"))},"image/png")})}function Lt(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)),d=document.createElement("canvas");d.width=l,d.height=s;const u=d.getContext("2d",{willReadFrequently:!0});if(!u)throw new Error("background_cleanup_context_failed");return u.drawImage(e,0,0,l,s),{canvas:d,context:u,width:l,height:s}}async function kt({imageElement:e,mask:t}){try{const{canvas:n,context:a,width:r,height:l}=Lt(e),s=a.getImageData(0,0,r,l),d=Ma({width:r,height:l,data:s.data},t),u=a.createImageData(r,l);u.data.set(d.imageData.data),a.putImageData(u,0,0);const i=await Rt(n);return{blob:i,dataUrl:await it(i),stats:d.stats}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}async function Ea({imageElement:e,mask:t}){try{const{width:n,height:a}=Lt(e,ka),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 d=0;for(let i=0;i<a;i+=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(i/a*t.height));if((t.data[_*t.width+f]??0)===0)continue;const B=(i*n+b)*4;s.data[B]=168,s.data[B+1]=85,s.data[B+2]=247,s.data[B+3]=150,d+=1}l.putImageData(s,0,0);const u=await Rt(r);return{dataUrl:await it(u),stats:{width:t.width,height:t.height,removedPixels:t.data.reduce((i,b)=>i+(b>0?1:0),0),removedPercent:t.data.length>0?d/(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 Sa(){return`cleanup_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function Le(e){return Math.max(0,Math.min(1,e))}function Ba(e){const t=[],n=Math.max(0,e.radius*.55);for(const a of e.points)t.push({...a}),!(n<=0)&&t.push({x:Le(a.x-n),y:a.y},{x:Le(a.x+n),y:a.y},{x:a.x,y:Le(a.y-n)},{x:a.x,y:Le(a.y+n)});return t}function ja(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 Ta({canvasOpen:e,currentImage:t,canvasDisplayImage:n,imageElementRef:a,canvasSourceImageRef:r,lastMergedDataUrlRef:l,setCanvasSaveState:s,setCanvasVersionItem:d,applyMergedCanvasImage:u,attachCanvasVersionReference:i,showToast:b,t:f}){const[_,B]=c.useState(!1),[A,O]=c.useState("remove"),[T,N]=c.useState("click"),[p,C]=c.useState("flat-flood-fill"),[M,y]=c.useState([]),[v,X]=c.useState([]),[R,$]=c.useState(28),[x,E]=c.useState(null),[S,P]=c.useState(null),[Y,ne]=c.useState(null),[ae,re]=c.useState(!1),[le,I]=c.useState(.018),[F,g]=c.useState(null),[D,J]=c.useState(!1),[de,ce]=c.useState(!1),G=c.useRef(null),Q=c.useRef(null),Z=c.useRef(null),K=c.useRef({past:[],future:[]}),k=c.useRef(0),H=c.useRef(null),ee=c.useCallback(()=>Ct({intent:A,tool:T,engine:p,seeds:M,brushStrokes:v,brushRadius:le,tolerance:R,removeMask:G.current,preserveMask:Q.current,preview:x,maskOverlay:S,stats:Y,active:ae,brushCursor:F}),[v,S,x,M,Y,R,F,le,p,A,T,ae]),U=c.useCallback(()=>{K.current={past:[...K.current.past.slice(-19),ee()],future:[]}},[ee]),te=c.useCallback(w=>{const m=Ct(w);G.current=m.removeMask,Q.current=m.preserveMask,Z.current=null,O(m.intent),N(m.tool),C(m.engine),y(m.seeds),X(m.brushStrokes),I(m.brushRadius),$(m.tolerance),E(m.preview),P(m.maskOverlay),ne(m.stats),re(m.active),g(m.brushCursor),J(!1),ce(!1)},[]),z=c.useCallback(async()=>{if(!a.current||!t)return;const w=Be(G.current,Q.current);if(!w){P(null),ne(null);return}const m=k.current+1;k.current=m,J(!0);try{const L=await Ea({imageElement:a.current,mask:w});if(k.current!==m)return;P(L),ne(L.stats)}catch{if(k.current!==m)return;b(f("canvas.toolbar.cleanupFailed"),!0)}finally{k.current===m&&J(!1)}},[t,a,b,f]),V=c.useCallback(async(w,m,L)=>{if(!a.current)return;const q=ja(a.current),ie=xt(q.width,q.height),Ce=xt(q.width,q.height);for(const be of w){const _e=be.intent==="remove"?ie:Ce;yt(_e,q,[be.point],L)}for(const be of m){const _e=be.intent==="remove"?ie:Ce;yt(_e,q,Ba(be),L)}G.current=ie,Q.current=Ce},[a]),he=c.useCallback(()=>{k.current+=1,H.current!=null&&(window.clearTimeout(H.current),H.current=null),G.current=null,Q.current=null,Z.current=null,K.current={past:[],future:[]},y([]),X([]),E(null),P(null),ne(null),re(!1),g(null),J(!1),ce(!1)},[]),oe=c.useCallback(()=>{const w=K.current.past.pop();return w?(K.current.future=[ee(),...K.current.future.slice(0,19)],te(w),!0):!1},[ee,te]),we=c.useCallback(()=>{const w=K.current.future.shift();return w?(K.current.past=[...K.current.past.slice(-19),ee()],te(w),!0):!1},[ee,te]),De=c.useCallback(w=>{U();const m=[...M,{point:w,intent:A}];y(m),E(null),V(m,v,R).then(z)},[v,M,R,A,U,V,z]),$e=c.useCallback(()=>{U();const w=et().map(m=>({point:m,intent:"remove"}));y(w),E(null),re(!1),V(w,v,R).then(z)},[v,R,U,V,z]),Ue=c.useCallback(()=>{U(),N("click"),re(w=>!w)},[U]),W=c.useCallback(w=>{U(),H.current!=null&&window.clearTimeout(H.current),$(w),E(null),H.current=window.setTimeout(()=>{H.current=null,V(M,v,w).then(z)},180)},[v,M,U,V,z]),We=c.useCallback(async()=>{if(!a.current||!t)return null;let w=Be(G.current,Q.current);if(!w){const L=et().map(q=>({point:q,intent:"remove"}));y(L),await V(L,v,R),w=Be(G.current,Q.current)}if(!w)return null;U();const m=k.current+1;k.current=m,J(!0);try{const L=await kt({imageElement:a.current,mask:w});return k.current!==m?null:(E(L),P(null),ne(L.stats),L)}catch{return k.current!==m||b(f("canvas.toolbar.cleanupFailed"),!0),null}finally{k.current===m&&J(!1)}},[v,R,t,a,U,V,b,f]),He=c.useCallback(()=>{U(),he()},[U,he]),Fe=c.useCallback(w=>{U();const m={id:Sa(),intent:A,points:[{...w}],radius:le};Z.current=m,g(w),X(L=>[...L,m])},[le,A,U]),Ve=c.useCallback(w=>{const m=Z.current;if(!m){g(w);return}m.points=[...m.points,{...w}],g(w),X(L=>L.map(q=>q.id===m.id?{...m,points:m.points.map(ie=>({...ie}))}:q)),V(M,v.map(L=>L.id===m.id?m:L),R).then(z)},[v,M,R,V,z]),ve=c.useCallback(()=>{Z.current=null,V(M,v,R).then(z)},[v,M,R,V,z]),fe=c.useCallback(async()=>{if(!t||!a.current)return;const w=r.current??t;if(!w?.filename){b(f("canvas.toolbar.cleanupFailed"),!0);return}let m=Be(G.current,Q.current);if(!m){const L=et().map(q=>({point:q,intent:"remove"}));y(L),await V(L,v,R),m=Be(G.current,Q.current)}if(m){ce(!0),s("saving");try{U();const L=await kt({imageElement:a.current,mask:m}),q=await St({sourceFilename:w.canvasSourceFilename??w.filename,image:L.blob,prompt:w.prompt}),ie=ct(q.item,w);l.current=L.dataUrl,d(ie),u(ie),await i(ie),s("saved"),E(null),P(null),ne(L.stats),re(!1),b(f("canvas.toolbar.cleanupApplied"))}catch{s("error"),b(f("canvas.toolbar.cleanupFailed"),!0)}finally{ce(!1)}}},[u,i,v,R,r,t,a,l,U,V,s,d,b,f]),ue=c.useCallback(()=>ae?(Z.current=null,re(!1),g(null),!0):!1,[ae]);return c.useEffect(()=>{const w=a.current;if(!w||!e){B(!1);return}const m=()=>B(pa(w));if(w.complete)m();else return w.addEventListener("load",m),()=>w.removeEventListener("load",m)},[e,n?.canvasMergedAt,n?.filename,n?.image,n?.url,x?.dataUrl,a]),{imageHasAlpha:_,backgroundCleanupSeeds:M,backgroundCleanupBrushStrokes:v,backgroundCleanupTolerance:R,backgroundCleanupPreview:x,backgroundCleanupMaskOverlay:S,backgroundCleanupStats:Y,cleanupIntent:A,setCleanupIntent:O,cleanupTool:T,setCleanupTool:N,cleanupClickEngine:p,setCleanupClickEngine:C,cleanupBrushRadius:le,setCleanupBrushRadius:I,cleanupBrushCursor:F,setCleanupBrushCursor:g,isBackgroundCleanupActive:ae,setIsBackgroundCleanupActive:re,isBackgroundCleanupPickingSeed:ae&&T==="click",isBackgroundCleanupPreviewing:D,isBackgroundCleanupApplying:de,hasActiveCleanupStroke:!!Z.current,canUndoBackgroundCleanup:K.current.past.length>0,canRedoBackgroundCleanup:K.current.future.length>0,resetBackgroundCleanup:he,undoBackgroundCleanup:oe,redoBackgroundCleanup:we,addBackgroundCleanupClick:De,addBackgroundCleanupSeed:De,runBackgroundCleanupPreview:We,handleBackgroundCleanupAutoSample:$e,handleBackgroundCleanupPickSeed:Ue,handleBackgroundCleanupToleranceChange:W,handleBackgroundCleanupReset:He,handleBackgroundCleanupApply:fe,handleBackgroundCleanupEscape:ue,startBackgroundCleanupBrushStroke:Fe,updateBackgroundCleanupBrushStroke:Ve,endBackgroundCleanupBrushStroke:ve}}function wt(e){return Math.min(1,Math.max(0,e))}function _t(e,t){const n=t.getBoundingClientRect();return{x:wt((e.clientX-n.left)/n.width),y:wt((e.clientY-n.top)/n.height)}}const Pa=.18,Da=.12;function Aa(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 Ot(e){return{id:e.id,x:e.x,y:e.y,width:Pa,height:Da,color:e.color,strokeWidth:1}}function Ia(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,d=a*a+r*r;if(d===0)return Math.hypot(e.x-t.x,e.y-t.y);const u=Math.max(0,Math.min(1,(l*a+s*r)/d));return Math.hypot(e.x-(t.x+u*a),e.y-(t.y+u*r))}function Na(e,t,n){for(let a=1;a<t.points.length;a+=1)if(Ia(e,t.points[a-1],t.points[a])<=n)return!0;return!1}function Mt(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 Ra(e,t){return e.points.some(n=>ot(n,t))}function Et(e){const t=e.tolerance??.015;for(const n of[...e.memos].reverse())if(ot(e.point,Ot(n),t))return Pt(n);for(const n of[...e.boxes].reverse())if(ot(e.point,n,t))return Tt(n);for(const n of[...e.paths].reverse())if(Na(e.point,n,t))return jt(n);return null}function La(e){const t=[];for(const n of e.annotations.paths)Ra(n,e.box)&&t.push(jt(n));for(const n of e.annotations.boxes)Mt(n,e.box)&&t.push(Tt(n));for(const n of e.annotations.memos)Mt(Ot(n),e.box)&&t.push(Pt(n));return t}function Oa({canvasOpen:e,canvasZoom:t,canvasPanX:n,canvasPanY:a,spaceHeld:r,canDragViewportWithSelect:l,isBackgroundCleanupActive:s,cleanupTool:d,annotationFrameRef:u,annotations:i,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}),[p,C]=c.useState(!1),M=x=>{x.currentTarget.setPointerCapture(x.pointerId),N.current={active:!0,startX:x.clientX,startY:x.clientY,basePanX:n,basePanY:a,pointerId:x.pointerId},C(!0)};return{viewportPanActive:p,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:x=>{if(!e||me(x.target)||!u.current)return;const E=x.button===1;if(r||E){x.preventDefault(),M(x);return}x.preventDefault();const S=_t(x,u.current);if(s){d==="click"?f(S):(x.currentTarget.setPointerCapture(x.pointerId),_(S));return}if(i.activeTool==="select"){const P=Et({point:S,paths:i.paths,boxes:i.boxes,memos:i.memos});if(P)x.shiftKey?i.toggleSelected(P):i.selectOne(P),i.startSelectedMove(),T.current={mode:"move",lastPoint:S,didMove:!1};else if(l&&t>1.01){M(x);return}else i.clearSelection(),i.startSelectionBox(S),T.current={mode:"box",lastPoint:S,didMove:!1};x.currentTarget.setPointerCapture(x.pointerId);return}if(i.activeTool==="memo"){i.createMemo(S),requestAnimationFrame(()=>{u.current?.querySelector(".canvas-memo--active")?.focus()});return}if(i.activeTool==="eraser"){if(i.eraserMode==="object"){const P=Et({point:S,paths:i.paths,boxes:i.boxes,memos:i.memos});P&&i.eraseObjectAtPoint(P);return}x.currentTarget.setPointerCapture(x.pointerId),i.startEraserStroke(S);return}x.currentTarget.setPointerCapture(x.pointerId),i.startDrawing(S)},handleAnnotationPointerMove:x=>{if(!e||me(x.target)||!u.current)return;if(N.current.active){const S=x.clientX-N.current.startX,P=x.clientY-N.current.startY;b(N.current.basePanX+S,N.current.basePanY+P);return}const E=_t(x,u.current);if(s){d==="brush"?B(E):O(E);return}if(i.activeTool==="select"){if(T.current.mode==="move"&&T.current.lastPoint){const S={x:E.x-T.current.lastPoint.x,y:E.y-T.current.lastPoint.y};(Math.abs(S.x)>5e-4||Math.abs(S.y)>5e-4)&&(i.moveSelected(S),T.current.didMove=!0),T.current.lastPoint=E}else T.current.mode==="box"&&i.updateSelectionBox(E);return}if(i.activeTool!=="memo"){if(i.activeTool==="eraser"){i.eraserMode==="brush"&&i.updateEraserStroke(E);return}i.moveDrawing(E)}},handleAnnotationPointerUp:x=>{if(e&&!me(x.target)){if(N.current.active&&N.current.pointerId===x.pointerId){x.currentTarget.hasPointerCapture(x.pointerId)&&x.currentTarget.releasePointerCapture(x.pointerId),N.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},C(!1);return}if(x.currentTarget.hasPointerCapture(x.pointerId)&&x.currentTarget.releasePointerCapture(x.pointerId),s){d==="brush"&&A();return}if(i.activeTool==="select"){T.current.mode==="move"&&T.current.didMove&&i.commitSelectedMove(),T.current.mode==="box"&&i.selectionBox&&i.endSelectionBox(La({box:Aa(i.selectionBox),annotations:i.toPayload()})),T.current={mode:null,lastPoint:null,didMove:!1};return}if(i.activeTool!=="memo"){if(i.activeTool==="eraser"){i.eraserMode==="brush"&&i.endEraserStroke();return}i.endDrawing()}}},handleAnnotationPointerLeave:()=>{s&&O(null)}}}function $a({canvasOpen:e,canvasZoom:t,currentImage:n,annotations:a,undoBackgroundCleanup:r,redoBackgroundCleanup:l,handleBackgroundCleanupEscape:s,handleCloseCanvas:d,selectHistoryShortcutTarget:u,trashHistoryItem:i,permanentlyDeleteHistoryItemByShortcut:b,setCanvasZoom:f,resetCanvasZoom:_,onCreateBlankCanvas:B,isCreatingBlankCanvas:A}){const[O,T]=c.useState(!1);return c.useEffect(()=>{if(!e)return;const p=v=>{v.preventDefault()},C=v=>{v.ctrlKey&&v.preventDefault()},M={passive:!1,capture:!0},y={passive:!1};return window.addEventListener("wheel",C,M),window.addEventListener("gesturestart",p,y),window.addEventListener("gesturechange",p,y),window.addEventListener("gestureend",p,y),()=>{window.removeEventListener("wheel",C,M),window.removeEventListener("gesturestart",p,y),window.removeEventListener("gesturechange",p,y),window.removeEventListener("gestureend",p,y)}},[e]),c.useEffect(()=>{if(!e)return;const p=M=>{M.code==="Space"&&(me(M.target)||(O||T(!0),M.preventDefault()))},C=M=>{M.code==="Space"&&T(!1)};return window.addEventListener("keydown",p),window.addEventListener("keyup",C),()=>{window.removeEventListener("keydown",p),window.removeEventListener("keyup",C)}},[e,O]),c.useEffect(()=>{if(!e)return;const p=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;d();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",p),()=>window.removeEventListener("keydown",p)},[a,a.focusMemo,a.redo,a.undo,e,d,s,A,B,l,r]),{spaceHeld:O,handleViewerKeyDown:p=>{if(me(p.target)){p.key==="Escape"&&(p.preventDefault(),p.target.blur(),a.focusMemo(null));return}if(e&&["1","2","3","4","5","6"].includes(p.key)){p.preventDefault();const C=["select","pen","box","arrow","memo","eraser"];a.setTool(C[Number(p.key)-1]);return}if(e&&p.key==="Escape"){if(p.preventDefault(),p.stopPropagation(),s())return;d();return}if(e&&p.key==="]"){p.preventDefault(),f(t+.1);return}if(e&&p.key==="["){p.preventDefault(),f(t-.1);return}if(e&&p.key==="0"){p.preventDefault(),_();return}if(p.key==="Delete"||p.key==="Backspace"){if(!n||p.target!==p.currentTarget)return;if(p.preventDefault(),p.shiftKey){b(n);return}i(n);return}p.key!=="ArrowLeft"&&p.key!=="ArrowRight"&&p.key!=="Home"&&p.key!=="End"||p.target===p.currentTarget&&(me(p.target)||(p.preventDefault(),p.key==="ArrowLeft"?u("previous"):p.key==="ArrowRight"?u("next"):p.key==="Home"?u("first"):p.key==="End"&&u("last")))}}}function Ua(e,t){return new Promise((n,a)=>{e.toBlob(r=>{if(r){n(r);return}a(new Error("canvas_blob_unavailable"))},t)})}async function $t(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)_n(n,l,a);return{blob:await Ua(t,"image/png"),dataUrl:t.toDataURL("image/png")}}async function Wa(e){return(await $t(e)).blob}function Ha(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 Fa(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 Va({imageElementRef:e,currentImage:t,canvasDisplayImage:n,canvasSourceImageRef:a,lastMergedDataUrlRef:r,canvasVersionItem:l,annotations:s,exportBackground:d,exportMatteColor:u,quality:i,format:b,moderation:f,provider:_,imageModel:B,reasoningEffort:A,promptMode:O,webSearchEnabled:T,getResolvedSize:N,setCanvasVersionItem:p,setCanvasSaveState:C,setIsApplying:M,setIsExporting:y,setIsEditingWithMask:v,applyMergedCanvasImage:X,addGeneratedHistoryItem:R,attachCanvasVersionReference:$,closeCanvas:x,resetCanvasSession:E,showToast:S,t:P}){const Y=c.useCallback(async()=>{if(!e.current||!t)return null;const I=a.current??t;if(!I?.filename)return S(P("canvas.version.failed"),!0),null;M(!0),C("saving");try{const F=await $t({imageElement:e.current,paths:s.paths,boxes:s.boxes,memos:s.memos});r.current=F.dataUrl;const g=l?.filename?await on(l.filename,{image:F.blob,sourceFilename:I.canvasSourceFilename??I.filename,prompt:I.prompt}):await St({sourceFilename:I.filename,image:F.blob,prompt:I.prompt}),D=ct(g.item,I);return p(D),X(D),await $(D),await Bt(I.filename).catch(()=>{}),s.resetLocal(),s.markSaved(),C("saved"),S(P("canvas.version.saved")),D}catch{return C("error"),S(P("canvas.version.failed"),!0),null}finally{M(!1)}},[s,X,$,a,l?.filename,t,e,r,C,p,M,S,P]);return{saveCanvasVersionAndUseReference:Y,handleApplyCanvas:async()=>{await Y()},handleCloseCanvas:async()=>{(s.hasAnnotations||s.isDirty)&&!await Y()||(x(),E())},handleExportCanvas:async()=>{if(!(!e.current||!t)){y(!0);try{const I=d==="matte",F=await Wa({imageElement:e.current,paths:s.paths,boxes:s.boxes,memos:s.memos,background:I?{mode:"matte",color:u}:{mode:"alpha"}});Fa(F,Ha({matte:I}))}catch{S(P("canvas.toolbar.exportFailed"),!0)}finally{y(!1)}}},handleEditWithMask:async()=>{if(!(!e.current||!n||s.boxes.length===0)){v(!0);try{let I=r.current;if(s.isDirty||s.hasAnnotations){if(!await Y())return;I=r.current}I||(I=await ya(e.current));const F=s.boxes.filter(de=>s.selectedIds.some(ce=>pe(ce,"box",de.id))),g=await xa({imageElement:e.current,boxes:F.length>0?F:s.boxes}),D=n.prompt??t?.prompt??"";if(!D.trim()){S(P("toast.noPromptToFork"),!0);return}const J=await sn({image:I,mask:await it(g),prompt:D,quality:i,size:n.size??t?.size??N(),format:b,moderation:f,provider:_,n:1,model:B,reasoningEffort:A,mode:O,webSearchEnabled:T});await R(fa(J,D))}catch(I){const F=I.code;S(P(F==="EDIT_MASK_NOT_SUPPORTED"?"canvas.toolbar.editMaskUnsupported":"canvas.toolbar.editMaskFailed"),!0)}finally{v(!1)}}}}}function za(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 se=h.multimodePreviewFlightId;return se?h.multimodeSequences[se]??null:null}),d=j(h=>h.selectHistoryShortcutTarget),u=j(h=>h.trashHistoryItem),i=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),p=j(h=>h.promptMode),C=j(h=>h.webSearchEnabled),M=j(h=>h.getResolvedSize),y=j(h=>h.showToast),v=j(h=>h.canvasOpen),X=j(h=>h.openCanvas),R=j(h=>h.closeCanvas),$=j(h=>h.canvasZoom),x=j(h=>h.canvasPanX),E=j(h=>h.canvasPanY),S=j(h=>h.setCanvasPan),P=j(h=>h.setCanvasZoom),Y=j(h=>h.resetCanvasZoom),ne=j(h=>h.canvasExportBackground),ae=j(h=>h.canvasExportMatteColor),re=j(h=>h.setCanvasExportBackground),le=j(h=>h.setCanvasExportMatteColor),I=j(h=>h.applyMergedCanvasImage),F=j(h=>h.addGeneratedHistoryItem),g=j(h=>h.attachCanvasVersionReference),{t:D}=ke(),{creatingBlankCanvas:J,createBlankCanvas:de}=ln(),ce=c.useRef(null),G=c.useRef(null),Q=c.useRef(null),Z=c.useRef(null),K=c.useRef(null),k=c.useRef(null),H=c.useRef(null),ee=c.useRef(null),[U,te]=c.useState(null),[z,V]=c.useState("idle"),[he,oe]=c.useState(!1),[we,De]=c.useState(!1),[$e,Ue]=c.useState(!1),W=wn(),We=()=>{t?.prompt&&(navigator.clipboard.writeText(t.prompt),y(D("toast.promptCopied")))},He=ia(t?.quality??_),Fe=ua(t?.size??M()),Ve=cn(t?.model),ve=t?.filename??t?.url??t?.image??null,fe=ha(n,t),ue=v?U??fe??t:t,w=ue?da(ue):null,m=Ta({canvasOpen:v,currentImage:t,canvasDisplayImage:ue,imageElementRef:G,canvasSourceImageRef:H,lastMergedDataUrlRef:ee,setCanvasSaveState:V,setCanvasVersionItem:te,applyMergedCanvasImage:I,attachCanvasVersionReference:g,showToast:y,t:D}),{imageHasAlpha:L,backgroundCleanupSeeds:q,backgroundCleanupPreview:ie,backgroundCleanupMaskOverlay:Ce,backgroundCleanupBrushStrokes:be,cleanupTool:_e,cleanupBrushRadius:Ut,cleanupBrushCursor:Wt,isBackgroundCleanupActive:Me}=m,Ke=m.backgroundCleanupPreview?.dataUrl??w,ze=()=>{H.current=null,K.current=null,k.current!=null&&(window.clearTimeout(k.current),k.current=null),te(null),V("idle"),m.resetBackgroundCleanup(),ee.current=null,Jt()};c.useEffect(()=>{if(!v){Z.current=ve,ze();return}if(Z.current===null){Z.current=ve,H.current=t,te(fe);return}Z.current!==ve&&(W.resetLocal(),ze(),H.current=t,te(fe),Z.current=ve)},[W.resetLocal,v,t,ve,fe]),c.useEffect(()=>{!v||!t||H.current||(H.current=t,te(fe))},[v,t,fe]),c.useEffect(()=>{if(!v||!t?.filename||t.canvasVersion)return;const h=t.filename;if(K.current===h)return;K.current=h;let se=!1;return un(h).then(Ee=>{!se&&Ee.annotations&&W.load(Ee.annotations)}).catch(()=>{}),()=>{se=!0}},[W.load,v,t?.canvasVersion,t?.filename]),c.useEffect(()=>{if(!v||!t?.filename||t.canvasVersion||!W.isDirty)return;const h=t.filename;return k.current!=null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{const se=W.toPayload();(W.hasAnnotations?dn(h,se):Bt(h)).then(()=>W.markSaved()).catch(()=>{})},500),()=>{k.current!=null&&(window.clearTimeout(k.current),k.current=null)}},[W,W.hasAnnotations,W.isDirty,v,t?.canvasVersion,t?.filename]);const Ht=h=>{me(h.target)||(b(),h.currentTarget.focus())},Ft=c.useCallback(()=>{window.requestAnimationFrame(()=>Q.current?.focus())},[]),Vt=h=>{if(v){if(h.preventDefault(),h.ctrlKey){P($-h.deltaY*.01);return}S(x-h.deltaX,E-h.deltaY)}},Kt=c.useCallback(h=>{Array.from(h.dataTransfer.types).includes("Files")&&(h.preventDefault(),l(se=>se||!0))},[]),zt=c.useCallback(h=>{h.currentTarget.contains(h.relatedTarget)||l(!1)},[]),Xt=c.useCallback(async h=>{if(!Array.from(h.dataTransfer.types).includes("Files"))return;h.preventDefault(),l(!1);const se=Array.from(h.dataTransfer.files).filter(Ee=>/^image\/(png|jpeg|webp)$/.test(Ee.type));se.length!==0&&await a(se[0])},[a]),{handleApplyCanvas:qt,handleCloseCanvas:dt,handleExportCanvas:Yt,handleEditWithMask:Gt}=Va({imageElementRef:G,currentImage:t,canvasDisplayImage:ue,canvasSourceImageRef:H,lastMergedDataUrlRef:ee,canvasVersionItem:U,annotations:W,exportBackground:ne,exportMatteColor:ae,quality:_,format:B,moderation:A,provider:O,imageModel:T,reasoningEffort:N,promptMode:p,webSearchEnabled:C,getResolvedSize:M,setCanvasVersionItem:te,setCanvasSaveState:V,setIsApplying:oe,setIsExporting:De,setIsEditingWithMask:Ue,applyMergedCanvasImage:I,addGeneratedHistoryItem:F,attachCanvasVersionReference:g,closeCanvas:R,resetCanvasSession:ze,showToast:y,t:D}),{spaceHeld:Xe,handleViewerKeyDown:Zt}=$a({canvasOpen:v,canvasZoom:$,currentImage:t,annotations:W,undoBackgroundCleanup:m.undoBackgroundCleanup,redoBackgroundCleanup:m.redoBackgroundCleanup,handleBackgroundCleanupEscape:m.handleBackgroundCleanupEscape,handleCloseCanvas:dt,selectHistoryShortcutTarget:d,trashHistoryItem:u,permanentlyDeleteHistoryItemByShortcut:i,setCanvasZoom:P,resetCanvasZoom:Y,onCreateBlankCanvas:de,isCreatingBlankCanvas:J}),qe=v&&$>1.01&&W.activeTool==="select"&&!Me,{viewportPanActive:Ye,resetPointerSession:Jt,handleAnnotationPointerDown:Qt,handleAnnotationPointerMove:en,handleAnnotationPointerUp:tn,handleAnnotationPointerLeave:nn}=Oa({canvasOpen:v,canvasZoom:$,canvasPanX:x,canvasPanY:E,spaceHeld:Xe,canDragViewportWithSelect:qe,isBackgroundCleanupActive:Me,cleanupTool:_e,annotationFrameRef:ce,annotations:W,setCanvasPan:S,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:Kt,onDragLeave:zt,onDrop:Xt,children:[r?o.jsx("div",{className:"canvas__drop-overlay","aria-hidden":!0,children:o.jsx("span",{className:"canvas__drop-hint",children:D("canvas.drop.hint")})}):null,v&&o.jsx(ra,{zoom:$,closeLabel:D("canvas.close"),blankCanvasLabel:D("canvas.blank.title"),blankCanvasAriaLabel:`${D(J?"canvas.blank.creating":"canvas.blank.create")} (Shift+B)`,blankCanvasShortcut:"Shift+B",blankCanvasBusy:J,shortcutHint:D("canvas.toolbar.zoomShortcutHint"),onZoomIn:()=>P($+.1),onZoomOut:()=>P($-.1),onZoomReset:Y,onCreateBlankCanvas:()=>{de()},onClose:()=>{dt()}}),o.jsx("div",{className:`progress-bar${f>0?" active":""}`}),s?o.jsx(hn,{}):t?o.jsxs("div",{ref:Q,className:"result-container visible",tabIndex:0,onMouseDown:Ht,onWheel:Vt,onKeyDown:Zt,"aria-label":D("canvas.imageViewerAria"),children:[o.jsx(Pn,{annotationFrameRef:ce,imageElementRef:G,frameClassName:`canvas-annotation-frame${(L||ie)&&v?" canvas-annotation-frame--alpha":""}${Me&&v?" canvas-annotation-frame--cleanup-picking":""}${Ce&&v?" canvas-annotation-frame--cleanup-mask":""}`,frameStyle:{cursor:Ye?"grabbing":Xe||qe?"grab":v?Me?"crosshair":W.activeTool==="select"?"default":W.activeTool==="eraser"?W.eraserMode==="object"?la:ca:"crosshair":"zoom-in",transform:v?`translate(${x}px, ${E}px) scale(${$})`:void 0,transition:v&&!Ye?"transform 0.2s ease":void 0},imageKey:`${ue?.filename??ue?.url??ue?.image}:${ue?.canvasMergedAt??""}`,imageSrc:Ke??t.image,fallbackImage:t.image,alt:D("canvas.resultAlt"),canvasOpen:v,maskOverlayUrl:Ce?.dataUrl??null,cleanupLayer:o.jsx(In,{seeds:q,brushStrokes:be,brushCursor:Wt,brushRadius:Ut,active:Me}),annotations:W,onOpenCanvas:X,onPointerDown:Qt,onPointerMove:en,onPointerUp:tn,onPointerLeave:nn}),v&&Ke?o.jsx(sa,{imageSrc:Ke,zoom:$,panX:x,panY:E,resetLabel:D("canvas.toolbar.zoomReset"),onReset:Y}):null,v&&o.jsx(Qn,{annotations:W,backgroundCleanup:m,backgroundCleanupPreview:ie,canvasState:{exportBackground:ne,exportMatteColor:ae,isApplying:he,isExporting:we,isEditingWithMask:$e},actions:{handleApplyCanvas:qt,handleExportCanvas:Yt,handleEditWithMask:Gt,setExportBackground:re,setExportMatteColor:le}}),v&&z!=="idle"?o.jsx("div",{className:`canvas-save-state canvas-save-state--${z}`,children:D(z==="saving"?"canvas.version.saving":z==="saved"?"canvas.version.saved":"canvas.version.failed")}):null,o.jsx(ea,{currentImage:t,canvasDisplayImage:ue,canvasOpen:v,displayQuality:He,displaySize:Fe,displayModel:Ve,onAfterDeleteFocus:Ft,onCopyPrompt:We})]}):null]})}export{za as CanvasModeWorkspace};