ima2-gen 3.12.2 → 3.12.3

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 (45) hide show
  1. package/bin/commands/vectorize.js +108 -0
  2. package/bin/ima2.js +5 -1
  3. package/docs/API.md +1 -1
  4. package/docs/API.zh-CN.md +1 -1
  5. package/docs/API.zh-TW.md +1 -1
  6. package/docs/CLI.md +1 -0
  7. package/docs/migration/runtime-test-inventory.md +6 -1
  8. package/lib/agentImageVideoGen.js +15 -1
  9. package/lib/agentQueueStore.js +11 -3
  10. package/lib/agentQueueWorker.js +6 -1
  11. package/lib/agentRuntime.js +4 -0
  12. package/lib/db.js +3 -0
  13. package/lib/imageThumb.js +9 -2
  14. package/lib/vectorizeImage.js +132 -0
  15. package/package.json +4 -3
  16. package/routes/assetDerived.js +79 -2
  17. package/server.js +8 -0
  18. package/skills/ima2/SKILL.md +37 -0
  19. package/ui/dist/.vite/manifest.json +33 -33
  20. package/ui/dist/assets/{AgentWorkspace-CW1x4uOl.js → AgentWorkspace-AJkVTaU5.js} +2 -2
  21. package/ui/dist/assets/AssetGenWorkspace-Cguej69V.js +2 -0
  22. package/ui/dist/assets/AssetsWorkspace-DIQ9wBuD.js +1 -0
  23. package/ui/dist/assets/{CardNewsWorkspace-nBKX5TXr.js → CardNewsWorkspace-C_Eb2g7d.js} +1 -1
  24. package/ui/dist/assets/{GenerationRequestLogPanel-CWqbfNis.js → GenerationRequestLogPanel-giH1e4hp.js} +1 -1
  25. package/ui/dist/assets/{HomeWorkspace-CxqIGhb9.js → HomeWorkspace-DHmXGtqC.js} +1 -1
  26. package/ui/dist/assets/{NodeCanvas-m41ECrFJ.js → NodeCanvas-CF_NHudI.js} +1 -1
  27. package/ui/dist/assets/{PromptBuilderPanel-ChOoMAVA.js → PromptBuilderPanel-D7NJto-1.js} +2 -2
  28. package/ui/dist/assets/{PromptImportDialog-8hDG8MeK.js → PromptImportDialog-B40X9UAa.js} +2 -2
  29. package/ui/dist/assets/{PromptImportDiscoverySection-D2_TAuLm.js → PromptImportDiscoverySection-BWoUDHj1.js} +1 -1
  30. package/ui/dist/assets/{PromptImportFolderSection-qv0qhTwq.js → PromptImportFolderSection-DBSEyJb-.js} +1 -1
  31. package/ui/dist/assets/{PromptLibraryPanel-BPOD61FZ.js → PromptLibraryPanel-DLywJBpt.js} +2 -2
  32. package/ui/dist/assets/{SettingsWorkspace-BKgXN2l9.js → SettingsWorkspace-BawWId1t.js} +1 -1
  33. package/ui/dist/assets/SpriteRecipeWorkspace-Biy2yRAk.js +1 -0
  34. package/ui/dist/assets/VectorizePanel-DdlVvwV1.js +1 -0
  35. package/ui/dist/assets/{index-Bzt4YWub.js → index-D05Ong5g.js} +3 -3
  36. package/ui/dist/assets/{index-DB9EfKr6.css → index-DGRIdnsL.css} +1 -1
  37. package/ui/dist/assets/{index-DTEhasVd.js → index-Sch70vBs.js} +17 -17
  38. package/ui/dist/assets/{pptxgen.es-BEVsR2-i.js → pptxgen.es-CSd_gCsx.js} +1 -1
  39. package/ui/dist/assets/useAgentDialogFocus-DcWwFfYd.js +1 -0
  40. package/ui/dist/index.html +2 -2
  41. package/ui/dist/assets/AssetGenWorkspace-BQkdilsH.js +0 -2
  42. package/ui/dist/assets/AssetsWorkspace-CYSkmYU-.js +0 -1
  43. package/ui/dist/assets/KeyingPanel-CtGvO6-u.js +0 -1
  44. package/ui/dist/assets/SpriteRecipeWorkspace-D8gHgnt8.js +0 -1
  45. package/ui/dist/assets/useAgentDialogFocus-Dyj_bA5Q.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pptxgen.es-BEVsR2-i.js","assets/index-DTEhasVd.js","assets/index-DB9EfKr6.css"])))=>i.map(i=>d[i]);
