ima2-gen 3.8.2 → 3.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/commands/gen.js +10 -0
- package/docs/migration/runtime-test-inventory.md +5 -1
- package/lib/alphaDecode.js +18 -0
- package/lib/atlasCloudImageAdapter.js +6 -1
- package/lib/backgroundPresets.js +28 -1
- package/lib/generatePipeline.js +74 -5
- package/lib/imageBackgroundParam.js +108 -0
- package/lib/promptImport/gptImageHints.js +4 -1
- package/lib/responsesFallback.js +8 -2
- package/lib/responsesImageAdapter.js +10 -1
- package/package.json +2 -2
- package/routes/video.js +7 -0
- package/skills/ima2/SKILL.md +28 -4
- package/skills/ima2-front/references/asset-requirements.md +23 -8
- package/skills/ima2-uiux/SKILL.md +15 -4
- package/ui/dist/.vite/manifest.json +32 -32
- package/ui/dist/assets/{AgentWorkspace-bUd5NsQ_.js → AgentWorkspace-fcIXiWV6.js} +1 -1
- package/ui/dist/assets/AssetGenWorkspace-CqXyN9at.js +2 -0
- package/ui/dist/assets/{AssetsWorkspace-DO_wfFQB.js → AssetsWorkspace-xwHFVOb7.js} +1 -1
- package/ui/dist/assets/{CardNewsWorkspace-D3M0w8pg.js → CardNewsWorkspace-ltdjG40R.js} +1 -1
- package/ui/dist/assets/{GenerationRequestLogPanel-WvSV0yXP.js → GenerationRequestLogPanel-B68EUfUg.js} +1 -1
- package/ui/dist/assets/{HomeWorkspace-BGCBf9iK.js → HomeWorkspace-BBOG_aNm.js} +1 -1
- package/ui/dist/assets/KeyingPanel-Bv0n_bhk.js +1 -0
- package/ui/dist/assets/{NodeCanvas-DwbR2nol.js → NodeCanvas-VwdctvAW.js} +1 -1
- package/ui/dist/assets/{PromptBuilderPanel-KSH3ChjC.js → PromptBuilderPanel-BBMpF_3Q.js} +1 -1
- package/ui/dist/assets/{PromptImportDialog-CjHiCEo9.js → PromptImportDialog-D4QYbRfH.js} +2 -2
- package/ui/dist/assets/{PromptImportDiscoverySection-CWU-vKyM.js → PromptImportDiscoverySection-Bx7BeTFh.js} +1 -1
- package/ui/dist/assets/{PromptImportFolderSection-_zRnJGkJ.js → PromptImportFolderSection-Bwf60URx.js} +1 -1
- package/ui/dist/assets/{PromptLibraryPanel-64VN4nml.js → PromptLibraryPanel-mNG2wZkQ.js} +2 -2
- package/ui/dist/assets/{SettingsWorkspace-DZMNEpuq.js → SettingsWorkspace-DA5tIa0Q.js} +1 -1
- package/ui/dist/assets/{SpriteRecipeWorkspace-Y6GqpVHs.js → SpriteRecipeWorkspace-Da9qTQX0.js} +1 -1
- package/ui/dist/assets/{index-CFixfKaC.js → index-Bv1Yrz8W.js} +3 -3
- package/ui/dist/assets/{index-waPOg2eb.css → index-C0nfanMr.css} +1 -1
- package/ui/dist/assets/{index-XXtoj9ME.js → index-CxEuSZMC.js} +16 -16
- package/ui/dist/assets/{pptxgen.es-hCJot2gG.js → pptxgen.es-BE4CSd5F.js} +1 -1
- package/ui/dist/assets/{useAgentDialogFocus-PWmMjerz.js → useAgentDialogFocus-R64NV-ZZ.js} +1 -1
- package/ui/dist/index.html +2 -2
- package/ui/dist/assets/AssetGenWorkspace-8fK-K64E.js +0 -2
- package/ui/dist/assets/KeyingPanel-CEBLIhhu.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pptxgen.es-
|
|
2
|
-
import{a as i,j as o,u as fe,f as gn,as as xn,at as yn,au as wn,av as Ot,aw as Lt,ax as be,aa as kn,ay as Cn,b as A,az as $t,aA as _n,aB as Mn,aC as Ut,aD as En,c as Sn,aE as Bn,aF as jn}from"./index-XXtoj9ME.js";const Ne=2,He=1e-6;function Tn({paths:e,points:t,radius:n,makeId:a=()=>crypto.randomUUID()}){if(e.length===0||t.length===0||n<=0)return{paths:e,changed:!1};let r=!1;const l=[];for(const s of e){const c=An(s,t,n,a);(c.length!==1||c[0]!==s)&&(r=!0),l.push(...c)}return{paths:l,changed:r}}function An(e,t,n,a=()=>crypto.randomUUID()){if(e.points.length<Ne||t.length===0||n<=0)return[e];const r=[];let l=Pe(e.points[0],t,n)?[]:[e.points[0]];for(let c=1;c<e.points.length;c+=1){const d=e.points[c-1],u=e.points[c],v=Pe(u,t,n),h=Pn(d,u,t,n);if(h){l.length===0&&!Pe(d,t,n)&&(l=[d]),l.length>0&&h.leftT>He&&xt(l,Re(d,u,h.leftT)),l.length>=Ne&&r.push(l),l=[],h.rightT<1-He&&!v&&(l=[Re(d,u,h.rightT),u]);continue}if(v){l.length>=Ne&&r.push(l),l=[];continue}l.length===0&&!Pe(d,t,n)&&(l=[d]),xt(l,u)}if(l.length>=Ne&&r.push(l),r.length===0)return[];if(r.length===1&&r[0].length===e.points.length)return[e];const s=e.tool==="arrow"?r.length-1:-1;return r.map((c,d)=>({...e,id:d===0?e.id:a(),tool:e.tool==="arrow"&&d!==s?"pen":e.tool,points:c}))}function Pe(e,t,n){if(t.length===1)return we(e,t[0])<=n;for(let a=1;a<t.length;a+=1)if(Dn(e,t[a-1],t[a])<=n)return!0;return!1}function we(e,t){const n=e.x-t.x,a=e.y-t.y;return Math.sqrt(n*n+a*a)}function Pn(e,t,n,a){const r=we(e,t);if(r<=He)return Pe(e,n,a)?{leftT:0,rightT:1}:null;let l=null,s=Number.POSITIVE_INFINITY;for(const d of n){const u=gt(d,e,t),v=Re(e,t,u),h=we(d,v);h<s&&(s=h,l=u)}for(let d=1;d<n.length;d+=1){const u=[0,.25,.5,.75,1];for(const v of u){const h=Re(n[d-1],n[d],v),_=gt(h,e,t),M=Re(e,t,_),T=we(h,M);T<s&&(s=T,l=_)}}if(l===null||s>a)return null;const c=Math.max(a/r,.01);return{leftT:Math.max(0,l-c),rightT:Math.min(1,l+c)}}function gt(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,c=a*a+r*r;return c===0?0:Math.max(0,Math.min(1,(l*a+s*r)/c))}function Re(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function xt(e,t){const n=e.at(-1);(!n||we(n,t)>He)&&e.push(t)}function Dn(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,c=a*a+r*r;if(c===0)return we(e,t);const d=Math.max(0,Math.min(1,(l*a+s*r)/c));return we(e,{x:t.x+d*a,y:t.y+d*r})}function ft(e,t){return`${e}:${t}`}function mt(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 Wt(e){return ft("path",e.id)}function Ft(e){return ft("box",e.id)}function Ht(e){return ft("memo",e.id)}function ve(e,t,n){const a=mt(e);return a?.kind===t&&a.id===n}const Kt="ima2.canvas.annotationStyle.v1",zt=["#ef4444","#f97316","#eab308","#22c55e","#38bdf8","#6366f1","#a855f7","#111827","#ffffff"],Vt=[2,3,5,8],Be={color:"#ef4444",strokeWidth:3};function Rn(){if(typeof window>"u")return Be;try{const e=window.localStorage.getItem(Kt);if(!e)return Be;const t=JSON.parse(e),n=typeof t.color=="string"&&zt.includes(t.color)?t.color:Be.color,a=typeof t.strokeWidth=="number"&&Vt.includes(t.strokeWidth)?t.strokeWidth:Be.strokeWidth;return{color:n,strokeWidth:a}}catch{return Be}}function In(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Kt,JSON.stringify(e))}catch{}}const yt=Rn(),ct={activeTool:"select",toolColor:yt.color,strokeWidth:yt.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 ye(e){return{paths:e.paths,boxes:e.boxes,memos:e.memos}}function xe(e){return{...e,past:[...e.past.slice(-49),ye(e)],future:[]}}function at(e,t){return{...e,past:[...e.past.slice(-49),t],future:[]}}function Nn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function wt(e,t){return{...e,...t,activeMemoId:null,activePath:null,activeBox:null,selectionBox:null,selectedIds:[],isDirty:!0}}function On(e,t,n){const{start:a,current:r}=e,l=Math.min(a.x,r.x),s=Math.min(a.y,r.y),c=Math.abs(r.x-a.x),d=Math.abs(r.y-a.y);return c<.01||d<.01?null:{id:crypto.randomUUID(),x:l,y:s,width:c,height:d,color:t,strokeWidth:n}}function Ln(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 $n(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}:{...xe(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=On(e.activeBox,e.toolColor,e.strokeWidth);return n?{...xe(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{...xe(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?Nn(e.memoBaseline,ye(e))?{...e,memoBaseline:null,activeMemoId:null}:{...at(e,e.memoBaseline),memoBaseline:null,activeMemoId:null,isDirty:!0}:{...e,activeMemoId:null};case"DELETE_MEMO":return{...xe(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=>!ve(n,"memo",t.id))};case"FOCUS_MEMO":return{...e,activeMemoId:t.id,memoBaseline:t.id&&e.activeMemoId!==t.id&&!e.memoBaseline?ye(e):e.memoBaseline};case"CLEAR":return{...xe(e),isDirty:!0,paths:[],boxes:[],memos:[],activeMemoId:null,activePath:null,activeBox:null,selectionBox:null,selectedIds:[]};case"LOAD":return{...ct,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{...ct,activeTool:e.activeTool,eraserMode:e.eraserMode,toolColor:e.toolColor,strokeWidth:e.strokeWidth};case"UNDO":{const n=e.past.at(-1);return n?{...wt(e,n),past:e.past.slice(0,-1),future:[ye(e),...e.future]}:e}case"REDO":{const n=e.future[0];return n?{...wt(e,n),past:[...e.past.slice(-49),ye(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:{...xe(e),isDirty:!0,paths:e.paths.filter(n=>!e.selectedIds.some(a=>ve(a,"path",n.id))),boxes:e.boxes.filter(n=>!e.selectedIds.some(a=>ve(a,"box",n.id))),memos:e.memos.filter(n=>!e.selectedIds.some(a=>ve(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=>ve(a,"path",n.id))?{...n,points:n.points.map(a=>rt(a,t.delta))}:n),boxes:e.boxes.map(n=>e.selectedIds.some(a=>ve(a,"box",n.id))?Ln(n,t.delta):n),memos:e.memos.map(n=>e.selectedIds.some(a=>ve(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:ye(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=mt(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:{...xe(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:ye(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=Tn({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 Un(){const[e,t]=i.useReducer($n,ct),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(m=>t({type:"SET_TOOL",tool:m}),[]),s=i.useCallback(m=>{In(m),t({type:"SET_STYLE",style:m})},[]),c=i.useCallback(()=>t({type:"CLEAR"}),[]),d=i.useCallback(m=>t({type:"LOAD",payload:m}),[]),u=i.useCallback(()=>t({type:"MARK_SAVED"}),[]),v=i.useCallback(()=>t({type:"RESET_LOCAL"}),[]),h=i.useCallback(()=>t({type:"UNDO"}),[]),_=i.useCallback(()=>t({type:"REDO"}),[]),M=i.useCallback(()=>t({type:"COMMIT_MEMO_EDIT"}),[]),T=i.useCallback(()=>t({type:"START_SELECTED_MOVE"}),[]),W=i.useCallback(()=>t({type:"COMMIT_SELECTED_MOVE"}),[]),P=i.useCallback(m=>{e.activeTool==="pen"||e.activeTool==="arrow"?t({type:"START_PATH",point:m}):e.activeTool==="box"&&t({type:"START_BOX",point:m})},[e.activeTool]),O=i.useCallback(m=>{e.activePath?t({type:"ADD_POINT",point:m}):e.activeBox&&t({type:"UPDATE_BOX",point:m})},[e.activePath,e.activeBox]),b=i.useCallback(()=>{e.activePath?t({type:"END_PATH"}):e.activeBox&&t({type:"END_BOX"})},[e.activePath,e.activeBox]),C=i.useCallback(m=>t({type:"CREATE_MEMO",point:m}),[]),E=i.useCallback((m,S)=>t({type:"UPDATE_MEMO",id:m,text:S}),[]),y=i.useCallback(m=>t({type:"DELETE_MEMO",id:m}),[]),p=i.useCallback(m=>t({type:"FOCUS_MEMO",id:m}),[]),J=i.useCallback(m=>t({type:"SET_ERASER_MODE",mode:m}),[]),I=i.useCallback(m=>t({type:"SELECT_ONE",id:m}),[]),K=i.useCallback(m=>t({type:"TOGGLE_SELECTED",id:m}),[]),g=i.useCallback(()=>t({type:"CLEAR_SELECTION"}),[]),j=i.useCallback(()=>t({type:"DELETE_SELECTED"}),[]),R=i.useCallback(m=>t({type:"MOVE_SELECTED",delta:m}),[]),D=i.useCallback(m=>t({type:"START_SELECTION_BOX",point:m}),[]),L=i.useCallback(m=>t({type:"UPDATE_SELECTION_BOX",point:m}),[]),Z=i.useCallback(m=>t({type:"END_SELECTION_BOX",ids:m}),[]),te=i.useCallback(m=>t({type:"ERASE_OBJECT",id:m}),[]),ne=i.useCallback(m=>t({type:"START_ERASER_STROKE",point:m}),[]),le=i.useCallback(m=>t({type:"UPDATE_ERASER_STROKE",point:m}),[]),ue=i.useCallback(()=>t({type:"END_ERASER_STROKE"}),[]),de=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:s,setEraserMode:J,startDrawing:P,moveDrawing:O,endDrawing:b,createMemo:C,updateMemo:E,commitMemoEdit:M,deleteMemo:y,focusMemo:p,clear:c,load:d,toPayload:de,markSaved:u,resetLocal:v,undo:h,redo:_,selectOne:I,toggleSelected:K,clearSelection:g,deleteSelected:j,moveSelected:R,startSelectedMove:T,commitSelectedMove:W,startSelectionBox:D,updateSelectionBox:L,endSelectionBox:Z,eraseObjectAtPoint:te,startEraserStroke:ne,updateEraserStroke:le,endEraserStroke:ue}}function De(e,t){return{x:e.x*t.width,y:e.y*t.height}}function qt(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 it(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);Hn(e,l,r,t.color,t.strokeWidth)}e.restore()}function ut(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 Wn(e,t,n){const a=t.x*n.width,r=t.y*n.height,l=Math.min(260,Math.max(150,n.width*.22)),s=12,c=18;e.save(),e.font="14px sans-serif";const d=Kn(e,t.text.trim()||" ",l-s*2),u=Math.max(52,s*2+d.length*c);e.fillStyle="rgba(255, 246, 179, 0.96)",e.strokeStyle="rgba(44, 37, 12, 0.28)",e.lineWidth=1,zn(e,a,r,l,u,8),e.fill(),e.stroke(),e.fillStyle="#2f2a13",e.textBaseline="top",d.forEach((v,h)=>{e.fillText(v,a+s,r+s+h*c)}),e.restore()}function Fn(e,t){const n=mt(e);if(!n)return null;if(n.kind==="box")return t.boxes.find(u=>u.id===n.id)??null;const a=n.kind==="memo"?t.memos.find(u=>u.id===n.id):null;if(a)return{id:a.id,x:a.x,y:a.y,width:.18,height:.12,color:a.color,strokeWidth:1};if(n.kind!=="path")return null;const r=t.paths.find(u=>u.id===n.id);if(!r||r.points.length===0)return null;const l=r.points.map(u=>u.x),s=r.points.map(u=>u.y),c=Math.min(...l),d=Math.min(...s);return{id:r.id,x:c,y:d,width:Math.max(.01,Math.max(...l)-c),height:Math.max(.01,Math.max(...s)-d),color:r.color,strokeWidth:r.strokeWidth}}function kt(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 Hn(e,t,n,a,r){const[l,s,c]=qt(t,n,r);e.save(),e.fillStyle=a,e.beginPath(),e.moveTo(l.x,l.y),e.lineTo(s.x,s.y),e.lineTo(c.x,c.y),e.closePath(),e.fill(),e.restore()}function Kn(e,t,n){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const r=[];let l="";for(const s of a){const c=l?`${l} ${s}`:s;if(e.measureText(c).width<=n||l===""){l=c;continue}r.push(l),l=s}return l&&r.push(l),r}function zn(e,t,n,a,r,l){const s=Math.min(l,a/2,r/2);e.beginPath(),e.moveTo(t+s,n),e.lineTo(t+a-s,n),e.quadraticCurveTo(t+a,n,t+a,n+s),e.lineTo(t+a,n+r-s),e.quadraticCurveTo(t+a,n+r,t+a-s,n+r),e.lineTo(t+s,n+r),e.quadraticCurveTo(t,n+r,t,n+r-s),e.lineTo(t,n+s),e.quadraticCurveTo(t,n,t+s,n),e.closePath()}function Vn({paths:e,boxes:t,memos:n=[],selectedIds:a=[],selectionBox:r=null,activePath:l,activeBox:s}){const c=i.useRef(null);return i.useEffect(()=>{const d=c.current;if(!d)return;const u=d.getBoundingClientRect(),v=window.devicePixelRatio||1;d.width=Math.max(1,Math.round(u.width*v)),d.height=Math.max(1,Math.round(u.height*v));const h=d.getContext("2d");if(!h)return;h.setTransform(v,0,0,v,0,0),h.clearRect(0,0,u.width,u.height);const _={width:u.width,height:u.height};for(const M of e)it(h,M,_);for(const M of t)ut(h,M,_,"committed");for(const M of a){const T=Fn(M,{paths:e,boxes:t,memos:n});T&&kt(h,T,_)}r&&kt(h,r,_),l&&it(h,l,_),s&&ut(h,s,_,"active")},[e,t,n,a,r,l,s]),o.jsx("canvas",{ref:c,className:"canvas-annotation-layer","aria-hidden":"true"})}function Oe(e){e.stopPropagation()}function qn({memos:e,activeMemoId:t,onUpdate:n,onDelete:a,onFocus:r,onCommit:l}){const{t:s}=fe();return o.jsx("div",{className:"canvas-memo-overlay",children:e.map(c=>o.jsx("textarea",{className:`canvas-memo${t===c.id?" canvas-memo--active":""}`,value:c.text,style:{left:`${c.x*100}%`,top:`${c.y*100}%`},autoFocus:t===c.id,onFocus:()=>r(c.id),onPointerDown:Oe,onPointerMove:Oe,onPointerUp:Oe,onPointerCancel:Oe,onChange:d=>n(c.id,d.currentTarget.value),onBlur:()=>{l?.(),c.text.trim()===""&&a(c.id)},"aria-label":s("common.canvasMemo")},c.id))})}function Xn({annotationFrameRef:e,imageElementRef:t,frameClassName:n,frameStyle:a,imageKey:r,imageSrc:l,fallbackImage:s,alt:c,canvasOpen:d,maskOverlayUrl:u,cleanupLayer:v,annotations:h,onOpenCanvas:_,onPointerDown:M,onPointerMove:T,onPointerUp:W,onPointerLeave:P}){return o.jsxs("div",{ref:e,className:n,onPointerDown:M,onPointerMove:T,onPointerUp:W,onPointerCancel:W,onPointerLeave:P,style:a,children:[o.jsx("img",{ref:t,className:"result-img",src:l??s,alt:c,decoding:"async",onDoubleClick:O=>{O.stopPropagation(),_()}},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(Vn,{paths:h.paths,boxes:h.boxes,memos:h.memos,selectedIds:h.selectedIds,selectionBox:h.selectionBox,activePath:h.activePath,activeBox:h.activeBox}),o.jsx(qn,{memos:h.memos,activeMemoId:h.activeMemoId,onUpdate:h.updateMemo,onDelete:h.deleteMemo,onFocus:h.focusMemo,onCommit:h.commitMemoEdit})]})]})}function Yn(e){return`${e.x*100} ${e.y*100}`}function Gn(e){return e.map(Yn).join(" ")}function Zn({seeds:e,brushStrokes:t,brushCursor:n,brushRadius:a,active:r}){if(!r&&e.length===0&&t.length===0)return null;const l=a*100;return o.jsxs("svg",{className:"canvas-cleanup-overlay",viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",children:[t.map(s=>o.jsx("polyline",{className:`canvas-cleanup-overlay__stroke canvas-cleanup-overlay__stroke--${s.intent}`,points:Gn(s.points),strokeWidth:Math.max(.3,s.radius*200),vectorEffect:"non-scaling-stroke"},s.id)),r&&n?o.jsx("circle",{className:"canvas-cleanup-cursor",cx:n.x*100,cy:n.y*100,r:Math.max(.6,l),vectorEffect:"non-scaling-stroke"}):null]})}function Jn({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 Ct({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 Qn({seedCount:e,tolerance:t,stats:n,hasPreview:a,isPickingSeed:r,intent:l,tool:s,brushRadius:c,isPreviewing:d,isApplying:u,keepOpen:v,disabled:h,onAutoSample:_,onPickSeed:M,onIntentChange:T,onToolChange:W,onBrushRadiusChange:P,onToleranceChange:O,onPreview:b,onApply:C,onReset:E}){const{t:y}=fe(),[p,J]=i.useState(!1),I=i.useRef(null),K=n?Math.round(n.removedPercent*1e3)/10:0,g=r||s==="brush";return i.useEffect(()=>{if(!p)return;const j=R=>{v||I.current?.contains(R.target)||J(!1)};return window.addEventListener("pointerdown",j),()=>window.removeEventListener("pointerdown",j)},[v,p]),o.jsxs("div",{className:"canvas-toolbar__cleanup",ref:I,children:[o.jsx("button",{type:"button",className:`canvas-toolbar__button${p||a?" canvas-toolbar__button--active":""}`,onClick:()=>J(j=>!j),disabled:h,"aria-expanded":p,"aria-label":y("canvas.toolbar.cleanup"),title:y("canvas.toolbar.cleanup"),children:o.jsx(ea,{})}),p?o.jsxs("div",{className:"canvas-toolbar__cleanup-panel",role:"group","aria-label":y("canvas.toolbar.cleanup"),children:[o.jsxs("div",{className:"canvas-toolbar__cleanup-row",children:[o.jsx("span",{className:"canvas-toolbar__cleanup-title",children:y("canvas.toolbar.cleanup")}),o.jsx("span",{className:"canvas-toolbar__cleanup-meta",children:y("canvas.toolbar.cleanupSeedCount",{n:e})})]}),o.jsx(Ct,{label:y("canvas.toolbar.cleanupMark"),value:l,options:[{value:"remove",label:y("canvas.toolbar.cleanupRemove")},{value:"preserve",label:y("canvas.toolbar.cleanupPreserve")}],onChange:T}),o.jsx(Ct,{label:y("canvas.toolbar.cleanupInput"),value:s,options:[{value:"click",label:y("canvas.toolbar.cleanupClick")},{value:"brush",label:y("canvas.toolbar.cleanupBrush")}],onChange:W}),o.jsxs("label",{className:"canvas-toolbar__cleanup-slider",children:[o.jsx("span",{children:y("canvas.toolbar.cleanupTolerance")}),o.jsx("input",{type:"range",min:"0",max:"96",value:t,onChange:j=>O(Number(j.target.value))}),o.jsx("output",{children:t})]}),s==="brush"?o.jsxs("label",{className:"canvas-toolbar__cleanup-slider",children:[o.jsx("span",{children:y("canvas.toolbar.cleanupBrushSize")}),o.jsx("input",{type:"range",min:"0.006",max:"0.06",step:"0.002",value:c,onChange:j=>P(Number(j.target.value))}),o.jsx("output",{children:Math.round(c*1e3)})]}):null,o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:_,children:y("canvas.toolbar.cleanupAutoSample")}),o.jsx("button",{type:"button",className:r?"active":"",onClick:M,children:y(g?"canvas.toolbar.cleanupActive":"canvas.toolbar.cleanupPickSeed")})]}),o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:b,disabled:d||e===0,children:y(d?"canvas.toolbar.cleanupPreviewing":"canvas.toolbar.cleanupPreview")}),o.jsx("button",{type:"button",onClick:C,disabled:u||!a&&e===0,children:y(u?"canvas.toolbar.cleanupApplying":"canvas.toolbar.cleanupApply")}),o.jsx("button",{type:"button",onClick:E,disabled:!a&&e===0,children:y("canvas.toolbar.cleanupReset")})]}),g?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:y(s==="brush"?"canvas.toolbar.cleanupBrushHint":"canvas.toolbar.cleanupPickHint")}):n&&!a?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:y("canvas.toolbar.cleanupMaskHint")}):null,n?o.jsx("div",{className:"canvas-toolbar__cleanup-status",children:y("canvas.toolbar.cleanupRemoved",{n:K})}):null]}):null]})}function ea(){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 ta=["png","svg","pptx"];function na({onExport:e,disabled:t,isExporting:n}){const{t:a}=fe(),[r,l]=i.useState(!1),s=i.useRef(null),c=i.useRef(null),d=i.useId();i.useEffect(()=>{if(!r)return;const h=()=>Array.from(c.current?.querySelectorAll("[role='menuitem']")??[]);window.requestAnimationFrame(()=>h()[0]?.focus());const _=M=>{const T=M.target;c.current?.contains(T)||s.current?.contains(T)||l(!1)};return document.addEventListener("pointerdown",_,!0),()=>document.removeEventListener("pointerdown",_,!0)},[r]);const u=h=>{l(!1),s.current?.focus()},v=h=>{if(h.key==="Escape"){h.preventDefault(),u();return}if(!["ArrowDown","ArrowUp","Home","End"].includes(h.key))return;h.preventDefault();const M=Array.from(c.current?.querySelectorAll("[role='menuitem']")??[]);if(M.length===0)return;const T=M.indexOf(document.activeElement),W=h.key==="Home"?0:h.key==="End"?M.length-1:T<0?0:(T+(h.key==="ArrowDown"?1:-1)+M.length)%M.length;M[W]?.focus()};return o.jsxs("div",{className:"canvas-export-menu",children:[o.jsx("button",{ref:s,type:"button",className:`canvas-toolbar__button${n?" canvas-toolbar__button--busy":""}`,onClick:()=>l(h=>!h),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(aa,{})}),r?o.jsx("div",{ref:c,id:d,role:"menu",className:"canvas-export-menu__list","aria-label":a("canvas.toolbar.exportFormat"),onKeyDown:v,children:ta.map(h=>o.jsx("button",{type:"button",role:"menuitem",className:"canvas-export-menu__item",onClick:()=>{u(),e(h)},children:a(`canvas.toolbar.exportAs.${h}`)},h))}):null]})}function aa(){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 ra({style:e,onStyleChange:t}){const{t:n}=fe(),[a,r]=i.useState(!1),l=i.useRef(null);return i.useEffect(()=>{if(!a)return;const s=c=>{l.current?.contains(c.target)||r(!1)};return window.addEventListener("pointerdown",s),()=>window.removeEventListener("pointerdown",s)},[a]),o.jsxs("div",{ref:l,className:`canvas-toolbar__split-button${a?" canvas-toolbar__split-button--active":""}`,onKeyDown:s=>{s.key==="Escape"&&a&&(s.preventDefault(),s.stopPropagation(),r(!1))},children:[o.jsxs("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__style-trigger",onClick:()=>r(s=>!s),"aria-haspopup":"dialog","aria-expanded":a,"aria-label":n("canvas.toolbar.style"),title:n("canvas.toolbar.style"),children:[o.jsx("span",{className:"canvas-style-trigger__swatch",style:{background:e.color},"aria-hidden":"true"}),o.jsx("span",{className:"canvas-style-trigger__width",style:{height:`${Math.min(8,Math.max(2,e.strokeWidth))}px`},"aria-hidden":"true"})]}),a?o.jsxs("div",{className:"canvas-style-popover",role:"dialog","aria-label":n("canvas.toolbar.style"),children:[o.jsx("div",{className:"canvas-style-popover__row",role:"group","aria-label":n("canvas.toolbar.color"),children:zt.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:Vt.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 oa({tools:e,activeTool:t,onToolChange:n}){const[a,r]=i.useState(!1),l=i.useRef(null),s=e.find(d=>d.id===t)??e[0],c=s.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":`${s.label} (${s.shortcut})`,"aria-pressed":t===s.id,"aria-haspopup":"menu","aria-expanded":a,title:`${s.label} (${s.shortcut})`,children:[o.jsx(c,{}),o.jsx("span",{className:"canvas-toolbar__shortcut","aria-hidden":"true",children:s.shortcut})]}),a?o.jsx("div",{className:"canvas-tool-picker__menu",role:"menu",children:e.map(d=>{const u=d.icon,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 sa({activeTool:e,hasAnnotations:t,hasExportableContent:n,onToolChange:a,eraserMode:r="object",onEraserModeChange:l,style:s,onStyleChange:c,onClear:d,onApply:u,onRevertAnnotations:v,onExport:h,onUndo:_,onRedo:M,canUndo:T,canRedo:W,onDeleteSelected:P,selectedCount:O=0,onEditWithMask:b,canEditWithMask:C,isEditingWithMask:E,isApplying:y,isExporting:p,exportBackground:J="alpha",exportMatteColor:I="#ffffff",onExportBackgroundChange:K,onExportMatteColorChange:g,cleanupTolerance:j=28,cleanupSeedCount:R=0,cleanupStats:D=null,cleanupHasPreview:L=!1,isCleanupPickingSeed:Z=!1,isCleanupActive:te=!1,cleanupIntent:ne="remove",cleanupTool:le="click",cleanupBrushRadius:ue=.018,isCleanupPreviewing:de=!1,isCleanupApplying:m=!1,onCleanupAutoSample:S,onCleanupPickSeed:$,onCleanupIntentChange:ae,onCleanupToolChange:re,onCleanupBrushRadiusChange:G,onCleanupToleranceChange:q,onCleanupPreview:U,onCleanupApply:H,onCleanupReset:N}){const{t:k}=fe(),[Y,F]=i.useState(!1),ce=i.useRef(null),X=n??t??!1,z=k(r==="object"?"canvas.toolbar.objectEraser":"canvas.toolbar.brushEraser"),he=[{id:"select",shortcut:"1",label:k("canvas.toolbar.select"),icon:la},{id:"pen",shortcut:"2",label:k("canvas.toolbar.pen"),icon:ca},{id:"box",shortcut:"3",label:k("canvas.toolbar.box"),icon:ia},{id:"arrow",shortcut:"4",label:k("canvas.toolbar.arrow"),icon:ua},{id:"memo",shortcut:"5",label:k("canvas.toolbar.memo"),icon:da}];i.useEffect(()=>{if(!Y)return;const oe=Ce=>{ce.current?.contains(Ce.target)||F(!1)};return window.addEventListener("pointerdown",oe),()=>window.removeEventListener("pointerdown",oe)},[Y]);const ke=oe=>{l?.(oe),a("eraser"),F(!1)};return o.jsxs("div",{className:"canvas-toolbar","aria-label":k("canvas.toolbar.label"),children:[o.jsx(oa,{tools:he,activeTool:e,onToolChange:a}),o.jsx(ra,{style:s,onStyleChange:c}),o.jsxs("div",{ref:ce,className:`canvas-toolbar__split-button${e==="eraser"?" canvas-toolbar__split-button--active":""}`,onKeyDown:oe=>{oe.key==="Escape"&&Y&&(oe.preventDefault(),F(!1))},children:[o.jsxs("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--split-main${e==="eraser"?" canvas-toolbar__button--active":""}`,onClick:()=>a("eraser"),"aria-label":`${z} (6)`,"aria-pressed":e==="eraser",title:`${z} (6)`,children:[o.jsx(ha,{}),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:()=>F(oe=>!oe),"aria-label":k("canvas.toolbar.eraserMenu"),"aria-haspopup":"menu","aria-expanded":Y,"aria-controls":"canvas-eraser-menu",title:k("canvas.toolbar.eraserMenu"),children:o.jsx(fa,{})}),Y?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:()=>ke("object"),children:k("canvas.toolbar.objectEraser")}),o.jsx("button",{type:"button",className:`canvas-toolbar__eraser-menu-item${r==="brush"?" canvas-toolbar__eraser-menu-item--active":""}`,role:"menuitemradio","aria-checked":r==="brush",onClick:()=>ke("brush"),children:k("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${y?" canvas-toolbar__button--busy":""}`,onClick:u,disabled:!X||y,"aria-label":k("canvas.toolbar.apply"),title:k("canvas.toolbar.apply"),children:o.jsx(ma,{})}):null,v?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:v,disabled:y,"aria-label":k("canvas.revert.action"),title:k("canvas.revert.action"),children:o.jsx(Mt,{})}):null,b?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--primary canvas-toolbar__button--mask${E?" canvas-toolbar__button--busy":""}`,onClick:b,disabled:!C||E,"aria-label":k(C?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),title:k(C?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),children:o.jsx(va,{})}):null,_?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:_,disabled:!T,"aria-label":k("canvas.toolbar.undo"),title:k("canvas.toolbar.undo"),children:o.jsx(Mt,{})}):null,M?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:M,disabled:!W,"aria-label":k("canvas.toolbar.redo"),title:k("canvas.toolbar.redo"),children:o.jsx(pa,{})}):null,P?o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:P,disabled:O===0,"aria-label":k("canvas.toolbar.deleteSelected"),title:k("canvas.toolbar.deleteSelected"),children:o.jsx(_t,{})}):null,h&&K&&g?o.jsx(Jn,{mode:J,matteColor:I,onModeChange:K,onMatteColorChange:g}):null,S&&$&&ae&&re&&G&&q&&U&&H&&N?o.jsx(Qn,{seedCount:R,tolerance:j,stats:D,hasPreview:L,isPickingSeed:Z,intent:ne,tool:le,brushRadius:ue,isPreviewing:de,isApplying:m,keepOpen:te,disabled:y||p,onAutoSample:S,onPickSeed:$,onIntentChange:ae,onToolChange:re,onBrushRadiusChange:G,onToleranceChange:q,onPreview:U,onApply:H,onReset:N}):null,h?o.jsx(na,{onExport:h,disabled:!X,isExporting:!!p}):null,o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:d,disabled:!X,"aria-label":k("canvas.toolbar.clear"),title:k("canvas.toolbar.clear"),children:o.jsx(_t,{})})]})}function la(){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 ca(){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 ia(){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 ua(){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 da(){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 ha(){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 fa(){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 ma(){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 _t(){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 Mt(){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 pa(){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 va(){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 ba({annotations:e,backgroundCleanup:t,backgroundCleanupPreview:n,canvasState:a,actions:r}){return o.jsx(sa,{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,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 ga({currentImage:e,canvasDisplayImage:t,canvasOpen:n,displayQuality:a,displaySize:r,displayModel:l,onAfterDeleteFocus:s,onCopyPrompt:c}){const{t:d}=fe(),u=[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?d("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,gn(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(xn,{imageOverride:n?t:null,onAfterDeleteFocus:s}),e.prompt?o.jsx(yn,{prompt:e.prompt,onCopy:c}):null]})}function xa({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(ya,{})}),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(wa,{})})]})}function ya(){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 wa(){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 ka({zoom:e,modeLabel:t,closeLabel:n,blankCanvasLabel:a,blankCanvasAriaLabel:r,blankCanvasShortcut:l,blankCanvasBusy:s,shortcutHint:c,onZoomIn:d,onZoomOut:u,onZoomReset:v,onCreateBlankCanvas:h,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(xa,{zoom:e,onZoomIn:d,onZoomOut:u,onZoomReset:v}),o.jsx("span",{className:"canvas-mode-topbar__shortcuts",children:c})]}),o.jsx("div",{className:"canvas-mode-topbar__center",children:o.jsxs("button",{type:"button",className:"canvas-mode-blank",onClick:h,disabled:s,"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 Ca({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),s=ot(50-n/40,r,100-r);return{width:`${a}%`,height:`${a}%`,left:`${l}%`,top:`${s}%`}}function _a({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:Ca({zoom:t,panX:n,panY:a}),"aria-hidden":"true"})]})}function Le(e){return Math.min(1,Math.max(0,e))}function Ma(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("mask_blob_unavailable"))},"image/png")})}async function Ea(e){const t=e.imageElement.naturalWidth,n=e.imageElement.naturalHeight;if(!t||!n)throw new Error("mask_source_size_unavailable");if(e.boxes.length===0)throw new Error("mask_boxes_required");const a=document.createElement("canvas");a.width=t,a.height=n;const r=a.getContext("2d");if(!r)throw new Error("mask_context_unavailable");r.fillStyle="rgba(0, 0, 0, 1)",r.fillRect(0,0,t,n),r.globalCompositeOperation="destination-out";for(const l of e.boxes){const s=Le(l.x)*t,c=Le(l.y)*n,d=Le(l.width)*t,u=Le(l.height)*n;d>0&&u>0&&r.fillRect(s,c,d,u)}return Ma(a)}async function Sa(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 pt(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 Ba=`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`,ja=`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 Ta(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function Aa(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function Pa(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 Da(e){const t=e.canvasSourceFilename??e.filename;return t?`/generated/${encodeURIComponent(t)}`:e.url??e.image}async function Et(e){const t=Da(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}),Sa(n)}function Ke(e,t){return!e.canvasVersion||e.prompt||!t?.prompt?e:{...e,prompt:t.prompt}}function Ra(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 Ia(e,t){if(wn(e)){const n=e.images[0];if(!n)throw new Error("edit_empty_response");return{...n,prompt:t,reasoningEffort:e.reasoningEffort,provider:e.provider,quality:e.quality,size:e.size,moderation:e.moderation,model:e.model,usage:e.usage,kind:"edit",createdAt:Date.now()}}return{image:e.image,url:e.filename?`/generated/${e.filename}`:e.image,thumb:e.image,filename:e.filename,prompt:t,elapsed:e.elapsed,reasoningEffort:e.reasoningEffort,provider:e.provider,quality:e.quality,size:e.size,moderation:e.moderation,model:e.model,usage:e.usage,revisedPrompt:e.revisedPrompt??null,promptMode:e.promptMode??null,kind:"edit",createdAt:Date.now()}}const st=new WeakMap;function Na(e){if(!e.complete||!e.naturalWidth||!e.naturalHeight)return!1;const t=st.get(e);if(t&&t.src===e.currentSrc&&t.width===e.naturalWidth&&t.height===e.naturalHeight)return t.result;const n=64,a=Math.min(n,e.naturalWidth),r=Math.min(n,e.naturalHeight),l=document.createElement("canvas");l.width=a,l.height=r;const s=l.getContext("2d",{willReadFrequently:!0});if(!s)return!1;try{s.drawImage(e,0,0,a,r);const c=s.getImageData(0,0,a,r).data;for(let d=3;d<c.length;d+=4)if(c[d]<250)return st.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!0}),!0;return st.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!1}),!1}catch{return!1}}function Oa(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 St(e,t){return{width:e,height:t,data:new Uint8Array(e*t)}}function dt(e){return{width:e.width,height:e.height,data:new Uint8Array(e.data)}}function La(e,t){Oa(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=dt(e);return t&&La(n,t),n}function $a(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 vt=[{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}],Ua=1024;function Wa(e){return Math.max(0,Math.min(255,Math.round(e)))}function Xt(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 Fa(e,t){return(t.length>0?t:vt).map(a=>{const r=Xt(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 Ha(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,s){if(e<0||e>=a.length||a[e])return r;const c=e*4;return(t.data[c+3]??0)===0?(a[e]=1,r):Ha(t.data,c,l,s)?(a[e]=1,n[r]=e,r+1):r}function lt(){return vt.map(e=>({...e}))}function Bt(e,t,n,a){if(e.width!==t.width||e.height!==t.height)throw new Error("cleanup_mask_size_mismatch");const{width:r,height:l}=t,s=r*l,c=new Uint8Array(s),d=new Int32Array(s),u=Fa(t,n),v=Wa(a);let h=0;for(const _ of n.length>0?n:vt)h=Te(Xt(_,r,l),t,d,c,h,u,v);for(;h>0;){const _=d[--h];e.data[_]=255;const M=_%r;M>0&&(h=Te(_-1,t,d,c,h,u,v)),M<r-1&&(h=Te(_+1,t,d,c,h,u,v)),_>=r&&(h=Te(_-r,t,d,c,h,u,v)),_<s-r&&(h=Te(_+r,t,d,c,h,u,v))}}function Ka(e,t){const n=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),a=$a(n,t),r=t.data.reduce((l,s)=>l+(s>0?1:0),0);return{imageData:{width:e.width,height:e.height,data:a.data},stats:{width:e.width,height:e.height,removedPixels:r,removedPercent:t.data.length>0?r/t.data.length:0}}}function Yt(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("background_cleanup_blob_failed"))},"image/png")})}function Gt(e,t){const n=e.naturalWidth,a=e.naturalHeight;if(n<=0||a<=0)throw new Error("background_cleanup_image_not_ready");const r=t&&t>0?Math.min(1,t/Math.max(n,a)):1,l=Math.max(1,Math.round(n*r)),s=Math.max(1,Math.round(a*r)),c=document.createElement("canvas");c.width=l,c.height=s;const d=c.getContext("2d",{willReadFrequently:!0});if(!d)throw new Error("background_cleanup_context_failed");return d.drawImage(e,0,0,l,s),{canvas:c,context:d,width:l,height:s}}async function jt({imageElement:e,mask:t}){try{const{canvas:n,context:a,width:r,height:l}=Gt(e),s=a.getImageData(0,0,r,l),c=Ka({width:r,height:l,data:s.data},t),d=a.createImageData(r,l);d.data.set(c.imageData.data),a.putImageData(d,0,0);const u=await Yt(n);return{blob:u,dataUrl:await pt(u),stats:c.stats}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}async function za({imageElement:e,mask:t}){try{const{width:n,height:a}=Gt(e,Ua),r=document.createElement("canvas");r.width=n,r.height=a;const l=r.getContext("2d");if(!l)throw new Error("background_cleanup_context_failed");const s=l.createImageData(n,a);let c=0;for(let u=0;u<a;u+=1)for(let v=0;v<n;v+=1){const h=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+h]??0)===0)continue;const M=(u*n+v)*4;s.data[M]=168,s.data[M+1]=85,s.data[M+2]=247,s.data[M+3]=150,c+=1}l.putImageData(s,0,0);const d=await Yt(r);return{dataUrl:await pt(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?c/(n*a):0}}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}function Tt(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?dt(e.removeMask):null,preserveMask:e.preserveMask?dt(e.preserveMask):null}}function Va(){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 qa(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 Xa(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 Ya({canvasOpen:e,currentImage:t,canvasDisplayImage:n,imageElementRef:a,canvasSourceImageRef:r,lastMergedDataUrlRef:l,setCanvasSaveState:s,setCanvasVersionItem:c,applyMergedCanvasImage:d,attachCanvasVersionReference:u,showToast:v,t:h}){const[_,M]=i.useState(!1),[T,W]=i.useState("remove"),[P,O]=i.useState("click"),[b,C]=i.useState("flat-flood-fill"),[E,y]=i.useState([]),[p,J]=i.useState([]),[I,K]=i.useState(28),[g,j]=i.useState(null),[R,D]=i.useState(null),[L,Z]=i.useState(null),[te,ne]=i.useState(!1),[le,ue]=i.useState(.018),[de,m]=i.useState(null),[S,$]=i.useState(!1),[ae,re]=i.useState(!1),G=i.useRef(null),q=i.useRef(null),U=i.useRef(null),H=i.useRef({past:[],future:[]}),N=i.useRef(0),k=i.useRef(null),Y=i.useCallback(()=>Tt({intent:T,tool:P,engine:b,seeds:E,brushStrokes:p,brushRadius:le,tolerance:I,removeMask:G.current,preserveMask:q.current,preview:g,maskOverlay:R,stats:L,active:te,brushCursor:de}),[p,R,g,E,L,I,de,le,b,T,P,te]),F=i.useCallback(()=>{H.current={past:[...H.current.past.slice(-19),Y()],future:[]}},[Y]),ce=i.useCallback(x=>{const w=Tt(x);G.current=w.removeMask,q.current=w.preserveMask,U.current=null,W(w.intent),O(w.tool),C(w.engine),y(w.seeds),J(w.brushStrokes),ue(w.brushRadius),K(w.tolerance),j(w.preview),D(w.maskOverlay),Z(w.stats),ne(w.active),m(w.brushCursor),$(!1),re(!1)},[]),X=i.useCallback(async()=>{if(!a.current||!t)return;const x=je(G.current,q.current);if(!x){D(null),Z(null);return}const w=N.current+1;N.current=w,$(!0);try{const B=await za({imageElement:a.current,mask:x});if(N.current!==w)return;D(B),Z(B.stats)}catch{if(N.current!==w)return;v(h("canvas.toolbar.cleanupFailed"),!0)}finally{N.current===w&&$(!1)}},[t,a,v,h]),z=i.useCallback(async(x,w,B)=>{if(!a.current)return;const Q=Xa(a.current),ie=St(Q.width,Q.height),_e=St(Q.width,Q.height);for(const pe of x){const Me=pe.intent==="remove"?ie:_e;Bt(Me,Q,[pe.point],B)}for(const pe of w){const Me=pe.intent==="remove"?ie:_e;Bt(Me,Q,qa(pe),B)}G.current=ie,q.current=_e},[a]),he=i.useCallback(()=>{N.current+=1,k.current!=null&&(window.clearTimeout(k.current),k.current=null),G.current=null,q.current=null,U.current=null,H.current={past:[],future:[]},y([]),J([]),j(null),D(null),Z(null),ne(!1),m(null),$(!1),re(!1)},[]),ke=i.useCallback(()=>{const x=H.current.past.pop();return x?(H.current.future=[Y(),...H.current.future.slice(0,19)],ce(x),!0):!1},[Y,ce]),oe=i.useCallback(()=>{const x=H.current.future.shift();return x?(H.current.past=[...H.current.past.slice(-19),Y()],ce(x),!0):!1},[Y,ce]),Ce=i.useCallback(x=>{F();const w=[...E,{point:x,intent:T}];y(w),j(null),z(w,p,I).then(X)},[p,E,I,T,F,z,X]),ze=i.useCallback(()=>{F();const x=lt().map(w=>({point:w,intent:"remove"}));y(x),j(null),ne(!1),z(x,p,I).then(X)},[p,I,F,z,X]),Ve=i.useCallback(()=>{F(),O("click"),ne(x=>!x)},[F]),qe=i.useCallback(x=>{F(),k.current!=null&&window.clearTimeout(k.current),K(x),j(null),k.current=window.setTimeout(()=>{k.current=null,z(E,p,x).then(X)},180)},[p,E,F,z,X]),V=i.useCallback(async()=>{if(!a.current||!t)return null;let x=je(G.current,q.current);if(!x){const B=lt().map(Q=>({point:Q,intent:"remove"}));y(B),await z(B,p,I),x=je(G.current,q.current)}if(!x)return null;F();const w=N.current+1;N.current=w,$(!0);try{const B=await jt({imageElement:a.current,mask:x});return N.current!==w?null:(j(B),D(null),Z(B.stats),B)}catch{return N.current!==w||v(h("canvas.toolbar.cleanupFailed"),!0),null}finally{N.current===w&&$(!1)}},[p,I,t,a,F,z,v,h]),Xe=i.useCallback(()=>{F(),he()},[F,he]),Ye=i.useCallback(x=>{F();const w={id:Va(),intent:T,points:[{...x}],radius:le};U.current=w,m(x),J(B=>[...B,w])},[le,T,F]),Ge=i.useCallback(x=>{const w=U.current;if(!w){m(x);return}w.points=[...w.points,{...x}],m(x),J(B=>B.map(Q=>Q.id===w.id?{...w,points:w.points.map(ie=>({...ie}))}:Q)),z(E,p.map(B=>B.id===w.id?w:B),I).then(X)},[p,E,I,z,X]),Ze=i.useCallback(()=>{U.current=null,z(E,p,I).then(X)},[p,E,I,z,X]),ge=i.useCallback(async()=>{if(!t||!a.current)return;const x=r.current??t;if(!x?.filename){v(h("canvas.toolbar.cleanupFailed"),!0);return}let w=je(G.current,q.current);if(!w){const B=lt().map(Q=>({point:Q,intent:"remove"}));y(B),await z(B,p,I),w=je(G.current,q.current)}if(w){re(!0),s("saving");try{F();const B=await jt({imageElement:a.current,mask:w}),Q=n?.canvasVersion&&n.filename?await Ot(n.filename,{sourceFilename:x.canvasSourceFilename??x.filename,image:B.blob,prompt:x.prompt,pixelEdited:!0}):await Lt({sourceFilename:x.canvasSourceFilename??x.filename,image:B.blob,prompt:x.prompt}),ie=Ke(Q.item,x);l.current=B.dataUrl,c(ie),d(ie),await u(ie),s("saved"),j(null),D(null),Z(B.stats),ne(!1),v(h("canvas.toolbar.cleanupApplied"))}catch{s("error"),v(h("canvas.toolbar.cleanupFailed"),!0)}finally{re(!1)}}},[d,u,p,I,n,r,t,a,l,F,z,s,c,v,h]),me=i.useCallback(()=>te?(U.current=null,ne(!1),m(null),!0):!1,[te]);return i.useEffect(()=>{const x=a.current;if(!x||!e){M(!1);return}const w=()=>M(Na(x));if(x.complete)w();else return x.addEventListener("load",w),()=>x.removeEventListener("load",w)},[e,n?.canvasMergedAt,n?.filename,n?.image,n?.url,g?.dataUrl,a]),{imageHasAlpha:_,backgroundCleanupSeeds:E,backgroundCleanupBrushStrokes:p,backgroundCleanupTolerance:I,backgroundCleanupPreview:g,backgroundCleanupMaskOverlay:R,backgroundCleanupStats:L,cleanupIntent:T,setCleanupIntent:W,cleanupTool:P,setCleanupTool:O,cleanupClickEngine:b,setCleanupClickEngine:C,cleanupBrushRadius:le,setCleanupBrushRadius:ue,cleanupBrushCursor:de,setCleanupBrushCursor:m,isBackgroundCleanupActive:te,setIsBackgroundCleanupActive:ne,isBackgroundCleanupPickingSeed:te&&P==="click",isBackgroundCleanupPreviewing:S,isBackgroundCleanupApplying:ae,hasActiveCleanupStroke:!!U.current,canUndoBackgroundCleanup:H.current.past.length>0,canRedoBackgroundCleanup:H.current.future.length>0,resetBackgroundCleanup:he,undoBackgroundCleanup:ke,redoBackgroundCleanup:oe,addBackgroundCleanupClick:Ce,addBackgroundCleanupSeed:Ce,runBackgroundCleanupPreview:V,handleBackgroundCleanupAutoSample:ze,handleBackgroundCleanupPickSeed:Ve,handleBackgroundCleanupToleranceChange:qe,handleBackgroundCleanupReset:Xe,handleBackgroundCleanupApply:ge,handleBackgroundCleanupEscape:me,startBackgroundCleanupBrushStroke:Ye,updateBackgroundCleanupBrushStroke:Ge,endBackgroundCleanupBrushStroke:Ze}}function At(e){return Math.min(1,Math.max(0,e))}function Pt(e,t){const n=t.getBoundingClientRect();return{x:At((e.clientX-n.left)/n.width),y:At((e.clientY-n.top)/n.height)}}const Ga=.18,Za=.12;function Ja(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 ht(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 Zt(e){return{id:e.id,x:e.x,y:e.y,width:Ga,height:Za,color:e.color,strokeWidth:1}}function Qa(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,c=a*a+r*r;if(c===0)return Math.hypot(e.x-t.x,e.y-t.y);const d=Math.max(0,Math.min(1,(l*a+s*r)/c));return Math.hypot(e.x-(t.x+d*a),e.y-(t.y+d*r))}function er(e,t,n){for(let a=1;a<t.points.length;a+=1)if(Qa(e,t.points[a-1],t.points[a])<=n)return!0;return!1}function Dt(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 tr(e,t){return e.points.some(n=>ht(n,t))}function Rt(e){const t=e.tolerance??.015;for(const n of[...e.memos].reverse())if(ht(e.point,Zt(n),t))return Ht(n);for(const n of[...e.boxes].reverse())if(ht(e.point,n,t))return Ft(n);for(const n of[...e.paths].reverse())if(er(e.point,n,t))return Wt(n);return null}function nr(e){const t=[];for(const n of e.annotations.paths)tr(n,e.box)&&t.push(Wt(n));for(const n of e.annotations.boxes)Dt(n,e.box)&&t.push(Ft(n));for(const n of e.annotations.memos)Dt(Zt(n),e.box)&&t.push(Ht(n));return t}function ar({canvasOpen:e,canvasZoom:t,canvasPanX:n,canvasPanY:a,spaceHeld:r,canDragViewportWithSelect:l,isBackgroundCleanupActive:s,cleanupTool:c,annotationFrameRef:d,annotations:u,setCanvasPan:v,addBackgroundCleanupClick:h,startBackgroundCleanupBrushStroke:_,updateBackgroundCleanupBrushStroke:M,endBackgroundCleanupBrushStroke:T,setCleanupBrushCursor:W}){const P=i.useRef({mode:null,lastPoint:null,didMove:!1}),O=i.useRef({active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null}),[b,C]=i.useState(!1),E=g=>{g.currentTarget.setPointerCapture(g.pointerId),O.current={active:!0,startX:g.clientX,startY:g.clientY,basePanX:n,basePanY:a,pointerId:g.pointerId},C(!0)};return{viewportPanActive:b,resetPointerSession:()=>{P.current={mode:null,lastPoint:null,didMove:!1},O.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},C(!1)},handleAnnotationPointerDown:g=>{if(!e||be(g.target)||!d.current)return;const j=g.button===1;if(r||j){g.preventDefault(),E(g);return}g.preventDefault();const R=Pt(g,d.current);if(s){c==="click"?h(R):(g.currentTarget.setPointerCapture(g.pointerId),_(R));return}if(u.activeTool==="select"){const D=Rt({point:R,paths:u.paths,boxes:u.boxes,memos:u.memos});if(D)g.shiftKey?u.toggleSelected(D):u.selectOne(D),u.startSelectedMove(),P.current={mode:"move",lastPoint:R,didMove:!1};else if(l&&t>1.01){E(g);return}else u.clearSelection(),u.startSelectionBox(R),P.current={mode:"box",lastPoint:R,didMove:!1};g.currentTarget.setPointerCapture(g.pointerId);return}if(u.activeTool==="memo"){u.createMemo(R),requestAnimationFrame(()=>{d.current?.querySelector(".canvas-memo--active")?.focus()});return}if(u.activeTool==="eraser"){if(u.eraserMode==="object"){const D=Rt({point:R,paths:u.paths,boxes:u.boxes,memos:u.memos});D&&u.eraseObjectAtPoint(D);return}g.currentTarget.setPointerCapture(g.pointerId),u.startEraserStroke(R);return}g.currentTarget.setPointerCapture(g.pointerId),u.startDrawing(R)},handleAnnotationPointerMove:g=>{if(!e||be(g.target)||!d.current)return;if(O.current.active){const R=g.clientX-O.current.startX,D=g.clientY-O.current.startY;v(O.current.basePanX+R,O.current.basePanY+D);return}const j=Pt(g,d.current);if(s){c==="brush"?M(j):W(j);return}if(u.activeTool==="select"){if(P.current.mode==="move"&&P.current.lastPoint){const R={x:j.x-P.current.lastPoint.x,y:j.y-P.current.lastPoint.y};(Math.abs(R.x)>5e-4||Math.abs(R.y)>5e-4)&&(u.moveSelected(R),P.current.didMove=!0),P.current.lastPoint=j}else P.current.mode==="box"&&u.updateSelectionBox(j);return}if(u.activeTool!=="memo"){if(u.activeTool==="eraser"){u.eraserMode==="brush"&&u.updateEraserStroke(j);return}u.moveDrawing(j)}},handleAnnotationPointerUp:g=>{if(e&&!be(g.target)){if(O.current.active&&O.current.pointerId===g.pointerId){g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),O.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},C(!1);return}if(g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),s){c==="brush"&&T();return}if(u.activeTool==="select"){P.current.mode==="move"&&P.current.didMove&&u.commitSelectedMove(),P.current.mode==="box"&&u.selectionBox&&u.endSelectionBox(nr({box:Ja(u.selectionBox),annotations:u.toPayload()})),P.current={mode:null,lastPoint:null,didMove:!1};return}if(u.activeTool!=="memo"){if(u.activeTool==="eraser"){u.eraserMode==="brush"&&u.endEraserStroke();return}u.endDrawing()}}},handleAnnotationPointerLeave:()=>{s&&W(null)}}}function rr({canvasOpen:e,canvasZoom:t,currentImage:n,annotations:a,undoBackgroundCleanup:r,redoBackgroundCleanup:l,handleBackgroundCleanupEscape:s,handleCloseCanvas:c,selectHistoryShortcutTarget:d,trashHistoryItem:u,permanentlyDeleteHistoryItemByShortcut:v,setCanvasZoom:h,resetCanvasZoom:_,onCreateBlankCanvas:M,isCreatingBlankCanvas:T}){const[W,P]=i.useState(!1);return i.useEffect(()=>{if(!e)return;const b=p=>{p.preventDefault()},C=p=>{p.ctrlKey&&p.preventDefault()},E={passive:!1,capture:!0},y={passive:!1};return window.addEventListener("wheel",C,E),window.addEventListener("gesturestart",b,y),window.addEventListener("gesturechange",b,y),window.addEventListener("gestureend",b,y),()=>{window.removeEventListener("wheel",C,E),window.removeEventListener("gesturestart",b,y),window.removeEventListener("gesturechange",b,y),window.removeEventListener("gestureend",b,y)}},[e]),i.useEffect(()=>{if(!e)return;const b=E=>{E.code==="Space"&&(be(E.target)||(W||P(!0),E.preventDefault()))},C=E=>{E.code==="Space"&&P(!1)};return window.addEventListener("keydown",b),window.addEventListener("keyup",C),()=>{window.removeEventListener("keydown",b),window.removeEventListener("keyup",C)}},[e,W]),i.useEffect(()=>{if(!e)return;const b=C=>{if(!C.defaultPrevented){if(be(C.target)){C.key==="Escape"&&(C.preventDefault(),C.target.blur(),a.focusMemo(null));return}if(C.key==="Escape"){if(C.preventDefault(),s())return;c();return}if(C.shiftKey&&!C.metaKey&&!C.ctrlKey&&!C.altKey&&C.key.toLowerCase()==="b"){C.preventDefault(),!T&&!C.repeat&&M();return}if((C.metaKey||C.ctrlKey)&&C.key.toLowerCase()==="z"){if(C.preventDefault(),C.shiftKey){if(l())return;a.redo();return}if(r())return;a.undo()}}};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[a,a.focusMemo,a.redo,a.undo,e,c,s,T,M,l,r]),{spaceHeld:W,handleViewerKeyDown:b=>{if(be(b.target)){b.key==="Escape"&&(b.preventDefault(),b.target.blur(),a.focusMemo(null));return}if(e&&["1","2","3","4","5","6"].includes(b.key)){b.preventDefault();const C=["select","pen","box","arrow","memo","eraser"];a.setTool(C[Number(b.key)-1]);return}if(e&&b.key==="Escape"){if(b.preventDefault(),b.stopPropagation(),s())return;c();return}if(e&&b.key==="]"){b.preventDefault(),h(t+.1);return}if(e&&b.key==="["){b.preventDefault(),h(t-.1);return}if(e&&b.key==="0"){b.preventDefault(),_();return}if(b.key==="Delete"||b.key==="Backspace"){if(!n||b.target!==b.currentTarget)return;if(b.preventDefault(),b.shiftKey){v(n);return}u(n);return}b.key!=="ArrowLeft"&&b.key!=="ArrowRight"&&b.key!=="Home"&&b.key!=="End"||b.target===b.currentTarget&&(be(b.target)||(b.preventDefault(),b.key==="ArrowLeft"?d("previous"):b.key==="ArrowRight"?d("next"):b.key==="Home"?d("first"):b.key==="End"&&d("last")))}}}function or(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)it(n,l,a);for(const l of e.boxes)ut(n,l,a,"committed");for(const l of e.memos)Wn(n,l,a);return{blob:await or(t,"image/png"),dataUrl:t.toDataURL("image/png")}}const sr=["left","center","right"],lr=["top","middle","bottom"];function cr(e,t){const n=sr[Math.min(2,Math.max(0,Math.floor(e*3)))],a=lr[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 It(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 ${cr(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 Nt=18,Ae=12,ir="14px sans-serif";function Ie(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ee(e){return Math.round(e*100)/100}function ur(e,t){if(e.points.length<2)return"";const n=e.points.map(c=>De(c,t)),a=n.map((c,d)=>`${d===0?"M":"L"}${ee(c.x)} ${ee(c.y)}`).join(" "),r=`stroke="${Ie(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 s=qt(n[n.length-2],n[n.length-1],e.strokeWidth).map(c=>`${ee(c.x)},${ee(c.y)}`).join(" ");return`${l}<polygon points="${s}" fill="${Ie(e.color)}" />`}function dr(e,t){return`<rect x="${ee(e.x*t.width)}" y="${ee(e.y*t.height)}" width="${ee(e.width*t.width)}" height="${ee(e.height*t.height)}" fill="none" stroke="${Ie(e.color)}" stroke-width="${e.strokeWidth}" />`}function hr(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 c=0;c<l.length;c+=t)a.push(l.slice(c,c+t));continue}const s=r?`${r} ${l}`:l;s.length<=t?r=s:(a.push(r),r=l)}return r&&a.push(r),a.length>0?a:[""]}function fr(e,t){const n=ee(e.x*t.width),a=ee(e.y*t.height),r=ee(Math.min(260,Math.max(150,t.width*.22))),l=Math.max(8,Math.floor((r-Ae*2)/7.5)),s=hr(e.text,l),c=ee(Math.max(52,Ae*2+s.length*Nt)),d=s.map((u,v)=>`<tspan x="${ee(n+Ae)}" dy="${v===0?0:Nt}">${Ie(u)}</tspan>`).join("");return`<g><rect x="${n}" y="${a}" width="${r}" height="${c}" rx="8" fill="rgba(255, 246, 179, 0.96)" stroke="rgba(44, 37, 12, 0.28)" stroke-width="1" /><text x="${ee(n+Ae)}" y="${ee(a+Ae+14)}" font="${ir}" font-family="sans-serif" font-size="14" fill="#2f2a13">${d}</text></g>`}function mr(e){const{imageSize:t,annotations:n}=e,a=[`<image href="${Ie(e.imageDataUrl)}" x="0" y="0" width="${t.width}" height="${t.height}" preserveAspectRatio="none" />`,...n.paths.map(r=>ur(r,t)),...n.boxes.map(r=>dr(r,t)),...n.memos.map(r=>fr(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 pr(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 vr(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 br(e){const{default:t}=await kn(async()=>{const{default:s}=await import("./pptxgen.es-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pptxgen.es-BE4CSd5F.js","assets/index-CxEuSZMC.js","assets/index-C0nfanMr.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{a as i,j as o,u as fe,f as gn,as as xn,at as yn,au as wn,av as Ot,aw as Lt,ax as be,aa as kn,ay as Cn,b as A,az as $t,aA as _n,aB as Mn,aC as Ut,aD as En,c as Sn,aE as Bn,aF as jn}from"./index-CxEuSZMC.js";const Ne=2,He=1e-6;function Tn({paths:e,points:t,radius:n,makeId:a=()=>crypto.randomUUID()}){if(e.length===0||t.length===0||n<=0)return{paths:e,changed:!1};let r=!1;const l=[];for(const s of e){const c=An(s,t,n,a);(c.length!==1||c[0]!==s)&&(r=!0),l.push(...c)}return{paths:l,changed:r}}function An(e,t,n,a=()=>crypto.randomUUID()){if(e.points.length<Ne||t.length===0||n<=0)return[e];const r=[];let l=Pe(e.points[0],t,n)?[]:[e.points[0]];for(let c=1;c<e.points.length;c+=1){const d=e.points[c-1],u=e.points[c],v=Pe(u,t,n),h=Pn(d,u,t,n);if(h){l.length===0&&!Pe(d,t,n)&&(l=[d]),l.length>0&&h.leftT>He&&xt(l,Re(d,u,h.leftT)),l.length>=Ne&&r.push(l),l=[],h.rightT<1-He&&!v&&(l=[Re(d,u,h.rightT),u]);continue}if(v){l.length>=Ne&&r.push(l),l=[];continue}l.length===0&&!Pe(d,t,n)&&(l=[d]),xt(l,u)}if(l.length>=Ne&&r.push(l),r.length===0)return[];if(r.length===1&&r[0].length===e.points.length)return[e];const s=e.tool==="arrow"?r.length-1:-1;return r.map((c,d)=>({...e,id:d===0?e.id:a(),tool:e.tool==="arrow"&&d!==s?"pen":e.tool,points:c}))}function Pe(e,t,n){if(t.length===1)return we(e,t[0])<=n;for(let a=1;a<t.length;a+=1)if(Dn(e,t[a-1],t[a])<=n)return!0;return!1}function we(e,t){const n=e.x-t.x,a=e.y-t.y;return Math.sqrt(n*n+a*a)}function Pn(e,t,n,a){const r=we(e,t);if(r<=He)return Pe(e,n,a)?{leftT:0,rightT:1}:null;let l=null,s=Number.POSITIVE_INFINITY;for(const d of n){const u=gt(d,e,t),v=Re(e,t,u),h=we(d,v);h<s&&(s=h,l=u)}for(let d=1;d<n.length;d+=1){const u=[0,.25,.5,.75,1];for(const v of u){const h=Re(n[d-1],n[d],v),_=gt(h,e,t),M=Re(e,t,_),T=we(h,M);T<s&&(s=T,l=_)}}if(l===null||s>a)return null;const c=Math.max(a/r,.01);return{leftT:Math.max(0,l-c),rightT:Math.min(1,l+c)}}function gt(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,c=a*a+r*r;return c===0?0:Math.max(0,Math.min(1,(l*a+s*r)/c))}function Re(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function xt(e,t){const n=e.at(-1);(!n||we(n,t)>He)&&e.push(t)}function Dn(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,c=a*a+r*r;if(c===0)return we(e,t);const d=Math.max(0,Math.min(1,(l*a+s*r)/c));return we(e,{x:t.x+d*a,y:t.y+d*r})}function ft(e,t){return`${e}:${t}`}function mt(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 Wt(e){return ft("path",e.id)}function Ft(e){return ft("box",e.id)}function Ht(e){return ft("memo",e.id)}function ve(e,t,n){const a=mt(e);return a?.kind===t&&a.id===n}const Kt="ima2.canvas.annotationStyle.v1",zt=["#ef4444","#f97316","#eab308","#22c55e","#38bdf8","#6366f1","#a855f7","#111827","#ffffff"],Vt=[2,3,5,8],Be={color:"#ef4444",strokeWidth:3};function Rn(){if(typeof window>"u")return Be;try{const e=window.localStorage.getItem(Kt);if(!e)return Be;const t=JSON.parse(e),n=typeof t.color=="string"&&zt.includes(t.color)?t.color:Be.color,a=typeof t.strokeWidth=="number"&&Vt.includes(t.strokeWidth)?t.strokeWidth:Be.strokeWidth;return{color:n,strokeWidth:a}}catch{return Be}}function In(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Kt,JSON.stringify(e))}catch{}}const yt=Rn(),ct={activeTool:"select",toolColor:yt.color,strokeWidth:yt.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 ye(e){return{paths:e.paths,boxes:e.boxes,memos:e.memos}}function xe(e){return{...e,past:[...e.past.slice(-49),ye(e)],future:[]}}function at(e,t){return{...e,past:[...e.past.slice(-49),t],future:[]}}function Nn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function wt(e,t){return{...e,...t,activeMemoId:null,activePath:null,activeBox:null,selectionBox:null,selectedIds:[],isDirty:!0}}function On(e,t,n){const{start:a,current:r}=e,l=Math.min(a.x,r.x),s=Math.min(a.y,r.y),c=Math.abs(r.x-a.x),d=Math.abs(r.y-a.y);return c<.01||d<.01?null:{id:crypto.randomUUID(),x:l,y:s,width:c,height:d,color:t,strokeWidth:n}}function Ln(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 $n(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}:{...xe(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=On(e.activeBox,e.toolColor,e.strokeWidth);return n?{...xe(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{...xe(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?Nn(e.memoBaseline,ye(e))?{...e,memoBaseline:null,activeMemoId:null}:{...at(e,e.memoBaseline),memoBaseline:null,activeMemoId:null,isDirty:!0}:{...e,activeMemoId:null};case"DELETE_MEMO":return{...xe(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=>!ve(n,"memo",t.id))};case"FOCUS_MEMO":return{...e,activeMemoId:t.id,memoBaseline:t.id&&e.activeMemoId!==t.id&&!e.memoBaseline?ye(e):e.memoBaseline};case"CLEAR":return{...xe(e),isDirty:!0,paths:[],boxes:[],memos:[],activeMemoId:null,activePath:null,activeBox:null,selectionBox:null,selectedIds:[]};case"LOAD":return{...ct,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{...ct,activeTool:e.activeTool,eraserMode:e.eraserMode,toolColor:e.toolColor,strokeWidth:e.strokeWidth};case"UNDO":{const n=e.past.at(-1);return n?{...wt(e,n),past:e.past.slice(0,-1),future:[ye(e),...e.future]}:e}case"REDO":{const n=e.future[0];return n?{...wt(e,n),past:[...e.past.slice(-49),ye(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:{...xe(e),isDirty:!0,paths:e.paths.filter(n=>!e.selectedIds.some(a=>ve(a,"path",n.id))),boxes:e.boxes.filter(n=>!e.selectedIds.some(a=>ve(a,"box",n.id))),memos:e.memos.filter(n=>!e.selectedIds.some(a=>ve(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=>ve(a,"path",n.id))?{...n,points:n.points.map(a=>rt(a,t.delta))}:n),boxes:e.boxes.map(n=>e.selectedIds.some(a=>ve(a,"box",n.id))?Ln(n,t.delta):n),memos:e.memos.map(n=>e.selectedIds.some(a=>ve(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:ye(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=mt(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:{...xe(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:ye(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=Tn({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 Un(){const[e,t]=i.useReducer($n,ct),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(m=>t({type:"SET_TOOL",tool:m}),[]),s=i.useCallback(m=>{In(m),t({type:"SET_STYLE",style:m})},[]),c=i.useCallback(()=>t({type:"CLEAR"}),[]),d=i.useCallback(m=>t({type:"LOAD",payload:m}),[]),u=i.useCallback(()=>t({type:"MARK_SAVED"}),[]),v=i.useCallback(()=>t({type:"RESET_LOCAL"}),[]),h=i.useCallback(()=>t({type:"UNDO"}),[]),_=i.useCallback(()=>t({type:"REDO"}),[]),M=i.useCallback(()=>t({type:"COMMIT_MEMO_EDIT"}),[]),T=i.useCallback(()=>t({type:"START_SELECTED_MOVE"}),[]),W=i.useCallback(()=>t({type:"COMMIT_SELECTED_MOVE"}),[]),P=i.useCallback(m=>{e.activeTool==="pen"||e.activeTool==="arrow"?t({type:"START_PATH",point:m}):e.activeTool==="box"&&t({type:"START_BOX",point:m})},[e.activeTool]),O=i.useCallback(m=>{e.activePath?t({type:"ADD_POINT",point:m}):e.activeBox&&t({type:"UPDATE_BOX",point:m})},[e.activePath,e.activeBox]),b=i.useCallback(()=>{e.activePath?t({type:"END_PATH"}):e.activeBox&&t({type:"END_BOX"})},[e.activePath,e.activeBox]),C=i.useCallback(m=>t({type:"CREATE_MEMO",point:m}),[]),E=i.useCallback((m,S)=>t({type:"UPDATE_MEMO",id:m,text:S}),[]),y=i.useCallback(m=>t({type:"DELETE_MEMO",id:m}),[]),p=i.useCallback(m=>t({type:"FOCUS_MEMO",id:m}),[]),J=i.useCallback(m=>t({type:"SET_ERASER_MODE",mode:m}),[]),I=i.useCallback(m=>t({type:"SELECT_ONE",id:m}),[]),K=i.useCallback(m=>t({type:"TOGGLE_SELECTED",id:m}),[]),g=i.useCallback(()=>t({type:"CLEAR_SELECTION"}),[]),j=i.useCallback(()=>t({type:"DELETE_SELECTED"}),[]),R=i.useCallback(m=>t({type:"MOVE_SELECTED",delta:m}),[]),D=i.useCallback(m=>t({type:"START_SELECTION_BOX",point:m}),[]),L=i.useCallback(m=>t({type:"UPDATE_SELECTION_BOX",point:m}),[]),Z=i.useCallback(m=>t({type:"END_SELECTION_BOX",ids:m}),[]),te=i.useCallback(m=>t({type:"ERASE_OBJECT",id:m}),[]),ne=i.useCallback(m=>t({type:"START_ERASER_STROKE",point:m}),[]),le=i.useCallback(m=>t({type:"UPDATE_ERASER_STROKE",point:m}),[]),ue=i.useCallback(()=>t({type:"END_ERASER_STROKE"}),[]),de=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:s,setEraserMode:J,startDrawing:P,moveDrawing:O,endDrawing:b,createMemo:C,updateMemo:E,commitMemoEdit:M,deleteMemo:y,focusMemo:p,clear:c,load:d,toPayload:de,markSaved:u,resetLocal:v,undo:h,redo:_,selectOne:I,toggleSelected:K,clearSelection:g,deleteSelected:j,moveSelected:R,startSelectedMove:T,commitSelectedMove:W,startSelectionBox:D,updateSelectionBox:L,endSelectionBox:Z,eraseObjectAtPoint:te,startEraserStroke:ne,updateEraserStroke:le,endEraserStroke:ue}}function De(e,t){return{x:e.x*t.width,y:e.y*t.height}}function qt(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 it(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);Hn(e,l,r,t.color,t.strokeWidth)}e.restore()}function ut(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 Wn(e,t,n){const a=t.x*n.width,r=t.y*n.height,l=Math.min(260,Math.max(150,n.width*.22)),s=12,c=18;e.save(),e.font="14px sans-serif";const d=Kn(e,t.text.trim()||" ",l-s*2),u=Math.max(52,s*2+d.length*c);e.fillStyle="rgba(255, 246, 179, 0.96)",e.strokeStyle="rgba(44, 37, 12, 0.28)",e.lineWidth=1,zn(e,a,r,l,u,8),e.fill(),e.stroke(),e.fillStyle="#2f2a13",e.textBaseline="top",d.forEach((v,h)=>{e.fillText(v,a+s,r+s+h*c)}),e.restore()}function Fn(e,t){const n=mt(e);if(!n)return null;if(n.kind==="box")return t.boxes.find(u=>u.id===n.id)??null;const a=n.kind==="memo"?t.memos.find(u=>u.id===n.id):null;if(a)return{id:a.id,x:a.x,y:a.y,width:.18,height:.12,color:a.color,strokeWidth:1};if(n.kind!=="path")return null;const r=t.paths.find(u=>u.id===n.id);if(!r||r.points.length===0)return null;const l=r.points.map(u=>u.x),s=r.points.map(u=>u.y),c=Math.min(...l),d=Math.min(...s);return{id:r.id,x:c,y:d,width:Math.max(.01,Math.max(...l)-c),height:Math.max(.01,Math.max(...s)-d),color:r.color,strokeWidth:r.strokeWidth}}function kt(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 Hn(e,t,n,a,r){const[l,s,c]=qt(t,n,r);e.save(),e.fillStyle=a,e.beginPath(),e.moveTo(l.x,l.y),e.lineTo(s.x,s.y),e.lineTo(c.x,c.y),e.closePath(),e.fill(),e.restore()}function Kn(e,t,n){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const r=[];let l="";for(const s of a){const c=l?`${l} ${s}`:s;if(e.measureText(c).width<=n||l===""){l=c;continue}r.push(l),l=s}return l&&r.push(l),r}function zn(e,t,n,a,r,l){const s=Math.min(l,a/2,r/2);e.beginPath(),e.moveTo(t+s,n),e.lineTo(t+a-s,n),e.quadraticCurveTo(t+a,n,t+a,n+s),e.lineTo(t+a,n+r-s),e.quadraticCurveTo(t+a,n+r,t+a-s,n+r),e.lineTo(t+s,n+r),e.quadraticCurveTo(t,n+r,t,n+r-s),e.lineTo(t,n+s),e.quadraticCurveTo(t,n,t+s,n),e.closePath()}function Vn({paths:e,boxes:t,memos:n=[],selectedIds:a=[],selectionBox:r=null,activePath:l,activeBox:s}){const c=i.useRef(null);return i.useEffect(()=>{const d=c.current;if(!d)return;const u=d.getBoundingClientRect(),v=window.devicePixelRatio||1;d.width=Math.max(1,Math.round(u.width*v)),d.height=Math.max(1,Math.round(u.height*v));const h=d.getContext("2d");if(!h)return;h.setTransform(v,0,0,v,0,0),h.clearRect(0,0,u.width,u.height);const _={width:u.width,height:u.height};for(const M of e)it(h,M,_);for(const M of t)ut(h,M,_,"committed");for(const M of a){const T=Fn(M,{paths:e,boxes:t,memos:n});T&&kt(h,T,_)}r&&kt(h,r,_),l&&it(h,l,_),s&&ut(h,s,_,"active")},[e,t,n,a,r,l,s]),o.jsx("canvas",{ref:c,className:"canvas-annotation-layer","aria-hidden":"true"})}function Oe(e){e.stopPropagation()}function qn({memos:e,activeMemoId:t,onUpdate:n,onDelete:a,onFocus:r,onCommit:l}){const{t:s}=fe();return o.jsx("div",{className:"canvas-memo-overlay",children:e.map(c=>o.jsx("textarea",{className:`canvas-memo${t===c.id?" canvas-memo--active":""}`,value:c.text,style:{left:`${c.x*100}%`,top:`${c.y*100}%`},autoFocus:t===c.id,onFocus:()=>r(c.id),onPointerDown:Oe,onPointerMove:Oe,onPointerUp:Oe,onPointerCancel:Oe,onChange:d=>n(c.id,d.currentTarget.value),onBlur:()=>{l?.(),c.text.trim()===""&&a(c.id)},"aria-label":s("common.canvasMemo")},c.id))})}function Xn({annotationFrameRef:e,imageElementRef:t,frameClassName:n,frameStyle:a,imageKey:r,imageSrc:l,fallbackImage:s,alt:c,canvasOpen:d,maskOverlayUrl:u,cleanupLayer:v,annotations:h,onOpenCanvas:_,onPointerDown:M,onPointerMove:T,onPointerUp:W,onPointerLeave:P}){return o.jsxs("div",{ref:e,className:n,onPointerDown:M,onPointerMove:T,onPointerUp:W,onPointerCancel:W,onPointerLeave:P,style:a,children:[o.jsx("img",{ref:t,className:"result-img",src:l??s,alt:c,decoding:"async",onDoubleClick:O=>{O.stopPropagation(),_()}},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(Vn,{paths:h.paths,boxes:h.boxes,memos:h.memos,selectedIds:h.selectedIds,selectionBox:h.selectionBox,activePath:h.activePath,activeBox:h.activeBox}),o.jsx(qn,{memos:h.memos,activeMemoId:h.activeMemoId,onUpdate:h.updateMemo,onDelete:h.deleteMemo,onFocus:h.focusMemo,onCommit:h.commitMemoEdit})]})]})}function Yn(e){return`${e.x*100} ${e.y*100}`}function Gn(e){return e.map(Yn).join(" ")}function Zn({seeds:e,brushStrokes:t,brushCursor:n,brushRadius:a,active:r}){if(!r&&e.length===0&&t.length===0)return null;const l=a*100;return o.jsxs("svg",{className:"canvas-cleanup-overlay",viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",children:[t.map(s=>o.jsx("polyline",{className:`canvas-cleanup-overlay__stroke canvas-cleanup-overlay__stroke--${s.intent}`,points:Gn(s.points),strokeWidth:Math.max(.3,s.radius*200),vectorEffect:"non-scaling-stroke"},s.id)),r&&n?o.jsx("circle",{className:"canvas-cleanup-cursor",cx:n.x*100,cy:n.y*100,r:Math.max(.6,l),vectorEffect:"non-scaling-stroke"}):null]})}function Jn({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 Ct({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 Qn({seedCount:e,tolerance:t,stats:n,hasPreview:a,isPickingSeed:r,intent:l,tool:s,brushRadius:c,isPreviewing:d,isApplying:u,keepOpen:v,disabled:h,onAutoSample:_,onPickSeed:M,onIntentChange:T,onToolChange:W,onBrushRadiusChange:P,onToleranceChange:O,onPreview:b,onApply:C,onReset:E}){const{t:y}=fe(),[p,J]=i.useState(!1),I=i.useRef(null),K=n?Math.round(n.removedPercent*1e3)/10:0,g=r||s==="brush";return i.useEffect(()=>{if(!p)return;const j=R=>{v||I.current?.contains(R.target)||J(!1)};return window.addEventListener("pointerdown",j),()=>window.removeEventListener("pointerdown",j)},[v,p]),o.jsxs("div",{className:"canvas-toolbar__cleanup",ref:I,children:[o.jsx("button",{type:"button",className:`canvas-toolbar__button${p||a?" canvas-toolbar__button--active":""}`,onClick:()=>J(j=>!j),disabled:h,"aria-expanded":p,"aria-label":y("canvas.toolbar.cleanup"),title:y("canvas.toolbar.cleanup"),children:o.jsx(ea,{})}),p?o.jsxs("div",{className:"canvas-toolbar__cleanup-panel",role:"group","aria-label":y("canvas.toolbar.cleanup"),children:[o.jsxs("div",{className:"canvas-toolbar__cleanup-row",children:[o.jsx("span",{className:"canvas-toolbar__cleanup-title",children:y("canvas.toolbar.cleanup")}),o.jsx("span",{className:"canvas-toolbar__cleanup-meta",children:y("canvas.toolbar.cleanupSeedCount",{n:e})})]}),o.jsx(Ct,{label:y("canvas.toolbar.cleanupMark"),value:l,options:[{value:"remove",label:y("canvas.toolbar.cleanupRemove")},{value:"preserve",label:y("canvas.toolbar.cleanupPreserve")}],onChange:T}),o.jsx(Ct,{label:y("canvas.toolbar.cleanupInput"),value:s,options:[{value:"click",label:y("canvas.toolbar.cleanupClick")},{value:"brush",label:y("canvas.toolbar.cleanupBrush")}],onChange:W}),o.jsxs("label",{className:"canvas-toolbar__cleanup-slider",children:[o.jsx("span",{children:y("canvas.toolbar.cleanupTolerance")}),o.jsx("input",{type:"range",min:"0",max:"96",value:t,onChange:j=>O(Number(j.target.value))}),o.jsx("output",{children:t})]}),s==="brush"?o.jsxs("label",{className:"canvas-toolbar__cleanup-slider",children:[o.jsx("span",{children:y("canvas.toolbar.cleanupBrushSize")}),o.jsx("input",{type:"range",min:"0.006",max:"0.06",step:"0.002",value:c,onChange:j=>P(Number(j.target.value))}),o.jsx("output",{children:Math.round(c*1e3)})]}):null,o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:_,children:y("canvas.toolbar.cleanupAutoSample")}),o.jsx("button",{type:"button",className:r?"active":"",onClick:M,children:y(g?"canvas.toolbar.cleanupActive":"canvas.toolbar.cleanupPickSeed")})]}),o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:b,disabled:d||e===0,children:y(d?"canvas.toolbar.cleanupPreviewing":"canvas.toolbar.cleanupPreview")}),o.jsx("button",{type:"button",onClick:C,disabled:u||!a&&e===0,children:y(u?"canvas.toolbar.cleanupApplying":"canvas.toolbar.cleanupApply")}),o.jsx("button",{type:"button",onClick:E,disabled:!a&&e===0,children:y("canvas.toolbar.cleanupReset")})]}),g?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:y(s==="brush"?"canvas.toolbar.cleanupBrushHint":"canvas.toolbar.cleanupPickHint")}):n&&!a?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:y("canvas.toolbar.cleanupMaskHint")}):null,n?o.jsx("div",{className:"canvas-toolbar__cleanup-status",children:y("canvas.toolbar.cleanupRemoved",{n:K})}):null]}):null]})}function ea(){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 ta=["png","svg","pptx"];function na({onExport:e,disabled:t,isExporting:n}){const{t:a}=fe(),[r,l]=i.useState(!1),s=i.useRef(null),c=i.useRef(null),d=i.useId();i.useEffect(()=>{if(!r)return;const h=()=>Array.from(c.current?.querySelectorAll("[role='menuitem']")??[]);window.requestAnimationFrame(()=>h()[0]?.focus());const _=M=>{const T=M.target;c.current?.contains(T)||s.current?.contains(T)||l(!1)};return document.addEventListener("pointerdown",_,!0),()=>document.removeEventListener("pointerdown",_,!0)},[r]);const u=h=>{l(!1),s.current?.focus()},v=h=>{if(h.key==="Escape"){h.preventDefault(),u();return}if(!["ArrowDown","ArrowUp","Home","End"].includes(h.key))return;h.preventDefault();const M=Array.from(c.current?.querySelectorAll("[role='menuitem']")??[]);if(M.length===0)return;const T=M.indexOf(document.activeElement),W=h.key==="Home"?0:h.key==="End"?M.length-1:T<0?0:(T+(h.key==="ArrowDown"?1:-1)+M.length)%M.length;M[W]?.focus()};return o.jsxs("div",{className:"canvas-export-menu",children:[o.jsx("button",{ref:s,type:"button",className:`canvas-toolbar__button${n?" canvas-toolbar__button--busy":""}`,onClick:()=>l(h=>!h),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(aa,{})}),r?o.jsx("div",{ref:c,id:d,role:"menu",className:"canvas-export-menu__list","aria-label":a("canvas.toolbar.exportFormat"),onKeyDown:v,children:ta.map(h=>o.jsx("button",{type:"button",role:"menuitem",className:"canvas-export-menu__item",onClick:()=>{u(),e(h)},children:a(`canvas.toolbar.exportAs.${h}`)},h))}):null]})}function aa(){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 ra({style:e,onStyleChange:t}){const{t:n}=fe(),[a,r]=i.useState(!1),l=i.useRef(null);return i.useEffect(()=>{if(!a)return;const s=c=>{l.current?.contains(c.target)||r(!1)};return window.addEventListener("pointerdown",s),()=>window.removeEventListener("pointerdown",s)},[a]),o.jsxs("div",{ref:l,className:`canvas-toolbar__split-button${a?" canvas-toolbar__split-button--active":""}`,onKeyDown:s=>{s.key==="Escape"&&a&&(s.preventDefault(),s.stopPropagation(),r(!1))},children:[o.jsxs("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__style-trigger",onClick:()=>r(s=>!s),"aria-haspopup":"dialog","aria-expanded":a,"aria-label":n("canvas.toolbar.style"),title:n("canvas.toolbar.style"),children:[o.jsx("span",{className:"canvas-style-trigger__swatch",style:{background:e.color},"aria-hidden":"true"}),o.jsx("span",{className:"canvas-style-trigger__width",style:{height:`${Math.min(8,Math.max(2,e.strokeWidth))}px`},"aria-hidden":"true"})]}),a?o.jsxs("div",{className:"canvas-style-popover",role:"dialog","aria-label":n("canvas.toolbar.style"),children:[o.jsx("div",{className:"canvas-style-popover__row",role:"group","aria-label":n("canvas.toolbar.color"),children:zt.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:Vt.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 oa({tools:e,activeTool:t,onToolChange:n}){const[a,r]=i.useState(!1),l=i.useRef(null),s=e.find(d=>d.id===t)??e[0],c=s.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":`${s.label} (${s.shortcut})`,"aria-pressed":t===s.id,"aria-haspopup":"menu","aria-expanded":a,title:`${s.label} (${s.shortcut})`,children:[o.jsx(c,{}),o.jsx("span",{className:"canvas-toolbar__shortcut","aria-hidden":"true",children:s.shortcut})]}),a?o.jsx("div",{className:"canvas-tool-picker__menu",role:"menu",children:e.map(d=>{const u=d.icon,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 sa({activeTool:e,hasAnnotations:t,hasExportableContent:n,onToolChange:a,eraserMode:r="object",onEraserModeChange:l,style:s,onStyleChange:c,onClear:d,onApply:u,onRevertAnnotations:v,onExport:h,onUndo:_,onRedo:M,canUndo:T,canRedo:W,onDeleteSelected:P,selectedCount:O=0,onEditWithMask:b,canEditWithMask:C,isEditingWithMask:E,isApplying:y,isExporting:p,exportBackground:J="alpha",exportMatteColor:I="#ffffff",onExportBackgroundChange:K,onExportMatteColorChange:g,cleanupTolerance:j=28,cleanupSeedCount:R=0,cleanupStats:D=null,cleanupHasPreview:L=!1,isCleanupPickingSeed:Z=!1,isCleanupActive:te=!1,cleanupIntent:ne="remove",cleanupTool:le="click",cleanupBrushRadius:ue=.018,isCleanupPreviewing:de=!1,isCleanupApplying:m=!1,onCleanupAutoSample:S,onCleanupPickSeed:$,onCleanupIntentChange:ae,onCleanupToolChange:re,onCleanupBrushRadiusChange:G,onCleanupToleranceChange:q,onCleanupPreview:U,onCleanupApply:H,onCleanupReset:N}){const{t:k}=fe(),[Y,F]=i.useState(!1),ce=i.useRef(null),X=n??t??!1,z=k(r==="object"?"canvas.toolbar.objectEraser":"canvas.toolbar.brushEraser"),he=[{id:"select",shortcut:"1",label:k("canvas.toolbar.select"),icon:la},{id:"pen",shortcut:"2",label:k("canvas.toolbar.pen"),icon:ca},{id:"box",shortcut:"3",label:k("canvas.toolbar.box"),icon:ia},{id:"arrow",shortcut:"4",label:k("canvas.toolbar.arrow"),icon:ua},{id:"memo",shortcut:"5",label:k("canvas.toolbar.memo"),icon:da}];i.useEffect(()=>{if(!Y)return;const oe=Ce=>{ce.current?.contains(Ce.target)||F(!1)};return window.addEventListener("pointerdown",oe),()=>window.removeEventListener("pointerdown",oe)},[Y]);const ke=oe=>{l?.(oe),a("eraser"),F(!1)};return o.jsxs("div",{className:"canvas-toolbar","aria-label":k("canvas.toolbar.label"),children:[o.jsx(oa,{tools:he,activeTool:e,onToolChange:a}),o.jsx(ra,{style:s,onStyleChange:c}),o.jsxs("div",{ref:ce,className:`canvas-toolbar__split-button${e==="eraser"?" canvas-toolbar__split-button--active":""}`,onKeyDown:oe=>{oe.key==="Escape"&&Y&&(oe.preventDefault(),F(!1))},children:[o.jsxs("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--split-main${e==="eraser"?" canvas-toolbar__button--active":""}`,onClick:()=>a("eraser"),"aria-label":`${z} (6)`,"aria-pressed":e==="eraser",title:`${z} (6)`,children:[o.jsx(ha,{}),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:()=>F(oe=>!oe),"aria-label":k("canvas.toolbar.eraserMenu"),"aria-haspopup":"menu","aria-expanded":Y,"aria-controls":"canvas-eraser-menu",title:k("canvas.toolbar.eraserMenu"),children:o.jsx(fa,{})}),Y?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:()=>ke("object"),children:k("canvas.toolbar.objectEraser")}),o.jsx("button",{type:"button",className:`canvas-toolbar__eraser-menu-item${r==="brush"?" canvas-toolbar__eraser-menu-item--active":""}`,role:"menuitemradio","aria-checked":r==="brush",onClick:()=>ke("brush"),children:k("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${y?" canvas-toolbar__button--busy":""}`,onClick:u,disabled:!X||y,"aria-label":k("canvas.toolbar.apply"),title:k("canvas.toolbar.apply"),children:o.jsx(ma,{})}):null,v?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:v,disabled:y,"aria-label":k("canvas.revert.action"),title:k("canvas.revert.action"),children:o.jsx(Mt,{})}):null,b?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--primary canvas-toolbar__button--mask${E?" canvas-toolbar__button--busy":""}`,onClick:b,disabled:!C||E,"aria-label":k(C?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),title:k(C?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),children:o.jsx(va,{})}):null,_?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:_,disabled:!T,"aria-label":k("canvas.toolbar.undo"),title:k("canvas.toolbar.undo"),children:o.jsx(Mt,{})}):null,M?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:M,disabled:!W,"aria-label":k("canvas.toolbar.redo"),title:k("canvas.toolbar.redo"),children:o.jsx(pa,{})}):null,P?o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:P,disabled:O===0,"aria-label":k("canvas.toolbar.deleteSelected"),title:k("canvas.toolbar.deleteSelected"),children:o.jsx(_t,{})}):null,h&&K&&g?o.jsx(Jn,{mode:J,matteColor:I,onModeChange:K,onMatteColorChange:g}):null,S&&$&&ae&&re&&G&&q&&U&&H&&N?o.jsx(Qn,{seedCount:R,tolerance:j,stats:D,hasPreview:L,isPickingSeed:Z,intent:ne,tool:le,brushRadius:ue,isPreviewing:de,isApplying:m,keepOpen:te,disabled:y||p,onAutoSample:S,onPickSeed:$,onIntentChange:ae,onToolChange:re,onBrushRadiusChange:G,onToleranceChange:q,onPreview:U,onApply:H,onReset:N}):null,h?o.jsx(na,{onExport:h,disabled:!X,isExporting:!!p}):null,o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:d,disabled:!X,"aria-label":k("canvas.toolbar.clear"),title:k("canvas.toolbar.clear"),children:o.jsx(_t,{})})]})}function la(){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 ca(){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 ia(){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 ua(){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 da(){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 ha(){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 fa(){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 ma(){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 _t(){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 Mt(){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 pa(){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 va(){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 ba({annotations:e,backgroundCleanup:t,backgroundCleanupPreview:n,canvasState:a,actions:r}){return o.jsx(sa,{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,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 ga({currentImage:e,canvasDisplayImage:t,canvasOpen:n,displayQuality:a,displaySize:r,displayModel:l,onAfterDeleteFocus:s,onCopyPrompt:c}){const{t:d}=fe(),u=[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?d("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,gn(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(xn,{imageOverride:n?t:null,onAfterDeleteFocus:s}),e.prompt?o.jsx(yn,{prompt:e.prompt,onCopy:c}):null]})}function xa({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(ya,{})}),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(wa,{})})]})}function ya(){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 wa(){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 ka({zoom:e,modeLabel:t,closeLabel:n,blankCanvasLabel:a,blankCanvasAriaLabel:r,blankCanvasShortcut:l,blankCanvasBusy:s,shortcutHint:c,onZoomIn:d,onZoomOut:u,onZoomReset:v,onCreateBlankCanvas:h,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(xa,{zoom:e,onZoomIn:d,onZoomOut:u,onZoomReset:v}),o.jsx("span",{className:"canvas-mode-topbar__shortcuts",children:c})]}),o.jsx("div",{className:"canvas-mode-topbar__center",children:o.jsxs("button",{type:"button",className:"canvas-mode-blank",onClick:h,disabled:s,"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 Ca({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),s=ot(50-n/40,r,100-r);return{width:`${a}%`,height:`${a}%`,left:`${l}%`,top:`${s}%`}}function _a({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:Ca({zoom:t,panX:n,panY:a}),"aria-hidden":"true"})]})}function Le(e){return Math.min(1,Math.max(0,e))}function Ma(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("mask_blob_unavailable"))},"image/png")})}async function Ea(e){const t=e.imageElement.naturalWidth,n=e.imageElement.naturalHeight;if(!t||!n)throw new Error("mask_source_size_unavailable");if(e.boxes.length===0)throw new Error("mask_boxes_required");const a=document.createElement("canvas");a.width=t,a.height=n;const r=a.getContext("2d");if(!r)throw new Error("mask_context_unavailable");r.fillStyle="rgba(0, 0, 0, 1)",r.fillRect(0,0,t,n),r.globalCompositeOperation="destination-out";for(const l of e.boxes){const s=Le(l.x)*t,c=Le(l.y)*n,d=Le(l.width)*t,u=Le(l.height)*n;d>0&&u>0&&r.fillRect(s,c,d,u)}return Ma(a)}async function Sa(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 pt(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 Ba=`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`,ja=`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 Ta(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function Aa(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function Pa(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 Da(e){const t=e.canvasSourceFilename??e.filename;return t?`/generated/${encodeURIComponent(t)}`:e.url??e.image}async function Et(e){const t=Da(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}),Sa(n)}function Ke(e,t){return!e.canvasVersion||e.prompt||!t?.prompt?e:{...e,prompt:t.prompt}}function Ra(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 Ia(e,t){if(wn(e)){const n=e.images[0];if(!n)throw new Error("edit_empty_response");return{...n,prompt:t,reasoningEffort:e.reasoningEffort,provider:e.provider,quality:e.quality,size:e.size,moderation:e.moderation,model:e.model,usage:e.usage,kind:"edit",createdAt:Date.now()}}return{image:e.image,url:e.filename?`/generated/${e.filename}`:e.image,thumb:e.image,filename:e.filename,prompt:t,elapsed:e.elapsed,reasoningEffort:e.reasoningEffort,provider:e.provider,quality:e.quality,size:e.size,moderation:e.moderation,model:e.model,usage:e.usage,revisedPrompt:e.revisedPrompt??null,promptMode:e.promptMode??null,kind:"edit",createdAt:Date.now()}}const st=new WeakMap;function Na(e){if(!e.complete||!e.naturalWidth||!e.naturalHeight)return!1;const t=st.get(e);if(t&&t.src===e.currentSrc&&t.width===e.naturalWidth&&t.height===e.naturalHeight)return t.result;const n=64,a=Math.min(n,e.naturalWidth),r=Math.min(n,e.naturalHeight),l=document.createElement("canvas");l.width=a,l.height=r;const s=l.getContext("2d",{willReadFrequently:!0});if(!s)return!1;try{s.drawImage(e,0,0,a,r);const c=s.getImageData(0,0,a,r).data;for(let d=3;d<c.length;d+=4)if(c[d]<250)return st.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!0}),!0;return st.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!1}),!1}catch{return!1}}function Oa(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 St(e,t){return{width:e,height:t,data:new Uint8Array(e*t)}}function dt(e){return{width:e.width,height:e.height,data:new Uint8Array(e.data)}}function La(e,t){Oa(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=dt(e);return t&&La(n,t),n}function $a(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 vt=[{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}],Ua=1024;function Wa(e){return Math.max(0,Math.min(255,Math.round(e)))}function Xt(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 Fa(e,t){return(t.length>0?t:vt).map(a=>{const r=Xt(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 Ha(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,s){if(e<0||e>=a.length||a[e])return r;const c=e*4;return(t.data[c+3]??0)===0?(a[e]=1,r):Ha(t.data,c,l,s)?(a[e]=1,n[r]=e,r+1):r}function lt(){return vt.map(e=>({...e}))}function Bt(e,t,n,a){if(e.width!==t.width||e.height!==t.height)throw new Error("cleanup_mask_size_mismatch");const{width:r,height:l}=t,s=r*l,c=new Uint8Array(s),d=new Int32Array(s),u=Fa(t,n),v=Wa(a);let h=0;for(const _ of n.length>0?n:vt)h=Te(Xt(_,r,l),t,d,c,h,u,v);for(;h>0;){const _=d[--h];e.data[_]=255;const M=_%r;M>0&&(h=Te(_-1,t,d,c,h,u,v)),M<r-1&&(h=Te(_+1,t,d,c,h,u,v)),_>=r&&(h=Te(_-r,t,d,c,h,u,v)),_<s-r&&(h=Te(_+r,t,d,c,h,u,v))}}function Ka(e,t){const n=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),a=$a(n,t),r=t.data.reduce((l,s)=>l+(s>0?1:0),0);return{imageData:{width:e.width,height:e.height,data:a.data},stats:{width:e.width,height:e.height,removedPixels:r,removedPercent:t.data.length>0?r/t.data.length:0}}}function Yt(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("background_cleanup_blob_failed"))},"image/png")})}function Gt(e,t){const n=e.naturalWidth,a=e.naturalHeight;if(n<=0||a<=0)throw new Error("background_cleanup_image_not_ready");const r=t&&t>0?Math.min(1,t/Math.max(n,a)):1,l=Math.max(1,Math.round(n*r)),s=Math.max(1,Math.round(a*r)),c=document.createElement("canvas");c.width=l,c.height=s;const d=c.getContext("2d",{willReadFrequently:!0});if(!d)throw new Error("background_cleanup_context_failed");return d.drawImage(e,0,0,l,s),{canvas:c,context:d,width:l,height:s}}async function jt({imageElement:e,mask:t}){try{const{canvas:n,context:a,width:r,height:l}=Gt(e),s=a.getImageData(0,0,r,l),c=Ka({width:r,height:l,data:s.data},t),d=a.createImageData(r,l);d.data.set(c.imageData.data),a.putImageData(d,0,0);const u=await Yt(n);return{blob:u,dataUrl:await pt(u),stats:c.stats}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}async function za({imageElement:e,mask:t}){try{const{width:n,height:a}=Gt(e,Ua),r=document.createElement("canvas");r.width=n,r.height=a;const l=r.getContext("2d");if(!l)throw new Error("background_cleanup_context_failed");const s=l.createImageData(n,a);let c=0;for(let u=0;u<a;u+=1)for(let v=0;v<n;v+=1){const h=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+h]??0)===0)continue;const M=(u*n+v)*4;s.data[M]=168,s.data[M+1]=85,s.data[M+2]=247,s.data[M+3]=150,c+=1}l.putImageData(s,0,0);const d=await Yt(r);return{dataUrl:await pt(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?c/(n*a):0}}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}function Tt(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?dt(e.removeMask):null,preserveMask:e.preserveMask?dt(e.preserveMask):null}}function Va(){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 qa(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 Xa(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 Ya({canvasOpen:e,currentImage:t,canvasDisplayImage:n,imageElementRef:a,canvasSourceImageRef:r,lastMergedDataUrlRef:l,setCanvasSaveState:s,setCanvasVersionItem:c,applyMergedCanvasImage:d,attachCanvasVersionReference:u,showToast:v,t:h}){const[_,M]=i.useState(!1),[T,W]=i.useState("remove"),[P,O]=i.useState("click"),[b,C]=i.useState("flat-flood-fill"),[E,y]=i.useState([]),[p,J]=i.useState([]),[I,K]=i.useState(28),[g,j]=i.useState(null),[R,D]=i.useState(null),[L,Z]=i.useState(null),[te,ne]=i.useState(!1),[le,ue]=i.useState(.018),[de,m]=i.useState(null),[S,$]=i.useState(!1),[ae,re]=i.useState(!1),G=i.useRef(null),q=i.useRef(null),U=i.useRef(null),H=i.useRef({past:[],future:[]}),N=i.useRef(0),k=i.useRef(null),Y=i.useCallback(()=>Tt({intent:T,tool:P,engine:b,seeds:E,brushStrokes:p,brushRadius:le,tolerance:I,removeMask:G.current,preserveMask:q.current,preview:g,maskOverlay:R,stats:L,active:te,brushCursor:de}),[p,R,g,E,L,I,de,le,b,T,P,te]),F=i.useCallback(()=>{H.current={past:[...H.current.past.slice(-19),Y()],future:[]}},[Y]),ce=i.useCallback(x=>{const w=Tt(x);G.current=w.removeMask,q.current=w.preserveMask,U.current=null,W(w.intent),O(w.tool),C(w.engine),y(w.seeds),J(w.brushStrokes),ue(w.brushRadius),K(w.tolerance),j(w.preview),D(w.maskOverlay),Z(w.stats),ne(w.active),m(w.brushCursor),$(!1),re(!1)},[]),X=i.useCallback(async()=>{if(!a.current||!t)return;const x=je(G.current,q.current);if(!x){D(null),Z(null);return}const w=N.current+1;N.current=w,$(!0);try{const B=await za({imageElement:a.current,mask:x});if(N.current!==w)return;D(B),Z(B.stats)}catch{if(N.current!==w)return;v(h("canvas.toolbar.cleanupFailed"),!0)}finally{N.current===w&&$(!1)}},[t,a,v,h]),z=i.useCallback(async(x,w,B)=>{if(!a.current)return;const Q=Xa(a.current),ie=St(Q.width,Q.height),_e=St(Q.width,Q.height);for(const pe of x){const Me=pe.intent==="remove"?ie:_e;Bt(Me,Q,[pe.point],B)}for(const pe of w){const Me=pe.intent==="remove"?ie:_e;Bt(Me,Q,qa(pe),B)}G.current=ie,q.current=_e},[a]),he=i.useCallback(()=>{N.current+=1,k.current!=null&&(window.clearTimeout(k.current),k.current=null),G.current=null,q.current=null,U.current=null,H.current={past:[],future:[]},y([]),J([]),j(null),D(null),Z(null),ne(!1),m(null),$(!1),re(!1)},[]),ke=i.useCallback(()=>{const x=H.current.past.pop();return x?(H.current.future=[Y(),...H.current.future.slice(0,19)],ce(x),!0):!1},[Y,ce]),oe=i.useCallback(()=>{const x=H.current.future.shift();return x?(H.current.past=[...H.current.past.slice(-19),Y()],ce(x),!0):!1},[Y,ce]),Ce=i.useCallback(x=>{F();const w=[...E,{point:x,intent:T}];y(w),j(null),z(w,p,I).then(X)},[p,E,I,T,F,z,X]),ze=i.useCallback(()=>{F();const x=lt().map(w=>({point:w,intent:"remove"}));y(x),j(null),ne(!1),z(x,p,I).then(X)},[p,I,F,z,X]),Ve=i.useCallback(()=>{F(),O("click"),ne(x=>!x)},[F]),qe=i.useCallback(x=>{F(),k.current!=null&&window.clearTimeout(k.current),K(x),j(null),k.current=window.setTimeout(()=>{k.current=null,z(E,p,x).then(X)},180)},[p,E,F,z,X]),V=i.useCallback(async()=>{if(!a.current||!t)return null;let x=je(G.current,q.current);if(!x){const B=lt().map(Q=>({point:Q,intent:"remove"}));y(B),await z(B,p,I),x=je(G.current,q.current)}if(!x)return null;F();const w=N.current+1;N.current=w,$(!0);try{const B=await jt({imageElement:a.current,mask:x});return N.current!==w?null:(j(B),D(null),Z(B.stats),B)}catch{return N.current!==w||v(h("canvas.toolbar.cleanupFailed"),!0),null}finally{N.current===w&&$(!1)}},[p,I,t,a,F,z,v,h]),Xe=i.useCallback(()=>{F(),he()},[F,he]),Ye=i.useCallback(x=>{F();const w={id:Va(),intent:T,points:[{...x}],radius:le};U.current=w,m(x),J(B=>[...B,w])},[le,T,F]),Ge=i.useCallback(x=>{const w=U.current;if(!w){m(x);return}w.points=[...w.points,{...x}],m(x),J(B=>B.map(Q=>Q.id===w.id?{...w,points:w.points.map(ie=>({...ie}))}:Q)),z(E,p.map(B=>B.id===w.id?w:B),I).then(X)},[p,E,I,z,X]),Ze=i.useCallback(()=>{U.current=null,z(E,p,I).then(X)},[p,E,I,z,X]),ge=i.useCallback(async()=>{if(!t||!a.current)return;const x=r.current??t;if(!x?.filename){v(h("canvas.toolbar.cleanupFailed"),!0);return}let w=je(G.current,q.current);if(!w){const B=lt().map(Q=>({point:Q,intent:"remove"}));y(B),await z(B,p,I),w=je(G.current,q.current)}if(w){re(!0),s("saving");try{F();const B=await jt({imageElement:a.current,mask:w}),Q=n?.canvasVersion&&n.filename?await Ot(n.filename,{sourceFilename:x.canvasSourceFilename??x.filename,image:B.blob,prompt:x.prompt,pixelEdited:!0}):await Lt({sourceFilename:x.canvasSourceFilename??x.filename,image:B.blob,prompt:x.prompt}),ie=Ke(Q.item,x);l.current=B.dataUrl,c(ie),d(ie),await u(ie),s("saved"),j(null),D(null),Z(B.stats),ne(!1),v(h("canvas.toolbar.cleanupApplied"))}catch{s("error"),v(h("canvas.toolbar.cleanupFailed"),!0)}finally{re(!1)}}},[d,u,p,I,n,r,t,a,l,F,z,s,c,v,h]),me=i.useCallback(()=>te?(U.current=null,ne(!1),m(null),!0):!1,[te]);return i.useEffect(()=>{const x=a.current;if(!x||!e){M(!1);return}const w=()=>M(Na(x));if(x.complete)w();else return x.addEventListener("load",w),()=>x.removeEventListener("load",w)},[e,n?.canvasMergedAt,n?.filename,n?.image,n?.url,g?.dataUrl,a]),{imageHasAlpha:_,backgroundCleanupSeeds:E,backgroundCleanupBrushStrokes:p,backgroundCleanupTolerance:I,backgroundCleanupPreview:g,backgroundCleanupMaskOverlay:R,backgroundCleanupStats:L,cleanupIntent:T,setCleanupIntent:W,cleanupTool:P,setCleanupTool:O,cleanupClickEngine:b,setCleanupClickEngine:C,cleanupBrushRadius:le,setCleanupBrushRadius:ue,cleanupBrushCursor:de,setCleanupBrushCursor:m,isBackgroundCleanupActive:te,setIsBackgroundCleanupActive:ne,isBackgroundCleanupPickingSeed:te&&P==="click",isBackgroundCleanupPreviewing:S,isBackgroundCleanupApplying:ae,hasActiveCleanupStroke:!!U.current,canUndoBackgroundCleanup:H.current.past.length>0,canRedoBackgroundCleanup:H.current.future.length>0,resetBackgroundCleanup:he,undoBackgroundCleanup:ke,redoBackgroundCleanup:oe,addBackgroundCleanupClick:Ce,addBackgroundCleanupSeed:Ce,runBackgroundCleanupPreview:V,handleBackgroundCleanupAutoSample:ze,handleBackgroundCleanupPickSeed:Ve,handleBackgroundCleanupToleranceChange:qe,handleBackgroundCleanupReset:Xe,handleBackgroundCleanupApply:ge,handleBackgroundCleanupEscape:me,startBackgroundCleanupBrushStroke:Ye,updateBackgroundCleanupBrushStroke:Ge,endBackgroundCleanupBrushStroke:Ze}}function At(e){return Math.min(1,Math.max(0,e))}function Pt(e,t){const n=t.getBoundingClientRect();return{x:At((e.clientX-n.left)/n.width),y:At((e.clientY-n.top)/n.height)}}const Ga=.18,Za=.12;function Ja(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 ht(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 Zt(e){return{id:e.id,x:e.x,y:e.y,width:Ga,height:Za,color:e.color,strokeWidth:1}}function Qa(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,c=a*a+r*r;if(c===0)return Math.hypot(e.x-t.x,e.y-t.y);const d=Math.max(0,Math.min(1,(l*a+s*r)/c));return Math.hypot(e.x-(t.x+d*a),e.y-(t.y+d*r))}function er(e,t,n){for(let a=1;a<t.points.length;a+=1)if(Qa(e,t.points[a-1],t.points[a])<=n)return!0;return!1}function Dt(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 tr(e,t){return e.points.some(n=>ht(n,t))}function Rt(e){const t=e.tolerance??.015;for(const n of[...e.memos].reverse())if(ht(e.point,Zt(n),t))return Ht(n);for(const n of[...e.boxes].reverse())if(ht(e.point,n,t))return Ft(n);for(const n of[...e.paths].reverse())if(er(e.point,n,t))return Wt(n);return null}function nr(e){const t=[];for(const n of e.annotations.paths)tr(n,e.box)&&t.push(Wt(n));for(const n of e.annotations.boxes)Dt(n,e.box)&&t.push(Ft(n));for(const n of e.annotations.memos)Dt(Zt(n),e.box)&&t.push(Ht(n));return t}function ar({canvasOpen:e,canvasZoom:t,canvasPanX:n,canvasPanY:a,spaceHeld:r,canDragViewportWithSelect:l,isBackgroundCleanupActive:s,cleanupTool:c,annotationFrameRef:d,annotations:u,setCanvasPan:v,addBackgroundCleanupClick:h,startBackgroundCleanupBrushStroke:_,updateBackgroundCleanupBrushStroke:M,endBackgroundCleanupBrushStroke:T,setCleanupBrushCursor:W}){const P=i.useRef({mode:null,lastPoint:null,didMove:!1}),O=i.useRef({active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null}),[b,C]=i.useState(!1),E=g=>{g.currentTarget.setPointerCapture(g.pointerId),O.current={active:!0,startX:g.clientX,startY:g.clientY,basePanX:n,basePanY:a,pointerId:g.pointerId},C(!0)};return{viewportPanActive:b,resetPointerSession:()=>{P.current={mode:null,lastPoint:null,didMove:!1},O.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},C(!1)},handleAnnotationPointerDown:g=>{if(!e||be(g.target)||!d.current)return;const j=g.button===1;if(r||j){g.preventDefault(),E(g);return}g.preventDefault();const R=Pt(g,d.current);if(s){c==="click"?h(R):(g.currentTarget.setPointerCapture(g.pointerId),_(R));return}if(u.activeTool==="select"){const D=Rt({point:R,paths:u.paths,boxes:u.boxes,memos:u.memos});if(D)g.shiftKey?u.toggleSelected(D):u.selectOne(D),u.startSelectedMove(),P.current={mode:"move",lastPoint:R,didMove:!1};else if(l&&t>1.01){E(g);return}else u.clearSelection(),u.startSelectionBox(R),P.current={mode:"box",lastPoint:R,didMove:!1};g.currentTarget.setPointerCapture(g.pointerId);return}if(u.activeTool==="memo"){u.createMemo(R),requestAnimationFrame(()=>{d.current?.querySelector(".canvas-memo--active")?.focus()});return}if(u.activeTool==="eraser"){if(u.eraserMode==="object"){const D=Rt({point:R,paths:u.paths,boxes:u.boxes,memos:u.memos});D&&u.eraseObjectAtPoint(D);return}g.currentTarget.setPointerCapture(g.pointerId),u.startEraserStroke(R);return}g.currentTarget.setPointerCapture(g.pointerId),u.startDrawing(R)},handleAnnotationPointerMove:g=>{if(!e||be(g.target)||!d.current)return;if(O.current.active){const R=g.clientX-O.current.startX,D=g.clientY-O.current.startY;v(O.current.basePanX+R,O.current.basePanY+D);return}const j=Pt(g,d.current);if(s){c==="brush"?M(j):W(j);return}if(u.activeTool==="select"){if(P.current.mode==="move"&&P.current.lastPoint){const R={x:j.x-P.current.lastPoint.x,y:j.y-P.current.lastPoint.y};(Math.abs(R.x)>5e-4||Math.abs(R.y)>5e-4)&&(u.moveSelected(R),P.current.didMove=!0),P.current.lastPoint=j}else P.current.mode==="box"&&u.updateSelectionBox(j);return}if(u.activeTool!=="memo"){if(u.activeTool==="eraser"){u.eraserMode==="brush"&&u.updateEraserStroke(j);return}u.moveDrawing(j)}},handleAnnotationPointerUp:g=>{if(e&&!be(g.target)){if(O.current.active&&O.current.pointerId===g.pointerId){g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),O.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},C(!1);return}if(g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),s){c==="brush"&&T();return}if(u.activeTool==="select"){P.current.mode==="move"&&P.current.didMove&&u.commitSelectedMove(),P.current.mode==="box"&&u.selectionBox&&u.endSelectionBox(nr({box:Ja(u.selectionBox),annotations:u.toPayload()})),P.current={mode:null,lastPoint:null,didMove:!1};return}if(u.activeTool!=="memo"){if(u.activeTool==="eraser"){u.eraserMode==="brush"&&u.endEraserStroke();return}u.endDrawing()}}},handleAnnotationPointerLeave:()=>{s&&W(null)}}}function rr({canvasOpen:e,canvasZoom:t,currentImage:n,annotations:a,undoBackgroundCleanup:r,redoBackgroundCleanup:l,handleBackgroundCleanupEscape:s,handleCloseCanvas:c,selectHistoryShortcutTarget:d,trashHistoryItem:u,permanentlyDeleteHistoryItemByShortcut:v,setCanvasZoom:h,resetCanvasZoom:_,onCreateBlankCanvas:M,isCreatingBlankCanvas:T}){const[W,P]=i.useState(!1);return i.useEffect(()=>{if(!e)return;const b=p=>{p.preventDefault()},C=p=>{p.ctrlKey&&p.preventDefault()},E={passive:!1,capture:!0},y={passive:!1};return window.addEventListener("wheel",C,E),window.addEventListener("gesturestart",b,y),window.addEventListener("gesturechange",b,y),window.addEventListener("gestureend",b,y),()=>{window.removeEventListener("wheel",C,E),window.removeEventListener("gesturestart",b,y),window.removeEventListener("gesturechange",b,y),window.removeEventListener("gestureend",b,y)}},[e]),i.useEffect(()=>{if(!e)return;const b=E=>{E.code==="Space"&&(be(E.target)||(W||P(!0),E.preventDefault()))},C=E=>{E.code==="Space"&&P(!1)};return window.addEventListener("keydown",b),window.addEventListener("keyup",C),()=>{window.removeEventListener("keydown",b),window.removeEventListener("keyup",C)}},[e,W]),i.useEffect(()=>{if(!e)return;const b=C=>{if(!C.defaultPrevented){if(be(C.target)){C.key==="Escape"&&(C.preventDefault(),C.target.blur(),a.focusMemo(null));return}if(C.key==="Escape"){if(C.preventDefault(),s())return;c();return}if(C.shiftKey&&!C.metaKey&&!C.ctrlKey&&!C.altKey&&C.key.toLowerCase()==="b"){C.preventDefault(),!T&&!C.repeat&&M();return}if((C.metaKey||C.ctrlKey)&&C.key.toLowerCase()==="z"){if(C.preventDefault(),C.shiftKey){if(l())return;a.redo();return}if(r())return;a.undo()}}};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[a,a.focusMemo,a.redo,a.undo,e,c,s,T,M,l,r]),{spaceHeld:W,handleViewerKeyDown:b=>{if(be(b.target)){b.key==="Escape"&&(b.preventDefault(),b.target.blur(),a.focusMemo(null));return}if(e&&["1","2","3","4","5","6"].includes(b.key)){b.preventDefault();const C=["select","pen","box","arrow","memo","eraser"];a.setTool(C[Number(b.key)-1]);return}if(e&&b.key==="Escape"){if(b.preventDefault(),b.stopPropagation(),s())return;c();return}if(e&&b.key==="]"){b.preventDefault(),h(t+.1);return}if(e&&b.key==="["){b.preventDefault(),h(t-.1);return}if(e&&b.key==="0"){b.preventDefault(),_();return}if(b.key==="Delete"||b.key==="Backspace"){if(!n||b.target!==b.currentTarget)return;if(b.preventDefault(),b.shiftKey){v(n);return}u(n);return}b.key!=="ArrowLeft"&&b.key!=="ArrowRight"&&b.key!=="Home"&&b.key!=="End"||b.target===b.currentTarget&&(be(b.target)||(b.preventDefault(),b.key==="ArrowLeft"?d("previous"):b.key==="ArrowRight"?d("next"):b.key==="Home"?d("first"):b.key==="End"&&d("last")))}}}function or(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)it(n,l,a);for(const l of e.boxes)ut(n,l,a,"committed");for(const l of e.memos)Wn(n,l,a);return{blob:await or(t,"image/png"),dataUrl:t.toDataURL("image/png")}}const sr=["left","center","right"],lr=["top","middle","bottom"];function cr(e,t){const n=sr[Math.min(2,Math.max(0,Math.floor(e*3)))],a=lr[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 It(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 ${cr(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 Nt=18,Ae=12,ir="14px sans-serif";function Ie(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ee(e){return Math.round(e*100)/100}function ur(e,t){if(e.points.length<2)return"";const n=e.points.map(c=>De(c,t)),a=n.map((c,d)=>`${d===0?"M":"L"}${ee(c.x)} ${ee(c.y)}`).join(" "),r=`stroke="${Ie(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 s=qt(n[n.length-2],n[n.length-1],e.strokeWidth).map(c=>`${ee(c.x)},${ee(c.y)}`).join(" ");return`${l}<polygon points="${s}" fill="${Ie(e.color)}" />`}function dr(e,t){return`<rect x="${ee(e.x*t.width)}" y="${ee(e.y*t.height)}" width="${ee(e.width*t.width)}" height="${ee(e.height*t.height)}" fill="none" stroke="${Ie(e.color)}" stroke-width="${e.strokeWidth}" />`}function hr(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 c=0;c<l.length;c+=t)a.push(l.slice(c,c+t));continue}const s=r?`${r} ${l}`:l;s.length<=t?r=s:(a.push(r),r=l)}return r&&a.push(r),a.length>0?a:[""]}function fr(e,t){const n=ee(e.x*t.width),a=ee(e.y*t.height),r=ee(Math.min(260,Math.max(150,t.width*.22))),l=Math.max(8,Math.floor((r-Ae*2)/7.5)),s=hr(e.text,l),c=ee(Math.max(52,Ae*2+s.length*Nt)),d=s.map((u,v)=>`<tspan x="${ee(n+Ae)}" dy="${v===0?0:Nt}">${Ie(u)}</tspan>`).join("");return`<g><rect x="${n}" y="${a}" width="${r}" height="${c}" rx="8" fill="rgba(255, 246, 179, 0.96)" stroke="rgba(44, 37, 12, 0.28)" stroke-width="1" /><text x="${ee(n+Ae)}" y="${ee(a+Ae+14)}" font="${ir}" font-family="sans-serif" font-size="14" fill="#2f2a13">${d}</text></g>`}function mr(e){const{imageSize:t,annotations:n}=e,a=[`<image href="${Ie(e.imageDataUrl)}" x="0" y="0" width="${t.width}" height="${t.height}" preserveAspectRatio="none" />`,...n.paths.map(r=>ur(r,t)),...n.boxes.map(r=>dr(r,t)),...n.memos.map(r=>fr(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 pr(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 vr(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 br(e){const{default:t}=await kn(async()=>{const{default:s}=await import("./pptxgen.es-BE4CSd5F.js");return{default:s}},__vite__mapDeps([0,1,2])),n=new t;n.layout="LAYOUT_16x9";const a=n.addSlide(),r=pr(e.imageSize);a.addImage({data:e.mergedDataUrl,...r});for(const s of e.memos){const c=s.text.trim();c&&a.addText(c,{...vr(s,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 gr(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 xr(e,t,n){const a={width:t.imageElement.naturalWidth,height:t.imageElement.naturalHeight};if(e==="svg"){const s=await Fe({...t,paths:[],boxes:[],memos:[]}),c=mr({imageDataUrl:s.dataUrl,imageSize:a,annotations:n});return new Blob([c],{type:"image/svg+xml"})}const r=await Fe(t);if(e==="png")return r.blob;const l=await Fe({...t,memos:[]});return br({mergedDataUrl:l.dataUrl,imageSize:a,memos:n.memos})}function yr(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 wr({imageElementRef:e,currentImage:t,canvasDisplayImage:n,canvasSourceImageRef:a,lastMergedDataUrlRef:r,lastCleanDataUrlRef:l,canvasVersionItem:s,annotations:c,exportBackground:d,exportMatteColor:u,quality:v,format:h,moderation:_,provider:M,imageModel:T,reasoningEffort:W,promptMode:P,webSearchEnabled:O,getResolvedSize:b,setCanvasVersionItem:C,setCanvasSaveState:E,setIsApplying:y,setIsExporting:p,setIsEditingWithMask:J,applyMergedCanvasImage:I,addGeneratedHistoryItem:K,attachCanvasVersionReference:g,closeCanvas:j,resetCanvasSession:R,showToast:D,t:L}){const Z=i.useCallback(async()=>{if(!e.current||!t)return null;const m=a.current??t;if(!m?.filename)return D(L("canvas.version.failed"),!0),null;y(!0),E("saving");try{const S=await Fe({imageElement:e.current,paths:c.paths,boxes:c.boxes,memos:c.memos});r.current=S.dataUrl;const $=await Et(m);l.current=$;const ae=s?.filename?await Ot(s.filename,{image:S.blob,sourceFilename:m.canvasSourceFilename??m.filename,prompt:m.prompt}):await Lt({sourceFilename:m.filename,image:S.blob,prompt:m.prompt}),re=c.toPayload(),G=!s||!!s.annotationOnly,q=await Cn(ae.item.filename,re,G),U=Ke(q.item,m);C(U),I(U),await g(U,$);const H=It(c.memos),N=`canvas-annotations:${m.canvasSourceFilename??m.filename}`,{insertPromptToComposer:k,removeInsertedPromptFromComposer:Y}=A.getState();return Y(N),H&&k({id:N,name:L("canvas.annotationInstructionsChip"),text:H,placement:"after"}),await $t(m.filename).catch(()=>{}),c.resetLocal(),c.markSaved(),E("saved"),D(L("canvas.version.saved")),U}catch{return E("error"),D(L("canvas.version.failed"),!0),null}finally{y(!1)}},[c,I,g,a,s?.filename,t,e,r,l,E,C,y,D,L]);return{saveCanvasVersionAndUseReference:Z,handleApplyCanvas:async()=>{await Z()},handleRevertAnnotations:async()=>{if(!(!s?.filename||!s.annotationsBaked)&&!(!s.annotationOnly&&!window.confirm(L("canvas.revert.mixedConfirm")))){y(!0),E("saving");try{const m=await Mn(s.filename),S=a.current??t??s,$=Ke(m.item,S);if(C($),I($),r.current=null,m.annotationOnly&&m.snapshot){c.load(m.snapshot);const ae=$.canvasSourceFilename??S.filename;ae&&await Ut(ae,m.snapshot),D(L("canvas.revert.restored"))}else c.resetLocal(),D(L("canvas.revert.completed"));E("saved")}catch{E("error"),D(L("canvas.revert.failed"),!0)}finally{y(!1)}}},handleCloseCanvas:async()=>{(c.hasAnnotations||c.isDirty)&&!await Z()||(j(),R())},handleExportCanvas:async(m="png")=>{if(!(!e.current||!t)){p(!0);try{const S=d==="matte",$=await xr(m,{imageElement:e.current,paths:c.paths,boxes:c.boxes,memos:c.memos,background:S?{mode:"matte",color:u}:{mode:"alpha"}},{paths:c.paths,boxes:c.boxes,memos:c.memos});yr($,gr({matte:S,format:m}))}catch{D(L("canvas.toolbar.exportFailed"),!0)}finally{p(!1)}}},handleEditWithMask:async()=>{if(!(!e.current||!n||c.boxes.length===0)){J(!0);try{const m=c.memos;let S=l.current;if(c.isDirty||c.hasAnnotations){if(!await Z())return;S=l.current}S||(S=await Et(a.current??n));const $=c.boxes.filter(k=>c.selectedIds.some(Y=>ve(Y,"box",k.id))),ae=await Ea({imageElement:e.current,boxes:$.length>0?$:c.boxes}),re=It(m),q=[(n.prompt??t?.prompt??"").trim(),re].filter(Boolean).join(`
|
|
4
4
|
|
|
5
5
|
`);if(!q.trim()){D(L("toast.noPromptToFork"),!0);return}const U=n.size??t?.size??null,H=U&&/^\d+x\d+$/.test(U)?U:b(),N=await _n({image:S,mask:await pt(ae),prompt:q,quality:v,size:H,format:h,moderation:_,provider:M,n:1,model:T,reasoningEffort:W,mode:P,webSearchEnabled:O});await K(Ia(N,q))}catch(m){const S=m.code;D(L(S==="EDIT_MASK_NOT_SUPPORTED"?"canvas.toolbar.editMaskUnsupported":"canvas.toolbar.editMaskFailed"),!0)}finally{J(!1)}}}}}function Cr(e){const t=A(f=>f.currentImage),n=A(f=>f.history),a=A(f=>f.importLocalImageToHistory),[r,l]=i.useState(!1),s=A(f=>{const se=f.multimodePreviewFlightId;return se?f.multimodeSequences[se]??null:null}),c=A(f=>f.selectHistoryShortcutTarget),d=A(f=>f.trashHistoryItem),u=A(f=>f.permanentlyDeleteHistoryItemByShortcut),v=A(f=>f.markGeneratedResultsSeen),h=A(f=>f.activeGenerations),_=A(f=>f.quality),M=A(f=>f.format),T=A(f=>f.moderation),W=A(f=>f.provider),P=A(f=>f.imageModel),O=A(f=>f.reasoningEffort),b=A(f=>f.promptMode),C=A(f=>f.webSearchEnabled),E=A(f=>f.getResolvedSize),y=A(f=>f.showToast),p=A(f=>f.canvasOpen),J=A(f=>f.openCanvas),I=A(f=>f.closeCanvas),K=A(f=>f.canvasZoom),g=A(f=>f.canvasPanX),j=A(f=>f.canvasPanY),R=A(f=>f.setCanvasPan),D=A(f=>f.setCanvasZoom),L=A(f=>f.resetCanvasZoom),Z=A(f=>f.canvasExportBackground),te=A(f=>f.canvasExportMatteColor),ne=A(f=>f.setCanvasExportBackground),le=A(f=>f.setCanvasExportMatteColor),ue=A(f=>f.applyMergedCanvasImage),de=A(f=>f.addGeneratedHistoryItem),m=A(f=>f.attachCanvasVersionReference),{t:S}=fe(),{creatingBlankCanvas:$,createBlankCanvas:ae}=En(),re=i.useRef(null),G=i.useRef(null),q=i.useRef(null),U=i.useRef(null),H=i.useRef(null),N=i.useRef(null),k=i.useRef(null),Y=i.useRef(null),F=i.useRef(null),[ce,X]=i.useState(null),[z,he]=i.useState("idle"),[ke,oe]=i.useState(!1),[Ce,ze]=i.useState(!1),[Ve,qe]=i.useState(!1),V=Un(),Xe=()=>{t?.prompt&&(navigator.clipboard.writeText(t.prompt),y(S("toast.promptCopied")))},Ye=Ta(t?.quality),Ge=Aa(t?.size),Ze=Sn(t?.model),ge=t?.filename??t?.url??t?.image??null,me=Ra(n,t),x=p?ce??me??t:t,w=x?Pa(x):null,B=Ya({canvasOpen:p,currentImage:t,canvasDisplayImage:x,imageElementRef:G,canvasSourceImageRef:k,lastMergedDataUrlRef:Y,setCanvasSaveState:he,setCanvasVersionItem:X,applyMergedCanvasImage:ue,attachCanvasVersionReference:m,showToast:y,t:S}),{imageHasAlpha:Q,backgroundCleanupSeeds:ie,backgroundCleanupPreview:_e,backgroundCleanupMaskOverlay:pe,backgroundCleanupBrushStrokes:Me,cleanupTool:Jt,cleanupBrushRadius:Qt,cleanupBrushCursor:en,isBackgroundCleanupActive:Ee}=B,Je=B.backgroundCleanupPreview?.dataUrl??w,Qe=()=>{k.current=null,H.current=null,N.current!=null&&(window.clearTimeout(N.current),N.current=null),X(null),he("idle"),B.resetBackgroundCleanup(),Y.current=null,F.current=null,fn()};i.useEffect(()=>{if(!p){U.current=ge,Qe();return}if(U.current===null){U.current=ge,k.current=t,X(me);return}U.current!==ge&&(V.resetLocal(),Qe(),k.current=t,X(me),U.current=ge)},[V.resetLocal,p,t,ge,me]),i.useEffect(()=>{!p||!t||k.current||(k.current=t,X(me))},[p,t,me]),i.useEffect(()=>{if(!p||!t?.filename||t.canvasVersion)return;const f=t.filename;if(H.current===f)return;H.current=f;let se=!1;return Bn(f).then(Se=>{!se&&Se.annotations&&V.load(Se.annotations)}).catch(()=>{}),()=>{se=!0}},[V.load,p,t?.canvasVersion,t?.filename]),i.useEffect(()=>{if(!p||!t?.filename||t.canvasVersion||!V.isDirty)return;const f=t.filename;return N.current!=null&&window.clearTimeout(N.current),N.current=window.setTimeout(()=>{const se=V.toPayload();(V.hasAnnotations?Ut(f,se):$t(f)).then(()=>V.markSaved()).catch(()=>{})},500),()=>{N.current!=null&&(window.clearTimeout(N.current),N.current=null)}},[V,V.hasAnnotations,V.isDirty,p,t?.canvasVersion,t?.filename]);const tn=f=>{be(f.target)||(v(),f.currentTarget.focus())},nn=i.useCallback(()=>{window.requestAnimationFrame(()=>q.current?.focus())},[]),an=f=>{if(p){if(f.preventDefault(),f.ctrlKey){D(K-f.deltaY*.01);return}R(g-f.deltaX,j-f.deltaY)}},rn=i.useCallback(f=>{Array.from(f.dataTransfer.types).includes("Files")&&(f.preventDefault(),l(se=>se||!0))},[]),on=i.useCallback(f=>{f.currentTarget.contains(f.relatedTarget)||l(!1)},[]),sn=i.useCallback(async f=>{if(!Array.from(f.dataTransfer.types).includes("Files"))return;f.preventDefault(),l(!1);const se=Array.from(f.dataTransfer.files).filter(Se=>/^image\/(png|jpeg|webp)$/.test(Se.type));se.length!==0&&await a(se[0])},[a]),{handleApplyCanvas:ln,handleRevertAnnotations:cn,handleCloseCanvas:bt,handleExportCanvas:un,handleEditWithMask:dn}=wr({imageElementRef:G,currentImage:t,canvasDisplayImage:x,canvasSourceImageRef:k,lastMergedDataUrlRef:Y,lastCleanDataUrlRef:F,canvasVersionItem:ce,annotations:V,exportBackground:Z,exportMatteColor:te,quality:_,format:M,moderation:T,provider:W,imageModel:P,reasoningEffort:O,promptMode:b,webSearchEnabled:C,getResolvedSize:E,setCanvasVersionItem:X,setCanvasSaveState:he,setIsApplying:oe,setIsExporting:ze,setIsEditingWithMask:qe,applyMergedCanvasImage:ue,addGeneratedHistoryItem:de,attachCanvasVersionReference:m,closeCanvas:I,resetCanvasSession:Qe,showToast:y,t:S}),{spaceHeld:et,handleViewerKeyDown:hn}=rr({canvasOpen:p,canvasZoom:K,currentImage:t,annotations:V,undoBackgroundCleanup:B.undoBackgroundCleanup,redoBackgroundCleanup:B.redoBackgroundCleanup,handleBackgroundCleanupEscape:B.handleBackgroundCleanupEscape,handleCloseCanvas:bt,selectHistoryShortcutTarget:c,trashHistoryItem:d,permanentlyDeleteHistoryItemByShortcut:u,setCanvasZoom:D,resetCanvasZoom:L,onCreateBlankCanvas:ae,isCreatingBlankCanvas:$}),tt=p&&K>1.01&&V.activeTool==="select"&&!Ee,{viewportPanActive:nt,resetPointerSession:fn,handleAnnotationPointerDown:mn,handleAnnotationPointerMove:pn,handleAnnotationPointerUp:vn,handleAnnotationPointerLeave:bn}=ar({canvasOpen:p,canvasZoom:K,canvasPanX:g,canvasPanY:j,spaceHeld:et,canDragViewportWithSelect:tt,isBackgroundCleanupActive:Ee,cleanupTool:Jt,annotationFrameRef:re,annotations:V,setCanvasPan:R,addBackgroundCleanupClick:B.addBackgroundCleanupClick,startBackgroundCleanupBrushStroke:B.startBackgroundCleanupBrushStroke,updateBackgroundCleanupBrushStroke:B.updateBackgroundCleanupBrushStroke,endBackgroundCleanupBrushStroke:B.endBackgroundCleanupBrushStroke,setCleanupBrushCursor:B.setCleanupBrushCursor});return o.jsxs("main",{className:`canvas${p?" canvas--mode-open":""}${r?" canvas--drop-active":""}${et?" canvas--space-held":""}${nt?" canvas--pan-active":""}${tt?" canvas--zoom-hand":""}`,onDragOver:rn,onDragLeave:on,onDrop:sn,children:[r?o.jsx("div",{className:"canvas__drop-overlay","aria-hidden":!0,children:o.jsx("span",{className:"canvas__drop-hint",children:S("canvas.drop.hint")})}):null,p&&o.jsx(ka,{zoom:K,modeLabel:S("canvas.modeTitle"),closeLabel:S("canvas.close"),blankCanvasLabel:S("canvas.blank.title"),blankCanvasAriaLabel:`${S($?"canvas.blank.creating":"canvas.blank.create")} (Shift+B)`,blankCanvasShortcut:"Shift+B",blankCanvasBusy:$,shortcutHint:S("canvas.toolbar.zoomShortcutHint"),onZoomIn:()=>D(K+.1),onZoomOut:()=>D(K-.1),onZoomReset:L,onCreateBlankCanvas:()=>{ae()},onClose:()=>{bt()}}),o.jsx("div",{className:`progress-bar${h>0?" active":""}`}),s?o.jsx(jn,{}):t?o.jsxs("div",{ref:q,className:"result-container visible",tabIndex:0,onMouseDown:tn,onWheel:an,onKeyDown:hn,"aria-label":S("canvas.imageViewerAria"),children:[o.jsx(Xn,{annotationFrameRef:re,imageElementRef:G,frameClassName:`canvas-annotation-frame${(Q||_e)&&p?" canvas-annotation-frame--alpha":""}${Ee&&p?" canvas-annotation-frame--cleanup-picking":""}${pe&&p?" canvas-annotation-frame--cleanup-mask":""}`,frameStyle:{cursor:nt?"grabbing":et||tt?"grab":p?Ee?"crosshair":V.activeTool==="select"?"default":V.activeTool==="eraser"?V.eraserMode==="object"?Ba:ja:"crosshair":"zoom-in",transform:p?`translate(${g}px, ${j}px) scale(${K})`:void 0,transition:p&&!nt?"transform 0.2s ease":void 0},imageKey:`${x?.filename??x?.url??x?.image}:${x?.canvasMergedAt??""}`,imageSrc:Je??t.image,fallbackImage:t.image,alt:S("canvas.resultAlt"),canvasOpen:p,maskOverlayUrl:pe?.dataUrl??null,cleanupLayer:o.jsx(Zn,{seeds:ie,brushStrokes:Me,brushCursor:en,brushRadius:Qt,active:Ee}),annotations:V,onOpenCanvas:J,onPointerDown:mn,onPointerMove:pn,onPointerUp:vn,onPointerLeave:bn}),p&&Je?o.jsx(_a,{imageSrc:Je,zoom:K,panX:g,panY:j,resetLabel:S("canvas.toolbar.zoomReset"),onReset:L}):null,p&&o.jsx(ba,{annotations:V,backgroundCleanup:B,backgroundCleanupPreview:_e,canvasState:{exportBackground:Z,exportMatteColor:te,isApplying:ke,isExporting:Ce,isEditingWithMask:Ve,canRevertAnnotations:!!ce?.annotationsBaked},actions:{handleApplyCanvas:ln,handleRevertAnnotations:cn,handleExportCanvas:un,handleEditWithMask:dn,setExportBackground:ne,setExportMatteColor:le}}),p&&z!=="idle"?o.jsx("div",{className:`canvas-save-state canvas-save-state--${z}`,children:S(z==="saving"?"canvas.version.saving":z==="saved"?"canvas.version.saved":"canvas.version.failed")}):null,o.jsx(ga,{currentImage:t,canvasDisplayImage:x,canvasOpen:p,displayQuality:Ye,displaySize:Ge,displayModel:Ze,onAfterDeleteFocus:nn,onCopyPrompt:Xe})]}):null]})}export{Cr as CanvasModeWorkspace};
|