2
- import{a as i,j as o,u as fe,p as En,f as Sn,az as Bn,aA as jn,aB as Tn,aC as Ft,aD as Ht,aE as me,ah as Pn,aF as An,b as P,aG as Kt,aH as kt,aI as Dn,aJ as Vt,aK as Rn,c as Nn,aL as In,aM as On}from"./index-DTEhasVd.js";const Ie=2,He=1e-6;function Ln({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 c of e){const s=$n(c,t,n,a);(s.length!==1||s[0]!==c)&&(r=!0),l.push(...s)}return{paths:l,changed:r}}function $n(e,t,n,a=()=>crypto.randomUUID()){if(e.points.length<Ie||t.length===0||n<=0)return[e];const r=[];let l=Ae(e.points[0],t,n)?[]:[e.points[0]];for(let s=1;s<e.points.length;s+=1){const d=e.points[s-1],u=e.points[s],v=Ae(u,t,n),f=Un(d,u,t,n);if(f){l.length===0&&!Ae(d,t,n)&&(l=[d]),l.length>0&&f.leftT>He&&Ct(l,Re(d,u,f.leftT)),l.length>=Ie&&r.push(l),l=[],f.rightT<1-He&&!v&&(l=[Re(d,u,f.rightT),u]);continue}if(v){l.length>=Ie&&r.push(l),l=[];continue}l.length===0&&!Ae(d,t,n)&&(l=[d]),Ct(l,u)}if(l.length>=Ie&&r.push(l),r.length===0)return[];if(r.length===1&&r[0].length===e.points.length)return[e];const c=e.tool==="arrow"?r.length-1:-1;return r.map((s,d)=>({...e,id:d===0?e.id:a(),tool:e.tool==="arrow"&&d!==c?"pen":e.tool,points:s}))}function Ae(e,t,n){if(t.length===1)return ye(e,t[0])<=n;for(let a=1;a<t.length;a+=1)if(Wn(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 Un(e,t,n,a){const r=ye(e,t);if(r<=He)return Ae(e,n,a)?{leftT:0,rightT:1}:null;let l=null,c=Number.POSITIVE_INFINITY;for(const d of n){const u=_t(d,e,t),v=Re(e,t,u),f=ye(d,v);f<c&&(c=f,l=u)}for(let d=1;d<n.length;d+=1){const u=[0,.25,.5,.75,1];for(const v of u){const f=Re(n[d-1],n[d],v),_=_t(f,e,t),C=Re(e,t,_),S=ye(f,C);S<c&&(c=S,l=_)}}if(l===null||c>a)return null;const s=Math.max(a/r,.01);return{leftT:Math.max(0,l-s),rightT:Math.min(1,l+s)}}function _t(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,c=e.y-t.y,s=a*a+r*r;return s===0?0:Math.max(0,Math.min(1,(l*a+c*r)/s))}function Re(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function Ct(e,t){const n=e.at(-1);(!n||ye(n,t)>He)&&e.push(t)}function Wn(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,c=e.y-t.y,s=a*a+r*r;if(s===0)return ye(e,t);const d=Math.max(0,Math.min(1,(l*a+c*r)/s));return ye(e,{x:t.x+d*a,y:t.y+d*r})}function mt(e,t){return`${e}:${t}`}function vt(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 zt(e){return mt("path",e.id)}function qt(e){return mt("box",e.id)}function Xt(e){return mt("memo",e.id)}function pe(e,t,n){const a=vt(e);return a?.kind===t&&a.id===n}const Gt="ima2.canvas.annotationStyle.v1",Yt=["#ef4444","#f97316","#eab308","#22c55e","#38bdf8","#6366f1","#a855f7","#111827","#ffffff"],Zt=[2,3,5,8],Be={color:"#ef4444",strokeWidth:3};function Fn(){if(typeof window>"u")return Be;try{const e=window.localStorage.getItem(Gt);if(!e)return Be;const t=JSON.parse(e),n=typeof t.color=="string"&&Yt.includes(t.color)?t.color:Be.color,a=typeof t.strokeWidth=="number"&&Zt.includes(t.strokeWidth)?t.strokeWidth:Be.strokeWidth;return{color:n,strokeWidth:a}}catch{return Be}}function Hn(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Gt,JSON.stringify(e))}catch{}}const Mt=Fn(),ut={activeTool:"select",toolColor:Mt.color,strokeWidth:Mt.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 at(e,t){return{...e,past:[...e.past.slice(-49),t],future:[]}}function Kn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Et(e,t){return{...e,...t,activeMemoId:null,activePath:null,activeBox:null,selectionBox:null,selectedIds:[],isDirty:!0}}function Vn(e,t,n){const{start:a,current:r}=e,l=Math.min(a.x,r.x),c=Math.min(a.y,r.y),s=Math.abs(r.x-a.x),d=Math.abs(r.y-a.y);return s<.01||d<.01?null:{id:crypto.randomUUID(),x:l,y:c,width:s,height:d,color:t,strokeWidth:n}}function zn(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 rt(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 qn(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=Vn(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?Kn(e.memoBaseline,xe(e))?{...e,memoBaseline:null,activeMemoId:null}:{...at(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{...ut,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{...ut,activeTool:e.activeTool,eraserMode:e.eraserMode,toolColor:e.toolColor,strokeWidth:e.strokeWidth};case"UNDO":{const n=e.past.at(-1);return n?{...Et(e,n),past:e.past.slice(0,-1),future:[xe(e),...e.future]}:e}case"REDO":{const n=e.future[0];return n?{...Et(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=>rt(a,t.delta))}:n),boxes:e.boxes.map(n=>e.selectedIds.some(a=>pe(a,"box",n.id))?zn(n,t.delta):n),memos:e.memos.map(n=>e.selectedIds.some(a=>pe(a,"memo",n.id))?{...n,x:rt(n,t.delta).x,y:rt(n,t.delta).y}:n)};case"START_SELECTED_MOVE":return{...e,moveBaseline:xe(e)};case"COMMIT_SELECTED_MOVE":return e.moveBaseline?{...at(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=vt(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=Ln({paths:e.paths,points:e.activeEraserStroke.points,radius:e.activeEraserStroke.radius});return n.changed?{...at(e,e.eraserBaseline),paths:n.paths,activeEraserStroke:null,eraserBaseline:null,selectedIds:[],isDirty:!0}:{...e,activeEraserStroke:null,eraserBaseline:null}}default:return e}}function Xn(){const[e,t]=i.useReducer(qn,ut),n=i.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=i.useCallback(k=>t({type:"SET_TOOL",tool:k}),[]),c=i.useCallback(k=>{Hn(k),t({type:"SET_STYLE",style:k})},[]),s=i.useCallback(()=>t({type:"CLEAR"}),[]),d=i.useCallback(k=>t({type:"LOAD",payload:k}),[]),u=i.useCallback(()=>t({type:"MARK_SAVED"}),[]),v=i.useCallback(()=>t({type:"RESET_LOCAL"}),[]),f=i.useCallback(()=>t({type:"UNDO"}),[]),_=i.useCallback(()=>t({type:"REDO"}),[]),C=i.useCallback(()=>t({type:"COMMIT_MEMO_EDIT"}),[]),S=i.useCallback(()=>t({type:"START_SELECTED_MOVE"}),[]),U=i.useCallback(()=>t({type:"COMMIT_SELECTED_MOVE"}),[]),L=i.useCallback(k=>{e.activeTool==="pen"||e.activeTool==="arrow"?t({type:"START_PATH",point:k}):e.activeTool==="box"&&t({type:"START_BOX",point:k})},[e.activeTool]),N=i.useCallback(k=>{e.activePath?t({type:"ADD_POINT",point:k}):e.activeBox&&t({type:"UPDATE_BOX",point:k})},[e.activePath,e.activeBox]),p=i.useCallback(()=>{e.activePath?t({type:"END_PATH"}):e.activeBox&&t({type:"END_BOX"})},[e.activePath,e.activeBox]),M=i.useCallback(k=>t({type:"CREATE_MEMO",point:k}),[]),B=i.useCallback((k,z)=>t({type:"UPDATE_MEMO",id:k,text:z}),[]),x=i.useCallback(k=>t({type:"DELETE_MEMO",id:k}),[]),b=i.useCallback(k=>t({type:"FOCUS_MEMO",id:k}),[]),J=i.useCallback(k=>t({type:"SET_ERASER_MODE",mode:k}),[]),O=i.useCallback(k=>t({type:"SELECT_ONE",id:k}),[]),V=i.useCallback(k=>t({type:"TOGGLE_SELECTED",id:k}),[]),Q=i.useCallback(()=>t({type:"CLEAR_SELECTION"}),[]),m=i.useCallback(()=>t({type:"DELETE_SELECTED"}),[]),$=i.useCallback(k=>t({type:"MOVE_SELECTED",delta:k}),[]),T=i.useCallback(k=>t({type:"START_SELECTION_BOX",point:k}),[]),A=i.useCallback(k=>t({type:"UPDATE_SELECTION_BOX",point:k}),[]),D=i.useCallback(k=>t({type:"END_SELECTION_BOX",ids:k}),[]),te=i.useCallback(k=>t({type:"ERASE_OBJECT",id:k}),[]),se=i.useCallback(k=>t({type:"START_ERASER_STROKE",point:k}),[]),ie=i.useCallback(k=>t({type:"UPDATE_ERASER_STROKE",point:k}),[]),de=i.useCallback(()=>t({type:"END_ERASER_STROKE"}),[]),he=i.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:c,setEraserMode:J,startDrawing:L,moveDrawing:N,endDrawing:p,createMemo:M,updateMemo:B,commitMemoEdit:C,deleteMemo:x,focusMemo:b,clear:s,load:d,toPayload:he,markSaved:u,resetLocal:v,undo:f,redo:_,selectOne:O,toggleSelected:V,clearSelection:Q,deleteSelected:m,moveSelected:$,startSelectedMove:S,commitSelectedMove:U,startSelectionBox:T,updateSelectionBox:A,endSelectionBox:D,eraseObjectAtPoint:te,startEraserStroke:se,updateEraserStroke:ie,endEraserStroke:de}}function De(e,t){return{x:e.x*t.width,y:e.y*t.height}}function Jt(e,t,n){const a=Math.atan2(t.y-e.y,t.x-e.x),r=Math.max(12,n*4),l=Math.PI/7;return[{x:t.x,y:t.y},{x:t.x-r*Math.cos(a-l),y:t.y-r*Math.sin(a-l)},{x:t.x-r*Math.cos(a+l),y:t.y-r*Math.sin(a+l)}]}function dt(e,t,n){if(t.points.length<2)return;const a=De(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=De(r,n);e.lineTo(l.x,l.y)}if(e.stroke(),t.tool==="arrow"){const r=De(t.points[t.points.length-1],n),l=De(t.points[t.points.length-2],n);Zn(e,l,r,t.color,t.strokeWidth)}e.restore()}function ht(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 Gn(e,t,n){const a=t.x*n.width,r=t.y*n.height,l=Math.min(260,Math.max(150,n.width*.22)),c=12,s=18;e.save(),e.font="14px sans-serif";const d=Jn(e,t.text.trim()||" ",l-c*2),u=Math.max(52,c*2+d.length*s);e.fillStyle="rgba(255, 246, 179, 0.96)",e.strokeStyle="rgba(44, 37, 12, 0.28)",e.lineWidth=1,Qn(e,a,r,l,u,8),e.fill(),e.stroke(),e.fillStyle="#2f2a13",e.textBaseline="top",d.forEach((v,f)=>{e.fillText(v,a+c,r+c+f*s)}),e.restore()}function St(e,t){const n=vt(e);if(!n)return null;if(n.kind==="box")return t.boxes.find(u=>u.id===n.id)??null;const a=n.kind==="memo"?t.memos.find(u=>u.id===n.id):null;if(a)return{id:a.id,x:a.x,y:a.y,width:.18,height:.12,color:a.color,strokeWidth:1};if(n.kind!=="path")return null;const r=t.paths.find(u=>u.id===n.id);if(!r||r.points.length===0)return null;const l=r.points.map(u=>u.x),c=r.points.map(u=>u.y),s=Math.min(...l),d=Math.min(...c);return{id:r.id,x:s,y:d,width:Math.max(.01,Math.max(...l)-s),height:Math.max(.01,Math.max(...c)-d),color:r.color,strokeWidth:r.strokeWidth}}function Bt(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 Yn(e,t,n){e.save(),e.strokeStyle="rgba(100, 200, 255, 0.5)",e.lineWidth=1.5,e.setLineDash([3,4]),e.strokeRect(t.x*n.width,t.y*n.height,t.width*n.width,t.height*n.height),e.restore()}function Zn(e,t,n,a,r){const[l,c,s]=Jt(t,n,r);e.save(),e.fillStyle=a,e.beginPath(),e.moveTo(l.x,l.y),e.lineTo(c.x,c.y),e.lineTo(s.x,s.y),e.closePath(),e.fill(),e.restore()}function Jn(e,t,n){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const r=[];let l="";for(const c of a){const s=l?`${l} ${c}`:c;if(e.measureText(s).width<=n||l===""){l=s;continue}r.push(l),l=c}return l&&r.push(l),r}function Qn(e,t,n,a,r,l){const c=Math.min(l,a/2,r/2);e.beginPath(),e.moveTo(t+c,n),e.lineTo(t+a-c,n),e.quadraticCurveTo(t+a,n,t+a,n+c),e.lineTo(t+a,n+r-c),e.quadraticCurveTo(t+a,n+r,t+a-c,n+r),e.lineTo(t+c,n+r),e.quadraticCurveTo(t,n+r,t,n+r-c),e.lineTo(t,n+c),e.quadraticCurveTo(t,n,t+c,n),e.closePath()}function ea({paths:e,boxes:t,memos:n=[],selectedIds:a=[],selectionBox:r=null,hoveredId:l=null,activePath:c,activeBox:s}){const d=i.useRef(null);return i.useEffect(()=>{const u=d.current;if(!u)return;const v=u.getBoundingClientRect(),f=window.devicePixelRatio||1;u.width=Math.max(1,Math.round(v.width*f)),u.height=Math.max(1,Math.round(v.height*f));const _=u.getContext("2d");if(!_)return;_.setTransform(f,0,0,f,0,0),_.clearRect(0,0,v.width,v.height);const C={width:v.width,height:v.height};for(const S of e)dt(_,S,C);for(const S of t)ht(_,S,C,"committed");for(const S of a){const U=St(S,{paths:e,boxes:t,memos:n});U&&Bt(_,U,C)}if(r&&Bt(_,r,C),l&&!a.includes(l)){const S=St(l,{paths:e,boxes:t,memos:n});S&&Yn(_,S,C)}c&&dt(_,c,C),s&&ht(_,s,C,"active")},[e,t,n,a,r,l,c,s]),o.jsx("canvas",{ref:d,className:"canvas-annotation-layer","aria-hidden":"true"})}function Oe(e){e.stopPropagation()}function ta({memos:e,activeMemoId:t,onUpdate:n,onDelete:a,onFocus:r,onCommit:l}){const{t:c}=fe();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:Oe,onPointerMove:Oe,onPointerUp:Oe,onPointerCancel:Oe,onChange:d=>n(s.id,d.currentTarget.value),onBlur:()=>{l?.(),s.text.trim()===""&&a(s.id)},"aria-label":c("common.canvasMemo")},s.id))})}function na({annotationFrameRef:e,imageElementRef:t,frameClassName:n,frameStyle:a,imageKey:r,imageSrc:l,fallbackImage:c,alt:s,canvasOpen:d,maskOverlayUrl:u,cleanupLayer:v,annotations:f,hoveredAnnotationId:_=null,onOpenCanvas:C,onPointerDown:S,onPointerMove:U,onPointerUp:L,onPointerLeave:N}){return o.jsxs("div",{ref:e,className:n,onPointerDown:S,onPointerMove:U,onPointerUp:L,onPointerCancel:L,onPointerLeave:N,style:a,children:[o.jsx("img",{ref:t,className:"result-img",src:l??c,alt:s,decoding:"async",onDoubleClick:p=>{p.stopPropagation(),C()}},r),d&&u?o.jsx("img",{className:"canvas-background-cleanup-mask",src:u,alt:"","aria-hidden":"true",decoding:"async"}):null,d?v:null,d&&o.jsxs(o.Fragment,{children:[o.jsx(ea,{paths:f.paths,boxes:f.boxes,memos:f.memos,selectedIds:f.selectedIds,selectionBox:f.selectionBox,hoveredId:_,activePath:f.activePath,activeBox:f.activeBox}),o.jsx(ta,{memos:f.memos,activeMemoId:f.activeMemoId,onUpdate:f.updateMemo,onDelete:f.deleteMemo,onFocus:f.focusMemo,onCommit:f.commitMemoEdit})]})]})}function aa(e){return`${e.x*100} ${e.y*100}`}function ra(e){return e.map(aa).join(" ")}function oa({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(c=>o.jsx("polyline",{className:`canvas-cleanup-overlay__stroke canvas-cleanup-overlay__stroke--${c.intent}`,points:ra(c.points),strokeWidth:Math.max(.3,c.radius*200),vectorEffect:"non-scaling-stroke"},c.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 sa({mode:e,matteColor:t,onModeChange:n,onMatteColorChange:a}){const{t:r}=fe();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 jt({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 la({seedCount:e,tolerance:t,stats:n,hasPreview:a,isPickingSeed:r,intent:l,tool:c,brushRadius:s,isPreviewing:d,isApplying:u,keepOpen:v,disabled:f,onAutoSample:_,onPickSeed:C,onIntentChange:S,onToolChange:U,onBrushRadiusChange:L,onToleranceChange:N,onPreview:p,onApply:M,onReset:B}){const{t:x}=fe(),[b,J]=i.useState(!1),O=i.useRef(null),V=n?Math.round(n.removedPercent*1e3)/10:0,Q=r||c==="brush";return i.useEffect(()=>{if(!b)return;const m=$=>{v||O.current?.contains($.target)||J(!1)};return window.addEventListener("pointerdown",m),()=>window.removeEventListener("pointerdown",m)},[v,b]),o.jsxs("div",{className:"canvas-toolbar__cleanup",ref:O,children:[o.jsx("button",{type:"button",className:`canvas-toolbar__button${b||a?" canvas-toolbar__button--active":""}`,onClick:()=>J(m=>!m),disabled:f,"aria-expanded":b,"aria-label":x("canvas.toolbar.cleanup"),title:x("canvas.toolbar.cleanup"),children:o.jsx(ca,{})}),b?o.jsxs("div",{className:"canvas-toolbar__cleanup-panel",role:"group","aria-label":x("canvas.toolbar.cleanup"),children:[o.jsxs("div",{className:"canvas-toolbar__cleanup-row",children:[o.jsx("span",{className:"canvas-toolbar__cleanup-title",children:x("canvas.toolbar.cleanup")}),o.jsx("span",{className:"canvas-toolbar__cleanup-meta",children:x("canvas.toolbar.cleanupSeedCount",{n:e})})]}),o.jsx(jt,{label:x("canvas.toolbar.cleanupMark"),value:l,options:[{value:"remove",label:x("canvas.toolbar.cleanupRemove")},{value:"preserve",label:x("canvas.toolbar.cleanupPreserve")}],onChange:S}),o.jsx(jt,{label:x("canvas.toolbar.cleanupInput"),value:c,options:[{value:"click",label:x("canvas.toolbar.cleanupClick")},{value:"brush",label:x("canvas.toolbar.cleanupBrush")}],onChange:U}),o.jsxs("label",{className:"canvas-toolbar__cleanup-slider",children:[o.jsx("span",{children:x("canvas.toolbar.cleanupTolerance")}),o.jsx("input",{type:"range",min:"0",max:"96",value:t,onChange:m=>N(Number(m.target.value))}),o.jsx("output",{children:t})]}),c==="brush"?o.jsxs("label",{className:"canvas-toolbar__cleanup-slider",children:[o.jsx("span",{children:x("canvas.toolbar.cleanupBrushSize")}),o.jsx("input",{type:"range",min:"0.006",max:"0.06",step:"0.002",value:s,onChange:m=>L(Number(m.target.value))}),o.jsx("output",{children:Math.round(s*1e3)})]}):null,o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:_,children:x("canvas.toolbar.cleanupAutoSample")}),o.jsx("button",{type:"button",className:r?"active":"",onClick:C,children:x(Q?"canvas.toolbar.cleanupActive":"canvas.toolbar.cleanupPickSeed")})]}),o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:p,disabled:d||e===0,children:x(d?"canvas.toolbar.cleanupPreviewing":"canvas.toolbar.cleanupPreview")}),o.jsx("button",{type:"button",onClick:M,disabled:u||!a&&e===0,children:x(u?"canvas.toolbar.cleanupApplying":"canvas.toolbar.cleanupApply")}),o.jsx("button",{type:"button",onClick:B,disabled:!a&&e===0,children:x("canvas.toolbar.cleanupReset")})]}),Q?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:x(c==="brush"?"canvas.toolbar.cleanupBrushHint":"canvas.toolbar.cleanupPickHint")}):n&&!a?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:x("canvas.toolbar.cleanupMaskHint")}):null,n?o.jsx("div",{className:"canvas-toolbar__cleanup-status",children:x("canvas.toolbar.cleanupRemoved",{n:V})}):null]}):null]})}function ca(){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"})]})}const ia=["png","svg","pptx"];function ua({onExport:e,disabled:t,isExporting:n}){const{t:a}=fe(),[r,l]=i.useState(!1),c=i.useRef(null),s=i.useRef(null),d=i.useId();i.useEffect(()=>{if(!r)return;const f=()=>Array.from(s.current?.querySelectorAll("[role='menuitem']")??[]);window.requestAnimationFrame(()=>f()[0]?.focus());const _=C=>{const S=C.target;s.current?.contains(S)||c.current?.contains(S)||l(!1)};return document.addEventListener("pointerdown",_,!0),()=>document.removeEventListener("pointerdown",_,!0)},[r]);const u=f=>{l(!1),c.current?.focus()},v=f=>{if(f.key==="Escape"){f.preventDefault(),u();return}if(!["ArrowDown","ArrowUp","Home","End"].includes(f.key))return;f.preventDefault();const C=Array.from(s.current?.querySelectorAll("[role='menuitem']")??[]);if(C.length===0)return;const S=C.indexOf(document.activeElement),U=f.key==="Home"?0:f.key==="End"?C.length-1:S<0?0:(S+(f.key==="ArrowDown"?1:-1)+C.length)%C.length;C[U]?.focus()};return o.jsxs("div",{className:"canvas-export-menu",children:[o.jsx("button",{ref:c,type:"button",className:`canvas-toolbar__button${n?" canvas-toolbar__button--busy":""}`,onClick:()=>l(f=>!f),disabled:t||n,"aria-haspopup":"menu","aria-expanded":r,"aria-controls":r?d:void 0,"aria-busy":n||void 0,"aria-label":a("canvas.toolbar.export"),title:a("canvas.toolbar.export"),children:o.jsx(da,{})}),r?o.jsx("div",{ref:s,id:d,role:"menu",className:"canvas-export-menu__list","aria-label":a("canvas.toolbar.exportFormat"),onKeyDown:v,children:ia.map(f=>o.jsx("button",{type:"button",role:"menuitem",className:"canvas-export-menu__item",onClick:()=>{u(),e(f)},children:a(`canvas.toolbar.exportAs.${f}`)},f))}):null]})}function da(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[o.jsx("path",{d:"M12 4v11"}),o.jsx("path",{d:"m8 11 4 4 4-4"}),o.jsx("path",{d:"M5 20h14"})]})}function ha({style:e,onStyleChange:t}){const{t:n}=fe(),[a,r]=i.useState(!1),l=En(a,()=>{r(!1)},{trap:!1,restoreFocus:s=>s!=="outsidePointer"}),c=i.useRef(null);return i.useEffect(()=>{if(!a)return;const s=d=>{c.current?.contains(d.target)||r(!1)};return window.addEventListener("pointerdown",s),()=>window.removeEventListener("pointerdown",s)},[a]),o.jsxs("div",{ref:c,className:`canvas-toolbar__split-button${a?" canvas-toolbar__split-button--active":""}`,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",{ref:l,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:Yt.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:Zt.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 fa({tools:e,activeTool:t,onToolChange:n}){const[a,r]=i.useState(!1),l=i.useRef(null),c=e.find(d=>d.id===t)??e[0],s=c.icon;return i.useEffect(()=>{if(!a)return;const d=u=>{l.current?.contains(u.target)||r(!1)};return window.addEventListener("pointerdown",d),()=>window.removeEventListener("pointerdown",d)},[a]),o.jsxs("div",{ref:l,className:"canvas-tool-picker",children:[o.jsxs("button",{type:"button",className:`canvas-toolbar__button canvas-tool-picker__trigger${t!=="eraser"?" canvas-toolbar__button--active":""}`,onClick:()=>r(d=>!d),"aria-label":`${c.label} (${c.shortcut})`,"aria-pressed":t===c.id,"aria-haspopup":"menu","aria-expanded":a,title:`${c.label} (${c.shortcut})`,children:[o.jsx(s,{}),o.jsx("span",{className:"canvas-toolbar__shortcut","aria-hidden":"true",children:c.shortcut})]}),a?o.jsx("div",{className:"canvas-tool-picker__menu",role:"menu",children:e.map(d=>{const u=d.icon,v=t===d.id;return o.jsxs("button",{type:"button",className:`canvas-tool-picker__item${v?" active":""}`,role:"menuitemradio","aria-checked":v,onClick:()=>{n(d.id),r(!1)},children:[o.jsx(u,{}),o.jsx("span",{children:d.label}),o.jsx("kbd",{children:d.shortcut})]},d.id)})}):null]})}function pa({activeTool:e,hasAnnotations:t,hasExportableContent:n,onToolChange:a,eraserMode:r="object",onEraserModeChange:l,style:c,onStyleChange:s,onClear:d,onApply:u,onRevertAnnotations:v,onExport:f,onUndo:_,onRedo:C,canUndo:S,canRedo:U,onDeleteSelected:L,selectedCount:N=0,onEditWithMask:p,canEditWithMask:M,isEditingWithMask:B,onGptTransparency:x,isTransparencyRunning:b,isApplying:J,isExporting:O,exportBackground:V="alpha",exportMatteColor:Q="#ffffff",onExportBackgroundChange:m,onExportMatteColorChange:$,cleanupTolerance:T=28,cleanupSeedCount:A=0,cleanupStats:D=null,cleanupHasPreview:te=!1,isCleanupPickingSeed:se=!1,isCleanupActive:ie=!1,cleanupIntent:de="remove",cleanupTool:he="click",cleanupBrushRadius:k=.018,isCleanupPreviewing:z=!1,isCleanupApplying:E=!1,onCleanupAutoSample:I,onCleanupPickSeed:F,onCleanupIntentChange:W,onCleanupToolChange:H,onCleanupBrushRadiusChange:ee,onCleanupToleranceChange:K,onCleanupPreview:R,onCleanupApply:q,onCleanupReset:ne}){const{t:y}=fe(),[ae,X]=i.useState(!1),G=i.useRef(null),ue=n??t??!1,we=y(r==="object"?"canvas.toolbar.objectEraser":"canvas.toolbar.brushEraser"),_e=[{id:"select",shortcut:"1",label:y("canvas.toolbar.select"),icon:ma},{id:"pen",shortcut:"2",label:y("canvas.toolbar.pen"),icon:va},{id:"box",shortcut:"3",label:y("canvas.toolbar.box"),icon:ba},{id:"arrow",shortcut:"4",label:y("canvas.toolbar.arrow"),icon:ga},{id:"memo",shortcut:"5",label:y("canvas.toolbar.memo"),icon:xa}];i.useEffect(()=>{if(!ae)return;const le=Ce=>{G.current?.contains(Ce.target)||X(!1)};return window.addEventListener("pointerdown",le),()=>window.removeEventListener("pointerdown",le)},[ae]);const ve=le=>{l?.(le),a("eraser"),X(!1)};return o.jsxs("div",{className:"canvas-toolbar","aria-label":y("canvas.toolbar.label"),children:[o.jsx(fa,{tools:_e,activeTool:e,onToolChange:a}),o.jsx(ha,{style:c,onStyleChange:s}),o.jsxs("div",{ref:G,className:`canvas-toolbar__split-button${e==="eraser"?" canvas-toolbar__split-button--active":""}`,onKeyDown:le=>{le.key==="Escape"&&ae&&(le.preventDefault(),X(!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":`${we} (6)`,"aria-pressed":e==="eraser",title:`${we} (6)`,children:[o.jsx(ya,{}),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:()=>X(le=>!le),"aria-label":y("canvas.toolbar.eraserMenu"),"aria-haspopup":"menu","aria-expanded":ae,"aria-controls":"canvas-eraser-menu",title:y("canvas.toolbar.eraserMenu"),children:o.jsx(wa,{})}),ae?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:()=>ve("object"),children:y("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:()=>ve("brush"),children:y("canvas.toolbar.brushEraser")})]}):null]}),o.jsx("span",{className:"canvas-toolbar__divider","aria-hidden":"true"}),u?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--primary${J?" canvas-toolbar__button--busy":""}`,onClick:u,disabled:!ue||J,"aria-label":y("canvas.toolbar.apply"),title:y("canvas.toolbar.apply"),children:o.jsx(ka,{})}):null,v?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:v,disabled:J,"aria-label":y("canvas.revert.action"),title:y("canvas.revert.action"),children:o.jsx(Pt,{})}):null,p?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--primary canvas-toolbar__button--mask${B?" canvas-toolbar__button--busy":""}`,onClick:p,disabled:!M||B,"aria-label":y(M?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),title:y(M?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),children:o.jsx(Ca,{})}):null,_?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:_,disabled:!S,"aria-label":y("canvas.toolbar.undo"),title:y("canvas.toolbar.undo"),children:o.jsx(Pt,{})}):null,C?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:C,disabled:!U,"aria-label":y("canvas.toolbar.redo"),title:y("canvas.toolbar.redo"),children:o.jsx(_a,{})}):null,L?o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:L,disabled:N===0,"aria-label":y("canvas.toolbar.deleteSelected"),title:y("canvas.toolbar.deleteSelected"),children:o.jsx(Tt,{})}):null,f&&m&&$?o.jsx(sa,{mode:V,matteColor:Q,onModeChange:m,onMatteColorChange:$}):null,I&&F&&W&&H&&ee&&K&&R&&q&&ne?o.jsx(la,{seedCount:A,tolerance:T,stats:D,hasPreview:te,isPickingSeed:se,intent:de,tool:he,brushRadius:k,isPreviewing:z,isApplying:E,keepOpen:ie,disabled:J||O,onAutoSample:I,onPickSeed:F,onIntentChange:W,onToolChange:H,onBrushRadiusChange:ee,onToleranceChange:K,onPreview:R,onApply:q,onReset:ne}):null,x?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--transparency${b?" canvas-toolbar__button--busy":""}`,onClick:x,disabled:b||J||B,"aria-label":y("canvas.toolbar.gptTransparency"),title:y("canvas.toolbar.gptTransparency"),children:b?o.jsx("span",{className:"canvas-toolbar__spinner","aria-hidden":"true"}):o.jsx(Ma,{})}):null,f?o.jsx(ua,{onExport:f,disabled:!ue,isExporting:!!O}):null,o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:d,disabled:!ue,"aria-label":y("canvas.toolbar.clear"),title:y("canvas.toolbar.clear"),children:o.jsx(Tt,{})})]})}function ma(){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 va(){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 ba(){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 ga(){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 xa(){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 ya(){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 wa(){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 ka(){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 Tt(){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 Pt(){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 _a(){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 Ca(){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 Ma(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",fill:"none"}),o.jsx("path",{d:"M4 8h4V4M12 4v4h4v4h4M4 12h4v4H4M12 12v4h-4M12 20v-4h4v4M20 16h-4",opacity:"0.55"})]})}function Ea({annotations:e,backgroundCleanup:t,backgroundCleanupPreview:n,canvasState:a,actions:r}){return o.jsx(pa,{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()},onRevertAnnotations:a.canRevertAnnotations?()=>{r.handleRevertAnnotations()}:void 0,onExport:l=>{r.handleExportCanvas(l)},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,onGptTransparency:()=>{r.handleGptTransparency()},isTransparencyRunning:a.isTransparencyRunning,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 Sa({currentImage:e,canvasDisplayImage:t,canvasOpen:n,displayQuality:a,displaySize:r,displayModel:l,onAfterDeleteFocus:c,onCopyPrompt:s}){const{t:d}=fe(),u=[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?d("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,Sn(e.reasoningEffort),a,r,l].filter(v=>!!v).join(" · ");return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"result-meta",children:u}),o.jsx(Bn,{imageOverride:n?t:null,onAfterDeleteFocus:c}),e.prompt?o.jsx(jn,{prompt:e.prompt,onCopy:s}):null]})}function Ba({zoom:e,onZoomIn:t,onZoomOut:n,onZoomReset:a}){const{t:r}=fe(),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(ja,{})}),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(Ta,{})})]})}function ja(){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 Ta(){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 Pa({zoom:e,modeLabel:t,closeLabel:n,blankCanvasLabel:a,blankCanvasAriaLabel:r,blankCanvasShortcut:l,blankCanvasBusy:c,shortcutHint:s,onZoomIn:d,onZoomOut:u,onZoomReset:v,onCreateBlankCanvas:f,onClose:_}){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:t}),o.jsx(Ba,{zoom:e,onZoomIn:d,onZoomOut:u,onZoomReset:v}),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:f,disabled:c,"aria-label":r,title:r,children:[o.jsx("span",{"aria-hidden":"true",children:"+"}),o.jsx("span",{children:a}),o.jsx("kbd",{children:l})]})}),o.jsxs("button",{type:"button",className:"canvas-mode-close",onClick:_,"aria-label":n,children:[o.jsx("kbd",{children:"ESC"}),o.jsx("span",{children:n})]})]})}function ot(e,t,n){return Math.max(t,Math.min(n,e))}function Aa({zoom:e,panX:t,panY:n}){const a=ot(100/Math.max(1,e),18,100),r=a/2,l=ot(50-t/40,r,100-r),c=ot(50-n/40,r,100-r);return{width:`${a}%`,height:`${a}%`,left:`${l}%`,top:`${c}%`}}function Da({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:Aa({zoom:t,panX:n,panY:a}),"aria-hidden":"true"})]})}function Le(e){return Math.min(1,Math.max(0,e))}function Ra(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("mask_blob_unavailable"))},"image/png")})}async function Na(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 c=Le(l.x)*t,s=Le(l.y)*n,d=Le(l.width)*t,u=Le(l.height)*n;d>0&&u>0&&r.fillRect(c,s,d,u)}return Ra(a)}async function Ia(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 bt(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 Oa=`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`,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.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 $a(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 Wa(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 Fa(e){const t=e.canvasSourceFilename??e.filename;return t?`/generated/${encodeURIComponent(t)}`:e.url??e.image}async function st(e){const t=Fa(e);if(t.startsWith("data:image/png;"))return t;const n=new Image;return await new Promise((a,r)=>{n.onload=()=>a(),n.onerror=()=>r(new Error("clean_source_load_failed")),n.src=t}),Ia(n)}function Ke(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?Ke(n,t):null}function At(e,t){if(Tn(e)){const n=e.images[0];if(!n)throw new Error("edit_empty_response");return{...n,prompt:t,reasoningEffort:e.reasoningEffort,provider:e.provider,quality:e.quality,size:e.size,moderation:e.moderation,model:e.model,usage:e.usage,alphaVerified:e.alphaVerified,alphaReason:e.alphaReason,kind:"edit",createdAt:Date.now()}}return{image:e.image,url:e.filename?`/generated/${e.filename}`:e.image,thumb:e.image,filename:e.filename,prompt:t,elapsed:e.elapsed,reasoningEffort:e.reasoningEffort,provider:e.provider,quality:e.quality,size:e.size,moderation:e.moderation,model:e.model,usage:e.usage,revisedPrompt:e.revisedPrompt??null,promptMode:e.promptMode??null,alphaVerified:e.alphaVerified,alphaReason:e.alphaReason,kind:"edit",createdAt:Date.now()}}const lt=new WeakMap;function Ka(e){if(!e.complete||!e.naturalWidth||!e.naturalHeight)return!1;const t=lt.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 c=l.getContext("2d",{willReadFrequently:!0});if(!c)return!1;try{c.drawImage(e,0,0,a,r);const s=c.getImageData(0,0,a,r).data;for(let d=3;d<s.length;d+=4)if(s[d]<250)return lt.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!0}),!0;return lt.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!1}),!1}catch{return!1}}function Va(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 Dt(e,t){return{width:e,height:t,data:new Uint8Array(e*t)}}function ft(e){return{width:e.width,height:e.height,data:new Uint8Array(e.data)}}function za(e,t){Va(e,t);for(let n=0;n<e.data.length;n+=1)(t.data[n]??0)>0&&(e.data[n]=0)}function je(e,t){if(!e)return null;const n=ft(e);return t&&za(n,t),n}function qa(e,t){if(e.width!==t.width||e.height!==t.height)throw new Error("cleanup_mask_size_mismatch");const n=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);for(let a=0;a<t.data.length;a+=1)(t.data[a]??0)>0&&(n.data[a*4+3]=0);return n}const gt=[{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}],Xa=1024;function Ga(e){return Math.max(0,Math.min(255,Math.round(e)))}function Qt(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 Ya(e,t){return(t.length>0?t:gt).map(a=>{const r=Qt(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 Za(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 Te(e,t,n,a,r,l,c){if(e<0||e>=a.length||a[e])return r;const s=e*4;return(t.data[s+3]??0)===0?(a[e]=1,r):Za(t.data,s,l,c)?(a[e]=1,n[r]=e,r+1):r}function ct(){return gt.map(e=>({...e}))}function Rt(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,c=r*l,s=new Uint8Array(c),d=new Int32Array(c),u=Ya(t,n),v=Ga(a);let f=0;for(const _ of n.length>0?n:gt)f=Te(Qt(_,r,l),t,d,s,f,u,v);for(;f>0;){const _=d[--f];e.data[_]=255;const C=_%r;C>0&&(f=Te(_-1,t,d,s,f,u,v)),C<r-1&&(f=Te(_+1,t,d,s,f,u,v)),_>=r&&(f=Te(_-r,t,d,s,f,u,v)),_<c-r&&(f=Te(_+r,t,d,s,f,u,v))}}function Ja(e,t){const n=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),a=qa(n,t),r=t.data.reduce((l,c)=>l+(c>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 en(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("background_cleanup_blob_failed"))},"image/png")})}function tn(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)),c=Math.max(1,Math.round(a*r)),s=document.createElement("canvas");s.width=l,s.height=c;const d=s.getContext("2d",{willReadFrequently:!0});if(!d)throw new Error("background_cleanup_context_failed");return d.drawImage(e,0,0,l,c),{canvas:s,context:d,width:l,height:c}}async function Nt({imageElement:e,mask:t}){try{const{canvas:n,context:a,width:r,height:l}=tn(e),c=a.getImageData(0,0,r,l),s=Ja({width:r,height:l,data:c.data},t),d=a.createImageData(r,l);d.data.set(s.imageData.data),a.putImageData(d,0,0);const u=await en(n);return{blob:u,dataUrl:await bt(u),stats:s.stats}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}async function Qa({imageElement:e,mask:t}){try{const{width:n,height:a}=tn(e,Xa),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 c=l.createImageData(n,a);let s=0;for(let u=0;u<a;u+=1)for(let v=0;v<n;v+=1){const f=Math.min(t.width-1,Math.floor(v/n*t.width)),_=Math.min(t.height-1,Math.floor(u/a*t.height));if((t.data[_*t.width+f]??0)===0)continue;const C=(u*n+v)*4;c.data[C]=168,c.data[C+1]=85,c.data[C+2]=247,c.data[C+3]=150,s+=1}l.putImageData(c,0,0);const d=await en(r);return{dataUrl:await bt(d),stats:{width:t.width,height:t.height,removedPixels:t.data.reduce((u,v)=>u+(v>0?1:0),0),removedPercent:t.data.length>0?s/(n*a):0}}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}function It(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?ft(e.removeMask):null,preserveMask:e.preserveMask?ft(e.preserveMask):null}}function er(){return`cleanup_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function $e(e){return Math.max(0,Math.min(1,e))}function tr(e){const t=[],n=Math.max(0,e.radius*.55);for(const a of e.points)t.push({...a}),!(n<=0)&&t.push({x:$e(a.x-n),y:a.y},{x:$e(a.x+n),y:a.y},{x:a.x,y:$e(a.y-n)},{x:a.x,y:$e(a.y+n)});return t}function nr(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 ar({canvasOpen:e,currentImage:t,canvasDisplayImage:n,imageElementRef:a,canvasSourceImageRef:r,lastMergedDataUrlRef:l,setCanvasSaveState:c,setCanvasVersionItem:s,applyMergedCanvasImage:d,attachCanvasVersionReference:u,showToast:v,t:f}){const[_,C]=i.useState(!1),[S,U]=i.useState("remove"),[L,N]=i.useState("click"),[p,M]=i.useState("flat-flood-fill"),[B,x]=i.useState([]),[b,J]=i.useState([]),[O,V]=i.useState(28),[Q,m]=i.useState(null),[$,T]=i.useState(null),[A,D]=i.useState(null),[te,se]=i.useState(!1),[ie,de]=i.useState(.018),[he,k]=i.useState(null),[z,E]=i.useState(!1),[I,F]=i.useState(!1),W=i.useRef(null),H=i.useRef(null),ee=i.useRef(null),K=i.useRef({past:[],future:[]}),R=i.useRef(0),q=i.useRef(null),ne=i.useCallback(()=>It({intent:S,tool:L,engine:p,seeds:B,brushStrokes:b,brushRadius:ie,tolerance:O,removeMask:W.current,preserveMask:H.current,preview:Q,maskOverlay:$,stats:A,active:te,brushCursor:he}),[b,$,Q,B,A,O,he,ie,p,S,L,te]),y=i.useCallback(()=>{K.current={past:[...K.current.past.slice(-19),ne()],future:[]}},[ne]),ae=i.useCallback(w=>{const g=It(w);W.current=g.removeMask,H.current=g.preserveMask,ee.current=null,U(g.intent),N(g.tool),M(g.engine),x(g.seeds),J(g.brushStrokes),de(g.brushRadius),V(g.tolerance),m(g.preview),T(g.maskOverlay),D(g.stats),se(g.active),k(g.brushCursor),E(!1),F(!1)},[]),X=i.useCallback(async()=>{if(!a.current||!t)return;const w=je(W.current,H.current);if(!w){T(null),D(null);return}const g=R.current+1;R.current=g,E(!0);try{const j=await Qa({imageElement:a.current,mask:w});if(R.current!==g)return;T(j),D(j.stats)}catch{if(R.current!==g)return;v(f("canvas.toolbar.cleanupFailed"),!0)}finally{R.current===g&&E(!1)}},[t,a,v,f]),G=i.useCallback(async(w,g,j)=>{if(!a.current)return;const re=nr(a.current),Z=Dt(re.width,re.height),Me=Dt(re.width,re.height);for(const be of w){const ke=be.intent==="remove"?Z:Me;Rt(ke,re,[be.point],j)}for(const be of g){const ke=be.intent==="remove"?Z:Me;Rt(ke,re,tr(be),j)}W.current=Z,H.current=Me},[a]),ue=i.useCallback(()=>{R.current+=1,q.current!=null&&(window.clearTimeout(q.current),q.current=null),W.current=null,H.current=null,ee.current=null,K.current={past:[],future:[]},x([]),J([]),m(null),T(null),D(null),se(!1),k(null),E(!1),F(!1)},[]),we=i.useCallback(()=>{const w=K.current.past.pop();return w?(K.current.future=[ne(),...K.current.future.slice(0,19)],ae(w),!0):!1},[ne,ae]),_e=i.useCallback(()=>{const w=K.current.future.shift();return w?(K.current.past=[...K.current.past.slice(-19),ne()],ae(w),!0):!1},[ne,ae]),ve=i.useCallback(w=>{y();const g=[...B,{point:w,intent:S}];x(g),m(null),G(g,b,O).then(X)},[b,B,O,S,y,G,X]),le=i.useCallback(()=>{y();const w=ct().map(g=>({point:g,intent:"remove"}));x(w),m(null),se(!1),G(w,b,O).then(X)},[b,O,y,G,X]),Ce=i.useCallback(()=>{y(),N("click"),se(w=>!w)},[y]),Ve=i.useCallback(w=>{y(),q.current!=null&&window.clearTimeout(q.current),V(w),m(null),q.current=window.setTimeout(()=>{q.current=null,G(B,b,w).then(X)},180)},[b,B,y,G,X]),ze=i.useCallback(async()=>{if(!a.current||!t)return null;let w=je(W.current,H.current);if(!w){const j=ct().map(re=>({point:re,intent:"remove"}));x(j),await G(j,b,O),w=je(W.current,H.current)}if(!w)return null;y();const g=R.current+1;R.current=g,E(!0);try{const j=await Nt({imageElement:a.current,mask:w});return R.current!==g?null:(m(j),T(null),D(j.stats),j)}catch{return R.current!==g||v(f("canvas.toolbar.cleanupFailed"),!0),null}finally{R.current===g&&E(!1)}},[b,O,t,a,y,G,v,f]),qe=i.useCallback(()=>{y(),ue()},[y,ue]),Y=i.useCallback(w=>{y();const g={id:er(),intent:S,points:[{...w}],radius:ie};ee.current=g,k(w),J(j=>[...j,g])},[ie,S,y]),Xe=i.useCallback(w=>{const g=ee.current;if(!g){k(w);return}g.points=[...g.points,{...w}],k(w),J(j=>j.map(re=>re.id===g.id?{...g,points:g.points.map(Z=>({...Z}))}:re)),G(B,b.map(j=>j.id===g.id?g:j),O).then(X)},[b,B,O,G,X]),Ge=i.useCallback(()=>{ee.current=null,G(B,b,O).then(X)},[b,B,O,G,X]),Ye=i.useCallback(async()=>{if(!t||!a.current)return;const w=r.current??t;if(!w?.filename){v(f("canvas.toolbar.cleanupFailed"),!0);return}let g=je(W.current,H.current);if(!g){const j=ct().map(re=>({point:re,intent:"remove"}));x(j),await G(j,b,O),g=je(W.current,H.current)}if(g){F(!0),c("saving");try{y();const j=await Nt({imageElement:a.current,mask:g}),re=n?.canvasVersion&&n.filename?await Ft(n.filename,{sourceFilename:w.canvasSourceFilename??w.filename,image:j.blob,prompt:w.prompt,pixelEdited:!0}):await Ht({sourceFilename:w.canvasSourceFilename??w.filename,image:j.blob,prompt:w.prompt}),Z=Ke(re.item,w);l.current=j.dataUrl,s(Z),d(Z),await u(Z),c("saved"),m(null),T(null),D(j.stats),se(!1),v(f("canvas.toolbar.cleanupApplied"))}catch{c("error"),v(f("canvas.toolbar.cleanupFailed"),!0)}finally{F(!1)}}},[d,u,b,O,n,r,t,a,l,y,G,c,s,v,f]),Ze=i.useCallback(()=>te?(ee.current=null,se(!1),k(null),!0):!1,[te]);return i.useEffect(()=>{const w=a.current;if(!w||!e){C(!1);return}const g=()=>C(Ka(w));if(w.complete)g();else return w.addEventListener("load",g),()=>w.removeEventListener("load",g)},[e,n?.canvasMergedAt,n?.filename,n?.image,n?.url,Q?.dataUrl,a]),{imageHasAlpha:_,backgroundCleanupSeeds:B,backgroundCleanupBrushStrokes:b,backgroundCleanupTolerance:O,backgroundCleanupPreview:Q,backgroundCleanupMaskOverlay:$,backgroundCleanupStats:A,cleanupIntent:S,setCleanupIntent:U,cleanupTool:L,setCleanupTool:N,cleanupClickEngine:p,setCleanupClickEngine:M,cleanupBrushRadius:ie,setCleanupBrushRadius:de,cleanupBrushCursor:he,setCleanupBrushCursor:k,isBackgroundCleanupActive:te,setIsBackgroundCleanupActive:se,isBackgroundCleanupPickingSeed:te&&L==="click",isBackgroundCleanupPreviewing:z,isBackgroundCleanupApplying:I,hasActiveCleanupStroke:!!ee.current,canUndoBackgroundCleanup:K.current.past.length>0,canRedoBackgroundCleanup:K.current.future.length>0,resetBackgroundCleanup:ue,undoBackgroundCleanup:we,redoBackgroundCleanup:_e,addBackgroundCleanupClick:ve,addBackgroundCleanupSeed:ve,runBackgroundCleanupPreview:ze,handleBackgroundCleanupAutoSample:le,handleBackgroundCleanupPickSeed:Ce,handleBackgroundCleanupToleranceChange:Ve,handleBackgroundCleanupReset:qe,handleBackgroundCleanupApply:Ye,handleBackgroundCleanupEscape:Ze,startBackgroundCleanupBrushStroke:Y,updateBackgroundCleanupBrushStroke:Xe,endBackgroundCleanupBrushStroke:Ge}}function Ot(e){return Math.min(1,Math.max(0,e))}function Lt(e,t){const n=t.getBoundingClientRect();return{x:Ot((e.clientX-n.left)/n.width),y:Ot((e.clientY-n.top)/n.height)}}const rr=.18,or=.12;function sr(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 pt(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 nn(e){return{id:e.id,x:e.x,y:e.y,width:rr,height:or,color:e.color,strokeWidth:1}}function lr(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,c=e.y-t.y,s=a*a+r*r;if(s===0)return Math.hypot(e.x-t.x,e.y-t.y);const d=Math.max(0,Math.min(1,(l*a+c*r)/s));return Math.hypot(e.x-(t.x+d*a),e.y-(t.y+d*r))}function cr(e,t,n){for(let a=1;a<t.points.length;a+=1)if(lr(e,t.points[a-1],t.points[a])<=n)return!0;return!1}function $t(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 ir(e,t){return e.points.some(n=>pt(n,t))}function it(e){const t=e.tolerance??.015;for(const n of[...e.memos].reverse())if(pt(e.point,nn(n),t))return Xt(n);for(const n of[...e.boxes].reverse())if(pt(e.point,n,t))return qt(n);for(const n of[...e.paths].reverse())if(cr(e.point,n,t))return zt(n);return null}function ur(e){const t=[];for(const n of e.annotations.paths)ir(n,e.box)&&t.push(zt(n));for(const n of e.annotations.boxes)$t(n,e.box)&&t.push(qt(n));for(const n of e.annotations.memos)$t(nn(n),e.box)&&t.push(Xt(n));return t}function dr({canvasOpen:e,canvasZoom:t,canvasPanX:n,canvasPanY:a,spaceHeld:r,canDragViewportWithSelect:l,isBackgroundCleanupActive:c,cleanupTool:s,annotationFrameRef:d,annotations:u,setCanvasPan:v,addBackgroundCleanupClick:f,startBackgroundCleanupBrushStroke:_,updateBackgroundCleanupBrushStroke:C,endBackgroundCleanupBrushStroke:S,setCleanupBrushCursor:U,setHoveredAnnotationId:L}){const N=i.useRef({mode:null,lastPoint:null,didMove:!1}),p=i.useRef({active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null}),[M,B]=i.useState(!1),x=m=>{m.currentTarget.setPointerCapture(m.pointerId),p.current={active:!0,startX:m.clientX,startY:m.clientY,basePanX:n,basePanY:a,pointerId:m.pointerId},B(!0)};return{viewportPanActive:M,resetPointerSession:()=>{N.current={mode:null,lastPoint:null,didMove:!1},p.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},B(!1),L(null)},handleAnnotationPointerDown:m=>{if(!e||me(m.target)||!d.current)return;const $=m.button===1;if(r||$){m.preventDefault(),x(m);return}m.preventDefault();const T=Lt(m,d.current);if(c){s==="click"?f(T):(m.currentTarget.setPointerCapture(m.pointerId),_(T));return}if(u.activeTool==="select"){const A=it({point:T,paths:u.paths,boxes:u.boxes,memos:u.memos});if(A)m.shiftKey?u.toggleSelected(A):u.selectOne(A),u.startSelectedMove(),N.current={mode:"move",lastPoint:T,didMove:!1};else if(l&&t>1.01){x(m);return}else u.clearSelection(),u.startSelectionBox(T),N.current={mode:"box",lastPoint:T,didMove:!1};m.currentTarget.setPointerCapture(m.pointerId);return}if(u.activeTool==="memo"){u.createMemo(T),requestAnimationFrame(()=>{d.current?.querySelector(".canvas-memo--active")?.focus()});return}if(u.activeTool==="eraser"){if(u.eraserMode==="object"){const A=it({point:T,paths:u.paths,boxes:u.boxes,memos:u.memos});A&&u.eraseObjectAtPoint(A);return}m.currentTarget.setPointerCapture(m.pointerId),u.startEraserStroke(T);return}m.currentTarget.setPointerCapture(m.pointerId),u.startDrawing(T)},handleAnnotationPointerMove:m=>{if(!e||me(m.target)||!d.current)return;if(p.current.active){const T=m.clientX-p.current.startX,A=m.clientY-p.current.startY;v(p.current.basePanX+T,p.current.basePanY+A);return}const $=Lt(m,d.current);if(c){L(null),s==="brush"?C($):U($);return}if(u.activeTool==="select"){if(N.current.mode===null){const T=it({point:$,paths:u.paths,boxes:u.boxes,memos:u.memos});L(T)}else L(null);if(N.current.mode==="move"&&N.current.lastPoint){const T={x:$.x-N.current.lastPoint.x,y:$.y-N.current.lastPoint.y};(Math.abs(T.x)>5e-4||Math.abs(T.y)>5e-4)&&(u.moveSelected(T),N.current.didMove=!0),N.current.lastPoint=$}else N.current.mode==="box"&&u.updateSelectionBox($);return}if(u.activeTool!=="memo"){if(u.activeTool==="eraser"){u.eraserMode==="brush"&&u.updateEraserStroke($);return}u.moveDrawing($)}},handleAnnotationPointerUp:m=>{if(e&&!me(m.target)){if(p.current.active&&p.current.pointerId===m.pointerId){m.currentTarget.hasPointerCapture(m.pointerId)&&m.currentTarget.releasePointerCapture(m.pointerId),p.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},B(!1);return}if(m.currentTarget.hasPointerCapture(m.pointerId)&&m.currentTarget.releasePointerCapture(m.pointerId),c){s==="brush"&&S();return}if(u.activeTool==="select"){N.current.mode==="move"&&N.current.didMove&&u.commitSelectedMove(),N.current.mode==="box"&&u.selectionBox&&u.endSelectionBox(ur({box:sr(u.selectionBox),annotations:u.toPayload()})),N.current={mode:null,lastPoint:null,didMove:!1};return}if(u.activeTool!=="memo"){if(u.activeTool==="eraser"){u.eraserMode==="brush"&&u.endEraserStroke();return}u.endDrawing()}}},handleAnnotationPointerLeave:()=>{c&&U(null),L(null)}}}function hr({canvasOpen:e,canvasZoom:t,currentImage:n,annotations:a,undoBackgroundCleanup:r,redoBackgroundCleanup:l,handleBackgroundCleanupEscape:c,handleCloseCanvas:s,selectHistoryShortcutTarget:d,trashHistoryItem:u,permanentlyDeleteHistoryItemByShortcut:v,setCanvasZoom:f,resetCanvasZoom:_,onCreateBlankCanvas:C,isCreatingBlankCanvas:S}){const[U,L]=i.useState(!1);return i.useEffect(()=>{if(!e)return;const p=b=>{b.preventDefault()},M=b=>{b.ctrlKey&&b.preventDefault()},B={passive:!1,capture:!0},x={passive:!1};return window.addEventListener("wheel",M,B),window.addEventListener("gesturestart",p,x),window.addEventListener("gesturechange",p,x),window.addEventListener("gestureend",p,x),()=>{window.removeEventListener("wheel",M,B),window.removeEventListener("gesturestart",p,x),window.removeEventListener("gesturechange",p,x),window.removeEventListener("gestureend",p,x)}},[e]),i.useEffect(()=>{if(!e)return;const p=B=>{B.code==="Space"&&(me(B.target)||(U||L(!0),B.preventDefault()))},M=B=>{B.code==="Space"&&L(!1)};return window.addEventListener("keydown",p),window.addEventListener("keyup",M),()=>{window.removeEventListener("keydown",p),window.removeEventListener("keyup",M)}},[e,U]),i.useEffect(()=>{if(!e)return;const p=M=>{if(!M.defaultPrevented){if(me(M.target)){M.key==="Escape"&&(M.preventDefault(),M.target.blur(),a.focusMemo(null));return}if(M.key==="Escape"){if(M.preventDefault(),c())return;s();return}if(M.shiftKey&&!M.metaKey&&!M.ctrlKey&&!M.altKey&&M.key.toLowerCase()==="b"){M.preventDefault(),!S&&!M.repeat&&C();return}if((M.metaKey||M.ctrlKey)&&M.key.toLowerCase()==="z"){if(M.preventDefault(),M.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,s,c,S,C,l,r]),{spaceHeld:U,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 M=["select","pen","box","arrow","memo","eraser"];a.setTool(M[Number(p.key)-1]);return}if(e&&p.key==="Escape"){if(p.preventDefault(),p.stopPropagation(),c())return;s();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){v(n);return}u(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"?d("previous"):p.key==="ArrowRight"?d("next"):p.key==="Home"?d("first"):p.key==="End"&&d("last")))}}}function fr(e,t){return new Promise((n,a)=>{e.toBlob(r=>{if(r){n(r);return}a(new Error("canvas_blob_unavailable"))},t)})}async function Fe(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)dt(n,l,a);for(const l of e.boxes)ht(n,l,a,"committed");for(const l of e.memos)Gn(n,l,a);return{blob:await fr(t,"image/png"),dataUrl:t.toDataURL("image/png")}}const pr=["left","center","right"],mr=["top","middle","bottom"];function vr(e,t){const n=pr[Math.min(2,Math.max(0,Math.floor(e*3)))],a=mr[Math.min(2,Math.max(0,Math.floor(t*3)))];return`${a==="middle"&&n==="center"?"center":`${a} ${n}`} area (x: ${Math.round(e*100)}%, y: ${Math.round(t*100)}% from top-left)`}function Ut(e){const t=e.map(n=>({...n,text:n.text.trim()})).filter(n=>n.text.length>0);return t.length===0?"":["The numbered notes below are temporary editing instructions written on the image. They are not image content: interpret each one to locate and apply the requested change (percentages are relative to image width and height).",...t.map((n,a)=>`${a+1}. At the ${vr(n.x,n.y)}: ${n.text}`),"After applying every numbered instruction, remove all annotation markup. Do not render any annotation text, sticky notes, boxes, arrows, or markup in the output image. Where markup covered the image, show the underlying content reconstructed to match the surrounding texture, lighting, and perspective, with no residue, outline, or discoloration.","Keep everything not named in the numbered instructions exactly the same as the source image: composition, subjects, lighting, colors, and background."].join(`
3
- `)}const Wt=18,Pe=12,br="14px sans-serif";function Ne(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function oe(e){return Math.round(e*100)/100}function gr(e,t){if(e.points.length<2)return"";const n=e.points.map(s=>De(s,t)),a=n.map((s,d)=>`${d===0?"M":"L"}${oe(s.x)} ${oe(s.y)}`).join(" "),r=`stroke="${Ne(e.color)}" stroke-width="${e.strokeWidth}" stroke-linecap="round" stroke-linejoin="round" fill="none"`,l=`<path d="${a}" ${r} />`;if(e.tool!=="arrow")return l;const c=Jt(n[n.length-2],n[n.length-1],e.strokeWidth).map(s=>`${oe(s.x)},${oe(s.y)}`).join(" ");return`${l}<polygon points="${c}" fill="${Ne(e.color)}" />`}function xr(e,t){return`<rect x="${oe(e.x*t.width)}" y="${oe(e.y*t.height)}" width="${oe(e.width*t.width)}" height="${oe(e.height*t.height)}" fill="none" stroke="${Ne(e.color)}" stroke-width="${e.strokeWidth}" />`}function yr(e,t){const n=e.trim();if(!n)return[""];const a=[];let r="";for(const l of n.split(/\s+/)){if(l.length>t){r&&(a.push(r),r="");for(let s=0;s<l.length;s+=t)a.push(l.slice(s,s+t));continue}const c=r?`${r} ${l}`:l;c.length<=t?r=c:(a.push(r),r=l)}return r&&a.push(r),a.length>0?a:[""]}function wr(e,t){const n=oe(e.x*t.width),a=oe(e.y*t.height),r=oe(Math.min(260,Math.max(150,t.width*.22))),l=Math.max(8,Math.floor((r-Pe*2)/7.5)),c=yr(e.text,l),s=oe(Math.max(52,Pe*2+c.length*Wt)),d=c.map((u,v)=>`<tspan x="${oe(n+Pe)}" dy="${v===0?0:Wt}">${Ne(u)}</tspan>`).join("");return`<g><rect x="${n}" y="${a}" width="${r}" height="${s}" rx="8" fill="rgba(255, 246, 179, 0.96)" stroke="rgba(44, 37, 12, 0.28)" stroke-width="1" /><text x="${oe(n+Pe)}" y="${oe(a+Pe+14)}" font="${br}" font-family="sans-serif" font-size="14" fill="#2f2a13">${d}</text></g>`}function kr(e){const{imageSize:t,annotations:n}=e,a=[`<image href="${Ne(e.imageDataUrl)}" x="0" y="0" width="${t.width}" height="${t.height}" preserveAspectRatio="none" />`,...n.paths.map(r=>gr(r,t)),...n.boxes.map(r=>xr(r,t)),...n.memos.map(r=>wr(r,t))].filter(Boolean);return`<svg xmlns="http://www.w3.org/2000/svg" width="${t.width}" height="${t.height}" viewBox="0 0 ${t.width} ${t.height}">`+a.join("")+"</svg>"}const Ue=10,We=5.625;function _r(e){const t=e.width/e.height,n=Ue/We,a=t>=n?Ue:We*t,r=t>=n?Ue/t:We;return{x:(Ue-a)/2,y:(We-r)/2,w:a,h:r}}function Cr(e,t){const n=Math.min(2.6,t.w*.24);return{x:t.x+e.x*t.w,y:t.y+e.y*t.h,w:n,h:.55}}async function Mr(e){const{default:t}=await Pn(async()=>{const{default:c}=await import("./pptxgen.es-BEVsR2-i.js");return{default:c}},__vite__mapDeps([0,1,2])),n=new t;n.layout="LAYOUT_16x9";const a=n.addSlide(),r=_r(e.imageSize);a.addImage({data:e.mergedDataUrl,...r});for(const c of e.memos){const s=c.text.trim();s&&a.addText(s,{...Cr(c,r),fontSize:11,color:"2F2A13",fill:{color:"FFF6B3"},line:{color:"2C250C",width:.5},align:"left",valign:"top",shrinkText:!0})}return await n.write({outputType:"blob"})}function Er(e={},t=new Date){const n=t.toISOString().slice(0,19).replace(/[-:T]/g,""),a=e.matte?"-flat":"";return`canvas-export-${n}${a}.${e.format??"png"}`}async function Sr(e,t,n){const a={width:t.imageElement.naturalWidth,height:t.imageElement.naturalHeight};if(e==="svg"){const c=await Fe({...t,paths:[],boxes:[],memos:[]}),s=kr({imageDataUrl:c.dataUrl,imageSize:a,annotations:n});return new Blob([s],{type:"image/svg+xml"})}const r=await Fe(t);if(e==="png")return r.blob;const l=await Fe({...t,memos:[]});return Mr({mergedDataUrl:l.dataUrl,imageSize:a,memos:n.memos})}function Br(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 jr({imageElementRef:e,currentImage:t,canvasDisplayImage:n,canvasSourceImageRef:a,lastMergedDataUrlRef:r,lastCleanDataUrlRef:l,canvasVersionItem:c,annotations:s,exportBackground:d,exportMatteColor:u,quality:v,format:f,moderation:_,provider:C,imageModel:S,reasoningEffort:U,promptMode:L,webSearchEnabled:N,getResolvedSize:p,setCanvasVersionItem:M,setCanvasSaveState:B,setIsApplying:x,setIsExporting:b,setIsEditingWithMask:J,setIsTransparencyRunning:O,applyMergedCanvasImage:V,addGeneratedHistoryItem:Q,attachCanvasVersionReference:m,closeCanvas:$,resetCanvasSession:T,showToast:A,t:D}){const te=i.useCallback(async()=>{if(!e.current||!t)return null;const E=a.current??t;if(!E?.filename)return A(D("canvas.version.failed"),!0),null;x(!0),B("saving");try{const I=await Fe({imageElement:e.current,paths:s.paths,boxes:s.boxes,memos:s.memos});r.current=I.dataUrl;const F=await st(E);l.current=F;const W=c?.filename?await Ft(c.filename,{image:I.blob,sourceFilename:E.canvasSourceFilename??E.filename,prompt:E.prompt}):await Ht({sourceFilename:E.filename,image:I.blob,prompt:E.prompt}),H=s.toPayload(),ee=!c||!!c.annotationOnly,K=await An(W.item.filename,H,ee),R=Ke(K.item,E);M(R),V(R),await m(R,F);const q=Ut(s.memos),ne=`canvas-annotations:${E.canvasSourceFilename??E.filename}`,{insertPromptToComposer:y,removeInsertedPromptFromComposer:ae}=P.getState();return ae(ne),q&&y({id:ne,name:D("canvas.annotationInstructionsChip"),text:q,placement:"after"}),await Kt(E.filename).catch(()=>{}),s.resetLocal(),s.markSaved(),B("saved"),A(D("canvas.version.saved")),R}catch{return B("error"),A(D("canvas.version.failed"),!0),null}finally{x(!1)}},[s,V,m,a,c?.filename,t,e,r,l,B,M,x,A,D]);return{saveCanvasVersionAndUseReference:te,handleApplyCanvas:async()=>{await te()},handleRevertAnnotations:async()=>{if(!(!c?.filename||!c.annotationsBaked)&&!(!c.annotationOnly&&!window.confirm(D("canvas.revert.mixedConfirm")))){x(!0),B("saving");try{const E=await Dn(c.filename),I=a.current??t??c,F=Ke(E.item,I);if(M(F),V(F),r.current=null,E.annotationOnly&&E.snapshot){s.load(E.snapshot);const W=F.canvasSourceFilename??I.filename;W&&await Vt(W,E.snapshot),A(D("canvas.revert.restored"))}else s.resetLocal(),A(D("canvas.revert.completed"));B("saved")}catch{B("error"),A(D("canvas.revert.failed"),!0)}finally{x(!1)}}},handleCloseCanvas:async()=>{(s.hasAnnotations||s.isDirty)&&!await te()||($(),T())},handleExportCanvas:async(E="png")=>{if(!(!e.current||!t)){b(!0);try{const I=d==="matte",F=await Sr(E,{imageElement:e.current,paths:s.paths,boxes:s.boxes,memos:s.memos,background:I?{mode:"matte",color:u}:{mode:"alpha"}},{paths:s.paths,boxes:s.boxes,memos:s.memos});Br(F,Er({matte:I,format:E}))}catch{A(D("canvas.toolbar.exportFailed"),!0)}finally{b(!1)}}},handleEditWithMask:async()=>{if(!(!e.current||!n||s.boxes.length===0)){J(!0);try{const E=s.memos;let I=l.current;if(C==="nai"){A(D("toast.naiEditUnsupported"),!0);return}if(s.isDirty||s.hasAnnotations){if(!await te())return;I=l.current}I||(I=await st(a.current??n));const F=s.boxes.filter(y=>s.selectedIds.some(ae=>pe(ae,"box",y.id))),W=await Na({imageElement:e.current,boxes:F.length>0?F:s.boxes}),H=Ut(E),K=[(n.prompt??t?.prompt??"").trim(),H].filter(Boolean).join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pptxgen.es-CSd_gCsx.js","assets/index-Sch70vBs.js","assets/index-DGRIdnsL.css"])))=>i.map(i=>d[i]);
2
+ import{a as i,j as o,u as fe,p as En,f as Sn,aA as Bn,aB as jn,aC as Tn,aD as Ft,aE as Ht,aF as me,ah as Pn,aG as An,b as P,aH as Kt,aI as kt,aJ as Dn,aK as Vt,aL as Rn,c as Nn,aM as In,aN as On}from"./index-Sch70vBs.js";const Ie=2,He=1e-6;function Ln({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 c of e){const s=$n(c,t,n,a);(s.length!==1||s[0]!==c)&&(r=!0),l.push(...s)}return{paths:l,changed:r}}function $n(e,t,n,a=()=>crypto.randomUUID()){if(e.points.length<Ie||t.length===0||n<=0)return[e];const r=[];let l=Ae(e.points[0],t,n)?[]:[e.points[0]];for(let s=1;s<e.points.length;s+=1){const d=e.points[s-1],u=e.points[s],v=Ae(u,t,n),f=Un(d,u,t,n);if(f){l.length===0&&!Ae(d,t,n)&&(l=[d]),l.length>0&&f.leftT>He&&Ct(l,Re(d,u,f.leftT)),l.length>=Ie&&r.push(l),l=[],f.rightT<1-He&&!v&&(l=[Re(d,u,f.rightT),u]);continue}if(v){l.length>=Ie&&r.push(l),l=[];continue}l.length===0&&!Ae(d,t,n)&&(l=[d]),Ct(l,u)}if(l.length>=Ie&&r.push(l),r.length===0)return[];if(r.length===1&&r[0].length===e.points.length)return[e];const c=e.tool==="arrow"?r.length-1:-1;return r.map((s,d)=>({...e,id:d===0?e.id:a(),tool:e.tool==="arrow"&&d!==c?"pen":e.tool,points:s}))}function Ae(e,t,n){if(t.length===1)return ye(e,t[0])<=n;for(let a=1;a<t.length;a+=1)if(Wn(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 Un(e,t,n,a){const r=ye(e,t);if(r<=He)return Ae(e,n,a)?{leftT:0,rightT:1}:null;let l=null,c=Number.POSITIVE_INFINITY;for(const d of n){const u=_t(d,e,t),v=Re(e,t,u),f=ye(d,v);f<c&&(c=f,l=u)}for(let d=1;d<n.length;d+=1){const u=[0,.25,.5,.75,1];for(const v of u){const f=Re(n[d-1],n[d],v),_=_t(f,e,t),C=Re(e,t,_),S=ye(f,C);S<c&&(c=S,l=_)}}if(l===null||c>a)return null;const s=Math.max(a/r,.01);return{leftT:Math.max(0,l-s),rightT:Math.min(1,l+s)}}function _t(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,c=e.y-t.y,s=a*a+r*r;return s===0?0:Math.max(0,Math.min(1,(l*a+c*r)/s))}function Re(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function Ct(e,t){const n=e.at(-1);(!n||ye(n,t)>He)&&e.push(t)}function Wn(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,c=e.y-t.y,s=a*a+r*r;if(s===0)return ye(e,t);const d=Math.max(0,Math.min(1,(l*a+c*r)/s));return ye(e,{x:t.x+d*a,y:t.y+d*r})}function mt(e,t){return`${e}:${t}`}function vt(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 zt(e){return mt("path",e.id)}function qt(e){return mt("box",e.id)}function Xt(e){return mt("memo",e.id)}function pe(e,t,n){const a=vt(e);return a?.kind===t&&a.id===n}const Gt="ima2.canvas.annotationStyle.v1",Yt=["#ef4444","#f97316","#eab308","#22c55e","#38bdf8","#6366f1","#a855f7","#111827","#ffffff"],Zt=[2,3,5,8],Be={color:"#ef4444",strokeWidth:3};function Fn(){if(typeof window>"u")return Be;try{const e=window.localStorage.getItem(Gt);if(!e)return Be;const t=JSON.parse(e),n=typeof t.color=="string"&&Yt.includes(t.color)?t.color:Be.color,a=typeof t.strokeWidth=="number"&&Zt.includes(t.strokeWidth)?t.strokeWidth:Be.strokeWidth;return{color:n,strokeWidth:a}}catch{return Be}}function Hn(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Gt,JSON.stringify(e))}catch{}}const Mt=Fn(),ut={activeTool:"select",toolColor:Mt.color,strokeWidth:Mt.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 at(e,t){return{...e,past:[...e.past.slice(-49),t],future:[]}}function Kn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Et(e,t){return{...e,...t,activeMemoId:null,activePath:null,activeBox:null,selectionBox:null,selectedIds:[],isDirty:!0}}function Vn(e,t,n){const{start:a,current:r}=e,l=Math.min(a.x,r.x),c=Math.min(a.y,r.y),s=Math.abs(r.x-a.x),d=Math.abs(r.y-a.y);return s<.01||d<.01?null:{id:crypto.randomUUID(),x:l,y:c,width:s,height:d,color:t,strokeWidth:n}}function zn(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 rt(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 qn(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=Vn(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?Kn(e.memoBaseline,xe(e))?{...e,memoBaseline:null,activeMemoId:null}:{...at(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{...ut,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{...ut,activeTool:e.activeTool,eraserMode:e.eraserMode,toolColor:e.toolColor,strokeWidth:e.strokeWidth};case"UNDO":{const n=e.past.at(-1);return n?{...Et(e,n),past:e.past.slice(0,-1),future:[xe(e),...e.future]}:e}case"REDO":{const n=e.future[0];return n?{...Et(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=>rt(a,t.delta))}:n),boxes:e.boxes.map(n=>e.selectedIds.some(a=>pe(a,"box",n.id))?zn(n,t.delta):n),memos:e.memos.map(n=>e.selectedIds.some(a=>pe(a,"memo",n.id))?{...n,x:rt(n,t.delta).x,y:rt(n,t.delta).y}:n)};case"START_SELECTED_MOVE":return{...e,moveBaseline:xe(e)};case"COMMIT_SELECTED_MOVE":return e.moveBaseline?{...at(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=vt(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=Ln({paths:e.paths,points:e.activeEraserStroke.points,radius:e.activeEraserStroke.radius});return n.changed?{...at(e,e.eraserBaseline),paths:n.paths,activeEraserStroke:null,eraserBaseline:null,selectedIds:[],isDirty:!0}:{...e,activeEraserStroke:null,eraserBaseline:null}}default:return e}}function Xn(){const[e,t]=i.useReducer(qn,ut),n=i.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=i.useCallback(k=>t({type:"SET_TOOL",tool:k}),[]),c=i.useCallback(k=>{Hn(k),t({type:"SET_STYLE",style:k})},[]),s=i.useCallback(()=>t({type:"CLEAR"}),[]),d=i.useCallback(k=>t({type:"LOAD",payload:k}),[]),u=i.useCallback(()=>t({type:"MARK_SAVED"}),[]),v=i.useCallback(()=>t({type:"RESET_LOCAL"}),[]),f=i.useCallback(()=>t({type:"UNDO"}),[]),_=i.useCallback(()=>t({type:"REDO"}),[]),C=i.useCallback(()=>t({type:"COMMIT_MEMO_EDIT"}),[]),S=i.useCallback(()=>t({type:"START_SELECTED_MOVE"}),[]),U=i.useCallback(()=>t({type:"COMMIT_SELECTED_MOVE"}),[]),L=i.useCallback(k=>{e.activeTool==="pen"||e.activeTool==="arrow"?t({type:"START_PATH",point:k}):e.activeTool==="box"&&t({type:"START_BOX",point:k})},[e.activeTool]),N=i.useCallback(k=>{e.activePath?t({type:"ADD_POINT",point:k}):e.activeBox&&t({type:"UPDATE_BOX",point:k})},[e.activePath,e.activeBox]),p=i.useCallback(()=>{e.activePath?t({type:"END_PATH"}):e.activeBox&&t({type:"END_BOX"})},[e.activePath,e.activeBox]),M=i.useCallback(k=>t({type:"CREATE_MEMO",point:k}),[]),B=i.useCallback((k,z)=>t({type:"UPDATE_MEMO",id:k,text:z}),[]),x=i.useCallback(k=>t({type:"DELETE_MEMO",id:k}),[]),b=i.useCallback(k=>t({type:"FOCUS_MEMO",id:k}),[]),J=i.useCallback(k=>t({type:"SET_ERASER_MODE",mode:k}),[]),O=i.useCallback(k=>t({type:"SELECT_ONE",id:k}),[]),V=i.useCallback(k=>t({type:"TOGGLE_SELECTED",id:k}),[]),Q=i.useCallback(()=>t({type:"CLEAR_SELECTION"}),[]),m=i.useCallback(()=>t({type:"DELETE_SELECTED"}),[]),$=i.useCallback(k=>t({type:"MOVE_SELECTED",delta:k}),[]),T=i.useCallback(k=>t({type:"START_SELECTION_BOX",point:k}),[]),A=i.useCallback(k=>t({type:"UPDATE_SELECTION_BOX",point:k}),[]),D=i.useCallback(k=>t({type:"END_SELECTION_BOX",ids:k}),[]),te=i.useCallback(k=>t({type:"ERASE_OBJECT",id:k}),[]),se=i.useCallback(k=>t({type:"START_ERASER_STROKE",point:k}),[]),ie=i.useCallback(k=>t({type:"UPDATE_ERASER_STROKE",point:k}),[]),de=i.useCallback(()=>t({type:"END_ERASER_STROKE"}),[]),he=i.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:c,setEraserMode:J,startDrawing:L,moveDrawing:N,endDrawing:p,createMemo:M,updateMemo:B,commitMemoEdit:C,deleteMemo:x,focusMemo:b,clear:s,load:d,toPayload:he,markSaved:u,resetLocal:v,undo:f,redo:_,selectOne:O,toggleSelected:V,clearSelection:Q,deleteSelected:m,moveSelected:$,startSelectedMove:S,commitSelectedMove:U,startSelectionBox:T,updateSelectionBox:A,endSelectionBox:D,eraseObjectAtPoint:te,startEraserStroke:se,updateEraserStroke:ie,endEraserStroke:de}}function De(e,t){return{x:e.x*t.width,y:e.y*t.height}}function Jt(e,t,n){const a=Math.atan2(t.y-e.y,t.x-e.x),r=Math.max(12,n*4),l=Math.PI/7;return[{x:t.x,y:t.y},{x:t.x-r*Math.cos(a-l),y:t.y-r*Math.sin(a-l)},{x:t.x-r*Math.cos(a+l),y:t.y-r*Math.sin(a+l)}]}function dt(e,t,n){if(t.points.length<2)return;const a=De(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=De(r,n);e.lineTo(l.x,l.y)}if(e.stroke(),t.tool==="arrow"){const r=De(t.points[t.points.length-1],n),l=De(t.points[t.points.length-2],n);Zn(e,l,r,t.color,t.strokeWidth)}e.restore()}function ht(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 Gn(e,t,n){const a=t.x*n.width,r=t.y*n.height,l=Math.min(260,Math.max(150,n.width*.22)),c=12,s=18;e.save(),e.font="14px sans-serif";const d=Jn(e,t.text.trim()||" ",l-c*2),u=Math.max(52,c*2+d.length*s);e.fillStyle="rgba(255, 246, 179, 0.96)",e.strokeStyle="rgba(44, 37, 12, 0.28)",e.lineWidth=1,Qn(e,a,r,l,u,8),e.fill(),e.stroke(),e.fillStyle="#2f2a13",e.textBaseline="top",d.forEach((v,f)=>{e.fillText(v,a+c,r+c+f*s)}),e.restore()}function St(e,t){const n=vt(e);if(!n)return null;if(n.kind==="box")return t.boxes.find(u=>u.id===n.id)??null;const a=n.kind==="memo"?t.memos.find(u=>u.id===n.id):null;if(a)return{id:a.id,x:a.x,y:a.y,width:.18,height:.12,color:a.color,strokeWidth:1};if(n.kind!=="path")return null;const r=t.paths.find(u=>u.id===n.id);if(!r||r.points.length===0)return null;const l=r.points.map(u=>u.x),c=r.points.map(u=>u.y),s=Math.min(...l),d=Math.min(...c);return{id:r.id,x:s,y:d,width:Math.max(.01,Math.max(...l)-s),height:Math.max(.01,Math.max(...c)-d),color:r.color,strokeWidth:r.strokeWidth}}function Bt(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 Yn(e,t,n){e.save(),e.strokeStyle="rgba(100, 200, 255, 0.5)",e.lineWidth=1.5,e.setLineDash([3,4]),e.strokeRect(t.x*n.width,t.y*n.height,t.width*n.width,t.height*n.height),e.restore()}function Zn(e,t,n,a,r){const[l,c,s]=Jt(t,n,r);e.save(),e.fillStyle=a,e.beginPath(),e.moveTo(l.x,l.y),e.lineTo(c.x,c.y),e.lineTo(s.x,s.y),e.closePath(),e.fill(),e.restore()}function Jn(e,t,n){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const r=[];let l="";for(const c of a){const s=l?`${l} ${c}`:c;if(e.measureText(s).width<=n||l===""){l=s;continue}r.push(l),l=c}return l&&r.push(l),r}function Qn(e,t,n,a,r,l){const c=Math.min(l,a/2,r/2);e.beginPath(),e.moveTo(t+c,n),e.lineTo(t+a-c,n),e.quadraticCurveTo(t+a,n,t+a,n+c),e.lineTo(t+a,n+r-c),e.quadraticCurveTo(t+a,n+r,t+a-c,n+r),e.lineTo(t+c,n+r),e.quadraticCurveTo(t,n+r,t,n+r-c),e.lineTo(t,n+c),e.quadraticCurveTo(t,n,t+c,n),e.closePath()}function ea({paths:e,boxes:t,memos:n=[],selectedIds:a=[],selectionBox:r=null,hoveredId:l=null,activePath:c,activeBox:s}){const d=i.useRef(null);return i.useEffect(()=>{const u=d.current;if(!u)return;const v=u.getBoundingClientRect(),f=window.devicePixelRatio||1;u.width=Math.max(1,Math.round(v.width*f)),u.height=Math.max(1,Math.round(v.height*f));const _=u.getContext("2d");if(!_)return;_.setTransform(f,0,0,f,0,0),_.clearRect(0,0,v.width,v.height);const C={width:v.width,height:v.height};for(const S of e)dt(_,S,C);for(const S of t)ht(_,S,C,"committed");for(const S of a){const U=St(S,{paths:e,boxes:t,memos:n});U&&Bt(_,U,C)}if(r&&Bt(_,r,C),l&&!a.includes(l)){const S=St(l,{paths:e,boxes:t,memos:n});S&&Yn(_,S,C)}c&&dt(_,c,C),s&&ht(_,s,C,"active")},[e,t,n,a,r,l,c,s]),o.jsx("canvas",{ref:d,className:"canvas-annotation-layer","aria-hidden":"true"})}function Oe(e){e.stopPropagation()}function ta({memos:e,activeMemoId:t,onUpdate:n,onDelete:a,onFocus:r,onCommit:l}){const{t:c}=fe();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:Oe,onPointerMove:Oe,onPointerUp:Oe,onPointerCancel:Oe,onChange:d=>n(s.id,d.currentTarget.value),onBlur:()=>{l?.(),s.text.trim()===""&&a(s.id)},"aria-label":c("common.canvasMemo")},s.id))})}function na({annotationFrameRef:e,imageElementRef:t,frameClassName:n,frameStyle:a,imageKey:r,imageSrc:l,fallbackImage:c,alt:s,canvasOpen:d,maskOverlayUrl:u,cleanupLayer:v,annotations:f,hoveredAnnotationId:_=null,onOpenCanvas:C,onPointerDown:S,onPointerMove:U,onPointerUp:L,onPointerLeave:N}){return o.jsxs("div",{ref:e,className:n,onPointerDown:S,onPointerMove:U,onPointerUp:L,onPointerCancel:L,onPointerLeave:N,style:a,children:[o.jsx("img",{ref:t,className:"result-img",src:l??c,alt:s,decoding:"async",onDoubleClick:p=>{p.stopPropagation(),C()}},r),d&&u?o.jsx("img",{className:"canvas-background-cleanup-mask",src:u,alt:"","aria-hidden":"true",decoding:"async"}):null,d?v:null,d&&o.jsxs(o.Fragment,{children:[o.jsx(ea,{paths:f.paths,boxes:f.boxes,memos:f.memos,selectedIds:f.selectedIds,selectionBox:f.selectionBox,hoveredId:_,activePath:f.activePath,activeBox:f.activeBox}),o.jsx(ta,{memos:f.memos,activeMemoId:f.activeMemoId,onUpdate:f.updateMemo,onDelete:f.deleteMemo,onFocus:f.focusMemo,onCommit:f.commitMemoEdit})]})]})}function aa(e){return`${e.x*100} ${e.y*100}`}function ra(e){return e.map(aa).join(" ")}function oa({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(c=>o.jsx("polyline",{className:`canvas-cleanup-overlay__stroke canvas-cleanup-overlay__stroke--${c.intent}`,points:ra(c.points),strokeWidth:Math.max(.3,c.radius*200),vectorEffect:"non-scaling-stroke"},c.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 sa({mode:e,matteColor:t,onModeChange:n,onMatteColorChange:a}){const{t:r}=fe();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 jt({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 la({seedCount:e,tolerance:t,stats:n,hasPreview:a,isPickingSeed:r,intent:l,tool:c,brushRadius:s,isPreviewing:d,isApplying:u,keepOpen:v,disabled:f,onAutoSample:_,onPickSeed:C,onIntentChange:S,onToolChange:U,onBrushRadiusChange:L,onToleranceChange:N,onPreview:p,onApply:M,onReset:B}){const{t:x}=fe(),[b,J]=i.useState(!1),O=i.useRef(null),V=n?Math.round(n.removedPercent*1e3)/10:0,Q=r||c==="brush";return i.useEffect(()=>{if(!b)return;const m=$=>{v||O.current?.contains($.target)||J(!1)};return window.addEventListener("pointerdown",m),()=>window.removeEventListener("pointerdown",m)},[v,b]),o.jsxs("div",{className:"canvas-toolbar__cleanup",ref:O,children:[o.jsx("button",{type:"button",className:`canvas-toolbar__button${b||a?" canvas-toolbar__button--active":""}`,onClick:()=>J(m=>!m),disabled:f,"aria-expanded":b,"aria-label":x("canvas.toolbar.cleanup"),title:x("canvas.toolbar.cleanup"),children:o.jsx(ca,{})}),b?o.jsxs("div",{className:"canvas-toolbar__cleanup-panel",role:"group","aria-label":x("canvas.toolbar.cleanup"),children:[o.jsxs("div",{className:"canvas-toolbar__cleanup-row",children:[o.jsx("span",{className:"canvas-toolbar__cleanup-title",children:x("canvas.toolbar.cleanup")}),o.jsx("span",{className:"canvas-toolbar__cleanup-meta",children:x("canvas.toolbar.cleanupSeedCount",{n:e})})]}),o.jsx(jt,{label:x("canvas.toolbar.cleanupMark"),value:l,options:[{value:"remove",label:x("canvas.toolbar.cleanupRemove")},{value:"preserve",label:x("canvas.toolbar.cleanupPreserve")}],onChange:S}),o.jsx(jt,{label:x("canvas.toolbar.cleanupInput"),value:c,options:[{value:"click",label:x("canvas.toolbar.cleanupClick")},{value:"brush",label:x("canvas.toolbar.cleanupBrush")}],onChange:U}),o.jsxs("label",{className:"canvas-toolbar__cleanup-slider",children:[o.jsx("span",{children:x("canvas.toolbar.cleanupTolerance")}),o.jsx("input",{type:"range",min:"0",max:"96",value:t,onChange:m=>N(Number(m.target.value))}),o.jsx("output",{children:t})]}),c==="brush"?o.jsxs("label",{className:"canvas-toolbar__cleanup-slider",children:[o.jsx("span",{children:x("canvas.toolbar.cleanupBrushSize")}),o.jsx("input",{type:"range",min:"0.006",max:"0.06",step:"0.002",value:s,onChange:m=>L(Number(m.target.value))}),o.jsx("output",{children:Math.round(s*1e3)})]}):null,o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:_,children:x("canvas.toolbar.cleanupAutoSample")}),o.jsx("button",{type:"button",className:r?"active":"",onClick:C,children:x(Q?"canvas.toolbar.cleanupActive":"canvas.toolbar.cleanupPickSeed")})]}),o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:p,disabled:d||e===0,children:x(d?"canvas.toolbar.cleanupPreviewing":"canvas.toolbar.cleanupPreview")}),o.jsx("button",{type:"button",onClick:M,disabled:u||!a&&e===0,children:x(u?"canvas.toolbar.cleanupApplying":"canvas.toolbar.cleanupApply")}),o.jsx("button",{type:"button",onClick:B,disabled:!a&&e===0,children:x("canvas.toolbar.cleanupReset")})]}),Q?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:x(c==="brush"?"canvas.toolbar.cleanupBrushHint":"canvas.toolbar.cleanupPickHint")}):n&&!a?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:x("canvas.toolbar.cleanupMaskHint")}):null,n?o.jsx("div",{className:"canvas-toolbar__cleanup-status",children:x("canvas.toolbar.cleanupRemoved",{n:V})}):null]}):null]})}function ca(){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"})]})}const ia=["png","svg","pptx"];function ua({onExport:e,disabled:t,isExporting:n}){const{t:a}=fe(),[r,l]=i.useState(!1),c=i.useRef(null),s=i.useRef(null),d=i.useId();i.useEffect(()=>{if(!r)return;const f=()=>Array.from(s.current?.querySelectorAll("[role='menuitem']")??[]);window.requestAnimationFrame(()=>f()[0]?.focus());const _=C=>{const S=C.target;s.current?.contains(S)||c.current?.contains(S)||l(!1)};return document.addEventListener("pointerdown",_,!0),()=>document.removeEventListener("pointerdown",_,!0)},[r]);const u=f=>{l(!1),c.current?.focus()},v=f=>{if(f.key==="Escape"){f.preventDefault(),u();return}if(!["ArrowDown","ArrowUp","Home","End"].includes(f.key))return;f.preventDefault();const C=Array.from(s.current?.querySelectorAll("[role='menuitem']")??[]);if(C.length===0)return;const S=C.indexOf(document.activeElement),U=f.key==="Home"?0:f.key==="End"?C.length-1:S<0?0:(S+(f.key==="ArrowDown"?1:-1)+C.length)%C.length;C[U]?.focus()};return o.jsxs("div",{className:"canvas-export-menu",children:[o.jsx("button",{ref:c,type:"button",className:`canvas-toolbar__button${n?" canvas-toolbar__button--busy":""}`,onClick:()=>l(f=>!f),disabled:t||n,"aria-haspopup":"menu","aria-expanded":r,"aria-controls":r?d:void 0,"aria-busy":n||void 0,"aria-label":a("canvas.toolbar.export"),title:a("canvas.toolbar.export"),children:o.jsx(da,{})}),r?o.jsx("div",{ref:s,id:d,role:"menu",className:"canvas-export-menu__list","aria-label":a("canvas.toolbar.exportFormat"),onKeyDown:v,children:ia.map(f=>o.jsx("button",{type:"button",role:"menuitem",className:"canvas-export-menu__item",onClick:()=>{u(),e(f)},children:a(`canvas.toolbar.exportAs.${f}`)},f))}):null]})}function da(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[o.jsx("path",{d:"M12 4v11"}),o.jsx("path",{d:"m8 11 4 4 4-4"}),o.jsx("path",{d:"M5 20h14"})]})}function ha({style:e,onStyleChange:t}){const{t:n}=fe(),[a,r]=i.useState(!1),l=En(a,()=>{r(!1)},{trap:!1,restoreFocus:s=>s!=="outsidePointer"}),c=i.useRef(null);return i.useEffect(()=>{if(!a)return;const s=d=>{c.current?.contains(d.target)||r(!1)};return window.addEventListener("pointerdown",s),()=>window.removeEventListener("pointerdown",s)},[a]),o.jsxs("div",{ref:c,className:`canvas-toolbar__split-button${a?" canvas-toolbar__split-button--active":""}`,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",{ref:l,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:Yt.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:Zt.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 fa({tools:e,activeTool:t,onToolChange:n}){const[a,r]=i.useState(!1),l=i.useRef(null),c=e.find(d=>d.id===t)??e[0],s=c.icon;return i.useEffect(()=>{if(!a)return;const d=u=>{l.current?.contains(u.target)||r(!1)};return window.addEventListener("pointerdown",d),()=>window.removeEventListener("pointerdown",d)},[a]),o.jsxs("div",{ref:l,className:"canvas-tool-picker",children:[o.jsxs("button",{type:"button",className:`canvas-toolbar__button canvas-tool-picker__trigger${t!=="eraser"?" canvas-toolbar__button--active":""}`,onClick:()=>r(d=>!d),"aria-label":`${c.label} (${c.shortcut})`,"aria-pressed":t===c.id,"aria-haspopup":"menu","aria-expanded":a,title:`${c.label} (${c.shortcut})`,children:[o.jsx(s,{}),o.jsx("span",{className:"canvas-toolbar__shortcut","aria-hidden":"true",children:c.shortcut})]}),a?o.jsx("div",{className:"canvas-tool-picker__menu",role:"menu",children:e.map(d=>{const u=d.icon,v=t===d.id;return o.jsxs("button",{type:"button",className:`canvas-tool-picker__item${v?" active":""}`,role:"menuitemradio","aria-checked":v,onClick:()=>{n(d.id),r(!1)},children:[o.jsx(u,{}),o.jsx("span",{children:d.label}),o.jsx("kbd",{children:d.shortcut})]},d.id)})}):null]})}function pa({activeTool:e,hasAnnotations:t,hasExportableContent:n,onToolChange:a,eraserMode:r="object",onEraserModeChange:l,style:c,onStyleChange:s,onClear:d,onApply:u,onRevertAnnotations:v,onExport:f,onUndo:_,onRedo:C,canUndo:S,canRedo:U,onDeleteSelected:L,selectedCount:N=0,onEditWithMask:p,canEditWithMask:M,isEditingWithMask:B,onGptTransparency:x,isTransparencyRunning:b,isApplying:J,isExporting:O,exportBackground:V="alpha",exportMatteColor:Q="#ffffff",onExportBackgroundChange:m,onExportMatteColorChange:$,cleanupTolerance:T=28,cleanupSeedCount:A=0,cleanupStats:D=null,cleanupHasPreview:te=!1,isCleanupPickingSeed:se=!1,isCleanupActive:ie=!1,cleanupIntent:de="remove",cleanupTool:he="click",cleanupBrushRadius:k=.018,isCleanupPreviewing:z=!1,isCleanupApplying:E=!1,onCleanupAutoSample:I,onCleanupPickSeed:F,onCleanupIntentChange:W,onCleanupToolChange:H,onCleanupBrushRadiusChange:ee,onCleanupToleranceChange:K,onCleanupPreview:R,onCleanupApply:q,onCleanupReset:ne}){const{t:y}=fe(),[ae,X]=i.useState(!1),G=i.useRef(null),ue=n??t??!1,we=y(r==="object"?"canvas.toolbar.objectEraser":"canvas.toolbar.brushEraser"),_e=[{id:"select",shortcut:"1",label:y("canvas.toolbar.select"),icon:ma},{id:"pen",shortcut:"2",label:y("canvas.toolbar.pen"),icon:va},{id:"box",shortcut:"3",label:y("canvas.toolbar.box"),icon:ba},{id:"arrow",shortcut:"4",label:y("canvas.toolbar.arrow"),icon:ga},{id:"memo",shortcut:"5",label:y("canvas.toolbar.memo"),icon:xa}];i.useEffect(()=>{if(!ae)return;const le=Ce=>{G.current?.contains(Ce.target)||X(!1)};return window.addEventListener("pointerdown",le),()=>window.removeEventListener("pointerdown",le)},[ae]);const ve=le=>{l?.(le),a("eraser"),X(!1)};return o.jsxs("div",{className:"canvas-toolbar","aria-label":y("canvas.toolbar.label"),children:[o.jsx(fa,{tools:_e,activeTool:e,onToolChange:a}),o.jsx(ha,{style:c,onStyleChange:s}),o.jsxs("div",{ref:G,className:`canvas-toolbar__split-button${e==="eraser"?" canvas-toolbar__split-button--active":""}`,onKeyDown:le=>{le.key==="Escape"&&ae&&(le.preventDefault(),X(!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":`${we} (6)`,"aria-pressed":e==="eraser",title:`${we} (6)`,children:[o.jsx(ya,{}),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:()=>X(le=>!le),"aria-label":y("canvas.toolbar.eraserMenu"),"aria-haspopup":"menu","aria-expanded":ae,"aria-controls":"canvas-eraser-menu",title:y("canvas.toolbar.eraserMenu"),children:o.jsx(wa,{})}),ae?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:()=>ve("object"),children:y("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:()=>ve("brush"),children:y("canvas.toolbar.brushEraser")})]}):null]}),o.jsx("span",{className:"canvas-toolbar__divider","aria-hidden":"true"}),u?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--primary${J?" canvas-toolbar__button--busy":""}`,onClick:u,disabled:!ue||J,"aria-label":y("canvas.toolbar.apply"),title:y("canvas.toolbar.apply"),children:o.jsx(ka,{})}):null,v?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:v,disabled:J,"aria-label":y("canvas.revert.action"),title:y("canvas.revert.action"),children:o.jsx(Pt,{})}):null,p?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--primary canvas-toolbar__button--mask${B?" canvas-toolbar__button--busy":""}`,onClick:p,disabled:!M||B,"aria-label":y(M?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),title:y(M?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),children:o.jsx(Ca,{})}):null,_?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:_,disabled:!S,"aria-label":y("canvas.toolbar.undo"),title:y("canvas.toolbar.undo"),children:o.jsx(Pt,{})}):null,C?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:C,disabled:!U,"aria-label":y("canvas.toolbar.redo"),title:y("canvas.toolbar.redo"),children:o.jsx(_a,{})}):null,L?o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:L,disabled:N===0,"aria-label":y("canvas.toolbar.deleteSelected"),title:y("canvas.toolbar.deleteSelected"),children:o.jsx(Tt,{})}):null,f&&m&&$?o.jsx(sa,{mode:V,matteColor:Q,onModeChange:m,onMatteColorChange:$}):null,I&&F&&W&&H&&ee&&K&&R&&q&&ne?o.jsx(la,{seedCount:A,tolerance:T,stats:D,hasPreview:te,isPickingSeed:se,intent:de,tool:he,brushRadius:k,isPreviewing:z,isApplying:E,keepOpen:ie,disabled:J||O,onAutoSample:I,onPickSeed:F,onIntentChange:W,onToolChange:H,onBrushRadiusChange:ee,onToleranceChange:K,onPreview:R,onApply:q,onReset:ne}):null,x?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--transparency${b?" canvas-toolbar__button--busy":""}`,onClick:x,disabled:b||J||B,"aria-label":y("canvas.toolbar.gptTransparency"),title:y("canvas.toolbar.gptTransparency"),children:b?o.jsx("span",{className:"canvas-toolbar__spinner","aria-hidden":"true"}):o.jsx(Ma,{})}):null,f?o.jsx(ua,{onExport:f,disabled:!ue,isExporting:!!O}):null,o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:d,disabled:!ue,"aria-label":y("canvas.toolbar.clear"),title:y("canvas.toolbar.clear"),children:o.jsx(Tt,{})})]})}function ma(){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 va(){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 ba(){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 ga(){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 xa(){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 ya(){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 wa(){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 ka(){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 Tt(){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 Pt(){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 _a(){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 Ca(){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 Ma(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",fill:"none"}),o.jsx("path",{d:"M4 8h4V4M12 4v4h4v4h4M4 12h4v4H4M12 12v4h-4M12 20v-4h4v4M20 16h-4",opacity:"0.55"})]})}function Ea({annotations:e,backgroundCleanup:t,backgroundCleanupPreview:n,canvasState:a,actions:r}){return o.jsx(pa,{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()},onRevertAnnotations:a.canRevertAnnotations?()=>{r.handleRevertAnnotations()}:void 0,onExport:l=>{r.handleExportCanvas(l)},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,onGptTransparency:()=>{r.handleGptTransparency()},isTransparencyRunning:a.isTransparencyRunning,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 Sa({currentImage:e,canvasDisplayImage:t,canvasOpen:n,displayQuality:a,displaySize:r,displayModel:l,onAfterDeleteFocus:c,onCopyPrompt:s}){const{t:d}=fe(),u=[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?d("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,Sn(e.reasoningEffort),a,r,l].filter(v=>!!v).join(" · ");return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"result-meta",children:u}),o.jsx(Bn,{imageOverride:n?t:null,onAfterDeleteFocus:c}),e.prompt?o.jsx(jn,{prompt:e.prompt,onCopy:s}):null]})}function Ba({zoom:e,onZoomIn:t,onZoomOut:n,onZoomReset:a}){const{t:r}=fe(),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(ja,{})}),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(Ta,{})})]})}function ja(){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 Ta(){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 Pa({zoom:e,modeLabel:t,closeLabel:n,blankCanvasLabel:a,blankCanvasAriaLabel:r,blankCanvasShortcut:l,blankCanvasBusy:c,shortcutHint:s,onZoomIn:d,onZoomOut:u,onZoomReset:v,onCreateBlankCanvas:f,onClose:_}){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:t}),o.jsx(Ba,{zoom:e,onZoomIn:d,onZoomOut:u,onZoomReset:v}),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:f,disabled:c,"aria-label":r,title:r,children:[o.jsx("span",{"aria-hidden":"true",children:"+"}),o.jsx("span",{children:a}),o.jsx("kbd",{children:l})]})}),o.jsxs("button",{type:"button",className:"canvas-mode-close",onClick:_,"aria-label":n,children:[o.jsx("kbd",{children:"ESC"}),o.jsx("span",{children:n})]})]})}function ot(e,t,n){return Math.max(t,Math.min(n,e))}function Aa({zoom:e,panX:t,panY:n}){const a=ot(100/Math.max(1,e),18,100),r=a/2,l=ot(50-t/40,r,100-r),c=ot(50-n/40,r,100-r);return{width:`${a}%`,height:`${a}%`,left:`${l}%`,top:`${c}%`}}function Da({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:Aa({zoom:t,panX:n,panY:a}),"aria-hidden":"true"})]})}function Le(e){return Math.min(1,Math.max(0,e))}function Ra(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("mask_blob_unavailable"))},"image/png")})}async function Na(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 c=Le(l.x)*t,s=Le(l.y)*n,d=Le(l.width)*t,u=Le(l.height)*n;d>0&&u>0&&r.fillRect(c,s,d,u)}return Ra(a)}async function Ia(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 bt(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 Oa=`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`,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.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 $a(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 Wa(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 Fa(e){const t=e.canvasSourceFilename??e.filename;return t?`/generated/${encodeURIComponent(t)}`:e.url??e.image}async function st(e){const t=Fa(e);if(t.startsWith("data:image/png;"))return t;const n=new Image;return await new Promise((a,r)=>{n.onload=()=>a(),n.onerror=()=>r(new Error("clean_source_load_failed")),n.src=t}),Ia(n)}function Ke(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?Ke(n,t):null}function At(e,t){if(Tn(e)){const n=e.images[0];if(!n)throw new Error("edit_empty_response");return{...n,prompt:t,reasoningEffort:e.reasoningEffort,provider:e.provider,quality:e.quality,size:e.size,moderation:e.moderation,model:e.model,usage:e.usage,alphaVerified:e.alphaVerified,alphaReason:e.alphaReason,kind:"edit",createdAt:Date.now()}}return{image:e.image,url:e.filename?`/generated/${e.filename}`:e.image,thumb:e.image,filename:e.filename,prompt:t,elapsed:e.elapsed,reasoningEffort:e.reasoningEffort,provider:e.provider,quality:e.quality,size:e.size,moderation:e.moderation,model:e.model,usage:e.usage,revisedPrompt:e.revisedPrompt??null,promptMode:e.promptMode??null,alphaVerified:e.alphaVerified,alphaReason:e.alphaReason,kind:"edit",createdAt:Date.now()}}const lt=new WeakMap;function Ka(e){if(!e.complete||!e.naturalWidth||!e.naturalHeight)return!1;const t=lt.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 c=l.getContext("2d",{willReadFrequently:!0});if(!c)return!1;try{c.drawImage(e,0,0,a,r);const s=c.getImageData(0,0,a,r).data;for(let d=3;d<s.length;d+=4)if(s[d]<250)return lt.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!0}),!0;return lt.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!1}),!1}catch{return!1}}function Va(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 Dt(e,t){return{width:e,height:t,data:new Uint8Array(e*t)}}function ft(e){return{width:e.width,height:e.height,data:new Uint8Array(e.data)}}function za(e,t){Va(e,t);for(let n=0;n<e.data.length;n+=1)(t.data[n]??0)>0&&(e.data[n]=0)}function je(e,t){if(!e)return null;const n=ft(e);return t&&za(n,t),n}function qa(e,t){if(e.width!==t.width||e.height!==t.height)throw new Error("cleanup_mask_size_mismatch");const n=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);for(let a=0;a<t.data.length;a+=1)(t.data[a]??0)>0&&(n.data[a*4+3]=0);return n}const gt=[{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}],Xa=1024;function Ga(e){return Math.max(0,Math.min(255,Math.round(e)))}function Qt(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 Ya(e,t){return(t.length>0?t:gt).map(a=>{const r=Qt(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 Za(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 Te(e,t,n,a,r,l,c){if(e<0||e>=a.length||a[e])return r;const s=e*4;return(t.data[s+3]??0)===0?(a[e]=1,r):Za(t.data,s,l,c)?(a[e]=1,n[r]=e,r+1):r}function ct(){return gt.map(e=>({...e}))}function Rt(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,c=r*l,s=new Uint8Array(c),d=new Int32Array(c),u=Ya(t,n),v=Ga(a);let f=0;for(const _ of n.length>0?n:gt)f=Te(Qt(_,r,l),t,d,s,f,u,v);for(;f>0;){const _=d[--f];e.data[_]=255;const C=_%r;C>0&&(f=Te(_-1,t,d,s,f,u,v)),C<r-1&&(f=Te(_+1,t,d,s,f,u,v)),_>=r&&(f=Te(_-r,t,d,s,f,u,v)),_<c-r&&(f=Te(_+r,t,d,s,f,u,v))}}function Ja(e,t){const n=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),a=qa(n,t),r=t.data.reduce((l,c)=>l+(c>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 en(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("background_cleanup_blob_failed"))},"image/png")})}function tn(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)),c=Math.max(1,Math.round(a*r)),s=document.createElement("canvas");s.width=l,s.height=c;const d=s.getContext("2d",{willReadFrequently:!0});if(!d)throw new Error("background_cleanup_context_failed");return d.drawImage(e,0,0,l,c),{canvas:s,context:d,width:l,height:c}}async function Nt({imageElement:e,mask:t}){try{const{canvas:n,context:a,width:r,height:l}=tn(e),c=a.getImageData(0,0,r,l),s=Ja({width:r,height:l,data:c.data},t),d=a.createImageData(r,l);d.data.set(s.imageData.data),a.putImageData(d,0,0);const u=await en(n);return{blob:u,dataUrl:await bt(u),stats:s.stats}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}async function Qa({imageElement:e,mask:t}){try{const{width:n,height:a}=tn(e,Xa),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 c=l.createImageData(n,a);let s=0;for(let u=0;u<a;u+=1)for(let v=0;v<n;v+=1){const f=Math.min(t.width-1,Math.floor(v/n*t.width)),_=Math.min(t.height-1,Math.floor(u/a*t.height));if((t.data[_*t.width+f]??0)===0)continue;const C=(u*n+v)*4;c.data[C]=168,c.data[C+1]=85,c.data[C+2]=247,c.data[C+3]=150,s+=1}l.putImageData(c,0,0);const d=await en(r);return{dataUrl:await bt(d),stats:{width:t.width,height:t.height,removedPixels:t.data.reduce((u,v)=>u+(v>0?1:0),0),removedPercent:t.data.length>0?s/(n*a):0}}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}function It(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?ft(e.removeMask):null,preserveMask:e.preserveMask?ft(e.preserveMask):null}}function er(){return`cleanup_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function $e(e){return Math.max(0,Math.min(1,e))}function tr(e){const t=[],n=Math.max(0,e.radius*.55);for(const a of e.points)t.push({...a}),!(n<=0)&&t.push({x:$e(a.x-n),y:a.y},{x:$e(a.x+n),y:a.y},{x:a.x,y:$e(a.y-n)},{x:a.x,y:$e(a.y+n)});return t}function nr(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 ar({canvasOpen:e,currentImage:t,canvasDisplayImage:n,imageElementRef:a,canvasSourceImageRef:r,lastMergedDataUrlRef:l,setCanvasSaveState:c,setCanvasVersionItem:s,applyMergedCanvasImage:d,attachCanvasVersionReference:u,showToast:v,t:f}){const[_,C]=i.useState(!1),[S,U]=i.useState("remove"),[L,N]=i.useState("click"),[p,M]=i.useState("flat-flood-fill"),[B,x]=i.useState([]),[b,J]=i.useState([]),[O,V]=i.useState(28),[Q,m]=i.useState(null),[$,T]=i.useState(null),[A,D]=i.useState(null),[te,se]=i.useState(!1),[ie,de]=i.useState(.018),[he,k]=i.useState(null),[z,E]=i.useState(!1),[I,F]=i.useState(!1),W=i.useRef(null),H=i.useRef(null),ee=i.useRef(null),K=i.useRef({past:[],future:[]}),R=i.useRef(0),q=i.useRef(null),ne=i.useCallback(()=>It({intent:S,tool:L,engine:p,seeds:B,brushStrokes:b,brushRadius:ie,tolerance:O,removeMask:W.current,preserveMask:H.current,preview:Q,maskOverlay:$,stats:A,active:te,brushCursor:he}),[b,$,Q,B,A,O,he,ie,p,S,L,te]),y=i.useCallback(()=>{K.current={past:[...K.current.past.slice(-19),ne()],future:[]}},[ne]),ae=i.useCallback(w=>{const g=It(w);W.current=g.removeMask,H.current=g.preserveMask,ee.current=null,U(g.intent),N(g.tool),M(g.engine),x(g.seeds),J(g.brushStrokes),de(g.brushRadius),V(g.tolerance),m(g.preview),T(g.maskOverlay),D(g.stats),se(g.active),k(g.brushCursor),E(!1),F(!1)},[]),X=i.useCallback(async()=>{if(!a.current||!t)return;const w=je(W.current,H.current);if(!w){T(null),D(null);return}const g=R.current+1;R.current=g,E(!0);try{const j=await Qa({imageElement:a.current,mask:w});if(R.current!==g)return;T(j),D(j.stats)}catch{if(R.current!==g)return;v(f("canvas.toolbar.cleanupFailed"),!0)}finally{R.current===g&&E(!1)}},[t,a,v,f]),G=i.useCallback(async(w,g,j)=>{if(!a.current)return;const re=nr(a.current),Z=Dt(re.width,re.height),Me=Dt(re.width,re.height);for(const be of w){const ke=be.intent==="remove"?Z:Me;Rt(ke,re,[be.point],j)}for(const be of g){const ke=be.intent==="remove"?Z:Me;Rt(ke,re,tr(be),j)}W.current=Z,H.current=Me},[a]),ue=i.useCallback(()=>{R.current+=1,q.current!=null&&(window.clearTimeout(q.current),q.current=null),W.current=null,H.current=null,ee.current=null,K.current={past:[],future:[]},x([]),J([]),m(null),T(null),D(null),se(!1),k(null),E(!1),F(!1)},[]),we=i.useCallback(()=>{const w=K.current.past.pop();return w?(K.current.future=[ne(),...K.current.future.slice(0,19)],ae(w),!0):!1},[ne,ae]),_e=i.useCallback(()=>{const w=K.current.future.shift();return w?(K.current.past=[...K.current.past.slice(-19),ne()],ae(w),!0):!1},[ne,ae]),ve=i.useCallback(w=>{y();const g=[...B,{point:w,intent:S}];x(g),m(null),G(g,b,O).then(X)},[b,B,O,S,y,G,X]),le=i.useCallback(()=>{y();const w=ct().map(g=>({point:g,intent:"remove"}));x(w),m(null),se(!1),G(w,b,O).then(X)},[b,O,y,G,X]),Ce=i.useCallback(()=>{y(),N("click"),se(w=>!w)},[y]),Ve=i.useCallback(w=>{y(),q.current!=null&&window.clearTimeout(q.current),V(w),m(null),q.current=window.setTimeout(()=>{q.current=null,G(B,b,w).then(X)},180)},[b,B,y,G,X]),ze=i.useCallback(async()=>{if(!a.current||!t)return null;let w=je(W.current,H.current);if(!w){const j=ct().map(re=>({point:re,intent:"remove"}));x(j),await G(j,b,O),w=je(W.current,H.current)}if(!w)return null;y();const g=R.current+1;R.current=g,E(!0);try{const j=await Nt({imageElement:a.current,mask:w});return R.current!==g?null:(m(j),T(null),D(j.stats),j)}catch{return R.current!==g||v(f("canvas.toolbar.cleanupFailed"),!0),null}finally{R.current===g&&E(!1)}},[b,O,t,a,y,G,v,f]),qe=i.useCallback(()=>{y(),ue()},[y,ue]),Y=i.useCallback(w=>{y();const g={id:er(),intent:S,points:[{...w}],radius:ie};ee.current=g,k(w),J(j=>[...j,g])},[ie,S,y]),Xe=i.useCallback(w=>{const g=ee.current;if(!g){k(w);return}g.points=[...g.points,{...w}],k(w),J(j=>j.map(re=>re.id===g.id?{...g,points:g.points.map(Z=>({...Z}))}:re)),G(B,b.map(j=>j.id===g.id?g:j),O).then(X)},[b,B,O,G,X]),Ge=i.useCallback(()=>{ee.current=null,G(B,b,O).then(X)},[b,B,O,G,X]),Ye=i.useCallback(async()=>{if(!t||!a.current)return;const w=r.current??t;if(!w?.filename){v(f("canvas.toolbar.cleanupFailed"),!0);return}let g=je(W.current,H.current);if(!g){const j=ct().map(re=>({point:re,intent:"remove"}));x(j),await G(j,b,O),g=je(W.current,H.current)}if(g){F(!0),c("saving");try{y();const j=await Nt({imageElement:a.current,mask:g}),re=n?.canvasVersion&&n.filename?await Ft(n.filename,{sourceFilename:w.canvasSourceFilename??w.filename,image:j.blob,prompt:w.prompt,pixelEdited:!0}):await Ht({sourceFilename:w.canvasSourceFilename??w.filename,image:j.blob,prompt:w.prompt}),Z=Ke(re.item,w);l.current=j.dataUrl,s(Z),d(Z),await u(Z),c("saved"),m(null),T(null),D(j.stats),se(!1),v(f("canvas.toolbar.cleanupApplied"))}catch{c("error"),v(f("canvas.toolbar.cleanupFailed"),!0)}finally{F(!1)}}},[d,u,b,O,n,r,t,a,l,y,G,c,s,v,f]),Ze=i.useCallback(()=>te?(ee.current=null,se(!1),k(null),!0):!1,[te]);return i.useEffect(()=>{const w=a.current;if(!w||!e){C(!1);return}const g=()=>C(Ka(w));if(w.complete)g();else return w.addEventListener("load",g),()=>w.removeEventListener("load",g)},[e,n?.canvasMergedAt,n?.filename,n?.image,n?.url,Q?.dataUrl,a]),{imageHasAlpha:_,backgroundCleanupSeeds:B,backgroundCleanupBrushStrokes:b,backgroundCleanupTolerance:O,backgroundCleanupPreview:Q,backgroundCleanupMaskOverlay:$,backgroundCleanupStats:A,cleanupIntent:S,setCleanupIntent:U,cleanupTool:L,setCleanupTool:N,cleanupClickEngine:p,setCleanupClickEngine:M,cleanupBrushRadius:ie,setCleanupBrushRadius:de,cleanupBrushCursor:he,setCleanupBrushCursor:k,isBackgroundCleanupActive:te,setIsBackgroundCleanupActive:se,isBackgroundCleanupPickingSeed:te&&L==="click",isBackgroundCleanupPreviewing:z,isBackgroundCleanupApplying:I,hasActiveCleanupStroke:!!ee.current,canUndoBackgroundCleanup:K.current.past.length>0,canRedoBackgroundCleanup:K.current.future.length>0,resetBackgroundCleanup:ue,undoBackgroundCleanup:we,redoBackgroundCleanup:_e,addBackgroundCleanupClick:ve,addBackgroundCleanupSeed:ve,runBackgroundCleanupPreview:ze,handleBackgroundCleanupAutoSample:le,handleBackgroundCleanupPickSeed:Ce,handleBackgroundCleanupToleranceChange:Ve,handleBackgroundCleanupReset:qe,handleBackgroundCleanupApply:Ye,handleBackgroundCleanupEscape:Ze,startBackgroundCleanupBrushStroke:Y,updateBackgroundCleanupBrushStroke:Xe,endBackgroundCleanupBrushStroke:Ge}}function Ot(e){return Math.min(1,Math.max(0,e))}function Lt(e,t){const n=t.getBoundingClientRect();return{x:Ot((e.clientX-n.left)/n.width),y:Ot((e.clientY-n.top)/n.height)}}const rr=.18,or=.12;function sr(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 pt(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 nn(e){return{id:e.id,x:e.x,y:e.y,width:rr,height:or,color:e.color,strokeWidth:1}}function lr(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,c=e.y-t.y,s=a*a+r*r;if(s===0)return Math.hypot(e.x-t.x,e.y-t.y);const d=Math.max(0,Math.min(1,(l*a+c*r)/s));return Math.hypot(e.x-(t.x+d*a),e.y-(t.y+d*r))}function cr(e,t,n){for(let a=1;a<t.points.length;a+=1)if(lr(e,t.points[a-1],t.points[a])<=n)return!0;return!1}function $t(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 ir(e,t){return e.points.some(n=>pt(n,t))}function it(e){const t=e.tolerance??.015;for(const n of[...e.memos].reverse())if(pt(e.point,nn(n),t))return Xt(n);for(const n of[...e.boxes].reverse())if(pt(e.point,n,t))return qt(n);for(const n of[...e.paths].reverse())if(cr(e.point,n,t))return zt(n);return null}function ur(e){const t=[];for(const n of e.annotations.paths)ir(n,e.box)&&t.push(zt(n));for(const n of e.annotations.boxes)$t(n,e.box)&&t.push(qt(n));for(const n of e.annotations.memos)$t(nn(n),e.box)&&t.push(Xt(n));return t}function dr({canvasOpen:e,canvasZoom:t,canvasPanX:n,canvasPanY:a,spaceHeld:r,canDragViewportWithSelect:l,isBackgroundCleanupActive:c,cleanupTool:s,annotationFrameRef:d,annotations:u,setCanvasPan:v,addBackgroundCleanupClick:f,startBackgroundCleanupBrushStroke:_,updateBackgroundCleanupBrushStroke:C,endBackgroundCleanupBrushStroke:S,setCleanupBrushCursor:U,setHoveredAnnotationId:L}){const N=i.useRef({mode:null,lastPoint:null,didMove:!1}),p=i.useRef({active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null}),[M,B]=i.useState(!1),x=m=>{m.currentTarget.setPointerCapture(m.pointerId),p.current={active:!0,startX:m.clientX,startY:m.clientY,basePanX:n,basePanY:a,pointerId:m.pointerId},B(!0)};return{viewportPanActive:M,resetPointerSession:()=>{N.current={mode:null,lastPoint:null,didMove:!1},p.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},B(!1),L(null)},handleAnnotationPointerDown:m=>{if(!e||me(m.target)||!d.current)return;const $=m.button===1;if(r||$){m.preventDefault(),x(m);return}m.preventDefault();const T=Lt(m,d.current);if(c){s==="click"?f(T):(m.currentTarget.setPointerCapture(m.pointerId),_(T));return}if(u.activeTool==="select"){const A=it({point:T,paths:u.paths,boxes:u.boxes,memos:u.memos});if(A)m.shiftKey?u.toggleSelected(A):u.selectOne(A),u.startSelectedMove(),N.current={mode:"move",lastPoint:T,didMove:!1};else if(l&&t>1.01){x(m);return}else u.clearSelection(),u.startSelectionBox(T),N.current={mode:"box",lastPoint:T,didMove:!1};m.currentTarget.setPointerCapture(m.pointerId);return}if(u.activeTool==="memo"){u.createMemo(T),requestAnimationFrame(()=>{d.current?.querySelector(".canvas-memo--active")?.focus()});return}if(u.activeTool==="eraser"){if(u.eraserMode==="object"){const A=it({point:T,paths:u.paths,boxes:u.boxes,memos:u.memos});A&&u.eraseObjectAtPoint(A);return}m.currentTarget.setPointerCapture(m.pointerId),u.startEraserStroke(T);return}m.currentTarget.setPointerCapture(m.pointerId),u.startDrawing(T)},handleAnnotationPointerMove:m=>{if(!e||me(m.target)||!d.current)return;if(p.current.active){const T=m.clientX-p.current.startX,A=m.clientY-p.current.startY;v(p.current.basePanX+T,p.current.basePanY+A);return}const $=Lt(m,d.current);if(c){L(null),s==="brush"?C($):U($);return}if(u.activeTool==="select"){if(N.current.mode===null){const T=it({point:$,paths:u.paths,boxes:u.boxes,memos:u.memos});L(T)}else L(null);if(N.current.mode==="move"&&N.current.lastPoint){const T={x:$.x-N.current.lastPoint.x,y:$.y-N.current.lastPoint.y};(Math.abs(T.x)>5e-4||Math.abs(T.y)>5e-4)&&(u.moveSelected(T),N.current.didMove=!0),N.current.lastPoint=$}else N.current.mode==="box"&&u.updateSelectionBox($);return}if(u.activeTool!=="memo"){if(u.activeTool==="eraser"){u.eraserMode==="brush"&&u.updateEraserStroke($);return}u.moveDrawing($)}},handleAnnotationPointerUp:m=>{if(e&&!me(m.target)){if(p.current.active&&p.current.pointerId===m.pointerId){m.currentTarget.hasPointerCapture(m.pointerId)&&m.currentTarget.releasePointerCapture(m.pointerId),p.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},B(!1);return}if(m.currentTarget.hasPointerCapture(m.pointerId)&&m.currentTarget.releasePointerCapture(m.pointerId),c){s==="brush"&&S();return}if(u.activeTool==="select"){N.current.mode==="move"&&N.current.didMove&&u.commitSelectedMove(),N.current.mode==="box"&&u.selectionBox&&u.endSelectionBox(ur({box:sr(u.selectionBox),annotations:u.toPayload()})),N.current={mode:null,lastPoint:null,didMove:!1};return}if(u.activeTool!=="memo"){if(u.activeTool==="eraser"){u.eraserMode==="brush"&&u.endEraserStroke();return}u.endDrawing()}}},handleAnnotationPointerLeave:()=>{c&&U(null),L(null)}}}function hr({canvasOpen:e,canvasZoom:t,currentImage:n,annotations:a,undoBackgroundCleanup:r,redoBackgroundCleanup:l,handleBackgroundCleanupEscape:c,handleCloseCanvas:s,selectHistoryShortcutTarget:d,trashHistoryItem:u,permanentlyDeleteHistoryItemByShortcut:v,setCanvasZoom:f,resetCanvasZoom:_,onCreateBlankCanvas:C,isCreatingBlankCanvas:S}){const[U,L]=i.useState(!1);return i.useEffect(()=>{if(!e)return;const p=b=>{b.preventDefault()},M=b=>{b.ctrlKey&&b.preventDefault()},B={passive:!1,capture:!0},x={passive:!1};return window.addEventListener("wheel",M,B),window.addEventListener("gesturestart",p,x),window.addEventListener("gesturechange",p,x),window.addEventListener("gestureend",p,x),()=>{window.removeEventListener("wheel",M,B),window.removeEventListener("gesturestart",p,x),window.removeEventListener("gesturechange",p,x),window.removeEventListener("gestureend",p,x)}},[e]),i.useEffect(()=>{if(!e)return;const p=B=>{B.code==="Space"&&(me(B.target)||(U||L(!0),B.preventDefault()))},M=B=>{B.code==="Space"&&L(!1)};return window.addEventListener("keydown",p),window.addEventListener("keyup",M),()=>{window.removeEventListener("keydown",p),window.removeEventListener("keyup",M)}},[e,U]),i.useEffect(()=>{if(!e)return;const p=M=>{if(!M.defaultPrevented){if(me(M.target)){M.key==="Escape"&&(M.preventDefault(),M.target.blur(),a.focusMemo(null));return}if(M.key==="Escape"){if(M.preventDefault(),c())return;s();return}if(M.shiftKey&&!M.metaKey&&!M.ctrlKey&&!M.altKey&&M.key.toLowerCase()==="b"){M.preventDefault(),!S&&!M.repeat&&C();return}if((M.metaKey||M.ctrlKey)&&M.key.toLowerCase()==="z"){if(M.preventDefault(),M.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,s,c,S,C,l,r]),{spaceHeld:U,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 M=["select","pen","box","arrow","memo","eraser"];a.setTool(M[Number(p.key)-1]);return}if(e&&p.key==="Escape"){if(p.preventDefault(),p.stopPropagation(),c())return;s();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){v(n);return}u(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"?d("previous"):p.key==="ArrowRight"?d("next"):p.key==="Home"?d("first"):p.key==="End"&&d("last")))}}}function fr(e,t){return new Promise((n,a)=>{e.toBlob(r=>{if(r){n(r);return}a(new Error("canvas_blob_unavailable"))},t)})}async function Fe(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)dt(n,l,a);for(const l of e.boxes)ht(n,l,a,"committed");for(const l of e.memos)Gn(n,l,a);return{blob:await fr(t,"image/png"),dataUrl:t.toDataURL("image/png")}}const pr=["left","center","right"],mr=["top","middle","bottom"];function vr(e,t){const n=pr[Math.min(2,Math.max(0,Math.floor(e*3)))],a=mr[Math.min(2,Math.max(0,Math.floor(t*3)))];return`${a==="middle"&&n==="center"?"center":`${a} ${n}`} area (x: ${Math.round(e*100)}%, y: ${Math.round(t*100)}% from top-left)`}function Ut(e){const t=e.map(n=>({...n,text:n.text.trim()})).filter(n=>n.text.length>0);return t.length===0?"":["The numbered notes below are temporary editing instructions written on the image. They are not image content: interpret each one to locate and apply the requested change (percentages are relative to image width and height).",...t.map((n,a)=>`${a+1}. At the ${vr(n.x,n.y)}: ${n.text}`),"After applying every numbered instruction, remove all annotation markup. Do not render any annotation text, sticky notes, boxes, arrows, or markup in the output image. Where markup covered the image, show the underlying content reconstructed to match the surrounding texture, lighting, and perspective, with no residue, outline, or discoloration.","Keep everything not named in the numbered instructions exactly the same as the source image: composition, subjects, lighting, colors, and background."].join(`
3
+ `)}const Wt=18,Pe=12,br="14px sans-serif";function Ne(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function oe(e){return Math.round(e*100)/100}function gr(e,t){if(e.points.length<2)return"";const n=e.points.map(s=>De(s,t)),a=n.map((s,d)=>`${d===0?"M":"L"}${oe(s.x)} ${oe(s.y)}`).join(" "),r=`stroke="${Ne(e.color)}" stroke-width="${e.strokeWidth}" stroke-linecap="round" stroke-linejoin="round" fill="none"`,l=`<path d="${a}" ${r} />`;if(e.tool!=="arrow")return l;const c=Jt(n[n.length-2],n[n.length-1],e.strokeWidth).map(s=>`${oe(s.x)},${oe(s.y)}`).join(" ");return`${l}<polygon points="${c}" fill="${Ne(e.color)}" />`}function xr(e,t){return`<rect x="${oe(e.x*t.width)}" y="${oe(e.y*t.height)}" width="${oe(e.width*t.width)}" height="${oe(e.height*t.height)}" fill="none" stroke="${Ne(e.color)}" stroke-width="${e.strokeWidth}" />`}function yr(e,t){const n=e.trim();if(!n)return[""];const a=[];let r="";for(const l of n.split(/\s+/)){if(l.length>t){r&&(a.push(r),r="");for(let s=0;s<l.length;s+=t)a.push(l.slice(s,s+t));continue}const c=r?`${r} ${l}`:l;c.length<=t?r=c:(a.push(r),r=l)}return r&&a.push(r),a.length>0?a:[""]}function wr(e,t){const n=oe(e.x*t.width),a=oe(e.y*t.height),r=oe(Math.min(260,Math.max(150,t.width*.22))),l=Math.max(8,Math.floor((r-Pe*2)/7.5)),c=yr(e.text,l),s=oe(Math.max(52,Pe*2+c.length*Wt)),d=c.map((u,v)=>`<tspan x="${oe(n+Pe)}" dy="${v===0?0:Wt}">${Ne(u)}</tspan>`).join("");return`<g><rect x="${n}" y="${a}" width="${r}" height="${s}" rx="8" fill="rgba(255, 246, 179, 0.96)" stroke="rgba(44, 37, 12, 0.28)" stroke-width="1" /><text x="${oe(n+Pe)}" y="${oe(a+Pe+14)}" font="${br}" font-family="sans-serif" font-size="14" fill="#2f2a13">${d}</text></g>`}function kr(e){const{imageSize:t,annotations:n}=e,a=[`<image href="${Ne(e.imageDataUrl)}" x="0" y="0" width="${t.width}" height="${t.height}" preserveAspectRatio="none" />`,...n.paths.map(r=>gr(r,t)),...n.boxes.map(r=>xr(r,t)),...n.memos.map(r=>wr(r,t))].filter(Boolean);return`<svg xmlns="http://www.w3.org/2000/svg" width="${t.width}" height="${t.height}" viewBox="0 0 ${t.width} ${t.height}">`+a.join("")+"</svg>"}const Ue=10,We=5.625;function _r(e){const t=e.width/e.height,n=Ue/We,a=t>=n?Ue:We*t,r=t>=n?Ue/t:We;return{x:(Ue-a)/2,y:(We-r)/2,w:a,h:r}}function Cr(e,t){const n=Math.min(2.6,t.w*.24);return{x:t.x+e.x*t.w,y:t.y+e.y*t.h,w:n,h:.55}}async function Mr(e){const{default:t}=await Pn(async()=>{const{default:c}=await import("./pptxgen.es-CSd_gCsx.js");return{default:c}},__vite__mapDeps([0,1,2])),n=new t;n.layout="LAYOUT_16x9";const a=n.addSlide(),r=_r(e.imageSize);a.addImage({data:e.mergedDataUrl,...r});for(const c of e.memos){const s=c.text.trim();s&&a.addText(s,{...Cr(c,r),fontSize:11,color:"2F2A13",fill:{color:"FFF6B3"},line:{color:"2C250C",width:.5},align:"left",valign:"top",shrinkText:!0})}return await n.write({outputType:"blob"})}function Er(e={},t=new Date){const n=t.toISOString().slice(0,19).replace(/[-:T]/g,""),a=e.matte?"-flat":"";return`canvas-export-${n}${a}.${e.format??"png"}`}async function Sr(e,t,n){const a={width:t.imageElement.naturalWidth,height:t.imageElement.naturalHeight};if(e==="svg"){const c=await Fe({...t,paths:[],boxes:[],memos:[]}),s=kr({imageDataUrl:c.dataUrl,imageSize:a,annotations:n});return new Blob([s],{type:"image/svg+xml"})}const r=await Fe(t);if(e==="png")return r.blob;const l=await Fe({...t,memos:[]});return Mr({mergedDataUrl:l.dataUrl,imageSize:a,memos:n.memos})}function Br(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 jr({imageElementRef:e,currentImage:t,canvasDisplayImage:n,canvasSourceImageRef:a,lastMergedDataUrlRef:r,lastCleanDataUrlRef:l,canvasVersionItem:c,annotations:s,exportBackground:d,exportMatteColor:u,quality:v,format:f,moderation:_,provider:C,imageModel:S,reasoningEffort:U,promptMode:L,webSearchEnabled:N,getResolvedSize:p,setCanvasVersionItem:M,setCanvasSaveState:B,setIsApplying:x,setIsExporting:b,setIsEditingWithMask:J,setIsTransparencyRunning:O,applyMergedCanvasImage:V,addGeneratedHistoryItem:Q,attachCanvasVersionReference:m,closeCanvas:$,resetCanvasSession:T,showToast:A,t:D}){const te=i.useCallback(async()=>{if(!e.current||!t)return null;const E=a.current??t;if(!E?.filename)return A(D("canvas.version.failed"),!0),null;x(!0),B("saving");try{const I=await Fe({imageElement:e.current,paths:s.paths,boxes:s.boxes,memos:s.memos});r.current=I.dataUrl;const F=await st(E);l.current=F;const W=c?.filename?await Ft(c.filename,{image:I.blob,sourceFilename:E.canvasSourceFilename??E.filename,prompt:E.prompt}):await Ht({sourceFilename:E.filename,image:I.blob,prompt:E.prompt}),H=s.toPayload(),ee=!c||!!c.annotationOnly,K=await An(W.item.filename,H,ee),R=Ke(K.item,E);M(R),V(R),await m(R,F);const q=Ut(s.memos),ne=`canvas-annotations:${E.canvasSourceFilename??E.filename}`,{insertPromptToComposer:y,removeInsertedPromptFromComposer:ae}=P.getState();return ae(ne),q&&y({id:ne,name:D("canvas.annotationInstructionsChip"),text:q,placement:"after"}),await Kt(E.filename).catch(()=>{}),s.resetLocal(),s.markSaved(),B("saved"),A(D("canvas.version.saved")),R}catch{return B("error"),A(D("canvas.version.failed"),!0),null}finally{x(!1)}},[s,V,m,a,c?.filename,t,e,r,l,B,M,x,A,D]);return{saveCanvasVersionAndUseReference:te,handleApplyCanvas:async()=>{await te()},handleRevertAnnotations:async()=>{if(!(!c?.filename||!c.annotationsBaked)&&!(!c.annotationOnly&&!window.confirm(D("canvas.revert.mixedConfirm")))){x(!0),B("saving");try{const E=await Dn(c.filename),I=a.current??t??c,F=Ke(E.item,I);if(M(F),V(F),r.current=null,E.annotationOnly&&E.snapshot){s.load(E.snapshot);const W=F.canvasSourceFilename??I.filename;W&&await Vt(W,E.snapshot),A(D("canvas.revert.restored"))}else s.resetLocal(),A(D("canvas.revert.completed"));B("saved")}catch{B("error"),A(D("canvas.revert.failed"),!0)}finally{x(!1)}}},handleCloseCanvas:async()=>{(s.hasAnnotations||s.isDirty)&&!await te()||($(),T())},handleExportCanvas:async(E="png")=>{if(!(!e.current||!t)){b(!0);try{const I=d==="matte",F=await Sr(E,{imageElement:e.current,paths:s.paths,boxes:s.boxes,memos:s.memos,background:I?{mode:"matte",color:u}:{mode:"alpha"}},{paths:s.paths,boxes:s.boxes,memos:s.memos});Br(F,Er({matte:I,format:E}))}catch{A(D("canvas.toolbar.exportFailed"),!0)}finally{b(!1)}}},handleEditWithMask:async()=>{if(!(!e.current||!n||s.boxes.length===0)){J(!0);try{const E=s.memos;let I=l.current;if(C==="nai"){A(D("toast.naiEditUnsupported"),!0);return}if(s.isDirty||s.hasAnnotations){if(!await te())return;I=l.current}I||(I=await st(a.current??n));const F=s.boxes.filter(y=>s.selectedIds.some(ae=>pe(ae,"box",y.id))),W=await Na({imageElement:e.current,boxes:F.length>0?F:s.boxes}),H=Ut(E),K=[(n.prompt??t?.prompt??"").trim(),H].filter(Boolean).join(`
4
4
 
5
5
  `);if(!K.trim()){A(D("toast.noPromptToFork"),!0);return}const R=n.size??t?.size??null,q=R&&/^\d+x\d+$/.test(R)?R:p(),ne=await kt({image:I,mask:await bt(W),prompt:K,quality:v,size:q,format:f,moderation:_,provider:C,n:1,model:S,reasoningEffort:U,mode:L,webSearchEnabled:N});await Q(At(ne,K))}catch(E){const I=E.code;A(D(I==="EDIT_MASK_NOT_SUPPORTED"?"canvas.toolbar.editMaskUnsupported":"canvas.toolbar.editMaskFailed"),!0)}finally{J(!1)}}},handleGptTransparency:async()=>{if(!(!n&&!t)){O(!0);try{const E=await st(n??a.current??t),I=n?.size??t?.size??null,F=I&&/^\d+x\d+$/.test(I)?I:p(),W=await kt({image:E,prompt:"Remove the background completely. Output a PNG with a fully transparent background (real alpha channel). Keep the subject pixel-identical — do not redraw, restyle, or crop the subject.",quality:"high",size:F,format:f,moderation:_,provider:"oauth",n:1,mode:"direct",webSearchEnabled:!1}),H=At(W,n?.prompt??t?.prompt??"transparent background");await Q(H),A(H.alphaVerified?D("canvas.toolbar.transparencyVerified"):H.alphaReason==="undetectable"?D("canvas.toolbar.transparencyUnverifiable"):D("canvas.toolbar.transparencyNoAlpha"),!H.alphaVerified)}catch(E){console.error("[canvas] gpt transparency failed",E);const I=E.code;A(I?`${D("canvas.toolbar.transparencyFailed")} (${I})`:D("canvas.toolbar.transparencyFailed"),!0)}finally{O(!1)}}}}}function Pr(e){const t=P(h=>h.currentImage),n=P(h=>h.history),a=P(h=>h.importLocalImageToHistory),[r,l]=i.useState(!1),c=P(h=>{const ce=h.multimodePreviewFlightId;return ce?h.multimodeSequences[ce]??null:null}),s=P(h=>h.selectHistoryShortcutTarget),d=P(h=>h.trashHistoryItem),u=P(h=>h.permanentlyDeleteHistoryItemByShortcut),v=P(h=>h.markGeneratedResultsSeen),f=P(h=>h.activeGenerations),_=P(h=>h.quality),C=P(h=>h.format),S=P(h=>h.moderation),U=P(h=>h.provider),L=P(h=>h.imageModel),N=P(h=>h.reasoningEffort),p=P(h=>h.promptMode),M=P(h=>h.webSearchEnabled),B=P(h=>h.getResolvedSize),x=P(h=>h.showToast),b=P(h=>h.canvasOpen),J=P(h=>h.openCanvas),O=P(h=>h.closeCanvas),V=P(h=>h.canvasZoom),Q=P(h=>h.canvasPanX),m=P(h=>h.canvasPanY),$=P(h=>h.setCanvasPan),T=P(h=>h.setCanvasZoom),A=P(h=>h.resetCanvasZoom),D=P(h=>h.canvasExportBackground),te=P(h=>h.canvasExportMatteColor),se=P(h=>h.setCanvasExportBackground),ie=P(h=>h.setCanvasExportMatteColor),de=P(h=>h.applyMergedCanvasImage),he=P(h=>h.addGeneratedHistoryItem),k=P(h=>h.attachCanvasVersionReference),{t:z}=fe(),{creatingBlankCanvas:E,createBlankCanvas:I}=Rn(),F=i.useRef(null),W=i.useRef(null),H=i.useRef(null),ee=i.useRef(null),K=i.useRef(null),R=i.useRef(null),q=i.useRef(null),ne=i.useRef(null),y=i.useRef(null),[ae,X]=i.useState(null),[G,ue]=i.useState("idle"),[we,_e]=i.useState(!1),[ve,le]=i.useState(!1),[Ce,Ve]=i.useState(!1),[ze,qe]=i.useState(!1),Y=Xn(),Xe=()=>{t?.prompt&&(navigator.clipboard.writeText(t.prompt),x(z("toast.promptCopied")))},Ge=$a(t?.quality),Ye=Ua(t?.size),Ze=Nn(t?.model),w=t?.filename??t?.url??t?.image??null,g=Ha(n,t),j=b?ae??g??t:t,re=j?Wa(j):null,Z=ar({canvasOpen:b,currentImage:t,canvasDisplayImage:j,imageElementRef:W,canvasSourceImageRef:q,lastMergedDataUrlRef:ne,setCanvasSaveState:ue,setCanvasVersionItem:X,applyMergedCanvasImage:de,attachCanvasVersionReference:k,showToast:x,t:z}),{imageHasAlpha:Me,backgroundCleanupSeeds:be,backgroundCleanupPreview:ke,backgroundCleanupMaskOverlay:xt,backgroundCleanupBrushStrokes:an,cleanupTool:rn,cleanupBrushRadius:on,cleanupBrushCursor:sn,isBackgroundCleanupActive:Ee}=Z,Je=Z.backgroundCleanupPreview?.dataUrl??re,Qe=()=>{q.current=null,K.current=null,R.current!=null&&(window.clearTimeout(R.current),R.current=null),X(null),ue("idle"),Z.resetBackgroundCleanup(),ne.current=null,y.current=null,wn()};i.useEffect(()=>{if(!b){ee.current=w,Qe();return}if(ee.current===null){ee.current=w,q.current=t,X(g);return}ee.current!==w&&(Y.resetLocal(),Qe(),q.current=t,X(g),ee.current=w)},[Y.resetLocal,b,t,w,g]),i.useEffect(()=>{!b||!t||q.current||(q.current=t,X(g))},[b,t,g]),i.useEffect(()=>{if(!b||!t?.filename||t.canvasVersion)return;const h=t.filename;if(K.current===h)return;K.current=h;let ce=!1;return In(h).then(Se=>{!ce&&Se.annotations&&Y.load(Se.annotations)}).catch(()=>{}),()=>{ce=!0}},[Y.load,b,t?.canvasVersion,t?.filename]),i.useEffect(()=>{if(!b||!t?.filename||t.canvasVersion||!Y.isDirty)return;const h=t.filename;return R.current!=null&&window.clearTimeout(R.current),R.current=window.setTimeout(()=>{const ce=Y.toPayload();(Y.hasAnnotations?Vt(h,ce):Kt(h)).then(()=>Y.markSaved()).catch(()=>{})},500),()=>{R.current!=null&&(window.clearTimeout(R.current),R.current=null)}},[Y,Y.hasAnnotations,Y.isDirty,b,t?.canvasVersion,t?.filename]);const ln=h=>{me(h.target)||(v(),h.currentTarget.focus())},cn=i.useCallback(()=>{window.requestAnimationFrame(()=>H.current?.focus())},[]),un=h=>{if(b){if(h.preventDefault(),h.ctrlKey){T(V-h.deltaY*.01);return}$(Q-h.deltaX,m-h.deltaY)}},dn=i.useCallback(h=>{Array.from(h.dataTransfer.types).includes("Files")&&(h.preventDefault(),l(ce=>ce||!0))},[]),hn=i.useCallback(h=>{h.currentTarget.contains(h.relatedTarget)||l(!1)},[]),fn=i.useCallback(async h=>{if(!Array.from(h.dataTransfer.types).includes("Files"))return;h.preventDefault(),l(!1);const ce=Array.from(h.dataTransfer.files).filter(Se=>/^image\/(png|jpeg|webp)$/.test(Se.type));ce.length!==0&&await a(ce[0])},[a]),{handleApplyCanvas:pn,handleRevertAnnotations:mn,handleCloseCanvas:yt,handleExportCanvas:vn,handleEditWithMask:bn,handleGptTransparency:gn}=jr({imageElementRef:W,currentImage:t,canvasDisplayImage:j,canvasSourceImageRef:q,lastMergedDataUrlRef:ne,lastCleanDataUrlRef:y,canvasVersionItem:ae,annotations:Y,exportBackground:D,exportMatteColor:te,quality:_,format:C,moderation:S,provider:U,imageModel:L,reasoningEffort:N,promptMode:p,webSearchEnabled:M,getResolvedSize:B,setCanvasVersionItem:X,setCanvasSaveState:ue,setIsApplying:_e,setIsExporting:le,setIsEditingWithMask:Ve,setIsTransparencyRunning:qe,applyMergedCanvasImage:de,addGeneratedHistoryItem:he,attachCanvasVersionReference:k,closeCanvas:O,resetCanvasSession:Qe,showToast:x,t:z}),{spaceHeld:et,handleViewerKeyDown:xn}=hr({canvasOpen:b,canvasZoom:V,currentImage:t,annotations:Y,undoBackgroundCleanup:Z.undoBackgroundCleanup,redoBackgroundCleanup:Z.redoBackgroundCleanup,handleBackgroundCleanupEscape:Z.handleBackgroundCleanupEscape,handleCloseCanvas:yt,selectHistoryShortcutTarget:s,trashHistoryItem:d,permanentlyDeleteHistoryItemByShortcut:u,setCanvasZoom:T,resetCanvasZoom:A,onCreateBlankCanvas:I,isCreatingBlankCanvas:E}),tt=b&&V>1.01&&Y.activeTool==="select"&&!Ee,[wt,yn]=i.useState(null),{viewportPanActive:nt,resetPointerSession:wn,handleAnnotationPointerDown:kn,handleAnnotationPointerMove:_n,handleAnnotationPointerUp:Cn,handleAnnotationPointerLeave:Mn}=dr({canvasOpen:b,canvasZoom:V,canvasPanX:Q,canvasPanY:m,spaceHeld:et,canDragViewportWithSelect:tt,isBackgroundCleanupActive:Ee,cleanupTool:rn,annotationFrameRef:F,annotations:Y,setCanvasPan:$,addBackgroundCleanupClick:Z.addBackgroundCleanupClick,startBackgroundCleanupBrushStroke:Z.startBackgroundCleanupBrushStroke,updateBackgroundCleanupBrushStroke:Z.updateBackgroundCleanupBrushStroke,endBackgroundCleanupBrushStroke:Z.endBackgroundCleanupBrushStroke,setCleanupBrushCursor:Z.setCleanupBrushCursor,setHoveredAnnotationId:yn});return o.jsxs("main",{className:`canvas${b?" canvas--mode-open":""}${r?" canvas--drop-active":""}${et?" canvas--space-held":""}${nt?" canvas--pan-active":""}${tt?" canvas--zoom-hand":""}`,onDragOver:dn,onDragLeave:hn,onDrop:fn,children:[r?o.jsx("div",{className:"canvas__drop-overlay","aria-hidden":!0,children:o.jsx("span",{className:"canvas__drop-hint",children:z("canvas.drop.hint")})}):null,b&&o.jsx(Pa,{zoom:V,modeLabel:z("canvas.modeTitle"),closeLabel:z("canvas.close"),blankCanvasLabel:z("canvas.blank.title"),blankCanvasAriaLabel:`${z(E?"canvas.blank.creating":"canvas.blank.create")} (Shift+B)`,blankCanvasShortcut:"Shift+B",blankCanvasBusy:E,shortcutHint:z("canvas.toolbar.zoomShortcutHint"),onZoomIn:()=>T(V+.1),onZoomOut:()=>T(V-.1),onZoomReset:A,onCreateBlankCanvas:()=>{I()},onClose:()=>{yt()}}),o.jsx("div",{className:`progress-bar${f>0?" active":""}`}),c?o.jsx(On,{}):t?o.jsxs("div",{ref:H,className:"result-container visible",tabIndex:0,onMouseDown:ln,onWheel:un,onKeyDown:xn,"aria-label":z("canvas.imageViewerAria"),children:[o.jsx(na,{annotationFrameRef:F,imageElementRef:W,frameClassName:`canvas-annotation-frame${(Me||ke)&&b?" canvas-annotation-frame--alpha":""}${Ee&&b?" canvas-annotation-frame--cleanup-picking":""}${xt&&b?" canvas-annotation-frame--cleanup-mask":""}`,frameStyle:{cursor:nt?"grabbing":et||tt?"grab":b?Ee?"crosshair":Y.activeTool==="select"?wt?"move":"default":Y.activeTool==="eraser"?Y.eraserMode==="object"?Oa:La:"crosshair":"zoom-in",transform:b?`translate(${Q}px, ${m}px) scale(${V})`:void 0,transition:b&&!nt?"transform 0.2s ease":void 0},imageKey:`${j?.filename??j?.url??j?.image}:${j?.canvasMergedAt??""}`,imageSrc:Je??t.image,fallbackImage:t.image,alt:z("canvas.resultAlt"),canvasOpen:b,maskOverlayUrl:xt?.dataUrl??null,cleanupLayer:o.jsx(oa,{seeds:be,brushStrokes:an,brushCursor:sn,brushRadius:on,active:Ee}),annotations:Y,hoveredAnnotationId:wt,onOpenCanvas:J,onPointerDown:kn,onPointerMove:_n,onPointerUp:Cn,onPointerLeave:Mn}),b&&Je?o.jsx(Da,{imageSrc:Je,zoom:V,panX:Q,panY:m,resetLabel:z("canvas.toolbar.zoomReset"),onReset:A}):null,b&&o.jsx(Ea,{annotations:Y,backgroundCleanup:Z,backgroundCleanupPreview:ke,canvasState:{exportBackground:D,exportMatteColor:te,isApplying:we,isExporting:ve,isEditingWithMask:Ce,isTransparencyRunning:ze,canRevertAnnotations:!!ae?.annotationsBaked},actions:{handleApplyCanvas:pn,handleRevertAnnotations:mn,handleExportCanvas:vn,handleEditWithMask:bn,handleGptTransparency:gn,setExportBackground:se,setExportMatteColor:ie}}),b&&G!=="idle"?o.jsx("div",{className:`canvas-save-state canvas-save-state--${G}`,children:z(G==="saving"?"canvas.version.saving":G==="saved"?"canvas.version.saved":"canvas.version.failed")}):null,o.jsx(Sa,{currentImage:t,canvasDisplayImage:j,canvasOpen:b,displayQuality:Ge,displaySize:Ye,displayModel:Ze,onAfterDeleteFocus:cn,onCopyPrompt:Xe})]}):null]})}export{Pr as CanvasModeWorkspace};