ima2-gen 2.0.2 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/bin/commands/gen.js +7 -5
  3. package/bin/commands/multimode.js +7 -5
  4. package/bin/commands/node.js +2 -1
  5. package/config.js +8 -1
  6. package/docs/API.md +5 -4
  7. package/docs/CLI.md +4 -4
  8. package/docs/FAQ.ko.md +1 -1
  9. package/docs/FAQ.md +1 -1
  10. package/docs/migration/runtime-test-inventory.md +11 -1
  11. package/lib/agentCommandParser.js +10 -6
  12. package/lib/agentGenerationPlanner.js +96 -19
  13. package/lib/agentImageVideoGen.js +26 -6
  14. package/lib/agentPlannerModel.js +172 -0
  15. package/lib/agentQuestionResponder.js +9 -3
  16. package/lib/agentQueueStore.js +42 -0
  17. package/lib/agentQueueWorker.js +57 -7
  18. package/lib/agentRuntime.js +96 -12
  19. package/lib/agentSettings.js +9 -6
  20. package/lib/agentToolManifest.js +90 -0
  21. package/lib/agentTypes.js +1 -0
  22. package/lib/agyCli.js +31 -0
  23. package/lib/agyImageAdapter.js +73 -8
  24. package/lib/capabilities.js +7 -5
  25. package/lib/configKeys.js +6 -0
  26. package/lib/geminiApiImageAdapter.js +11 -4
  27. package/lib/generationRequestLog.js +25 -0
  28. package/lib/grokImageAdapter.js +27 -34
  29. package/lib/grokMultimodeAdapter.js +2 -1
  30. package/lib/grokVideoAdapter.js +3 -2
  31. package/lib/grokVideoPlannerPrompt.js +18 -25
  32. package/lib/inflight.js +1 -1
  33. package/lib/multimodeHelpers.js +3 -2
  34. package/lib/oauthProxy/generators.js +6 -5
  35. package/lib/oauthProxy/prompts.js +41 -16
  36. package/lib/oauthProxy/streams.js +1 -1
  37. package/lib/promptSafetyPolicy.js +1 -1
  38. package/lib/responsesDoctor.js +3 -3
  39. package/lib/responsesFallback.js +27 -14
  40. package/lib/responsesImageAdapter.js +11 -7
  41. package/node_modules/qs/CHANGELOG.md +10 -0
  42. package/node_modules/qs/README.md +1 -1
  43. package/node_modules/qs/dist/qs.js +15 -15
  44. package/node_modules/qs/eslint.config.mjs +1 -0
  45. package/node_modules/qs/lib/parse.js +52 -22
  46. package/node_modules/qs/lib/stringify.js +11 -4
  47. package/node_modules/qs/package.json +2 -2
  48. package/node_modules/qs/test/parse.js +49 -0
  49. package/node_modules/qs/test/stringify.js +129 -0
  50. package/package.json +1 -1
  51. package/routes/agent.js +19 -2
  52. package/routes/agy.js +5 -1
  53. package/routes/generate.js +12 -1
  54. package/routes/generationRequestLog.js +16 -0
  55. package/routes/index.js +2 -0
  56. package/routes/keys.js +22 -2
  57. package/routes/multimode.js +1 -1
  58. package/routes/nodes.js +5 -5
  59. package/ui/dist/.vite/manifest.json +22 -12
  60. package/ui/dist/assets/AgentWorkspace-qEMrATBP.js +3 -0
  61. package/ui/dist/assets/{CardNewsWorkspace-Dav3K5CT.js → CardNewsWorkspace-DoJnVHmn.js} +1 -1
  62. package/ui/dist/assets/GenerationRequestLogPanel-BDWRRLNV.js +1 -0
  63. package/ui/dist/assets/{NodeCanvas-C4ifFzB1.js → NodeCanvas-DIMo45sp.js} +3 -3
  64. package/ui/dist/assets/{PromptBuilderPanel-CEcyU9PL.js → PromptBuilderPanel-BF3lcSJD.js} +2 -2
  65. package/ui/dist/assets/{PromptImportDialog-CgQ94Gth.js → PromptImportDialog-Cy6ZymKG.js} +2 -2
  66. package/ui/dist/assets/{PromptImportDiscoverySection-CuzyzbNI.js → PromptImportDiscoverySection-CzuW-8P2.js} +1 -1
  67. package/ui/dist/assets/PromptImportFolderSection-DP5ywnsv.js +1 -0
  68. package/ui/dist/assets/{PromptLibraryPanel-BOe18we8.js → PromptLibraryPanel-CAsKr7CV.js} +2 -2
  69. package/ui/dist/assets/SettingsWorkspace-_PdPVsxi.js +1 -0
  70. package/ui/dist/assets/index-BUinlX2n.js +4 -0
  71. package/ui/dist/assets/index-CX3fge8X.css +1 -0
  72. package/ui/dist/assets/index-ygo6nfqx.js +23 -0
  73. package/ui/dist/index.html +2 -2
  74. package/ui/dist/assets/AgentWorkspace-Dth6YijN.js +0 -3
  75. package/ui/dist/assets/PromptImportFolderSection-DHLGlO6l.js +0 -1
  76. package/ui/dist/assets/SettingsWorkspace-Cdgnm4Wa.js +0 -1
  77. package/ui/dist/assets/index-C5PSahkr.js +0 -1
  78. package/ui/dist/assets/index-Dn2AhL6d.css +0 -1
  79. package/ui/dist/assets/index-Tjqx6wUV.js +0 -23
@@ -1,2 +1,2 @@
1
- import{J as I,K as S,b as u,u as f,j as t,a as _}from"./index-Tjqx6wUV.js";function T(e){return e.filename??e.url??e.image}let M=0;function y(){return`pb_${Date.now()}_${++M}`}async function A(e){const n=y(),s=e.type.startsWith("image/")?"image":"file";if(s==="image"){const r=await new Promise(o=>{const l=new FileReader;l.onload=()=>o(l.result),l.readAsDataURL(e)});return{id:n,kind:s,name:e.name,mimeType:e.type,size:e.size,dataUrl:r}}return{id:n,kind:s,name:e.name,mimeType:e.type,size:e.size}}const p=I()((e,n)=>({messages:[],scope:{kind:"draft"},draft:"",model:"gpt-5.5",loading:!1,attachments:[],error:null,setDraft:s=>e({draft:s}),setModel:s=>e({model:s}),clearMessages:()=>e({messages:[],error:null}),clearImageScope:()=>e({scope:{kind:"draft"}}),setScopeFromImage:s=>{const r=T(s);e({scope:{kind:"image",imageKey:r}})},addAttachments:async s=>{const r=await Promise.all(s.map(A));e(o=>({attachments:[...o.attachments,...r]}))},removeAttachment:s=>{e(r=>({attachments:r.attachments.filter(o=>o.id!==s)}))},sendMessage:async s=>{const{draft:r,attachments:o,model:l,messages:i}=n(),d=r.trim()||(o.length>0?"Use the attached file as context and help with the prompt":"");if(!d&&o.length===0)return;const c={id:y(),role:"user",content:d,attachments:o.length>0?[...o]:void 0};e(m=>({messages:[...m.messages,c],draft:"",attachments:[],loading:!0,error:null}));try{const m=[...i,c].map(x=>({role:x.role,content:x.content,attachments:x.attachments?.map(h=>({kind:h.kind,name:h.name,mimeType:h.mimeType,size:h.size,dataUrl:h.dataUrl,text:h.text}))})),g=await S({model:l,messages:m,context:s}),j={id:y(),role:"assistant",content:g.message.content};e(x=>({messages:[...x.messages,j],loading:!1}))}catch(m){const g=m instanceof Error?m.message:"Prompt builder request failed";e({loading:!1,error:g})}}}));function P(e){return e?.filename??e?.url??e?.image??null}function C(e){const n=e.split(/[\\/]/).pop()??e;return n.length<=32?n:`${n.slice(0,14)}...${n.slice(-12)}`}function E(){const e=p(c=>c.scope),n=p(c=>c.clearImageScope),s=u(c=>c.currentImage),r=u(c=>c.history),{t:o}=f();if(e.kind==="draft")return t.jsx("span",{className:"prompt-builder__scope",children:o("promptBuilder.scopeDraft")});const i=P(s)===e.imageKey?s:r.find(c=>P(c)===e.imageKey)??null;if(!i)return t.jsx("span",{className:"prompt-builder__scope",children:o("promptBuilder.scopeDraft")});const d=o("promptBuilder.scopeImage",{name:C(e.imageKey)||o("promptBuilder.scopeImageFallback")});return t.jsxs("div",{className:"prompt-builder__scope-card",children:[t.jsx("img",{className:"prompt-builder__scope-thumb",src:i.thumb||i.url||i.image,alt:""}),t.jsx("span",{className:"prompt-builder__scope-name",children:d}),t.jsx("button",{type:"button",className:"prompt-builder__scope-remove",onClick:n,"aria-label":o("promptBuilder.removeScopeImage"),title:o("promptBuilder.removeScopeImage"),children:"×"})]})}const K=["gpt-5.5","gpt-5.4","gpt-5.4-mini"];function $(){const e=p(l=>l.model),n=p(l=>l.setModel),[s,r]=_.useState(!1),{t:o}=f();return t.jsxs("div",{className:"prompt-builder__model-picker",onBlur:l=>{const i=l.relatedTarget;i instanceof Node&&l.currentTarget.contains(i)||r(!1)},children:[t.jsx("button",{type:"button",className:"prompt-builder__model-trigger","aria-label":o("promptBuilder.model"),"aria-haspopup":"listbox","aria-expanded":s,onClick:()=>r(l=>!l),onKeyDown:l=>{l.key==="Escape"&&r(!1)},children:t.jsx("span",{children:e})}),s&&t.jsx("div",{className:"prompt-builder__model-menu",role:"listbox","aria-label":o("promptBuilder.model"),children:K.map(l=>t.jsx("button",{type:"button",role:"option","aria-selected":l===e,className:`prompt-builder__model-option${l===e?" active":""}`,onClick:()=>{n(l),r(!1)},children:l},l))})]})}const D={"Brief Intent Summary":"summary","Final Prompt - Korean":"ko","Final Prompt - English":"en",Notes:"notes"},F=/^(Brief Intent Summary|Final Prompt - Korean|Final Prompt - English|Notes):\s*(.*)$/gim;function w(e){const n=e.trim();return(n.match(/^```(?:[a-zA-Z0-9_-]+)?\s*([\s\S]*?)\s*```$/)?.[1]??n).trim()}function R(e){const n={},s=Array.from(e.matchAll(F));for(let r=0;r<s.length;r+=1){const o=s[r],l=o[1]??"",i=D[l];if(!i||typeof o.index!="number")continue;const d=o[2]?.trim()??"",c=o.index+o[0].length,m=s[r+1]?.index??e.length,g=w([d,e.slice(c,m)].filter(Boolean).join(`
2
- `));g&&(n[i]=g)}return n}function z(e){const n=R(e),s=[];return n.ko&&s.push({language:"ko",heading:"Final Prompt - Korean",text:n.ko}),n.en&&s.push({language:"en",heading:"Final Prompt - English",text:n.en}),s.length===0?null:{summary:n.summary,prompts:s,notes:n.notes}}function U({messageId:e,prompt:n}){const s=u(m=>m.setPrompt),r=u(m=>m.insertPromptToComposer),o=u(m=>m.showToast),{t:l}=f(),i=n.language==="ko"?l("promptBuilder.finalKoreanPrompt"):l("promptBuilder.finalEnglishPrompt"),d=()=>{s(n.text),o(l("promptBuilder.applied"))},c=()=>{r({id:`builder_${e}_${n.language}`,name:i,text:n.text,placement:"after"}),o(l("promptBuilder.inserted"))};return t.jsxs("section",{className:"prompt-builder__structured-card","aria-label":i,children:[t.jsxs("div",{className:"prompt-builder__structured-card-header",children:[t.jsx("strong",{children:i}),t.jsx("span",{children:n.language.toUpperCase()})]}),t.jsx("p",{children:n.text}),t.jsxs("div",{className:"prompt-builder__structured-actions",children:[t.jsx("button",{type:"button",onClick:d,children:l("promptBuilder.applyToPrompt")}),t.jsx("button",{type:"button",onClick:c,children:l("promptBuilder.insertAsBlock")})]})]})}function L(e){return e.kind==="image"?"IMG":e.kind==="text"?"TXT":"FILE"}function O({message:e}){const{t:n}=f(),s=e.role==="assistant"?z(e.content):null;return t.jsxs("article",{className:`prompt-builder__message prompt-builder__message--${e.role}`,children:[t.jsx("div",{className:"prompt-builder__message-role",children:e.role==="user"?n("promptBuilder.user"):n("promptBuilder.assistant")}),s?t.jsxs("div",{className:"prompt-builder__structured-prompts",children:[s.summary?t.jsx("p",{className:"prompt-builder__structured-summary",children:s.summary}):null,s.prompts.map(r=>t.jsx(U,{messageId:e.id,prompt:r},`${e.id}-${r.language}`)),s.notes?t.jsx("p",{className:"prompt-builder__structured-notes",children:s.notes}):null]}):t.jsx("p",{children:e.content}),e.attachments&&e.attachments.length>0?t.jsx("div",{className:"prompt-builder__message-attachments",children:e.attachments.map(r=>t.jsxs("span",{className:"prompt-builder__message-attachment",children:[r.kind==="image"&&r.dataUrl?t.jsx("img",{src:r.dataUrl,alt:""}):t.jsx("span",{children:L(r)}),t.jsx("em",{children:r.name})]},r.id))}):null]})}function q(){const e=p(o=>o.messages),n=p(o=>o.loading),s=_.useRef(null),{t:r}=f();return _.useEffect(()=>{const o=s.current;o&&(o.scrollTop=o.scrollHeight)},[e.length,n]),t.jsxs("div",{ref:s,className:"prompt-builder__messages",children:[e.length===0&&t.jsx("div",{className:"prompt-builder__empty",children:r("promptBuilder.empty")}),e.map(o=>t.jsx(O,{message:o},o.id)),n&&t.jsxs("div",{className:"prompt-builder__thinking",role:"status","aria-live":"polite",children:[t.jsxs("span",{className:"prompt-builder__thinking-dots","aria-hidden":"true",children:[t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{})]}),t.jsx("span",{children:r("promptBuilder.thinking")})]})]})}function G(e){return e.kind==="image"?"IMG":e.kind==="text"?"TXT":"FILE"}function H(){const e=p(r=>r.attachments),n=p(r=>r.removeAttachment),{t:s}=f();return e.length===0?null:t.jsx("div",{className:"prompt-builder__attachments",children:e.map(r=>t.jsxs("span",{className:"prompt-builder__attachment",children:[r.kind==="image"&&r.dataUrl?t.jsx("img",{src:r.dataUrl,alt:""}):t.jsx("span",{children:G(r)}),t.jsx("em",{children:r.name}),t.jsx("button",{type:"button",onClick:()=>n(r.id),"aria-label":s("promptBuilder.removeAttachment",{name:r.name}),title:s("promptBuilder.removeAttachment",{name:r.name}),children:"×"})]},r.id))})}function X(){const e=p(a=>a.draft),n=p(a=>a.setDraft),s=p(a=>a.loading),r=p(a=>a.addAttachments),o=p(a=>a.sendMessage),l=p(a=>a.messages),i=p(a=>a.clearMessages),d=p(a=>a.attachments),c=u(a=>a.prompt),m=u(a=>a.insertedPrompts),g=u(a=>a.quality),j=u(a=>a.getResolvedSize),x=u(a=>a.currentImage),h=_.useRef(null),{t:b}=f(),B=()=>{!e.trim()&&d.length===0||s||o({currentPrompt:c,insertedPrompts:m.map(a=>({name:a.name,text:a.text})),settings:{quality:g,size:j()},currentResultPrompt:x?.prompt??null})},N=a=>{a.length!==0&&r(a)},v=a=>{const k=Array.from(a.clipboardData?.files??[]);k.length!==0&&(a.preventDefault(),N(k))};return t.jsxs("div",{className:"prompt-builder__composer",children:[t.jsx(H,{}),t.jsx("textarea",{value:e,placeholder:b("promptBuilder.placeholder"),onChange:a=>n(a.target.value),onPaste:v,onKeyDown:a=>{a.key==="Enter"&&(a.ctrlKey||a.metaKey)&&(a.preventDefault(),B())}}),t.jsx("input",{ref:h,type:"file",multiple:!0,hidden:!0,onChange:a=>{N(Array.from(a.target.files??[])),a.target.value=""}}),t.jsxs("div",{className:"prompt-builder__composer-actions",children:[t.jsx("button",{type:"button",className:"prompt-builder__attach",onClick:()=>h.current?.click(),disabled:s,"aria-label":b("promptBuilder.attach"),title:b("promptBuilder.attach"),children:"+"}),t.jsx("button",{type:"button",className:"prompt-builder__clear",onClick:i,disabled:l.length===0||s,children:b("promptBuilder.clear")}),t.jsx("button",{type:"button",className:"prompt-builder__send",onClick:B,disabled:!e.trim()&&d.length===0||s,children:b(s?"promptBuilder.sending":"promptBuilder.send")})]})]})}function W({variant:e="panel"}){const{t:n}=f();return t.jsxs("section",{className:`prompt-builder prompt-builder--${e}`,"aria-label":n("promptBuilder.title"),children:[t.jsxs("div",{className:"prompt-builder__header",children:[t.jsxs("div",{children:[t.jsx("span",{className:"section-title",children:n("promptBuilder.title")}),t.jsx(E,{})]}),t.jsx("div",{className:"prompt-builder__header-actions",children:t.jsx($,{})})]}),t.jsx(q,{}),t.jsx(X,{})]})}export{W as PromptBuilderPanel};
1
+ import{K as I,L as S,b as u,u as f,j as t,a as _}from"./index-ygo6nfqx.js";function T(e){return e.filename??e.url??e.image}let M=0;function y(){return`pb_${Date.now()}_${++M}`}async function A(e){const n=y(),s=e.type.startsWith("image/")?"image":"file";if(s==="image"){const r=await new Promise(o=>{const l=new FileReader;l.onload=()=>o(l.result),l.readAsDataURL(e)});return{id:n,kind:s,name:e.name,mimeType:e.type,size:e.size,dataUrl:r}}return{id:n,kind:s,name:e.name,mimeType:e.type,size:e.size}}const p=I()((e,n)=>({messages:[],scope:{kind:"draft"},draft:"",model:"gpt-5.5",loading:!1,attachments:[],error:null,setDraft:s=>e({draft:s}),setModel:s=>e({model:s}),clearMessages:()=>e({messages:[],error:null}),clearImageScope:()=>e({scope:{kind:"draft"}}),setScopeFromImage:s=>{const r=T(s);e({scope:{kind:"image",imageKey:r}})},addAttachments:async s=>{const r=await Promise.all(s.map(A));e(o=>({attachments:[...o.attachments,...r]}))},removeAttachment:s=>{e(r=>({attachments:r.attachments.filter(o=>o.id!==s)}))},sendMessage:async s=>{const{draft:r,attachments:o,model:l,messages:i}=n(),d=r.trim()||(o.length>0?"Use the attached file as context and help with the prompt":"");if(!d&&o.length===0)return;const c={id:y(),role:"user",content:d,attachments:o.length>0?[...o]:void 0};e(m=>({messages:[...m.messages,c],draft:"",attachments:[],loading:!0,error:null}));try{const m=[...i,c].map(x=>({role:x.role,content:x.content,attachments:x.attachments?.map(h=>({kind:h.kind,name:h.name,mimeType:h.mimeType,size:h.size,dataUrl:h.dataUrl,text:h.text}))})),g=await S({model:l,messages:m,context:s}),j={id:y(),role:"assistant",content:g.message.content};e(x=>({messages:[...x.messages,j],loading:!1}))}catch(m){const g=m instanceof Error?m.message:"Prompt builder request failed";e({loading:!1,error:g})}}}));function P(e){return e?.filename??e?.url??e?.image??null}function C(e){const n=e.split(/[\\/]/).pop()??e;return n.length<=32?n:`${n.slice(0,14)}...${n.slice(-12)}`}function E(){const e=p(c=>c.scope),n=p(c=>c.clearImageScope),s=u(c=>c.currentImage),r=u(c=>c.history),{t:o}=f();if(e.kind==="draft")return t.jsx("span",{className:"prompt-builder__scope",children:o("promptBuilder.scopeDraft")});const i=P(s)===e.imageKey?s:r.find(c=>P(c)===e.imageKey)??null;if(!i)return t.jsx("span",{className:"prompt-builder__scope",children:o("promptBuilder.scopeDraft")});const d=o("promptBuilder.scopeImage",{name:C(e.imageKey)||o("promptBuilder.scopeImageFallback")});return t.jsxs("div",{className:"prompt-builder__scope-card",children:[t.jsx("img",{className:"prompt-builder__scope-thumb",src:i.thumb||i.url||i.image,alt:""}),t.jsx("span",{className:"prompt-builder__scope-name",children:d}),t.jsx("button",{type:"button",className:"prompt-builder__scope-remove",onClick:n,"aria-label":o("promptBuilder.removeScopeImage"),title:o("promptBuilder.removeScopeImage"),children:"×"})]})}const K=["gpt-5.5","gpt-5.4","gpt-5.4-mini"];function $(){const e=p(l=>l.model),n=p(l=>l.setModel),[s,r]=_.useState(!1),{t:o}=f();return t.jsxs("div",{className:"prompt-builder__model-picker",onBlur:l=>{const i=l.relatedTarget;i instanceof Node&&l.currentTarget.contains(i)||r(!1)},children:[t.jsx("button",{type:"button",className:"prompt-builder__model-trigger","aria-label":o("promptBuilder.model"),"aria-haspopup":"listbox","aria-expanded":s,onClick:()=>r(l=>!l),onKeyDown:l=>{l.key==="Escape"&&r(!1)},children:t.jsx("span",{children:e})}),s&&t.jsx("div",{className:"prompt-builder__model-menu",role:"listbox","aria-label":o("promptBuilder.model"),children:K.map(l=>t.jsx("button",{type:"button",role:"option","aria-selected":l===e,className:`prompt-builder__model-option${l===e?" active":""}`,onClick:()=>{n(l),r(!1)},children:l},l))})]})}const D={"Brief Intent Summary":"summary","Final Prompt - Korean":"ko","Final Prompt - English":"en",Notes:"notes"},F=/^(Brief Intent Summary|Final Prompt - Korean|Final Prompt - English|Notes):\s*(.*)$/gim;function w(e){const n=e.trim();return(n.match(/^```(?:[a-zA-Z0-9_-]+)?\s*([\s\S]*?)\s*```$/)?.[1]??n).trim()}function R(e){const n={},s=Array.from(e.matchAll(F));for(let r=0;r<s.length;r+=1){const o=s[r],l=o[1]??"",i=D[l];if(!i||typeof o.index!="number")continue;const d=o[2]?.trim()??"",c=o.index+o[0].length,m=s[r+1]?.index??e.length,g=w([d,e.slice(c,m)].filter(Boolean).join(`
2
+ `));g&&(n[i]=g)}return n}function z(e){const n=R(e),s=[];return n.ko&&s.push({language:"ko",heading:"Final Prompt - Korean",text:n.ko}),n.en&&s.push({language:"en",heading:"Final Prompt - English",text:n.en}),s.length===0?null:{summary:n.summary,prompts:s,notes:n.notes}}function U({messageId:e,prompt:n}){const s=u(m=>m.setPrompt),r=u(m=>m.insertPromptToComposer),o=u(m=>m.showToast),{t:l}=f(),i=n.language==="ko"?l("promptBuilder.finalKoreanPrompt"):l("promptBuilder.finalEnglishPrompt"),d=()=>{s(n.text),o(l("promptBuilder.applied"))},c=()=>{r({id:`builder_${e}_${n.language}`,name:i,text:n.text,placement:"after"}),o(l("promptBuilder.inserted"))};return t.jsxs("section",{className:"prompt-builder__structured-card","aria-label":i,children:[t.jsxs("div",{className:"prompt-builder__structured-card-header",children:[t.jsx("strong",{children:i}),t.jsx("span",{children:n.language.toUpperCase()})]}),t.jsx("p",{children:n.text}),t.jsxs("div",{className:"prompt-builder__structured-actions",children:[t.jsx("button",{type:"button",onClick:d,children:l("promptBuilder.applyToPrompt")}),t.jsx("button",{type:"button",onClick:c,children:l("promptBuilder.insertAsBlock")})]})]})}function L(e){return e.kind==="image"?"IMG":e.kind==="text"?"TXT":"FILE"}function O({message:e}){const{t:n}=f(),s=e.role==="assistant"?z(e.content):null;return t.jsxs("article",{className:`prompt-builder__message prompt-builder__message--${e.role}`,children:[t.jsx("div",{className:"prompt-builder__message-role",children:e.role==="user"?n("promptBuilder.user"):n("promptBuilder.assistant")}),s?t.jsxs("div",{className:"prompt-builder__structured-prompts",children:[s.summary?t.jsx("p",{className:"prompt-builder__structured-summary",children:s.summary}):null,s.prompts.map(r=>t.jsx(U,{messageId:e.id,prompt:r},`${e.id}-${r.language}`)),s.notes?t.jsx("p",{className:"prompt-builder__structured-notes",children:s.notes}):null]}):t.jsx("p",{children:e.content}),e.attachments&&e.attachments.length>0?t.jsx("div",{className:"prompt-builder__message-attachments",children:e.attachments.map(r=>t.jsxs("span",{className:"prompt-builder__message-attachment",children:[r.kind==="image"&&r.dataUrl?t.jsx("img",{src:r.dataUrl,alt:""}):t.jsx("span",{children:L(r)}),t.jsx("em",{children:r.name})]},r.id))}):null]})}function q(){const e=p(o=>o.messages),n=p(o=>o.loading),s=_.useRef(null),{t:r}=f();return _.useEffect(()=>{const o=s.current;o&&(o.scrollTop=o.scrollHeight)},[e.length,n]),t.jsxs("div",{ref:s,className:"prompt-builder__messages",children:[e.length===0&&t.jsx("div",{className:"prompt-builder__empty",children:r("promptBuilder.empty")}),e.map(o=>t.jsx(O,{message:o},o.id)),n&&t.jsxs("div",{className:"prompt-builder__thinking",role:"status","aria-live":"polite",children:[t.jsxs("span",{className:"prompt-builder__thinking-dots","aria-hidden":"true",children:[t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{})]}),t.jsx("span",{children:r("promptBuilder.thinking")})]})]})}function G(e){return e.kind==="image"?"IMG":e.kind==="text"?"TXT":"FILE"}function H(){const e=p(r=>r.attachments),n=p(r=>r.removeAttachment),{t:s}=f();return e.length===0?null:t.jsx("div",{className:"prompt-builder__attachments",children:e.map(r=>t.jsxs("span",{className:"prompt-builder__attachment",children:[r.kind==="image"&&r.dataUrl?t.jsx("img",{src:r.dataUrl,alt:""}):t.jsx("span",{children:G(r)}),t.jsx("em",{children:r.name}),t.jsx("button",{type:"button",onClick:()=>n(r.id),"aria-label":s("promptBuilder.removeAttachment",{name:r.name}),title:s("promptBuilder.removeAttachment",{name:r.name}),children:"×"})]},r.id))})}function X(){const e=p(a=>a.draft),n=p(a=>a.setDraft),s=p(a=>a.loading),r=p(a=>a.addAttachments),o=p(a=>a.sendMessage),l=p(a=>a.messages),i=p(a=>a.clearMessages),d=p(a=>a.attachments),c=u(a=>a.prompt),m=u(a=>a.insertedPrompts),g=u(a=>a.quality),j=u(a=>a.getResolvedSize),x=u(a=>a.currentImage),h=_.useRef(null),{t:b}=f(),B=()=>{!e.trim()&&d.length===0||s||o({currentPrompt:c,insertedPrompts:m.map(a=>({name:a.name,text:a.text})),settings:{quality:g,size:j()},currentResultPrompt:x?.prompt??null})},N=a=>{a.length!==0&&r(a)},v=a=>{const k=Array.from(a.clipboardData?.files??[]);k.length!==0&&(a.preventDefault(),N(k))};return t.jsxs("div",{className:"prompt-builder__composer",children:[t.jsx(H,{}),t.jsx("textarea",{value:e,placeholder:b("promptBuilder.placeholder"),onChange:a=>n(a.target.value),onPaste:v,onKeyDown:a=>{a.key==="Enter"&&(a.ctrlKey||a.metaKey)&&(a.preventDefault(),B())}}),t.jsx("input",{ref:h,type:"file",multiple:!0,hidden:!0,onChange:a=>{N(Array.from(a.target.files??[])),a.target.value=""}}),t.jsxs("div",{className:"prompt-builder__composer-actions",children:[t.jsx("button",{type:"button",className:"prompt-builder__attach",onClick:()=>h.current?.click(),disabled:s,"aria-label":b("promptBuilder.attach"),title:b("promptBuilder.attach"),children:"+"}),t.jsx("button",{type:"button",className:"prompt-builder__clear",onClick:i,disabled:l.length===0||s,children:b("promptBuilder.clear")}),t.jsx("button",{type:"button",className:"prompt-builder__send",onClick:B,disabled:!e.trim()&&d.length===0||s,children:b(s?"promptBuilder.sending":"promptBuilder.send")})]})]})}function Y({variant:e="panel"}){const{t:n}=f();return t.jsxs("section",{className:`prompt-builder prompt-builder--${e}`,"aria-label":n("promptBuilder.title"),children:[t.jsxs("div",{className:"prompt-builder__header",children:[t.jsxs("div",{children:[t.jsx("span",{className:"section-title",children:n("promptBuilder.title")}),t.jsx(E,{})]}),t.jsx("div",{className:"prompt-builder__header-actions",children:t.jsx($,{})})]}),t.jsx(q,{}),t.jsx(X,{})]})}export{Y as PromptBuilderPanel};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PromptImportDiscoverySection-CuzyzbNI.js","assets/index-Tjqx6wUV.js","assets/index-Dn2AhL6d.css","assets/PromptImportFolderSection-DHLGlO6l.js"])))=>i.map(i=>d[i]);
2
- import{u as V,j as e,b as ce,a as o,L as K,N as M,O as pe,P as de,Q as me,_ as J}from"./index-Tjqx6wUV.js";function ue(i){const t=i.source;if(!t)return"";if(t.owner&&t.repo){const u=t.ref?`@${t.ref}`:"",s=t.path?`:${t.path}`:"";return`${t.owner}/${t.repo}${u}${s}`}return t.filename??t.sourceId??t.kind??""}function he(i,t){const u=i.tags.find(s=>s.toLowerCase().startsWith(t));return u?u.slice(t.length):null}function be(i){return i.tags.includes("attribution-required")||i.warnings?.some(t=>t.toLowerCase().includes("attribution"))===!0}function ge({candidate:i,selected:t,disabled:u=!1,onToggleSelected:s,onImportOne:g}){const{t:n}=V();if(!i)return e.jsx("aside",{className:"prompt-import-dialog__candidate-preview","aria-label":n("promptLibrary.previewPrompt"),children:e.jsx("div",{className:"prompt-import-dialog__empty",children:n("promptLibrary.importPreviewEmpty")})});const x=ue(i),v=he(i,"license:"),h=be(i);return e.jsxs("aside",{className:"prompt-import-dialog__candidate-preview","aria-label":n("promptLibrary.previewPrompt"),children:[e.jsxs("div",{className:"prompt-import-dialog__preview-header",children:[e.jsxs("div",{children:[e.jsx("span",{children:n("promptLibrary.previewPrompt")}),e.jsx("h4",{children:i.name})]}),e.jsx("button",{type:"button",onClick:()=>g(i),disabled:u,children:n("promptLibrary.importThisPrompt")})]}),e.jsxs("label",{className:"prompt-import-dialog__preview-select",children:[e.jsx("input",{type:"checkbox",checked:t,disabled:u,onChange:l=>s(i.id,l.target.checked)}),e.jsx("span",{children:n(t?"promptLibrary.selectedPrompt":"promptLibrary.selectPrompt")})]}),e.jsxs("div",{className:"prompt-import-dialog__preview-field",children:[e.jsx("strong",{children:n("promptLibrary.promptText")}),e.jsx("p",{children:i.text})]}),i.tags.length>0?e.jsxs("div",{className:"prompt-import-dialog__preview-field",children:[e.jsx("strong",{children:n("promptLibrary.tags")}),e.jsx("div",{className:"prompt-import-dialog__preview-chips",children:i.tags.map(l=>e.jsx("em",{children:l},l))})]}):null,i.warnings?.length?e.jsxs("div",{className:"prompt-import-dialog__preview-field",children:[e.jsx("strong",{children:n("promptLibrary.compatibilityWarnings")}),e.jsx("div",{className:"prompt-import-dialog__preview-chips",children:i.warnings.map(l=>e.jsx("b",{children:l},l))})]}):null,x||v||h?e.jsxs("div",{className:"prompt-import-dialog__preview-field",children:[e.jsx("strong",{children:n("promptLibrary.sourceDetails")}),x?e.jsx("small",{children:x}):null,v?e.jsxs("small",{children:[n("promptLibrary.license"),": ",v]}):null,h?e.jsx("small",{children:n("promptLibrary.attributionRequired")}):null]}):null]})}function fe(i){const t=i.source;if(!t)return"";if(t.owner&&t.repo){const u=t.path?` · ${t.path}`:"";return`github · ${t.owner}/${t.repo}${u}`}return t.filename?t.filename:t.sourceId?t.sourceId:t.kind??""}function ye(i){const t=i.replace(/\s+/g," ").trim();return t.length>220?`${t.slice(0,220)}...`:t}function xe({candidates:i,selectedIds:t,activeCandidateId:u,busy:s=!1,onSelectCandidate:g,onToggleSelected:n,onSelectAll:x,onClearSelection:v,onImportOne:h}){const{t:l}=V();if(i.length===0)return e.jsx("section",{className:"prompt-import-dialog__results","aria-label":l("promptLibrary.searchResults"),children:e.jsx("div",{className:"prompt-import-dialog__empty",children:l("promptLibrary.importPreviewEmpty")})});const f=i.every(p=>t.has(p.id));return e.jsxs("section",{className:"prompt-import-dialog__results","aria-label":l("promptLibrary.searchResults"),children:[e.jsxs("header",{className:"prompt-import-dialog__results-header",children:[e.jsx("strong",{children:l("promptLibrary.searchResultsHeader",{count:i.length})}),e.jsxs("div",{className:"prompt-import-dialog__results-header-actions",children:[e.jsx("button",{type:"button",onClick:x,disabled:f,children:l("promptLibrary.selectAllCandidates")}),e.jsx("button",{type:"button",onClick:v,disabled:t.size===0,children:l("promptLibrary.clearCandidateSelection")})]})]}),i.map(p=>{const y=t.has(p.id),S=u===p.id,j=fe(p);return e.jsxs("article",{className:`prompt-import-dialog__result-card${S?" active":""}`,children:[e.jsxs("button",{type:"button",className:"prompt-import-dialog__result-main",onClick:()=>g(p),children:[e.jsx("strong",{children:p.name}),e.jsx("span",{children:ye(p.text)}),j?e.jsx("small",{children:j}):null]}),e.jsxs("div",{className:"prompt-import-dialog__result-meta",children:[p.warnings?.slice(0,2).map(b=>e.jsx("b",{className:"prompt-import-dialog__hint-chip",children:b},b)),p.tags.slice(0,4).map(b=>e.jsx("em",{children:b},b))]}),e.jsxs("div",{className:"prompt-import-dialog__result-actions",children:[e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:y,onChange:b=>n(p.id,b.target.checked)}),e.jsx("span",{children:l(y?"promptLibrary.selectedPrompt":"promptLibrary.selectPrompt")})]}),e.jsx("button",{type:"button",onClick:()=>g(p),children:l("promptLibrary.previewPrompt")}),e.jsx("button",{type:"button",onClick:()=>h(p),disabled:s,children:l("promptLibrary.importThisPrompt")})]})]},p.id)})]})}const ve=o.lazy(()=>J(()=>import("./PromptImportDiscoverySection-CuzyzbNI.js"),__vite__mapDeps([0,1,2])).then(i=>({default:i.PromptImportDiscoverySection}))),je=o.lazy(()=>J(()=>import("./PromptImportFolderSection-DHLGlO6l.js"),__vite__mapDeps([3,1,2])).then(i=>({default:i.PromptImportFolderSection}))),_e=/\.(txt|md|markdown)$/i;function Se({open:i,onClose:t,onImported:u}){const{t:s}=V(),g=ce(r=>r.showToast),n=o.useRef(null),x=o.useRef(null),v=o.useRef(null),[h,l]=o.useState(""),[f,p]=o.useState([]),[y,S]=o.useState(new Set),[j,b]=o.useState(null),[_,L]=o.useState(!1),[W,m]=o.useState(null),[X,N]=o.useState(!1),[Y,A]=o.useState([]),[$,Z]=o.useState(""),[P,z]=o.useState(new Set),[O,E]=o.useState(!1),[q,I]=o.useState([]),[C,B]=o.useState("curated"),[G,ee]=o.useState(!1),H=f.length>0,D=!H||G;o.useEffect(()=>{if(i)return v.current=document.activeElement,window.setTimeout(()=>x.current?.focus(),0),()=>v.current?.focus()},[i]);const re=o.useCallback(async()=>{const r=await K();A(r.sources),z(new Set)},[]);o.useEffect(()=>{if(!i)return;let r=!1;return K().then(a=>{r||(A(a.sources),z(new Set))}).catch(()=>{r||A([])}),()=>{r=!0}},[i]);const w=o.useCallback(r=>{p(a=>{const c=new Set(a.map(k=>k.id)),d=[...a];for(const k of r)c.has(k.id)||d.push(k);return b(k=>k??d[0]?.id??null),d})},[]),R=o.useCallback(async r=>{const a=r.filter(c=>_e.test(c.name));if(a.length===0){m(s("promptLibrary.importNoValidFiles"));return}L(!0),m(null);try{const c=[];for(const d of a)c.push(await M({source:{kind:"local",filename:d.name,text:await d.text()}}));w(c.flatMap(d=>d.candidates))}catch(c){m(c instanceof Error?c.message:s("promptLibrary.importFailed"))}finally{L(!1)}},[w,s]),te=o.useCallback(async()=>{if(h.trim()){L(!0),m(null);try{const r=await M({source:{kind:"github",input:h.trim()}});w(r.candidates)}catch(r){m(r instanceof Error?r.message:s("promptLibrary.importFailed"))}finally{L(!1)}}},[w,h,s]),se=o.useCallback(async()=>{E(!0),m(null),I([]);try{const r=await pe({q:$.trim(),sourceIds:[...P]});w(r.results),I(r.warnings),r.results.length===0&&m(s("promptLibrary.noCuratedResults"))}catch(r){m(r instanceof Error?r.message:s("promptLibrary.importFailed"))}finally{E(!1)}},[w,$,P,s]),ie=o.useCallback(async r=>{E(!0),m(null),I([]);try{const a=await de({sourceId:r});I(a.warnings),g(s("promptLibrary.curatedRefreshed",{count:a.candidateCount}))}catch(a){m(a instanceof Error?a.message:s("promptLibrary.importFailed"))}finally{E(!1)}},[g,s]),Q=o.useCallback((r,a)=>{S(c=>{const d=new Set(c);return a?d.add(r):d.delete(r),d})},[]),oe=o.useCallback(()=>{S(new Set(f.map(r=>r.id)))},[f]),ae=o.useCallback(()=>{S(new Set)},[]),T=o.useCallback(async r=>{if(r.length===0){m(s("promptLibrary.importSelectAtLeastOne"));return}L(!0),m(null);try{const a=await me({candidates:r});await u(),g(s("promptLibrary.imported",{count:a.promptsImported})),t()}catch(a){m(a instanceof Error?a.message:s("promptLibrary.importFailed"))}finally{L(!1)}},[t,u,g,s]),le=o.useCallback(async()=>{const r=f.filter(a=>y.has(a.id));await T(r)},[f,T,y]),U=o.useCallback(r=>{S(new Set([r.id])),T([r])},[T]),ne=o.useCallback(r=>{const a=Array.from(r.target.files??[]);a.length>0&&R(a),r.target.value=""},[R]),F=o.useCallback(r=>{r.preventDefault(),r.stopPropagation(),N(!1);const a=Array.from(r.dataTransfer?.files??[]);a.length>0&&R(a)},[R]);return o.useEffect(()=>{if(!i)return;const r=c=>{c.preventDefault(),N(!0)},a=c=>{c.relatedTarget===null&&N(!1)};return window.addEventListener("dragover",r),window.addEventListener("dragleave",a),window.addEventListener("drop",F),()=>{window.removeEventListener("dragover",r),window.removeEventListener("dragleave",a),window.removeEventListener("drop",F)}},[F,i]),i?e.jsxs("div",{className:"prompt-import-dialog",role:"presentation",children:[e.jsx("div",{className:"prompt-import-dialog__backdrop",onClick:t}),e.jsxs("div",{ref:x,className:"prompt-import-dialog__panel",role:"dialog","aria-modal":"true","aria-labelledby":"prompt-import-title",tabIndex:-1,onKeyDown:r=>{r.key==="Escape"&&t()},children:[e.jsxs("div",{className:"prompt-import-dialog__header",children:[e.jsx("h3",{id:"prompt-import-title",children:s("promptLibrary.importTitle")}),e.jsx("button",{type:"button",onClick:t,"aria-label":s("common.close"),children:"×"})]}),D&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`prompt-import-dialog__dropzone${X?" active":""}`,onDragOver:r=>{r.preventDefault(),N(!0)},onDragLeave:()=>N(!1),onDrop:F,children:[e.jsx("strong",{children:s("promptLibrary.importDropTitle")}),e.jsx("span",{children:s("promptLibrary.importDropHint")}),e.jsx("button",{type:"button",onClick:()=>n.current?.click(),children:s("promptLibrary.importChooseFiles")}),e.jsx("input",{ref:n,className:"prompt-library-panel__file-input",type:"file",accept:".txt,.md,.markdown,text/plain,text/markdown",multiple:!0,onChange:ne})]}),e.jsxs("div",{className:"prompt-import-dialog__github",children:[e.jsx("label",{htmlFor:"prompt-import-github",children:s("promptLibrary.importGithubLabel")}),e.jsxs("div",{children:[e.jsx("input",{id:"prompt-import-github",type:"text",value:h,onChange:r=>l(r.target.value),placeholder:"owner/repo:path/to/prompts.md"}),e.jsx("button",{type:"button",onClick:()=>{te()},disabled:_||!h.trim(),children:s("promptLibrary.importPreview")})]})]}),e.jsx(o.Suspense,{fallback:null,children:e.jsx(je,{input:h,disabled:_,onCandidates:w,onError:m})}),e.jsxs("div",{className:"prompt-import-dialog__source-tabs",role:"tablist","aria-label":s("promptLibrary.curatedSources"),children:[e.jsx("button",{type:"button",className:C==="curated"?"active":"",onClick:()=>B("curated"),"aria-pressed":C==="curated",children:s("promptLibrary.curatedSources")}),e.jsx("button",{type:"button",className:C==="discovery"?"active":"",onClick:()=>B("discovery"),"aria-pressed":C==="discovery",children:s("promptLibrary.discovery")})]})]}),(D?C==="curated":!0)&&e.jsxs("div",{className:"prompt-import-dialog__curated",children:[D&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"prompt-import-dialog__section-title",children:[e.jsx("strong",{children:s("promptLibrary.curatedSources")}),e.jsx("span",{children:s("promptLibrary.curatedSourcesHint")})]}),e.jsx("div",{className:"prompt-import-dialog__source-list",children:Y.filter(r=>r.trustTier!=="manual-review").map(r=>e.jsxs("label",{className:"prompt-import-dialog__source",children:[e.jsx("input",{type:"checkbox",checked:P.has(r.id),onChange:a=>{z(c=>{const d=new Set(c);return a.target.checked?d.add(r.id):d.delete(r.id),d})}}),e.jsxs("span",{children:[e.jsx("strong",{children:r.displayName}),e.jsxs("small",{children:[r.licenseSpdx," · ",r.trustTier]})]}),e.jsx("button",{type:"button",onClick:()=>{ie(r.id)},disabled:O,children:s("promptLibrary.refreshSource")})]},r.id))})]}),e.jsxs("div",{className:"prompt-import-dialog__search-results",children:[e.jsx("input",{type:"text",value:$,onChange:r=>Z(r.target.value),placeholder:s("promptLibrary.curatedSearchPlaceholder"),"aria-label":s("promptLibrary.curatedSearch")}),e.jsx("button",{type:"button",onClick:()=>{se()},disabled:O||P.size===0,children:s(O?"common.loading":"promptLibrary.curatedSearch")})]}),q.length>0?e.jsx("div",{className:"prompt-import-dialog__warning",children:q.slice(0,3).join(" · ")}):null]}),D&&C==="discovery"&&e.jsx(o.Suspense,{fallback:e.jsx("div",{className:"prompt-import-dialog__empty",children:s("common.loading")}),children:e.jsx(ve,{disabled:_,onError:m,onSourcesChanged:re})}),H&&!G&&e.jsx("button",{type:"button",className:"prompt-import-dialog__add-source-toggle",onClick:()=>ee(!0),children:s("promptLibrary.addAnotherSource")}),W?e.jsx("div",{className:"prompt-import-dialog__error",role:"alert",children:W}):null,e.jsxs("div",{className:"prompt-import-dialog__workspace","aria-live":"polite",children:[e.jsx(xe,{candidates:f,selectedIds:y,activeCandidateId:j,busy:_,onSelectCandidate:r=>b(r.id),onToggleSelected:Q,onSelectAll:oe,onClearSelection:ae,onImportOne:U}),e.jsx(ge,{candidate:f.find(r=>r.id===j)??null,selected:j?y.has(j):!1,disabled:_,onToggleSelected:Q,onImportOne:U})]}),e.jsxs("div",{className:"prompt-import-dialog__footer",children:[e.jsx("button",{type:"button",onClick:t,children:s("common.cancel")}),e.jsx("button",{type:"button",onClick:()=>{le()},disabled:_||y.size===0,children:_?s("common.loading"):s("promptLibrary.importSelected",{count:y.size})})]})]})]}):null}export{Se as PromptImportDialog};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PromptImportDiscoverySection-CzuW-8P2.js","assets/index-ygo6nfqx.js","assets/index-CX3fge8X.css","assets/PromptImportFolderSection-DP5ywnsv.js"])))=>i.map(i=>d[i]);
2
+ import{u as V,j as e,b as ce,a as o,O as K,P as M,Q as pe,U as de,V as me,_ as J}from"./index-ygo6nfqx.js";function ue(i){const t=i.source;if(!t)return"";if(t.owner&&t.repo){const u=t.ref?`@${t.ref}`:"",s=t.path?`:${t.path}`:"";return`${t.owner}/${t.repo}${u}${s}`}return t.filename??t.sourceId??t.kind??""}function he(i,t){const u=i.tags.find(s=>s.toLowerCase().startsWith(t));return u?u.slice(t.length):null}function be(i){return i.tags.includes("attribution-required")||i.warnings?.some(t=>t.toLowerCase().includes("attribution"))===!0}function ge({candidate:i,selected:t,disabled:u=!1,onToggleSelected:s,onImportOne:g}){const{t:n}=V();if(!i)return e.jsx("aside",{className:"prompt-import-dialog__candidate-preview","aria-label":n("promptLibrary.previewPrompt"),children:e.jsx("div",{className:"prompt-import-dialog__empty",children:n("promptLibrary.importPreviewEmpty")})});const x=ue(i),v=he(i,"license:"),h=be(i);return e.jsxs("aside",{className:"prompt-import-dialog__candidate-preview","aria-label":n("promptLibrary.previewPrompt"),children:[e.jsxs("div",{className:"prompt-import-dialog__preview-header",children:[e.jsxs("div",{children:[e.jsx("span",{children:n("promptLibrary.previewPrompt")}),e.jsx("h4",{children:i.name})]}),e.jsx("button",{type:"button",onClick:()=>g(i),disabled:u,children:n("promptLibrary.importThisPrompt")})]}),e.jsxs("label",{className:"prompt-import-dialog__preview-select",children:[e.jsx("input",{type:"checkbox",checked:t,disabled:u,onChange:l=>s(i.id,l.target.checked)}),e.jsx("span",{children:n(t?"promptLibrary.selectedPrompt":"promptLibrary.selectPrompt")})]}),e.jsxs("div",{className:"prompt-import-dialog__preview-field",children:[e.jsx("strong",{children:n("promptLibrary.promptText")}),e.jsx("p",{children:i.text})]}),i.tags.length>0?e.jsxs("div",{className:"prompt-import-dialog__preview-field",children:[e.jsx("strong",{children:n("promptLibrary.tags")}),e.jsx("div",{className:"prompt-import-dialog__preview-chips",children:i.tags.map(l=>e.jsx("em",{children:l},l))})]}):null,i.warnings?.length?e.jsxs("div",{className:"prompt-import-dialog__preview-field",children:[e.jsx("strong",{children:n("promptLibrary.compatibilityWarnings")}),e.jsx("div",{className:"prompt-import-dialog__preview-chips",children:i.warnings.map(l=>e.jsx("b",{children:l},l))})]}):null,x||v||h?e.jsxs("div",{className:"prompt-import-dialog__preview-field",children:[e.jsx("strong",{children:n("promptLibrary.sourceDetails")}),x?e.jsx("small",{children:x}):null,v?e.jsxs("small",{children:[n("promptLibrary.license"),": ",v]}):null,h?e.jsx("small",{children:n("promptLibrary.attributionRequired")}):null]}):null]})}function fe(i){const t=i.source;if(!t)return"";if(t.owner&&t.repo){const u=t.path?` · ${t.path}`:"";return`github · ${t.owner}/${t.repo}${u}`}return t.filename?t.filename:t.sourceId?t.sourceId:t.kind??""}function ye(i){const t=i.replace(/\s+/g," ").trim();return t.length>220?`${t.slice(0,220)}...`:t}function xe({candidates:i,selectedIds:t,activeCandidateId:u,busy:s=!1,onSelectCandidate:g,onToggleSelected:n,onSelectAll:x,onClearSelection:v,onImportOne:h}){const{t:l}=V();if(i.length===0)return e.jsx("section",{className:"prompt-import-dialog__results","aria-label":l("promptLibrary.searchResults"),children:e.jsx("div",{className:"prompt-import-dialog__empty",children:l("promptLibrary.importPreviewEmpty")})});const f=i.every(p=>t.has(p.id));return e.jsxs("section",{className:"prompt-import-dialog__results","aria-label":l("promptLibrary.searchResults"),children:[e.jsxs("header",{className:"prompt-import-dialog__results-header",children:[e.jsx("strong",{children:l("promptLibrary.searchResultsHeader",{count:i.length})}),e.jsxs("div",{className:"prompt-import-dialog__results-header-actions",children:[e.jsx("button",{type:"button",onClick:x,disabled:f,children:l("promptLibrary.selectAllCandidates")}),e.jsx("button",{type:"button",onClick:v,disabled:t.size===0,children:l("promptLibrary.clearCandidateSelection")})]})]}),i.map(p=>{const y=t.has(p.id),S=u===p.id,j=fe(p);return e.jsxs("article",{className:`prompt-import-dialog__result-card${S?" active":""}`,children:[e.jsxs("button",{type:"button",className:"prompt-import-dialog__result-main",onClick:()=>g(p),children:[e.jsx("strong",{children:p.name}),e.jsx("span",{children:ye(p.text)}),j?e.jsx("small",{children:j}):null]}),e.jsxs("div",{className:"prompt-import-dialog__result-meta",children:[p.warnings?.slice(0,2).map(b=>e.jsx("b",{className:"prompt-import-dialog__hint-chip",children:b},b)),p.tags.slice(0,4).map(b=>e.jsx("em",{children:b},b))]}),e.jsxs("div",{className:"prompt-import-dialog__result-actions",children:[e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:y,onChange:b=>n(p.id,b.target.checked)}),e.jsx("span",{children:l(y?"promptLibrary.selectedPrompt":"promptLibrary.selectPrompt")})]}),e.jsx("button",{type:"button",onClick:()=>g(p),children:l("promptLibrary.previewPrompt")}),e.jsx("button",{type:"button",onClick:()=>h(p),disabled:s,children:l("promptLibrary.importThisPrompt")})]})]},p.id)})]})}const ve=o.lazy(()=>J(()=>import("./PromptImportDiscoverySection-CzuW-8P2.js"),__vite__mapDeps([0,1,2])).then(i=>({default:i.PromptImportDiscoverySection}))),je=o.lazy(()=>J(()=>import("./PromptImportFolderSection-DP5ywnsv.js"),__vite__mapDeps([3,1,2])).then(i=>({default:i.PromptImportFolderSection}))),_e=/\.(txt|md|markdown)$/i;function Se({open:i,onClose:t,onImported:u}){const{t:s}=V(),g=ce(r=>r.showToast),n=o.useRef(null),x=o.useRef(null),v=o.useRef(null),[h,l]=o.useState(""),[f,p]=o.useState([]),[y,S]=o.useState(new Set),[j,b]=o.useState(null),[_,L]=o.useState(!1),[W,m]=o.useState(null),[X,N]=o.useState(!1),[Y,A]=o.useState([]),[$,Z]=o.useState(""),[P,z]=o.useState(new Set),[O,E]=o.useState(!1),[q,I]=o.useState([]),[C,B]=o.useState("curated"),[G,ee]=o.useState(!1),H=f.length>0,D=!H||G;o.useEffect(()=>{if(i)return v.current=document.activeElement,window.setTimeout(()=>x.current?.focus(),0),()=>v.current?.focus()},[i]);const re=o.useCallback(async()=>{const r=await K();A(r.sources),z(new Set)},[]);o.useEffect(()=>{if(!i)return;let r=!1;return K().then(a=>{r||(A(a.sources),z(new Set))}).catch(()=>{r||A([])}),()=>{r=!0}},[i]);const w=o.useCallback(r=>{p(a=>{const c=new Set(a.map(k=>k.id)),d=[...a];for(const k of r)c.has(k.id)||d.push(k);return b(k=>k??d[0]?.id??null),d})},[]),R=o.useCallback(async r=>{const a=r.filter(c=>_e.test(c.name));if(a.length===0){m(s("promptLibrary.importNoValidFiles"));return}L(!0),m(null);try{const c=[];for(const d of a)c.push(await M({source:{kind:"local",filename:d.name,text:await d.text()}}));w(c.flatMap(d=>d.candidates))}catch(c){m(c instanceof Error?c.message:s("promptLibrary.importFailed"))}finally{L(!1)}},[w,s]),te=o.useCallback(async()=>{if(h.trim()){L(!0),m(null);try{const r=await M({source:{kind:"github",input:h.trim()}});w(r.candidates)}catch(r){m(r instanceof Error?r.message:s("promptLibrary.importFailed"))}finally{L(!1)}}},[w,h,s]),se=o.useCallback(async()=>{E(!0),m(null),I([]);try{const r=await pe({q:$.trim(),sourceIds:[...P]});w(r.results),I(r.warnings),r.results.length===0&&m(s("promptLibrary.noCuratedResults"))}catch(r){m(r instanceof Error?r.message:s("promptLibrary.importFailed"))}finally{E(!1)}},[w,$,P,s]),ie=o.useCallback(async r=>{E(!0),m(null),I([]);try{const a=await de({sourceId:r});I(a.warnings),g(s("promptLibrary.curatedRefreshed",{count:a.candidateCount}))}catch(a){m(a instanceof Error?a.message:s("promptLibrary.importFailed"))}finally{E(!1)}},[g,s]),Q=o.useCallback((r,a)=>{S(c=>{const d=new Set(c);return a?d.add(r):d.delete(r),d})},[]),oe=o.useCallback(()=>{S(new Set(f.map(r=>r.id)))},[f]),ae=o.useCallback(()=>{S(new Set)},[]),T=o.useCallback(async r=>{if(r.length===0){m(s("promptLibrary.importSelectAtLeastOne"));return}L(!0),m(null);try{const a=await me({candidates:r});await u(),g(s("promptLibrary.imported",{count:a.promptsImported})),t()}catch(a){m(a instanceof Error?a.message:s("promptLibrary.importFailed"))}finally{L(!1)}},[t,u,g,s]),le=o.useCallback(async()=>{const r=f.filter(a=>y.has(a.id));await T(r)},[f,T,y]),U=o.useCallback(r=>{S(new Set([r.id])),T([r])},[T]),ne=o.useCallback(r=>{const a=Array.from(r.target.files??[]);a.length>0&&R(a),r.target.value=""},[R]),F=o.useCallback(r=>{r.preventDefault(),r.stopPropagation(),N(!1);const a=Array.from(r.dataTransfer?.files??[]);a.length>0&&R(a)},[R]);return o.useEffect(()=>{if(!i)return;const r=c=>{c.preventDefault(),N(!0)},a=c=>{c.relatedTarget===null&&N(!1)};return window.addEventListener("dragover",r),window.addEventListener("dragleave",a),window.addEventListener("drop",F),()=>{window.removeEventListener("dragover",r),window.removeEventListener("dragleave",a),window.removeEventListener("drop",F)}},[F,i]),i?e.jsxs("div",{className:"prompt-import-dialog",role:"presentation",children:[e.jsx("div",{className:"prompt-import-dialog__backdrop",onClick:t}),e.jsxs("div",{ref:x,className:"prompt-import-dialog__panel",role:"dialog","aria-modal":"true","aria-labelledby":"prompt-import-title",tabIndex:-1,onKeyDown:r=>{r.key==="Escape"&&t()},children:[e.jsxs("div",{className:"prompt-import-dialog__header",children:[e.jsx("h3",{id:"prompt-import-title",children:s("promptLibrary.importTitle")}),e.jsx("button",{type:"button",onClick:t,"aria-label":s("common.close"),children:"×"})]}),D&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`prompt-import-dialog__dropzone${X?" active":""}`,onDragOver:r=>{r.preventDefault(),N(!0)},onDragLeave:()=>N(!1),onDrop:F,children:[e.jsx("strong",{children:s("promptLibrary.importDropTitle")}),e.jsx("span",{children:s("promptLibrary.importDropHint")}),e.jsx("button",{type:"button",onClick:()=>n.current?.click(),children:s("promptLibrary.importChooseFiles")}),e.jsx("input",{ref:n,className:"prompt-library-panel__file-input",type:"file",accept:".txt,.md,.markdown,text/plain,text/markdown",multiple:!0,onChange:ne})]}),e.jsxs("div",{className:"prompt-import-dialog__github",children:[e.jsx("label",{htmlFor:"prompt-import-github",children:s("promptLibrary.importGithubLabel")}),e.jsxs("div",{children:[e.jsx("input",{id:"prompt-import-github",type:"text",value:h,onChange:r=>l(r.target.value),placeholder:"owner/repo:path/to/prompts.md"}),e.jsx("button",{type:"button",onClick:()=>{te()},disabled:_||!h.trim(),children:s("promptLibrary.importPreview")})]})]}),e.jsx(o.Suspense,{fallback:null,children:e.jsx(je,{input:h,disabled:_,onCandidates:w,onError:m})}),e.jsxs("div",{className:"prompt-import-dialog__source-tabs",role:"tablist","aria-label":s("promptLibrary.curatedSources"),children:[e.jsx("button",{type:"button",className:C==="curated"?"active":"",onClick:()=>B("curated"),"aria-pressed":C==="curated",children:s("promptLibrary.curatedSources")}),e.jsx("button",{type:"button",className:C==="discovery"?"active":"",onClick:()=>B("discovery"),"aria-pressed":C==="discovery",children:s("promptLibrary.discovery")})]})]}),(D?C==="curated":!0)&&e.jsxs("div",{className:"prompt-import-dialog__curated",children:[D&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"prompt-import-dialog__section-title",children:[e.jsx("strong",{children:s("promptLibrary.curatedSources")}),e.jsx("span",{children:s("promptLibrary.curatedSourcesHint")})]}),e.jsx("div",{className:"prompt-import-dialog__source-list",children:Y.filter(r=>r.trustTier!=="manual-review").map(r=>e.jsxs("label",{className:"prompt-import-dialog__source",children:[e.jsx("input",{type:"checkbox",checked:P.has(r.id),onChange:a=>{z(c=>{const d=new Set(c);return a.target.checked?d.add(r.id):d.delete(r.id),d})}}),e.jsxs("span",{children:[e.jsx("strong",{children:r.displayName}),e.jsxs("small",{children:[r.licenseSpdx," · ",r.trustTier]})]}),e.jsx("button",{type:"button",onClick:()=>{ie(r.id)},disabled:O,children:s("promptLibrary.refreshSource")})]},r.id))})]}),e.jsxs("div",{className:"prompt-import-dialog__search-results",children:[e.jsx("input",{type:"text",value:$,onChange:r=>Z(r.target.value),placeholder:s("promptLibrary.curatedSearchPlaceholder"),"aria-label":s("promptLibrary.curatedSearch")}),e.jsx("button",{type:"button",onClick:()=>{se()},disabled:O||P.size===0,children:s(O?"common.loading":"promptLibrary.curatedSearch")})]}),q.length>0?e.jsx("div",{className:"prompt-import-dialog__warning",children:q.slice(0,3).join(" · ")}):null]}),D&&C==="discovery"&&e.jsx(o.Suspense,{fallback:e.jsx("div",{className:"prompt-import-dialog__empty",children:s("common.loading")}),children:e.jsx(ve,{disabled:_,onError:m,onSourcesChanged:re})}),H&&!G&&e.jsx("button",{type:"button",className:"prompt-import-dialog__add-source-toggle",onClick:()=>ee(!0),children:s("promptLibrary.addAnotherSource")}),W?e.jsx("div",{className:"prompt-import-dialog__error",role:"alert",children:W}):null,e.jsxs("div",{className:"prompt-import-dialog__workspace","aria-live":"polite",children:[e.jsx(xe,{candidates:f,selectedIds:y,activeCandidateId:j,busy:_,onSelectCandidate:r=>b(r.id),onToggleSelected:Q,onSelectAll:oe,onClearSelection:ae,onImportOne:U}),e.jsx(ge,{candidate:f.find(r=>r.id===j)??null,selected:j?y.has(j):!1,disabled:_,onToggleSelected:Q,onImportOne:U})]}),e.jsxs("div",{className:"prompt-import-dialog__footer",children:[e.jsx("button",{type:"button",onClick:t,children:s("common.cancel")}),e.jsx("button",{type:"button",onClick:()=>{le()},disabled:_||y.size===0,children:_?s("common.loading"):s("promptLibrary.importSelected",{count:y.size})})]})]})]}):null}export{Se as PromptImportDialog};
@@ -1 +1 @@
1
- import{u as L,a as t,V as S,X as C,Y as P,j as r}from"./index-Tjqx6wUV.js";const R=["gpt-image-2 prompt","nano banana prompts","typography image prompt"];function k({disabled:d=!1,onError:a,onSourcesChanged:y}){const{t:s}=L(),[l,N]=t.useState("gpt-image-2 prompt"),[v,p]=t.useState([]),[n,c]=t.useState(!1),[g,m]=t.useState([]),[h,_]=t.useState({});t.useEffect(()=>{let e=!1;return S().then(i=>{e||p(i.candidates)}).catch(()=>{e||p([])}),()=>{e=!0}},[]);const w=t.useCallback(async()=>{c(!0),m([]),a(null);try{const e=await C({q:l.trim(),seeds:R});p(e.candidates),m([...e.warnings,...e.rateLimit?.remaining===0?["github-rate-limit-exhausted"]:[]]),e.candidates.length===0&&a(s("promptLibrary.discoveryNoResults"))}catch(e){a(e instanceof Error?e.message:s("promptLibrary.importFailed"))}finally{c(!1)}},[a,l,s]),x=t.useCallback(async(e,i)=>{c(!0),m([]),a(null);try{const j=(h[e.fullName]||"").split(/\r?\n|,/).map(u=>u.trim()).filter(Boolean),b=await P({repo:e.fullName,status:i,allowedPaths:i==="approved"?j:[],defaultSearch:i==="approved"&&j.length>0});m(b.warnings),p(u=>u.map(f=>f.fullName===e.fullName?b.candidate:f)),await y()}catch(o){a(o instanceof Error?o.message:s("promptLibrary.importFailed"))}finally{c(!1)}},[h,a,y,s]);return r.jsxs("div",{className:"prompt-import-dialog__discovery",children:[r.jsxs("div",{className:"prompt-import-dialog__section-title",children:[r.jsx("strong",{children:s("promptLibrary.discovery")}),r.jsx("span",{children:s("promptLibrary.discoveryReviewQueue")})]}),r.jsxs("div",{className:"prompt-import-dialog__discovery-actions",children:[r.jsx("input",{type:"text",value:l,onChange:e=>N(e.target.value),placeholder:s("promptLibrary.discoverySearchPlaceholder"),"aria-label":s("promptLibrary.discoverySearch")}),r.jsx("button",{type:"button",onClick:()=>{w()},disabled:d||n||!l.trim(),children:s(n?"common.loading":"promptLibrary.discoverySearch")})]}),g.length>0?r.jsx("div",{className:"prompt-import-dialog__discovery-warning",children:g.slice(0,3).join(" · ")}):null,v.length===0?r.jsx("div",{className:"prompt-import-dialog__empty",children:s("promptLibrary.discoveryNoResults")}):r.jsx("div",{className:"prompt-import-dialog__discovery-list",children:v.map(e=>r.jsxs("article",{className:"prompt-import-dialog__discovery-candidate",children:[r.jsxs("div",{children:[r.jsx("strong",{children:e.fullName}),r.jsx("small",{children:e.description||e.htmlUrl})]}),r.jsxs("div",{className:"prompt-import-dialog__score",children:[r.jsxs("span",{children:[s("promptLibrary.discoveryScore"),": ",e.score]}),r.jsx("span",{children:e.licenseSpdx}),r.jsx("span",{children:e.status})]}),e.scoreReasons.length>0?r.jsx("em",{children:e.scoreReasons.slice(0,3).join(" · ")}):null,e.warnings.length>0?r.jsx("b",{children:e.warnings.slice(0,2).join(" · ")}):null,r.jsx("textarea",{value:h[e.fullName]||"",onChange:i=>_(o=>({...o,[e.fullName]:i.target.value})),placeholder:"README.md, prompts/example.md","aria-label":s("promptLibrary.discoveryRequiresPaths")}),r.jsxs("div",{className:"prompt-import-dialog__review-actions",children:[r.jsx("button",{type:"button",onClick:()=>{x(e,"approved")},disabled:d||n,children:s("promptLibrary.discoveryApprove")}),r.jsx("button",{type:"button",onClick:()=>{x(e,"rejected")},disabled:d||n,children:s("promptLibrary.discoveryReject")})]})]},e.fullName))})]})}export{k as PromptImportDiscoverySection};
1
+ import{u as L,a as t,X as S,Y as C,Z as P,j as r}from"./index-ygo6nfqx.js";const R=["gpt-image-2 prompt","nano banana prompts","typography image prompt"];function k({disabled:d=!1,onError:a,onSourcesChanged:y}){const{t:s}=L(),[l,N]=t.useState("gpt-image-2 prompt"),[v,p]=t.useState([]),[n,c]=t.useState(!1),[g,m]=t.useState([]),[h,_]=t.useState({});t.useEffect(()=>{let e=!1;return S().then(i=>{e||p(i.candidates)}).catch(()=>{e||p([])}),()=>{e=!0}},[]);const w=t.useCallback(async()=>{c(!0),m([]),a(null);try{const e=await C({q:l.trim(),seeds:R});p(e.candidates),m([...e.warnings,...e.rateLimit?.remaining===0?["github-rate-limit-exhausted"]:[]]),e.candidates.length===0&&a(s("promptLibrary.discoveryNoResults"))}catch(e){a(e instanceof Error?e.message:s("promptLibrary.importFailed"))}finally{c(!1)}},[a,l,s]),x=t.useCallback(async(e,i)=>{c(!0),m([]),a(null);try{const j=(h[e.fullName]||"").split(/\r?\n|,/).map(u=>u.trim()).filter(Boolean),b=await P({repo:e.fullName,status:i,allowedPaths:i==="approved"?j:[],defaultSearch:i==="approved"&&j.length>0});m(b.warnings),p(u=>u.map(f=>f.fullName===e.fullName?b.candidate:f)),await y()}catch(o){a(o instanceof Error?o.message:s("promptLibrary.importFailed"))}finally{c(!1)}},[h,a,y,s]);return r.jsxs("div",{className:"prompt-import-dialog__discovery",children:[r.jsxs("div",{className:"prompt-import-dialog__section-title",children:[r.jsx("strong",{children:s("promptLibrary.discovery")}),r.jsx("span",{children:s("promptLibrary.discoveryReviewQueue")})]}),r.jsxs("div",{className:"prompt-import-dialog__discovery-actions",children:[r.jsx("input",{type:"text",value:l,onChange:e=>N(e.target.value),placeholder:s("promptLibrary.discoverySearchPlaceholder"),"aria-label":s("promptLibrary.discoverySearch")}),r.jsx("button",{type:"button",onClick:()=>{w()},disabled:d||n||!l.trim(),children:s(n?"common.loading":"promptLibrary.discoverySearch")})]}),g.length>0?r.jsx("div",{className:"prompt-import-dialog__discovery-warning",children:g.slice(0,3).join(" · ")}):null,v.length===0?r.jsx("div",{className:"prompt-import-dialog__empty",children:s("promptLibrary.discoveryNoResults")}):r.jsx("div",{className:"prompt-import-dialog__discovery-list",children:v.map(e=>r.jsxs("article",{className:"prompt-import-dialog__discovery-candidate",children:[r.jsxs("div",{children:[r.jsx("strong",{children:e.fullName}),r.jsx("small",{children:e.description||e.htmlUrl})]}),r.jsxs("div",{className:"prompt-import-dialog__score",children:[r.jsxs("span",{children:[s("promptLibrary.discoveryScore"),": ",e.score]}),r.jsx("span",{children:e.licenseSpdx}),r.jsx("span",{children:e.status})]}),e.scoreReasons.length>0?r.jsx("em",{children:e.scoreReasons.slice(0,3).join(" · ")}):null,e.warnings.length>0?r.jsx("b",{children:e.warnings.slice(0,2).join(" · ")}):null,r.jsx("textarea",{value:h[e.fullName]||"",onChange:i=>_(o=>({...o,[e.fullName]:i.target.value})),placeholder:"README.md, prompts/example.md","aria-label":s("promptLibrary.discoveryRequiresPaths")}),r.jsxs("div",{className:"prompt-import-dialog__review-actions",children:[r.jsx("button",{type:"button",onClick:()=>{x(e,"approved")},disabled:d||n,children:s("promptLibrary.discoveryApprove")}),r.jsx("button",{type:"button",onClick:()=>{x(e,"rejected")},disabled:d||n,children:s("promptLibrary.discoveryReject")})]})]},e.fullName))})]})}export{k as PromptImportDiscoverySection};
@@ -0,0 +1 @@
1
+ import{u as w,a,$ as S,a0 as _,j as t}from"./index-ygo6nfqx.js";function F({input:i,disabled:h=!1,onCandidates:u,onError:l}){const{t:s}=w(),[f,g]=a.useState([]),[o,p]=a.useState(new Set),[d,n]=a.useState(!1),[x,c]=a.useState([]),y=a.useCallback(async()=>{if(i.trim()){n(!0),c([]),l(null);try{const e=await S({source:{kind:"github-folder",input:i.trim()}});g(e.files),p(new Set(e.files.slice(0,5).map(r=>r.path))),c(e.warnings),e.files.length===0&&l(s("promptLibrary.folderFilesEmpty"))}catch(e){g([]),p(new Set),l(e instanceof Error?e.message:s("promptLibrary.folderUnsupported"))}finally{n(!1)}}},[i,l,s]),b=a.useCallback(async()=>{const e=[...o];if(e.length===0){l(s("promptLibrary.folderNoSelection"));return}n(!0),c([]),l(null);try{const r=await _({source:{kind:"github-folder",input:i.trim()},paths:e});c(r.warnings),u(r.candidates)}catch(r){l(r instanceof Error?r.message:s("promptLibrary.importFailed"))}finally{n(!1)}},[i,u,l,o,s]);return t.jsxs("div",{className:"prompt-import-dialog__folder",children:[t.jsxs("div",{className:"prompt-import-dialog__section-title",children:[t.jsx("strong",{children:s("promptLibrary.folderFiles")}),t.jsx("span",{children:s("promptLibrary.folderBrowseHint")})]}),t.jsxs("div",{className:"prompt-import-dialog__folder-actions",children:[t.jsx("button",{type:"button",onClick:()=>{y()},disabled:h||d||!i.trim(),children:s(d?"common.loading":"promptLibrary.folderBrowse")}),t.jsx("button",{type:"button",onClick:()=>{b()},disabled:h||d||o.size===0,children:s("promptLibrary.folderPreviewSelected")}),t.jsx("span",{children:s("promptLibrary.folderSelectedCount",{count:o.size})})]}),f.length>0?t.jsx("div",{className:"prompt-import-dialog__folder-list",children:f.map(e=>t.jsxs("label",{className:"prompt-import-dialog__folder-file",children:[t.jsx("input",{type:"checkbox",checked:o.has(e.path),onChange:r=>{p(j=>{const m=new Set(j);return r.target.checked?m.add(e.path):m.delete(e.path),m})}}),t.jsxs("span",{children:[t.jsx("strong",{children:e.name}),t.jsx("small",{children:e.path})]}),t.jsxs("em",{children:[Math.ceil(e.sizeBytes/1024)," KB"]})]},e.path))}):null,x.length>0?t.jsx("div",{className:"prompt-import-dialog__folder-warning",children:x.slice(0,3).join(" · ")}):null]})}export{F as PromptImportFolderSection};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PromptImportDialog-CgQ94Gth.js","assets/index-Tjqx6wUV.js","assets/index-Dn2AhL6d.css"])))=>i.map(i=>d[i]);
2
- import{u,j as r,a as n,b as s,S as E,_ as $}from"./index-Tjqx6wUV.js";function A({prompt:a,onClose:c,onLoad:d,onInsert:t,onDelete:m,onToggleFavorite:l}){const{t:o}=u(),p=async()=>{try{await navigator.clipboard.writeText(a.text)}catch{}};return r.jsxs("div",{className:"prompt-detail-modal",onClick:c,children:[r.jsx("div",{className:"prompt-detail-modal__backdrop"}),r.jsxs("div",{className:"prompt-detail-modal__content",onClick:i=>i.stopPropagation(),children:[r.jsxs("div",{className:"prompt-detail-modal__header",children:[r.jsx("h4",{children:a.name||o("promptLibrary.untitled")}),r.jsx("button",{className:"prompt-detail-modal__close",onClick:c,"aria-label":o("common.close"),children:"×"})]}),r.jsxs("div",{className:"prompt-detail-modal__body",children:[r.jsx("div",{className:"prompt-detail-modal__label",children:o("promptLibrary.content")}),r.jsx("div",{className:"prompt-detail-modal__prompt",children:a.text}),a.tags.length>0&&r.jsxs("div",{className:"prompt-detail-modal__tags",children:[r.jsx("div",{className:"prompt-detail-modal__label",children:o("promptLibrary.tags")}),r.jsx("div",{className:"prompt-detail-modal__tag-list",children:a.tags.map(i=>r.jsxs("span",{className:"prompt-detail-modal__tag",children:["#",i]},i))})]})]}),r.jsxs("div",{className:"prompt-detail-modal__footer",children:[r.jsx("button",{className:"prompt-detail-modal__load",onClick:d,children:o("promptLibrary.load")}),r.jsx("button",{className:"prompt-detail-modal__copy",onClick:p,children:o("promptLibrary.copy")}),r.jsxs("button",{className:"prompt-detail-modal__insert",onClick:t,children:["+ ",o("promptLibrary.insert")]}),r.jsx("button",{className:`prompt-detail-modal__favorite${a.isFavorite?" prompt-detail-modal__favorite--on":""}`,onClick:l,children:a.isFavorite?"★ "+o("promptLibrary.unfavorite"):"☆ "+o("promptLibrary.favorite")}),r.jsx("button",{className:"prompt-detail-modal__delete",onClick:m,children:o("common.delete")})]})]})]})}function R({prompt:a,onLoad:c,onInsert:d,onDelete:t,onToggleFavorite:m}){const{t:l}=u(),[o,p]=n.useState(!1),i=a.text.length>45?a.text.slice(0,45)+"...":a.text;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"prompt-library-row",onClick:()=>p(!0),children:[r.jsxs("div",{className:"prompt-library-row__main",children:[r.jsx("div",{className:"prompt-library-row__title",children:a.name||l("promptLibrary.untitled")}),r.jsx("div",{className:"prompt-library-row__preview",children:i})]}),r.jsxs("div",{className:"prompt-library-row__actions",children:[r.jsx("button",{className:"prompt-library-row__insert",onClick:b=>{b.stopPropagation(),d()},title:l("promptLibrary.insert"),"aria-label":l("promptLibrary.insert"),children:"+"}),r.jsx("button",{className:`prompt-library-row__star${a.isFavorite?" prompt-library-row__star--on":""}`,onClick:b=>{b.stopPropagation(),m()},"aria-label":a.isFavorite?l("promptLibrary.unfavorite"):l("promptLibrary.favorite"),children:a.isFavorite?"★":"☆"}),r.jsx("span",{className:"prompt-library-row__chevron",children:"›"})]})]}),o&&r.jsx(A,{prompt:a,onClose:()=>p(!1),onLoad:()=>{c(),p(!1)},onInsert:()=>{d(),p(!1)},onDelete:t,onToggleFavorite:m})]})}const z=n.lazy(()=>$(()=>import("./PromptImportDialog-CgQ94Gth.js"),__vite__mapDeps([0,1,2])).then(a=>({default:a.PromptImportDialog})));function V({variant:a="overlay",forceOpen:c=!1,onRequestClose:d}){const{t}=u(),m=s(e=>e.promptLibraryOpen),l=s(e=>e.togglePromptLibrary),o=s(e=>e.promptLibrary),p=s(e=>e.promptLibraryLoading),i=s(e=>e.loadPromptLibrary),b=s(e=>e.deletePromptFromLibrary),P=s(e=>e.togglePromptFavorite),w=s(e=>e.setPrompt),j=s(e=>e.insertPromptToComposer),k=s(e=>e.clearInsertedPrompts),L=s(e=>e.showToast),[y,F]=n.useState(""),[x,O]=n.useState(!1),[S,N]=n.useState(!1),[f,g]=n.useState(!1),h=c||m,_=d??l;n.useEffect(()=>{h&&i()},[h,i]);const I=n.useCallback(e=>{j({id:e.id,name:e.name||t("promptLibrary.untitled"),text:e.text}),L(t("promptLibrary.inserted")),_()},[_,j,L,t]);if(!h)return null;const C=o.prompts.filter(e=>{if(x&&!e.isFavorite)return!1;if(!y.trim())return!0;const v=y.toLowerCase();return e.name.toLowerCase().includes(v)||e.text.toLowerCase().includes(v)||e.tags.some(T=>T.toLowerCase().includes(v))}),D=r.jsxs("div",{className:"prompt-library-panel__drawer",children:[r.jsxs("div",{className:"prompt-library-panel__header",children:[r.jsx("h3",{children:t("promptLibrary.title")}),r.jsxs("div",{className:"prompt-library-panel__actions",children:[r.jsx("button",{className:"prompt-library-panel__add",onClick:()=>N(e=>!e),title:t("promptLibrary.addNew"),"aria-label":t("promptLibrary.addNew"),children:"+"}),r.jsx("button",{className:"prompt-library-panel__import",onClick:()=>g(!0),title:t("promptLibrary.importFiles"),"aria-label":t("promptLibrary.importFiles"),children:t("promptLibrary.import")}),r.jsx("button",{onClick:_,"aria-label":t("common.close"),children:"×"})]}),S&&r.jsx(E,{text:"",onClose:()=>N(!1)})]}),r.jsxs("div",{className:"prompt-library-panel__search",children:[r.jsx("input",{type:"text",placeholder:t("promptLibrary.search"),value:y,onChange:e=>F(e.target.value)}),r.jsxs("button",{type:"button",className:`prompt-library-panel__filter-toggle${x?" active":""}`,"aria-pressed":x,title:t("promptLibrary.favorites"),onClick:()=>O(e=>!e),children:[r.jsx("span",{"aria-hidden":"true",children:"★"}),r.jsx("span",{children:t("promptLibrary.favorites")})]})]}),p?r.jsx("div",{className:"prompt-library-panel__loading",children:t("common.loading")}):r.jsx("div",{className:"prompt-library-panel__list",children:C.length===0?r.jsx("div",{className:"prompt-library-panel__empty",children:t("promptLibrary.empty")}):C.map(e=>r.jsx(R,{prompt:e,onLoad:()=>{k(),w(e.text),l()},onInsert:()=>I(e),onDelete:()=>b(e.id),onToggleFavorite:()=>P(e.id)},e.id))}),f?r.jsx(n.Suspense,{fallback:null,children:r.jsx(z,{open:f,onClose:()=>g(!1),onImported:i})}):null]});return r.jsxs("div",{className:`prompt-library-panel prompt-library-panel--${a}`,children:[a==="overlay"?r.jsx("div",{className:"prompt-library-panel__backdrop",onClick:_}):null,D]})}export{V as PromptLibraryPanel};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PromptImportDialog-Cy6ZymKG.js","assets/index-ygo6nfqx.js","assets/index-CX3fge8X.css"])))=>i.map(i=>d[i]);
2
+ import{u,j as r,a as n,b as s,S as E,_ as $}from"./index-ygo6nfqx.js";function A({prompt:a,onClose:c,onLoad:d,onInsert:t,onDelete:m,onToggleFavorite:l}){const{t:o}=u(),p=async()=>{try{await navigator.clipboard.writeText(a.text)}catch{}};return r.jsxs("div",{className:"prompt-detail-modal",onClick:c,children:[r.jsx("div",{className:"prompt-detail-modal__backdrop"}),r.jsxs("div",{className:"prompt-detail-modal__content",onClick:i=>i.stopPropagation(),children:[r.jsxs("div",{className:"prompt-detail-modal__header",children:[r.jsx("h4",{children:a.name||o("promptLibrary.untitled")}),r.jsx("button",{className:"prompt-detail-modal__close",onClick:c,"aria-label":o("common.close"),children:"×"})]}),r.jsxs("div",{className:"prompt-detail-modal__body",children:[r.jsx("div",{className:"prompt-detail-modal__label",children:o("promptLibrary.content")}),r.jsx("div",{className:"prompt-detail-modal__prompt",children:a.text}),a.tags.length>0&&r.jsxs("div",{className:"prompt-detail-modal__tags",children:[r.jsx("div",{className:"prompt-detail-modal__label",children:o("promptLibrary.tags")}),r.jsx("div",{className:"prompt-detail-modal__tag-list",children:a.tags.map(i=>r.jsxs("span",{className:"prompt-detail-modal__tag",children:["#",i]},i))})]})]}),r.jsxs("div",{className:"prompt-detail-modal__footer",children:[r.jsx("button",{className:"prompt-detail-modal__load",onClick:d,children:o("promptLibrary.load")}),r.jsx("button",{className:"prompt-detail-modal__copy",onClick:p,children:o("promptLibrary.copy")}),r.jsxs("button",{className:"prompt-detail-modal__insert",onClick:t,children:["+ ",o("promptLibrary.insert")]}),r.jsx("button",{className:`prompt-detail-modal__favorite${a.isFavorite?" prompt-detail-modal__favorite--on":""}`,onClick:l,children:a.isFavorite?"★ "+o("promptLibrary.unfavorite"):"☆ "+o("promptLibrary.favorite")}),r.jsx("button",{className:"prompt-detail-modal__delete",onClick:m,children:o("common.delete")})]})]})]})}function R({prompt:a,onLoad:c,onInsert:d,onDelete:t,onToggleFavorite:m}){const{t:l}=u(),[o,p]=n.useState(!1),i=a.text.length>45?a.text.slice(0,45)+"...":a.text;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"prompt-library-row",onClick:()=>p(!0),children:[r.jsxs("div",{className:"prompt-library-row__main",children:[r.jsx("div",{className:"prompt-library-row__title",children:a.name||l("promptLibrary.untitled")}),r.jsx("div",{className:"prompt-library-row__preview",children:i})]}),r.jsxs("div",{className:"prompt-library-row__actions",children:[r.jsx("button",{className:"prompt-library-row__insert",onClick:b=>{b.stopPropagation(),d()},title:l("promptLibrary.insert"),"aria-label":l("promptLibrary.insert"),children:"+"}),r.jsx("button",{className:`prompt-library-row__star${a.isFavorite?" prompt-library-row__star--on":""}`,onClick:b=>{b.stopPropagation(),m()},"aria-label":a.isFavorite?l("promptLibrary.unfavorite"):l("promptLibrary.favorite"),children:a.isFavorite?"★":"☆"}),r.jsx("span",{className:"prompt-library-row__chevron",children:"›"})]})]}),o&&r.jsx(A,{prompt:a,onClose:()=>p(!1),onLoad:()=>{c(),p(!1)},onInsert:()=>{d(),p(!1)},onDelete:t,onToggleFavorite:m})]})}const z=n.lazy(()=>$(()=>import("./PromptImportDialog-Cy6ZymKG.js"),__vite__mapDeps([0,1,2])).then(a=>({default:a.PromptImportDialog})));function V({variant:a="overlay",forceOpen:c=!1,onRequestClose:d}){const{t}=u(),m=s(e=>e.promptLibraryOpen),l=s(e=>e.togglePromptLibrary),o=s(e=>e.promptLibrary),p=s(e=>e.promptLibraryLoading),i=s(e=>e.loadPromptLibrary),b=s(e=>e.deletePromptFromLibrary),P=s(e=>e.togglePromptFavorite),w=s(e=>e.setPrompt),j=s(e=>e.insertPromptToComposer),k=s(e=>e.clearInsertedPrompts),L=s(e=>e.showToast),[y,F]=n.useState(""),[x,O]=n.useState(!1),[S,N]=n.useState(!1),[f,g]=n.useState(!1),h=c||m,_=d??l;n.useEffect(()=>{h&&i()},[h,i]);const I=n.useCallback(e=>{j({id:e.id,name:e.name||t("promptLibrary.untitled"),text:e.text}),L(t("promptLibrary.inserted")),_()},[_,j,L,t]);if(!h)return null;const C=o.prompts.filter(e=>{if(x&&!e.isFavorite)return!1;if(!y.trim())return!0;const v=y.toLowerCase();return e.name.toLowerCase().includes(v)||e.text.toLowerCase().includes(v)||e.tags.some(T=>T.toLowerCase().includes(v))}),D=r.jsxs("div",{className:"prompt-library-panel__drawer",children:[r.jsxs("div",{className:"prompt-library-panel__header",children:[r.jsx("h3",{children:t("promptLibrary.title")}),r.jsxs("div",{className:"prompt-library-panel__actions",children:[r.jsx("button",{className:"prompt-library-panel__add",onClick:()=>N(e=>!e),title:t("promptLibrary.addNew"),"aria-label":t("promptLibrary.addNew"),children:"+"}),r.jsx("button",{className:"prompt-library-panel__import",onClick:()=>g(!0),title:t("promptLibrary.importFiles"),"aria-label":t("promptLibrary.importFiles"),children:t("promptLibrary.import")}),r.jsx("button",{onClick:_,"aria-label":t("common.close"),children:"×"})]}),S&&r.jsx(E,{text:"",onClose:()=>N(!1)})]}),r.jsxs("div",{className:"prompt-library-panel__search",children:[r.jsx("input",{type:"text",placeholder:t("promptLibrary.search"),value:y,onChange:e=>F(e.target.value)}),r.jsxs("button",{type:"button",className:`prompt-library-panel__filter-toggle${x?" active":""}`,"aria-pressed":x,title:t("promptLibrary.favorites"),onClick:()=>O(e=>!e),children:[r.jsx("span",{"aria-hidden":"true",children:"★"}),r.jsx("span",{children:t("promptLibrary.favorites")})]})]}),p?r.jsx("div",{className:"prompt-library-panel__loading",children:t("common.loading")}):r.jsx("div",{className:"prompt-library-panel__list",children:C.length===0?r.jsx("div",{className:"prompt-library-panel__empty",children:t("promptLibrary.empty")}):C.map(e=>r.jsx(R,{prompt:e,onLoad:()=>{k(),w(e.text),l()},onInsert:()=>I(e),onDelete:()=>b(e.id),onToggleFavorite:()=>P(e.id)},e.id))}),f?r.jsx(n.Suspense,{fallback:null,children:r.jsx(z,{open:f,onClose:()=>g(!1),onImported:i})}):null]});return r.jsxs("div",{className:`prompt-library-panel prompt-library-panel--${a}`,children:[a==="overlay"?r.jsx("div",{className:"prompt-library-panel__backdrop",onClick:_}):null,D]})}export{V as PromptLibraryPanel};
@@ -0,0 +1 @@
1
+ import{a as c,u as j,j as e,h as M,k as I,l as B,m as F,b as y,o as P,p as z,T as D,I as U,W as G}from"./index-ygo6nfqx.js";function W(){const[s,a]=c.useState(null);return c.useEffect(()=>{let r=!1;return(async()=>{try{const i=await fetch("/api/agy/status");if(r)return;const u=await i.json();a(u)}catch{r||a({installed:!1})}})(),()=>{r=!0}},[]),s}function L({provider:s,label:a,placeholder:r,maskedKey:t,source:i,configured:u,onSaved:o}){const{t:d}=j(),[g,n]=c.useState(""),[m,p]=c.useState(!1),[h,b]=c.useState(!1),[l,x]=c.useState(null),[f,N]=c.useState(!1),_=i==="env",v=g.trim().length>0,k=u&&!m&&!v,E=c.useCallback(async()=>{if(v){b(!0),x(null),N(!1);try{const $=await(await fetch(`/api/keys/${s}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:g.trim()})})).json();$.ok?(n(""),p(!1),N(!0),o(),setTimeout(()=>N(!1),3e3)):x($.error||"Failed to save")}catch(w){x(w.message||"Network error")}finally{b(!1)}}},[g,s,v,o]),S=c.useCallback(async()=>{try{if(!(await fetch(`/api/keys/${s}`,{method:"DELETE"})).ok){x("Failed to remove key");return}n(""),p(!1),o()}catch(w){x(w.message||"Failed to remove key")}},[s,o]),T=c.useCallback(()=>{u&&p(!0)},[u]),O=c.useCallback(()=>{v||p(!1)},[v]);return e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("p",{className:"settings-eyebrow",children:d(_?"settings.apiKeys.envSource":"settings.apiKeys.configSource")}),e.jsx("h4",{children:a}),e.jsxs("div",{className:"api-key-input-group",children:[k?e.jsx("input",{type:"text",className:"api-key-input is-masked",value:t||"●●●●●●",readOnly:!0,onFocus:T,onClick:T}):e.jsx("input",{type:"password",className:`api-key-input${l?" is-invalid":""}`,placeholder:r,value:g,onChange:w=>{n(w.target.value),x(null)},onBlur:O,readOnly:!1,autoComplete:"off",autoFocus:m,spellCheck:!1,"data-1p-ignore":!0,"data-lpignore":"true","data-form-type":"other"}),e.jsxs("div",{className:"api-key-actions",children:[e.jsx("button",{type:"button",className:"settings-action-btn",onClick:E,disabled:!v||h,children:d(h?"settings.apiKeys.saving":f?"settings.apiKeys.saved":"settings.apiKeys.save")}),u&&!_&&e.jsx("button",{type:"button",className:"settings-action-btn settings-action-btn--danger",onClick:S,children:d("settings.apiKeys.remove")})]})]}),l&&e.jsx("p",{className:"api-key-error",children:l})]}),e.jsxs("div",{className:`settings-status${u?" is-ok":""}`,children:[e.jsx("span",{"aria-hidden":"true"}),d(u?"settings.apiKeys.status.valid":"settings.apiKeys.status.notConfigured")]})]})}function J({configured:s,maskedKey:a,source:r,onSaved:t}){const{t:i}=j(),[u,o]=c.useState(""),[d,g]=c.useState(!1),[n,m]=c.useState(!1),[p,h]=c.useState(null),[b,l]=c.useState(!1),x=r==="env",f=u.trim().length>0,N=s&&!d&&!f,_=c.useCallback(async()=>{if(f){m(!0),h(null),l(!1);try{const T=await(await fetch("/api/keys/vertex",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceAccountJson:u.trim()})})).json();T.ok?(o(""),g(!1),l(!0),t(),setTimeout(()=>l(!1),3e3)):h(T.error||"Failed to save")}catch(S){h(S.message||"Network error")}finally{m(!1)}}},[u,f,t]),v=c.useCallback(async()=>{try{await fetch("/api/keys/vertex",{method:"DELETE"}),o(""),g(!1),t()}catch{}},[t]),k=c.useCallback(()=>{s&&!x&&g(!0)},[s,x]),E=c.useCallback(()=>{f||g(!1)},[f]);return e.jsxs("div",{className:"vertex-json-section",children:[e.jsx("p",{className:"settings-eyebrow",children:i(x?"settings.apiKeys.envSource":"settings.apiKeys.configSource")}),s&&a&&e.jsx("p",{className:"vertex-project-id",children:a}),N?e.jsx("textarea",{className:"vertex-json-textarea is-masked",value:"●●● (configured — click to replace)",readOnly:!0,onFocus:k,onClick:k}):e.jsx("textarea",{className:`vertex-json-textarea${p?" is-invalid":""}`,placeholder:i("settings.apiKeys.vertex.placeholder"),value:u,onChange:S=>{o(S.target.value),h(null)},onBlur:E,readOnly:x,autoFocus:d,spellCheck:!1,"data-1p-ignore":!0,"data-lpignore":"true","data-form-type":"other"}),e.jsxs("div",{className:"api-key-actions",style:{marginTop:8},children:[!x&&e.jsx("button",{type:"button",className:"settings-action-btn",onClick:_,disabled:!f||n,children:i(n?"settings.apiKeys.saving":b?"settings.apiKeys.saved":"settings.apiKeys.save")}),s&&!x&&e.jsx("button",{type:"button",className:"settings-action-btn settings-action-btn--danger",onClick:v,children:i("settings.apiKeys.remove")})]}),p&&e.jsx("p",{className:"api-key-error",children:p}),e.jsxs("div",{className:`settings-status${s?" is-ok":""}`,style:{marginTop:8},children:[e.jsx("span",{"aria-hidden":"true"}),i(s?"settings.apiKeys.status.valid":"settings.apiKeys.status.notConfigured")]})]})}function V({keyStatus:s,onSaved:a}){const{t:r}=j(),t=s.vertex?.configured??!1,i=s.gemini?.configured??!1,u=s.geminiAuthMode==="vertex"?"vertex":"apikey",[o,d]=c.useState(u),[g,n]=c.useState(!1);c.useEffect(()=>{g||d(u)},[u,g]);const m=p=>{n(!0),d(p),fetch("/api/keys/gemini-auth-mode",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:p})}).catch(()=>{})};return e.jsxs("div",{className:"gemini-key-section",children:[e.jsxs("div",{className:"gemini-key-section__header",children:[e.jsx("h5",{children:r("settings.apiKeys.gemini.label")}),e.jsxs("select",{value:o,onChange:p=>m(p.target.value),className:"gemini-auth-mode-select",children:[e.jsx("option",{value:"apikey",children:r("settings.apiKeys.vertex.authModeApiKey")}),e.jsx("option",{value:"vertex",children:r("settings.apiKeys.vertex.authModeVertex")})]})]}),o==="apikey"?e.jsx(L,{provider:"gemini",label:"",placeholder:r("settings.apiKeys.gemini.placeholder"),maskedKey:s.gemini?.maskedKey??null,source:s.gemini?.source??"none",configured:i,onSaved:a}):e.jsx(J,{configured:t,maskedKey:s.vertex?.maskedKey??null,source:s.vertex?.source??"none",onSaved:a})]})}function R(s,a){return s(a==="ready"?"settings.account.status.ready":a==="auth_required"?"settings.account.status.authRequired":a==="starting"?"settings.account.status.starting":a==="offline"?"settings.account.status.offline":a==="no_image_model"?"settings.account.status.noImageModel":a==="error"?"settings.account.status.error":"settings.account.status.checking")}function H(){const{t:s}=j(),a=M(),r=I(),t=W(),{data:i,error:u}=B(),{data:o,mutate:d}=F(),[g,n]=c.useState(!1),m=i?.apiKeySource==="env"||i?.apiKeySource==="config"||i?.apiKeyValid===!0,p=a?.status==="ready",h=i?.apiKeySource==="config"?s("settings.account.apiSourceConfig"):s("settings.account.apiSourceEnv"),b=i?.apiKeyValid===!0,l=r?.status==="ready";return e.jsxs(e.Fragment,{children:[e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("p",{className:"settings-eyebrow",children:s("settings.account.primaryEyebrow")}),e.jsx("h4",{children:s("settings.account.oauthTitle")}),e.jsx("p",{children:s("settings.account.oauthBody")})]}),e.jsxs("div",{className:`settings-status${p?" is-ok":""}`,children:[e.jsx("span",{"aria-hidden":"true"}),R(s,a?.status)]})]}),m?e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("p",{className:"settings-eyebrow",children:h}),e.jsx("h4",{children:s("settings.account.apiTitle")}),e.jsx("p",{children:s("settings.account.apiBody")})]}),e.jsxs("div",{className:`settings-status${b?" is-ok":" is-muted"}`,children:[e.jsx("span",{"aria-hidden":"true"}),s(u?"settings.account.apiUnknown":b?"settings.account.apiReady":"settings.account.apiUnavailable")]})]}):null,e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("p",{className:"settings-eyebrow",children:s("settings.account.grokEyebrow")}),e.jsx("h4",{children:s("settings.account.grokTitle")}),e.jsx("p",{children:s("settings.account.grokBody")})]}),e.jsxs("div",{className:`settings-status${l?" is-ok":" is-muted"}`,children:[e.jsx("span",{"aria-hidden":"true"}),R(s,r?.status)]})]}),e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("p",{className:"settings-eyebrow",children:s("settings.account.agyEyebrow")}),e.jsx("h4",{children:s("settings.account.agyTitle")}),t?.installed?e.jsx("p",{children:s("settings.account.agyInstalledBody")}):e.jsxs("p",{children:[s("settings.account.agyMissingBody")," ",e.jsx("a",{href:"https://antigravity.google/docs/cli-install",target:"_blank",rel:"noopener noreferrer",children:s("settings.account.agyMissingLink")})]}),e.jsx("p",{style:{fontSize:"12px",color:"var(--text-dim, #888)",marginTop:"4px"},children:s("settings.account.agyFineprint")})]}),e.jsxs("div",{className:`settings-status${t?.installed?" is-ok":" is-muted"}`,children:[e.jsx("span",{"aria-hidden":"true"}),t?.installed?s("settings.account.agyInstalled"):s("settings.account.agyMissing")]})]}),o&&e.jsxs("article",{className:"settings-row settings-accordion",children:[e.jsxs("button",{type:"button",className:"settings-accordion__trigger",onClick:()=>n(!g),children:[e.jsx("h4",{children:s("settings.apiKeys.accordionTitle")}),e.jsx("span",{className:`settings-accordion__arrow${g?" is-open":""}`,children:"▼"})]}),g&&e.jsxs("div",{className:"settings-accordion__body",children:[e.jsx(L,{provider:"openai",label:s("settings.apiKeys.openai.label"),placeholder:s("settings.apiKeys.openai.placeholder"),maskedKey:o.openai?.maskedKey??null,source:o.openai?.source??"none",configured:o.openai?.configured??!1,onSaved:d}),e.jsx(L,{provider:"xai",label:s("settings.apiKeys.xai.label"),placeholder:s("settings.apiKeys.xai.placeholder"),maskedKey:o.xai?.maskedKey??null,source:o.xai?.source??"none",configured:o.xai?.configured??!1,onSaved:d}),e.jsx(V,{keyStatus:o,onSaved:d})]})]})]})}function Q(){const{t:s}=j(),a=y(i=>i.reasoningEffort),r=y(i=>i.setReasoningEffort),t=i=>{r(i.target.value)};return e.jsx("div",{className:"image-model-select image-model-select--settings",children:e.jsx("select",{id:"settings-reasoning-effort",value:a,onChange:t,children:P.map(i=>e.jsx("option",{value:i.value,children:s(i.fullLabelKey)},i.value))})})}const X={ko:"KO",en:"EN"};function Y(){const{t:s,locale:a}=j(),r=y(t=>t.setLocale);return e.jsx("div",{className:"lang-toggle",role:"group","aria-label":s("language.label"),children:z.map(t=>e.jsx("button",{type:"button",className:`lang-toggle__btn ${a===t?"is-active":""}`,onClick:()=>r(t),"aria-pressed":a===t,title:s(`language.${t}`),children:e.jsx("span",{className:"lang-toggle__label",children:X[t]})},t))})}const Z=["system","dark","light"];function ee(){const{t:s}=j(),a=y(n=>n.theme),r=y(n=>n.setTheme),t=y(n=>n.themeFamily),i=y(n=>n.setThemeFamily),[u,o]=c.useState(!1),d=c.useRef(null);c.useEffect(()=>{if(!u)return;const n=p=>{d.current&&(d.current.contains(p.target)||o(!1))},m=p=>{p.key==="Escape"&&o(!1)};return document.addEventListener("mousedown",n),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",n),document.removeEventListener("keydown",m)}},[u]);const g=n=>s(`theme.family.${n}`);return e.jsxs("div",{className:"theme-toggle","aria-label":s("theme.label"),children:[e.jsxs("div",{className:"theme-toggle__row",children:[e.jsx("span",{className:"theme-toggle__label",id:"theme-style-label",children:s("theme.styleLabel")}),e.jsxs("div",{className:"theme-toggle__family",ref:d,children:[e.jsxs("button",{type:"button",className:"theme-toggle__family-trigger","aria-haspopup":"listbox","aria-expanded":u,"aria-labelledby":"theme-style-label",onClick:()=>o(n=>!n),children:[e.jsx("span",{className:`theme-toggle__family-dot theme-toggle__family-dot--${t}`,"aria-hidden":"true"}),e.jsx("span",{className:"theme-toggle__family-name",children:g(t)}),e.jsx("span",{className:"theme-toggle__family-caret","aria-hidden":"true",children:"▾"})]}),u?e.jsx("ul",{className:"theme-toggle__family-menu",role:"listbox","aria-labelledby":"theme-style-label",children:D.map(n=>e.jsx("li",{role:"none",children:e.jsxs("button",{type:"button",role:"option","aria-selected":t===n,className:`theme-toggle__family-option ${t===n?"is-active":""}`,onClick:()=>{i(n),o(!1)},children:[e.jsx("span",{className:`theme-toggle__family-dot theme-toggle__family-dot--${n}`,"aria-hidden":"true"}),e.jsx("span",{className:"theme-toggle__family-name",children:g(n)})]})},n))}):null]})]}),e.jsxs("div",{className:"theme-toggle__row",children:[e.jsx("span",{className:"theme-toggle__label",id:"theme-mode-label",children:s("theme.modeLabel")}),e.jsx("div",{className:"theme-toggle__mode",role:"group","aria-labelledby":"theme-mode-label",children:Z.map(n=>e.jsx("button",{type:"button",className:`theme-toggle__btn ${a===n?"is-active":""}`,onClick:()=>r(n),"aria-pressed":a===n,title:s(`theme.${n}`),children:s(`theme.${n}`)},n))})]})]})}const se=["rail","horizontal","sidebar"];function te(){const{t:s}=j(),a=y(t=>t.historyStripLayout),r=y(t=>t.setHistoryStripLayout);return e.jsx("div",{className:"history-layout-toggle",role:"group","aria-label":s("settings.appearance.historyStripLayoutTitle"),children:se.map(t=>e.jsx("button",{type:"button",className:`history-layout-toggle__btn ${a===t?"is-active":""}`,onClick:()=>r(t),"aria-pressed":a===t,title:s(`settings.appearance.historyStripLayout.${t}`),children:s(`settings.appearance.historyStripLayout.${t}`)},t))})}const ae=[{value:"default",labelKey:"workspace.defaultLabel",descKey:"workspace.defaultDesc"},{value:"prompt-studio",labelKey:"workspace.promptStudioLabel",descKey:"workspace.promptStudioDesc"}];function ne(){const s=y(t=>t.workspaceProfile),a=y(t=>t.setWorkspaceProfile),{t:r}=j();return e.jsx("div",{className:"settings-field",children:e.jsx("select",{id:"workspace-profile-select",className:"settings-field__select",value:s,onChange:t=>a(t.target.value),"aria-label":r("workspace.profileLabel"),children:ae.map(t=>e.jsx("option",{value:t.value,children:r(t.labelKey)},t.value))})})}function ie(s){return s>80?"var(--error, #e53935)":s>50?"var(--warning, #f59e0b)":"var(--info, #3b82f6)"}function re(s){if(!s)return"";const a=new Date(s);return`${a.getMonth()+1}/${a.getDate()} ${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}function le(){return e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:e.jsx("path",{d:"M22.282 9.821a5.985 5.985 0 0 0-.516-4.91 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a5.998 5.998 0 0 0-3.998 2.9 6.049 6.049 0 0 0 .743 7.097 5.98 5.98 0 0 0 .51 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073zM13.26 22.43a4.476 4.476 0 0 1-2.876-1.04l.141-.081 4.779-2.758a.795.795 0 0 0 .392-.681v-6.737l2.02 1.168a.071.071 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494zM3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.759a.771.771 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646zM2.34 7.896a4.485 4.485 0 0 1 2.366-1.973V11.6a.766.766 0 0 0 .388.676l5.815 3.355-2.02 1.168a.076.076 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.872zm16.597 3.855l-5.833-3.387L15.119 7.2a.076.076 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.667zm2.01-3.023l-.141-.085-4.774-2.782a.776.776 0 0 0-.785 0L9.409 9.23V6.897a.066.066 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135l-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.795.795 0 0 0-.393.681zm1.097-2.365l2.602-1.5 2.607 1.5v2.999l-2.597 1.5-2.612-1.5z"})})}function ce(){return e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",fillRule:"evenodd","aria-hidden":"true",children:e.jsx("path",{d:"M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"})})}function A({window:s}){const a=re(s.resetsAt);return e.jsxs("div",{className:"quota-bar",children:[e.jsx("span",{className:"quota-bar__label",children:s.label}),e.jsx("div",{className:"quota-bar__track",children:e.jsx("div",{className:"quota-bar__fill",style:{width:`${Math.min(s.percent,100)}%`,background:ie(s.percent)}})}),e.jsxs("span",{className:"quota-bar__pct",children:[s.percent,"%"]}),a&&e.jsx("span",{className:"quota-bar__reset",children:a})]})}function q({provider:s,onComplete:a}){const[r,t]=c.useState({phase:"idle"}),[i,u]=c.useState(!1),o=c.useRef(!1),d=c.useCallback(async()=>{if(!o.current){o.current=!0,t({phase:"starting"});try{const g=await fetch("/api/auth/switch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:s})});if(!g.ok){const m=await g.json().catch(()=>({error:"Request failed"}));t({phase:"error",error:m.error||`HTTP ${g.status}`});return}const n=await g.json();t({phase:"waiting",...n}),window.open(n.verificationUrl,"_blank")}catch(g){o.current=!1,t({phase:"error",error:g.message})}}},[s]);return c.useEffect(()=>{if(r.phase!=="waiting"||!r.sessionId)return;let g=!1;const n=async()=>{try{const h=await(await fetch(`/api/auth/switch/${r.sessionId}`)).json();if(g)return;if(h.status==="complete"){t({phase:"complete"}),setTimeout(a,1e3);return}if(h.status==="error"||h.status==="expired"){t({phase:"error",error:h.error||h.status});return}}catch{}g||setTimeout(n,3e3)},m=setTimeout(n,3e3);return()=>{g=!0,clearTimeout(m)}},[r.phase,r.sessionId,a]),r.phase==="idle"?e.jsxs("button",{type:"button",className:"settings-action-btn",style:{width:"100%",marginTop:"6px"},onClick:d,children:["Switch ",s==="grok"?"Grok":"Codex"," Account"]}):r.phase==="starting"?e.jsx("div",{className:"quota-card__hint",style:{textAlign:"center",marginTop:"6px"},children:"Starting login..."}):r.phase==="waiting"?e.jsxs("div",{style:{marginTop:"6px",padding:"8px",background:"var(--surface, #f5f5f5)",borderRadius:"6px",fontSize:"12px"},children:[e.jsx("div",{style:{textAlign:"center",marginBottom:"4px"},children:"Enter this code in the opened tab:"}),e.jsx("div",{style:{textAlign:"center",fontSize:"18px",fontWeight:700,fontFamily:"monospace",letterSpacing:"2px",margin:"6px 0"},children:r.userCode}),r.verificationUrl&&e.jsxs("div",{style:{display:"flex",gap:"4px",margin:"6px 0"},children:[e.jsx("button",{type:"button",className:"settings-action-btn",style:{flex:1,fontSize:"11px"},onClick:()=>{o.current=!1,d()},children:"Retry"}),e.jsx("button",{type:"button",className:"settings-action-btn",style:{flex:1,fontSize:"11px"},onClick:()=>{navigator.clipboard?.writeText(r.verificationUrl).then(()=>{u(!0),setTimeout(()=>u(!1),2e3)})},children:i?"Copied!":"Copy link"})]}),e.jsx("div",{style:{textAlign:"center",color:"var(--text-dim, #888)",fontSize:"11px"},children:"Waiting for approval..."})]}):r.phase==="complete"?e.jsx("div",{className:"quota-card__hint",style:{textAlign:"center",marginTop:"6px",color:"var(--success, #22c55e)"},children:"Account switched! Refreshing..."}):e.jsxs("div",{style:{marginTop:"6px"},children:[e.jsx("div",{className:"quota-card__hint",style:{color:"var(--error, #e53935)",marginBottom:"4px"},children:r.error||"Switch failed"}),e.jsx("button",{type:"button",className:"settings-action-btn",style:{width:"100%",fontSize:"11px"},onClick:()=>{o.current=!1,t({phase:"idle"})},children:"Try again"})]})}function oe(){const{t:s}=j(),[a,r]=c.useState(null),[t,i]=c.useState(!0),u=c.useCallback(()=>{i(!0),fetch("/api/quota").then(h=>h.json()).then(r).catch(()=>r(null)).finally(()=>i(!1))},[]);c.useEffect(()=>{const h=setTimeout(u,1500);return()=>clearTimeout(h)},[u]);const o=a?.codex,d=a?.grok,g=o?.windows&&o.windows.length>0,n=d?.windows&&d.windows.length>0,m=o?.account?[o.account.email,o.account.plan].filter(Boolean).join(" · "):null,p=d?.account?[d.account.email,d.account.plan].filter(Boolean).join(" · "):null;return e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("p",{className:"settings-eyebrow",children:s("settings.quota.eyebrow")}),e.jsx("h4",{children:s("settings.quota.title")})]}),e.jsxs("div",{className:"settings-row__control quota-cards",children:[e.jsxs("div",{className:"quota-card",children:[e.jsxs("div",{className:"quota-card__header",children:[e.jsx(le,{}),e.jsx("strong",{children:"Codex"}),m&&e.jsx("span",{className:"quota-card__account",children:m})]}),t?e.jsx("span",{className:"quota-card__loading",children:s("common.loading")}):g?o.windows.map(h=>e.jsx(A,{window:h},h.label)):o?.authenticated===!1?e.jsx("span",{className:"quota-card__hint",children:s("settings.quota.codexNotLoggedIn")}):o?.error?e.jsx("span",{className:"quota-card__hint",children:s("settings.quota.fetchError")}):e.jsx("span",{className:"quota-card__hint",children:s("settings.quota.noData")}),e.jsx(q,{provider:"codex",onComplete:u})]}),e.jsxs("div",{className:"quota-card",children:[e.jsxs("div",{className:"quota-card__header",style:{display:"flex",alignItems:"center"},children:[e.jsx(ce,{}),e.jsx("strong",{children:"Grok"}),p&&e.jsx("span",{className:"quota-card__account",children:p}),d?.billing&&e.jsxs("span",{style:{marginLeft:"auto",fontSize:"11px",color:"var(--text-dim, #888)",whiteSpace:"nowrap"},children:["$",d.billing.usedUsd.toFixed(1),"/$",d.billing.limitUsd]})]}),t?e.jsx("span",{className:"quota-card__loading",children:s("common.loading")}):n?d.windows.map(h=>e.jsx(A,{window:h},h.label)):d?.authenticated===!1?e.jsx("span",{className:"quota-card__hint",children:"Not logged in"}):e.jsx("a",{href:"https://grok.com/?_s=usage",target:"_blank",rel:"noopener noreferrer",className:"settings-action-btn",children:s("settings.quota.grokUsageLink")}),e.jsx(q,{provider:"grok",onComplete:u})]})]})]})}function de(){const{t:s}=j(),[a,r]=c.useState(null);c.useEffect(()=>{fetch("/api/config/grok-planner").then(i=>i.json()).then(r).catch(()=>{})},[]);const t=async i=>{try{await fetch("/api/config/grok-planner",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:i})}),r(u=>u?{...u,model:i}:null)}catch{}};return a?e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("h4",{children:s("settings.grokPlanner.title")}),e.jsx("p",{children:s("settings.grokPlanner.body")})]}),e.jsx("div",{className:"settings-row__control",children:e.jsx("select",{value:a.model,onChange:i=>{t(i.target.value)},"aria-label":s("settings.grokPlanner.title"),children:a.options.map(i=>e.jsx("option",{value:i,children:i},i))})})]}):null}const K=["account","generation","appearance","workspace","language","future"];function C({id:s,setRef:a,children:r}){const{t}=j();return e.jsxs("section",{id:s,ref:i=>a(s,i),className:"settings-section","aria-labelledby":`settings-section-${s}`,children:[e.jsx("header",{className:"settings-section__header",children:e.jsxs("div",{children:[e.jsx("h3",{id:`settings-section-${s}`,children:t(`settings.sections.${s}.title`)}),e.jsx("p",{children:t(`settings.sections.${s}.hint`)})]})}),e.jsx("div",{className:"settings-section__body",children:r})]})}function ge(){const{t:s}=j(),a=y(l=>l.activeSettingsSection),r=y(l=>l.setActiveSettingsSection),t=y(l=>l.closeSettings),i=y(l=>l.openReadinessPopup),u=y(l=>l.galleryDefaultScope),o=y(l=>l.setGalleryDefaultScope),d=y(l=>l.provider),g=c.useRef(null),n=c.useRef(null),m=c.useRef(!1),p=c.useRef({account:null,generation:null,appearance:null,workspace:null,language:null,future:null}),h=(l,x)=>{p.current[l]=x},b=l=>{r(l),m.current=!0,p.current[l]?.scrollIntoView({behavior:"auto",block:"start"}),n.current!==null&&window.clearTimeout(n.current),n.current=window.setTimeout(()=>{m.current=!1,n.current=null},120)};return c.useEffect(()=>{const l=x=>{x.key==="Escape"&&t()};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[t]),c.useEffect(()=>{const l=g.current;if(!l||typeof IntersectionObserver!="function")return;const x=new IntersectionObserver(f=>{if(m.current)return;const _=f.filter(v=>v.isIntersecting).sort((v,k)=>k.intersectionRatio-v.intersectionRatio)[0]?.target.id;_&&K.includes(_)&&r(_)},{root:l,threshold:[.35,.6]});for(const f of K){const N=p.current[f];N&&x.observe(N)}return()=>x.disconnect()},[r]),c.useEffect(()=>()=>{n.current!==null&&window.clearTimeout(n.current)},[]),e.jsx("main",{ref:g,className:"settings-workspace","aria-labelledby":"settings-title",children:e.jsxs("div",{className:"settings-shell",children:[e.jsxs("header",{className:"settings-header",children:[e.jsxs("div",{children:[e.jsx("p",{className:"settings-eyebrow",children:s("settings.eyebrow")}),e.jsx("h2",{id:"settings-title",children:s("settings.title")}),e.jsx("p",{children:s("settings.subtitle")})]}),e.jsx("button",{type:"button",className:"settings-close",onClick:t,"aria-label":s("settings.closeAria"),title:s("settings.closeTitle"),children:"X"})]}),e.jsxs("div",{className:"settings-layout",children:[e.jsx("nav",{className:"settings-nav settings-nav--mobile","aria-label":s("settings.navAria"),children:e.jsx("div",{className:"settings-mobile-nav",role:"list",children:K.map(l=>e.jsxs("button",{type:"button",className:`settings-mobile-nav__item${a===l?" is-active":""}`,onClick:()=>b(l),"aria-current":a===l?"true":void 0,children:[e.jsx("span",{children:s(`settings.sections.${l}.title`)}),e.jsx("small",{children:s(`settings.sections.${l}.hint`)})]},l))})}),e.jsx("nav",{className:"settings-nav","aria-label":s("settings.navAria"),children:K.map(l=>e.jsxs("button",{type:"button",className:`settings-nav__item${a===l?" is-active":""}`,onClick:()=>b(l),"aria-label":s("settings.jumpTo",{section:s(`settings.sections.${l}.title`)}),children:[e.jsx("span",{children:s(`settings.sections.${l}.title`)}),e.jsx("small",{children:s(`settings.sections.${l}.hint`)})]},l))}),e.jsxs("section",{className:"settings-content","aria-label":s("settings.contentAria"),children:[e.jsxs(C,{id:"account",setRef:h,children:[e.jsx(H,{}),e.jsx(oe,{}),e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("h4",{children:s("readiness.settingsTitle")}),e.jsx("p",{children:s("readiness.settingsBody")})]}),e.jsx("div",{className:"settings-row__control",children:e.jsx("button",{type:"button",className:"settings-action-btn",onClick:i,children:s("readiness.open")})})]})]}),e.jsxs(C,{id:"generation",setRef:h,children:[e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("h4",{children:s("settings.imageModel.title")}),e.jsx("p",{children:s("settings.imageModel.body")}),e.jsx("p",{className:"settings-row__microcopy",children:s("settings.imageModel.unsupportedHelp")})]}),e.jsx("div",{className:"settings-row__control",children:e.jsx(U,{variant:"settings"})})]}),d==="grok"?e.jsxs(e.Fragment,{children:[e.jsx("article",{className:"settings-row",children:e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("h4",{children:s("settings.grokCompatibility.title")}),e.jsx("p",{children:s("settings.grokCompatibility.body")})]})}),e.jsx(de,{})]}):d==="agy"||d==="gemini-api"?e.jsx("article",{className:"settings-row",children:e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("h4",{children:s(d==="gemini-api"?"provider.geminiApiCompatTitle":"provider.agyCompatTitle")}),e.jsx("p",{children:s(d==="gemini-api"?"provider.geminiApiCompatBodyLong":"provider.agyCompatBodyLong")})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("h4",{children:s("settings.reasoning.title")}),e.jsx("p",{children:s("settings.reasoning.body")})]}),e.jsx("div",{className:"settings-row__control",children:e.jsx(Q,{})})]}),e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("h4",{children:s("settings.webSearch.title")}),e.jsx("p",{children:s("settings.webSearch.body")})]}),e.jsx("div",{className:"settings-row__control",children:e.jsx(G,{})})]})]}),e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("h4",{children:s("settings.gallery.defaultScopeTitle")}),e.jsx("p",{children:s("settings.gallery.defaultScopeBody")})]}),e.jsx("div",{className:"settings-row__control",children:e.jsxs("select",{value:u,onChange:l=>o(l.target.value),"aria-label":s("settings.gallery.defaultScopeTitle"),children:[e.jsx("option",{value:"current-session",children:s("gallery.scope.current")}),e.jsx("option",{value:"all",children:s("gallery.scope.all")})]})})]})]}),e.jsxs(C,{id:"appearance",setRef:h,children:[e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("h4",{children:s("settings.appearance.themeTitle")}),e.jsx("p",{children:s("settings.appearance.themeBody")})]}),e.jsx("div",{className:"settings-row__control",children:e.jsx(ee,{})})]}),e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("h4",{children:s("settings.appearance.historyStripLayoutTitle")}),e.jsx("p",{children:s("settings.appearance.historyStripLayoutBody")})]}),e.jsx("div",{className:"settings-row__control",children:e.jsx(te,{})})]})]}),e.jsx(C,{id:"workspace",setRef:h,children:e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("h4",{children:s("workspace.sectionTitle")}),e.jsx("p",{children:s("workspace.sectionBody")})]}),e.jsx("div",{className:"settings-row__control",children:e.jsx(ne,{})})]})}),e.jsx(C,{id:"language",setRef:h,children:e.jsxs("article",{className:"settings-row",children:[e.jsxs("div",{className:"settings-row__copy",children:[e.jsx("h4",{children:s("settings.language.title")}),e.jsx("p",{children:s("settings.language.body")})]}),e.jsx("div",{className:"settings-row__control",children:e.jsx(Y,{})})]})}),e.jsx(C,{id:"future",setRef:h,children:e.jsxs("article",{className:"settings-note",children:[e.jsx("h4",{children:s("settings.future.title")}),e.jsx("p",{children:s("settings.future.body")})]})})]})]})]})})}export{ge as SettingsWorkspace};
@@ -0,0 +1,4 @@
1
+ import{a as c,j as o,u as ye,f as on,w as sn,x as ln,y as cn,z as Bt,B as me,C as un,D as jt,E as dn,b as j,F as hn,c as fn,G as pn,H as mn,J as vn}from"./index-ygo6nfqx.js";const De=2,Le=1e-6;function bn({paths:e,points:t,radius:n,makeId:a=()=>crypto.randomUUID()}){if(e.length===0||t.length===0||n<=0)return{paths:e,changed:!1};let r=!1;const l=[];for(const s of e){const i=gn(s,t,n,a);(i.length!==1||i[0]!==s)&&(r=!0),l.push(...i)}return{paths:l,changed:r}}function gn(e,t,n,a=()=>crypto.randomUUID()){if(e.points.length<De||t.length===0||n<=0)return[e];const r=[];let l=je(e.points[0],t,n)?[]:[e.points[0]];for(let i=1;i<e.points.length;i+=1){const d=e.points[i-1],u=e.points[i],b=je(u,t,n),f=xn(d,u,t,n);if(f){l.length===0&&!je(d,t,n)&&(l=[d]),l.length>0&&f.leftT>Le&&ft(l,Te(d,u,f.leftT)),l.length>=De&&r.push(l),l=[],f.rightT<1-Le&&!b&&(l=[Te(d,u,f.rightT),u]);continue}if(b){l.length>=De&&r.push(l),l=[];continue}l.length===0&&!je(d,t,n)&&(l=[d]),ft(l,u)}if(l.length>=De&&r.push(l),r.length===0)return[];if(r.length===1&&r[0].length===e.points.length)return[e];const s=e.tool==="arrow"?r.length-1:-1;return r.map((i,d)=>({...e,id:d===0?e.id:a(),tool:e.tool==="arrow"&&d!==s?"pen":e.tool,points:i}))}function je(e,t,n){if(t.length===1)return xe(e,t[0])<=n;for(let a=1;a<t.length;a+=1)if(yn(e,t[a-1],t[a])<=n)return!0;return!1}function xe(e,t){const n=e.x-t.x,a=e.y-t.y;return Math.sqrt(n*n+a*a)}function xn(e,t,n,a){const r=xe(e,t);if(r<=Le)return je(e,n,a)?{leftT:0,rightT:1}:null;let l=null,s=Number.POSITIVE_INFINITY;for(const d of n){const u=ht(d,e,t),b=Te(e,t,u),f=xe(d,b);f<s&&(s=f,l=u)}for(let d=1;d<n.length;d+=1){const u=[0,.25,.5,.75,1];for(const b of u){const f=Te(n[d-1],n[d],b),_=ht(f,e,t),B=Te(e,t,_),A=xe(f,B);A<s&&(s=A,l=_)}}if(l===null||s>a)return null;const i=Math.max(a/r,.01);return{leftT:Math.max(0,l-i),rightT:Math.min(1,l+i)}}function ht(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,i=a*a+r*r;return i===0?0:Math.max(0,Math.min(1,(l*a+s*r)/i))}function Te(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function ft(e,t){const n=e.at(-1);(!n||xe(n,t)>Le)&&e.push(t)}function yn(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,i=a*a+r*r;if(i===0)return xe(e,t);const d=Math.max(0,Math.min(1,(l*a+s*r)/i));return xe(e,{x:t.x+d*a,y:t.y+d*r})}function st(e,t){return`${e}:${t}`}function lt(e){const t=e.indexOf(":");if(t<=0)return null;const n=e.slice(0,t),a=e.slice(t+1);return!a||n!=="path"&&n!=="box"&&n!=="memo"?null:{kind:n,id:a}}function Tt(e){return st("path",e.id)}function Pt(e){return st("box",e.id)}function Dt(e){return st("memo",e.id)}function pe(e,t,n){const a=lt(e);return a?.kind===t&&a.id===n}const At="ima2.canvas.annotationStyle.v1",It=["#ef4444","#f97316","#eab308","#22c55e","#38bdf8","#6366f1","#a855f7","#111827","#ffffff"],Nt=[2,3,5,8],Ee={color:"#ef4444",strokeWidth:3};function kn(){if(typeof window>"u")return Ee;try{const e=window.localStorage.getItem(At);if(!e)return Ee;const t=JSON.parse(e),n=typeof t.color=="string"&&It.includes(t.color)?t.color:Ee.color,a=typeof t.strokeWidth=="number"&&Nt.includes(t.strokeWidth)?t.strokeWidth:Ee.strokeWidth;return{color:n,strokeWidth:a}}catch{return Ee}}function wn(e){if(!(typeof window>"u"))try{window.localStorage.setItem(At,JSON.stringify(e))}catch{}}const pt=kn(),tt={activeTool:"select",toolColor:pt.color,strokeWidth:pt.strokeWidth,paths:[],boxes:[],memos:[],activeMemoId:null,activePath:null,activeBox:null,eraserMode:"object",activeEraserStroke:null,eraserBaseline:null,selectionBox:null,selectedIds:[],past:[],future:[],memoBaseline:null,moveBaseline:null,isDirty:!1};function ge(e){return{paths:e.paths,boxes:e.boxes,memos:e.memos}}function be(e){return{...e,past:[...e.past.slice(-49),ge(e)],future:[]}}function Ge(e,t){return{...e,past:[...e.past.slice(-49),t],future:[]}}function Cn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function mt(e,t){return{...e,...t,activeMemoId:null,activePath:null,activeBox:null,selectionBox:null,selectedIds:[],isDirty:!0}}function _n(e,t,n){const{start:a,current:r}=e,l=Math.min(a.x,r.x),s=Math.min(a.y,r.y),i=Math.abs(r.x-a.x),d=Math.abs(r.y-a.y);return i<.01||d<.01?null:{id:crypto.randomUUID(),x:l,y:s,width:i,height:d,color:t,strokeWidth:n}}function Mn(e,t){return{...e,x:Math.min(1-e.width,Math.max(0,e.x+t.x)),y:Math.min(1-e.height,Math.max(0,e.y+t.y))}}function Ze(e,t){return{x:Math.min(1,Math.max(0,e.x+t.x)),y:Math.min(1,Math.max(0,e.y+t.y))}}function En(e,t){switch(t.type){case"SET_TOOL":return{...e,activeTool:t.tool};case"SET_ERASER_MODE":return{...e,eraserMode:t.mode};case"SET_STYLE":return{...e,toolColor:t.style.color,strokeWidth:t.style.strokeWidth};case"START_PATH":return{...e,isDirty:!0,activePath:{id:crypto.randomUUID(),tool:e.activeTool,points:[t.point],color:e.toolColor,strokeWidth:e.strokeWidth}};case"ADD_POINT":return e.activePath?{...e,activePath:{...e.activePath,points:[...e.activePath.points,t.point]}}:e;case"END_PATH":return!e.activePath||e.activePath.points.length<2?{...e,activePath:null}:{...be(e),isDirty:!0,paths:[...e.paths,e.activePath],activePath:null};case"START_BOX":return{...e,isDirty:!0,activeBox:{start:t.point,current:t.point}};case"UPDATE_BOX":return e.activeBox?{...e,activeBox:{...e.activeBox,current:t.point}}:e;case"END_BOX":{if(!e.activeBox)return e;const n=_n(e.activeBox,e.toolColor,e.strokeWidth);return n?{...be(e),isDirty:!0,boxes:[...e.boxes,n],activeBox:null}:{...e,activeBox:null}}case"CREATE_MEMO":{const n=crypto.randomUUID(),a={id:n,x:t.point.x,y:t.point.y,text:"",color:e.toolColor};return{...be(e),isDirty:!0,memos:[...e.memos,a],activeMemoId:n}}case"UPDATE_MEMO":return{...e,isDirty:!0,memos:e.memos.map(n=>n.id===t.id?{...n,text:t.text}:n)};case"COMMIT_MEMO_EDIT":return e.memoBaseline?Cn(e.memoBaseline,ge(e))?{...e,memoBaseline:null,activeMemoId:null}:{...Ge(e,e.memoBaseline),memoBaseline:null,activeMemoId:null,isDirty:!0}:{...e,activeMemoId:null};case"DELETE_MEMO":return{...be(e),isDirty:!0,memos:e.memos.filter(n=>n.id!==t.id),activeMemoId:e.activeMemoId===t.id?null:e.activeMemoId,selectedIds:e.selectedIds.filter(n=>!pe(n,"memo",t.id))};case"FOCUS_MEMO":return{...e,activeMemoId:t.id,memoBaseline:t.id&&e.activeMemoId!==t.id&&!e.memoBaseline?ge(e):e.memoBaseline};case"CLEAR":return{...be(e),isDirty:!0,paths:[],boxes:[],memos:[],activeMemoId:null,activePath:null,activeBox:null,selectionBox:null,selectedIds:[]};case"LOAD":return{...tt,activeTool:e.activeTool,eraserMode:e.eraserMode,toolColor:e.toolColor,strokeWidth:e.strokeWidth,...t.payload};case"MARK_SAVED":return{...e,isDirty:!1};case"RESET_LOCAL":return{...tt,activeTool:e.activeTool,eraserMode:e.eraserMode,toolColor:e.toolColor,strokeWidth:e.strokeWidth};case"UNDO":{const n=e.past.at(-1);return n?{...mt(e,n),past:e.past.slice(0,-1),future:[ge(e),...e.future]}:e}case"REDO":{const n=e.future[0];return n?{...mt(e,n),past:[...e.past.slice(-49),ge(e)],future:e.future.slice(1)}:e}case"SELECT_ONE":return{...e,selectedIds:[t.id],selectionBox:null};case"TOGGLE_SELECTED":return{...e,selectedIds:e.selectedIds.includes(t.id)?e.selectedIds.filter(n=>n!==t.id):[...e.selectedIds,t.id],selectionBox:null};case"CLEAR_SELECTION":return{...e,selectedIds:[],selectionBox:null};case"DELETE_SELECTED":return e.selectedIds.length===0?e:{...be(e),isDirty:!0,paths:e.paths.filter(n=>!e.selectedIds.some(a=>pe(a,"path",n.id))),boxes:e.boxes.filter(n=>!e.selectedIds.some(a=>pe(a,"box",n.id))),memos:e.memos.filter(n=>!e.selectedIds.some(a=>pe(a,"memo",n.id))),selectedIds:[]};case"MOVE_SELECTED":return e.selectedIds.length===0?e:{...e,isDirty:!0,paths:e.paths.map(n=>e.selectedIds.some(a=>pe(a,"path",n.id))?{...n,points:n.points.map(a=>Ze(a,t.delta))}:n),boxes:e.boxes.map(n=>e.selectedIds.some(a=>pe(a,"box",n.id))?Mn(n,t.delta):n),memos:e.memos.map(n=>e.selectedIds.some(a=>pe(a,"memo",n.id))?{...n,x:Ze(n,t.delta).x,y:Ze(n,t.delta).y}:n)};case"START_SELECTED_MOVE":return{...e,moveBaseline:ge(e)};case"COMMIT_SELECTED_MOVE":return e.moveBaseline?{...Ge(e,e.moveBaseline),moveBaseline:null,isDirty:!0}:e;case"START_SELECTION_BOX":return{...e,selectionBox:{start:t.point,current:t.point},selectedIds:[]};case"UPDATE_SELECTION_BOX":return e.selectionBox?{...e,selectionBox:{...e.selectionBox,current:t.point}}:e;case"END_SELECTION_BOX":return{...e,selectionBox:null,selectedIds:t.ids};case"ERASE_OBJECT":{const n=lt(t.id);return!n||!(n.kind==="path"?e.paths.some(r=>r.id===n.id):n.kind==="box"?e.boxes.some(r=>r.id===n.id):e.memos.some(r=>r.id===n.id))?e:{...be(e),isDirty:!0,paths:n.kind==="path"?e.paths.filter(r=>r.id!==n.id):e.paths,boxes:n.kind==="box"?e.boxes.filter(r=>r.id!==n.id):e.boxes,memos:n.kind==="memo"?e.memos.filter(r=>r.id!==n.id):e.memos,selectedIds:e.selectedIds.filter(r=>r!==t.id)}}case"START_ERASER_STROKE":return{...e,activeEraserStroke:{points:[t.point],radius:.018},eraserBaseline:ge(e)};case"UPDATE_ERASER_STROKE":return e.activeEraserStroke?{...e,activeEraserStroke:{...e.activeEraserStroke,points:[...e.activeEraserStroke.points,t.point]}}:e;case"END_ERASER_STROKE":{if(!e.activeEraserStroke||!e.eraserBaseline)return{...e,activeEraserStroke:null,eraserBaseline:null};const n=bn({paths:e.paths,points:e.activeEraserStroke.points,radius:e.activeEraserStroke.radius});return n.changed?{...Ge(e,e.eraserBaseline),paths:n.paths,activeEraserStroke:null,eraserBaseline:null,selectedIds:[],isDirty:!0}:{...e,activeEraserStroke:null,eraserBaseline:null}}default:return e}}function Sn(){const[e,t]=c.useReducer(En,tt),n=c.useMemo(()=>e.paths.length>0||e.boxes.length>0||e.memos.length>0,[e.paths.length,e.boxes.length,e.memos.length]),a=e.past.length>0,r=e.future.length>0,l=c.useCallback(p=>t({type:"SET_TOOL",tool:p}),[]),s=c.useCallback(p=>{wn(p),t({type:"SET_STYLE",style:p})},[]),i=c.useCallback(()=>t({type:"CLEAR"}),[]),d=c.useCallback(p=>t({type:"LOAD",payload:p}),[]),u=c.useCallback(()=>t({type:"MARK_SAVED"}),[]),b=c.useCallback(()=>t({type:"RESET_LOCAL"}),[]),f=c.useCallback(()=>t({type:"UNDO"}),[]),_=c.useCallback(()=>t({type:"REDO"}),[]),B=c.useCallback(()=>t({type:"COMMIT_MEMO_EDIT"}),[]),A=c.useCallback(()=>t({type:"START_SELECTED_MOVE"}),[]),O=c.useCallback(()=>t({type:"COMMIT_SELECTED_MOVE"}),[]),T=c.useCallback(p=>{e.activeTool==="pen"||e.activeTool==="arrow"?t({type:"START_PATH",point:p}):e.activeTool==="box"&&t({type:"START_BOX",point:p})},[e.activeTool]),N=c.useCallback(p=>{e.activePath?t({type:"ADD_POINT",point:p}):e.activeBox&&t({type:"UPDATE_BOX",point:p})},[e.activePath,e.activeBox]),m=c.useCallback(()=>{e.activePath?t({type:"END_PATH"}):e.activeBox&&t({type:"END_BOX"})},[e.activePath,e.activeBox]),C=c.useCallback(p=>t({type:"CREATE_MEMO",point:p}),[]),E=c.useCallback((p,R)=>t({type:"UPDATE_MEMO",id:p,text:R}),[]),y=c.useCallback(p=>t({type:"DELETE_MEMO",id:p}),[]),v=c.useCallback(p=>t({type:"FOCUS_MEMO",id:p}),[]),Z=c.useCallback(p=>t({type:"SET_ERASER_MODE",mode:p}),[]),I=c.useCallback(p=>t({type:"SELECT_ONE",id:p}),[]),U=c.useCallback(p=>t({type:"TOGGLE_SELECTED",id:p}),[]),g=c.useCallback(()=>t({type:"CLEAR_SELECTION"}),[]),S=c.useCallback(()=>t({type:"DELETE_SELECTED"}),[]),D=c.useCallback(p=>t({type:"MOVE_SELECTED",delta:p}),[]),P=c.useCallback(p=>t({type:"START_SELECTION_BOX",point:p}),[]),V=c.useCallback(p=>t({type:"UPDATE_SELECTION_BOX",point:p}),[]),Y=c.useCallback(p=>t({type:"END_SELECTION_BOX",ids:p}),[]),te=c.useCallback(p=>t({type:"ERASE_OBJECT",id:p}),[]),ne=c.useCallback(p=>t({type:"START_ERASER_STROKE",point:p}),[]),se=c.useCallback(p=>t({type:"UPDATE_ERASER_STROKE",point:p}),[]),ue=c.useCallback(()=>t({type:"END_ERASER_STROKE"}),[]),L=c.useCallback(()=>({paths:e.paths,boxes:e.boxes,memos:e.memos}),[e.paths,e.boxes,e.memos]);return{...e,canUndo:a,canRedo:r,hasAnnotations:n,setTool:l,setStyle:s,setEraserMode:Z,startDrawing:T,moveDrawing:N,endDrawing:m,createMemo:C,updateMemo:E,commitMemoEdit:B,deleteMemo:y,focusMemo:v,clear:i,load:d,toPayload:L,markSaved:u,resetLocal:b,undo:f,redo:_,selectOne:I,toggleSelected:U,clearSelection:g,deleteSelected:S,moveSelected:D,startSelectedMove:A,commitSelectedMove:O,startSelectionBox:P,updateSelectionBox:V,endSelectionBox:Y,eraseObjectAtPoint:te,startEraserStroke:ne,updateEraserStroke:se,endEraserStroke:ue}}function Ae(e,t){return{x:e.x*t.width,y:e.y*t.height}}function nt(e,t,n){if(t.points.length<2)return;const a=Ae(t.points[0],n);e.save(),e.beginPath(),e.strokeStyle=t.color,e.lineWidth=t.strokeWidth,e.lineCap="round",e.lineJoin="round",e.moveTo(a.x,a.y);for(const r of t.points.slice(1)){const l=Ae(r,n);e.lineTo(l.x,l.y)}if(e.stroke(),t.tool==="arrow"){const r=Ae(t.points[t.points.length-1],n),l=Ae(t.points[t.points.length-2],n);Tn(e,l,r,t.color,t.strokeWidth)}e.restore()}function at(e,t,n,a){const r="start"in t?{x:Math.min(t.start.x,t.current.x),y:Math.min(t.start.y,t.current.y),width:Math.abs(t.current.x-t.start.x),height:Math.abs(t.current.y-t.start.y),color:"#64c8ff",strokeWidth:2}:t;e.save(),e.strokeStyle=r.color,e.lineWidth=a==="active"?Math.max(2,r.strokeWidth):r.strokeWidth,a==="active"&&e.setLineDash([8,6]),e.strokeRect(r.x*n.width,r.y*n.height,r.width*n.width,r.height*n.height),e.restore()}function Bn(e,t,n){const a=t.x*n.width,r=t.y*n.height,l=Math.min(260,Math.max(150,n.width*.22)),s=12,i=18;e.save(),e.font="14px sans-serif";const d=Pn(e,t.text.trim()||" ",l-s*2),u=Math.max(52,s*2+d.length*i);e.fillStyle="rgba(255, 246, 179, 0.96)",e.strokeStyle="rgba(44, 37, 12, 0.28)",e.lineWidth=1,Dn(e,a,r,l,u,8),e.fill(),e.stroke(),e.fillStyle="#2f2a13",e.textBaseline="top",d.forEach((b,f)=>{e.fillText(b,a+s,r+s+f*i)}),e.restore()}function jn(e,t){const n=lt(e);if(!n)return null;if(n.kind==="box")return t.boxes.find(u=>u.id===n.id)??null;const a=n.kind==="memo"?t.memos.find(u=>u.id===n.id):null;if(a)return{id:a.id,x:a.x,y:a.y,width:.18,height:.12,color:a.color,strokeWidth:1};if(n.kind!=="path")return null;const r=t.paths.find(u=>u.id===n.id);if(!r||r.points.length===0)return null;const l=r.points.map(u=>u.x),s=r.points.map(u=>u.y),i=Math.min(...l),d=Math.min(...s);return{id:r.id,x:i,y:d,width:Math.max(.01,Math.max(...l)-i),height:Math.max(.01,Math.max(...s)-d),color:r.color,strokeWidth:r.strokeWidth}}function vt(e,t,n){const a="start"in t?{x:Math.min(t.start.x,t.current.x),y:Math.min(t.start.y,t.current.y),width:Math.abs(t.current.x-t.start.x),height:Math.abs(t.current.y-t.start.y)}:t;e.save(),e.strokeStyle="#64c8ff",e.lineWidth=2,e.setLineDash([5,5]),e.strokeRect(a.x*n.width,a.y*n.height,a.width*n.width,a.height*n.height),e.restore()}function Tn(e,t,n,a,r){const l=Math.atan2(n.y-t.y,n.x-t.x),s=Math.max(12,r*4),i=Math.PI/7;e.save(),e.fillStyle=a,e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x-s*Math.cos(l-i),n.y-s*Math.sin(l-i)),e.lineTo(n.x-s*Math.cos(l+i),n.y-s*Math.sin(l+i)),e.closePath(),e.fill(),e.restore()}function Pn(e,t,n){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const r=[];let l="";for(const s of a){const i=l?`${l} ${s}`:s;if(e.measureText(i).width<=n||l===""){l=i;continue}r.push(l),l=s}return l&&r.push(l),r}function Dn(e,t,n,a,r,l){const s=Math.min(l,a/2,r/2);e.beginPath(),e.moveTo(t+s,n),e.lineTo(t+a-s,n),e.quadraticCurveTo(t+a,n,t+a,n+s),e.lineTo(t+a,n+r-s),e.quadraticCurveTo(t+a,n+r,t+a-s,n+r),e.lineTo(t+s,n+r),e.quadraticCurveTo(t,n+r,t,n+r-s),e.lineTo(t,n+s),e.quadraticCurveTo(t,n,t+s,n),e.closePath()}function An({paths:e,boxes:t,memos:n=[],selectedIds:a=[],selectionBox:r=null,activePath:l,activeBox:s}){const i=c.useRef(null);return c.useEffect(()=>{const d=i.current;if(!d)return;const u=d.getBoundingClientRect(),b=window.devicePixelRatio||1;d.width=Math.max(1,Math.round(u.width*b)),d.height=Math.max(1,Math.round(u.height*b));const f=d.getContext("2d");if(!f)return;f.setTransform(b,0,0,b,0,0),f.clearRect(0,0,u.width,u.height);const _={width:u.width,height:u.height};for(const B of e)nt(f,B,_);for(const B of t)at(f,B,_,"committed");for(const B of a){const A=jn(B,{paths:e,boxes:t,memos:n});A&&vt(f,A,_)}r&&vt(f,r,_),l&&nt(f,l,_),s&&at(f,s,_,"active")},[e,t,n,a,r,l,s]),o.jsx("canvas",{ref:i,className:"canvas-annotation-layer","aria-hidden":"true"})}function Ie(e){e.stopPropagation()}function In({memos:e,activeMemoId:t,onUpdate:n,onDelete:a,onFocus:r,onCommit:l}){return o.jsx("div",{className:"canvas-memo-overlay",children:e.map(s=>o.jsx("textarea",{className:`canvas-memo${t===s.id?" canvas-memo--active":""}`,value:s.text,style:{left:`${s.x*100}%`,top:`${s.y*100}%`},autoFocus:t===s.id,onFocus:()=>r(s.id),onPointerDown:Ie,onPointerMove:Ie,onPointerUp:Ie,onPointerCancel:Ie,onChange:i=>n(s.id,i.currentTarget.value),onBlur:()=>{l?.(),s.text.trim()===""&&a(s.id)},"aria-label":"Canvas memo"},s.id))})}function Nn({annotationFrameRef:e,imageElementRef:t,frameClassName:n,frameStyle:a,imageKey:r,imageSrc:l,fallbackImage:s,alt:i,canvasOpen:d,maskOverlayUrl:u,cleanupLayer:b,annotations:f,onOpenCanvas:_,onPointerDown:B,onPointerMove:A,onPointerUp:O,onPointerLeave:T}){return o.jsxs("div",{ref:e,className:n,onPointerDown:B,onPointerMove:A,onPointerUp:O,onPointerCancel:O,onPointerLeave:T,style:a,children:[o.jsx("img",{ref:t,className:"result-img",src:l??s,alt:i,decoding:"async",onDoubleClick:N=>{N.stopPropagation(),_()}},r),d&&u?o.jsx("img",{className:"canvas-background-cleanup-mask",src:u,alt:"","aria-hidden":"true",decoding:"async"}):null,d?b:null,d&&o.jsxs(o.Fragment,{children:[o.jsx(An,{paths:f.paths,boxes:f.boxes,memos:f.memos,selectedIds:f.selectedIds,selectionBox:f.selectionBox,activePath:f.activePath,activeBox:f.activeBox}),o.jsx(In,{memos:f.memos,activeMemoId:f.activeMemoId,onUpdate:f.updateMemo,onDelete:f.deleteMemo,onFocus:f.focusMemo,onCommit:f.commitMemoEdit})]})]})}function Rn(e){return`${e.x*100} ${e.y*100}`}function Ln(e){return e.map(Rn).join(" ")}function On({seeds:e,brushStrokes:t,brushCursor:n,brushRadius:a,active:r}){if(!r&&e.length===0&&t.length===0)return null;const l=a*100;return o.jsxs("svg",{className:"canvas-cleanup-overlay",viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",children:[t.map(s=>o.jsx("polyline",{className:`canvas-cleanup-overlay__stroke canvas-cleanup-overlay__stroke--${s.intent}`,points:Ln(s.points),strokeWidth:Math.max(.3,s.radius*200),vectorEffect:"non-scaling-stroke"},s.id)),r&&n?o.jsx("circle",{className:"canvas-cleanup-cursor",cx:n.x*100,cy:n.y*100,r:Math.max(.6,l),vectorEffect:"non-scaling-stroke"}):null]})}function $n({mode:e,matteColor:t,onModeChange:n,onMatteColorChange:a}){const{t:r}=ye();return o.jsxs("div",{className:"canvas-toolbar__bg",role:"group","aria-label":r("canvas.toolbar.bgGroup"),children:[o.jsx("button",{type:"button",className:`canvas-toolbar__bg-tab${e==="alpha"?" active":""}`,onClick:()=>n("alpha"),children:r("canvas.toolbar.bgAlpha")}),o.jsx("button",{type:"button",className:`canvas-toolbar__bg-tab${e==="matte"?" active":""}`,onClick:()=>n("matte"),children:r("canvas.toolbar.bgMatte")}),e==="matte"?o.jsx("input",{type:"color","aria-label":r("canvas.toolbar.bgMatteColor"),value:t,onChange:l=>a(l.target.value)}):null]})}function bt({label:e,value:t,options:n,onChange:a}){return o.jsxs("div",{className:"canvas-toolbar__segmented-row",children:[o.jsx("span",{className:"canvas-toolbar__segmented-label",children:e}),o.jsx("div",{className:"canvas-toolbar__segmented",role:"group","aria-label":e,children:n.map(r=>o.jsx("button",{type:"button",className:"canvas-toolbar__segmented-button","data-value":r.value,"aria-pressed":t===r.value,onClick:()=>a(r.value),children:r.label},r.value))})]})}function Un({seedCount:e,tolerance:t,stats:n,hasPreview:a,isPickingSeed:r,intent:l,tool:s,brushRadius:i,isPreviewing:d,isApplying:u,keepOpen:b,disabled:f,onAutoSample:_,onPickSeed:B,onIntentChange:A,onToolChange:O,onBrushRadiusChange:T,onToleranceChange:N,onPreview:m,onApply:C,onReset:E}){const{t:y}=ye(),[v,Z]=c.useState(!1),I=c.useRef(null),U=n?Math.round(n.removedPercent*1e3)/10:0,g=r||s==="brush";return c.useEffect(()=>{if(!v)return;const S=D=>{b||I.current?.contains(D.target)||Z(!1)};return window.addEventListener("pointerdown",S),()=>window.removeEventListener("pointerdown",S)},[b,v]),o.jsxs("div",{className:"canvas-toolbar__cleanup",ref:I,children:[o.jsx("button",{type:"button",className:`canvas-toolbar__button${v||a?" canvas-toolbar__button--active":""}`,onClick:()=>Z(S=>!S),disabled:f,"aria-expanded":v,"aria-label":y("canvas.toolbar.cleanup"),title:y("canvas.toolbar.cleanup"),children:o.jsx(Wn,{})}),v?o.jsxs("div",{className:"canvas-toolbar__cleanup-panel",role:"group","aria-label":y("canvas.toolbar.cleanup"),children:[o.jsxs("div",{className:"canvas-toolbar__cleanup-row",children:[o.jsx("span",{className:"canvas-toolbar__cleanup-title",children:y("canvas.toolbar.cleanup")}),o.jsx("span",{className:"canvas-toolbar__cleanup-meta",children:y("canvas.toolbar.cleanupSeedCount",{n:e})})]}),o.jsx(bt,{label:y("canvas.toolbar.cleanupMark"),value:l,options:[{value:"remove",label:y("canvas.toolbar.cleanupRemove")},{value:"preserve",label:y("canvas.toolbar.cleanupPreserve")}],onChange:A}),o.jsx(bt,{label:y("canvas.toolbar.cleanupInput"),value:s,options:[{value:"click",label:y("canvas.toolbar.cleanupClick")},{value:"brush",label:y("canvas.toolbar.cleanupBrush")}],onChange:O}),o.jsxs("label",{className:"canvas-toolbar__cleanup-slider",children:[o.jsx("span",{children:y("canvas.toolbar.cleanupTolerance")}),o.jsx("input",{type:"range",min:"0",max:"96",value:t,onChange:S=>N(Number(S.target.value))}),o.jsx("output",{children:t})]}),s==="brush"?o.jsxs("label",{className:"canvas-toolbar__cleanup-slider",children:[o.jsx("span",{children:y("canvas.toolbar.cleanupBrushSize")}),o.jsx("input",{type:"range",min:"0.006",max:"0.06",step:"0.002",value:i,onChange:S=>T(Number(S.target.value))}),o.jsx("output",{children:Math.round(i*1e3)})]}):null,o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:_,children:y("canvas.toolbar.cleanupAutoSample")}),o.jsx("button",{type:"button",className:r?"active":"",onClick:B,children:y(g?"canvas.toolbar.cleanupActive":"canvas.toolbar.cleanupPickSeed")})]}),o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:m,disabled:d||e===0,children:y(d?"canvas.toolbar.cleanupPreviewing":"canvas.toolbar.cleanupPreview")}),o.jsx("button",{type:"button",onClick:C,disabled:u||!a&&e===0,children:y(u?"canvas.toolbar.cleanupApplying":"canvas.toolbar.cleanupApply")}),o.jsx("button",{type:"button",onClick:E,disabled:!a&&e===0,children:y("canvas.toolbar.cleanupReset")})]}),g?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:y(s==="brush"?"canvas.toolbar.cleanupBrushHint":"canvas.toolbar.cleanupPickHint")}):n&&!a?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:y("canvas.toolbar.cleanupMaskHint")}):null,n?o.jsx("div",{className:"canvas-toolbar__cleanup-status",children:y("canvas.toolbar.cleanupRemoved",{n:U})}):null]}):null]})}function Wn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M5 7.5h14"}),o.jsx("path",{d:"M7 12h10"}),o.jsx("path",{d:"M10 16.5h4"}),o.jsx("path",{d:"M7.5 5.5 9 4l1.5 1.5L9 7 7.5 5.5Z"}),o.jsx("path",{d:"M13.5 11 15 9.5l1.5 1.5L15 12.5 13.5 11Z"}),o.jsx("path",{d:"M4.5 15.5 6 14l1.5 1.5L6 17 4.5 15.5Z"})]})}function Hn({style:e,onStyleChange:t}){const{t:n}=ye(),[a,r]=c.useState(!1),l=c.useRef(null);return c.useEffect(()=>{if(!a)return;const s=i=>{l.current?.contains(i.target)||r(!1)};return window.addEventListener("pointerdown",s),()=>window.removeEventListener("pointerdown",s)},[a]),o.jsxs("div",{ref:l,className:`canvas-toolbar__split-button${a?" canvas-toolbar__split-button--active":""}`,onKeyDown:s=>{s.key==="Escape"&&a&&(s.preventDefault(),s.stopPropagation(),r(!1))},children:[o.jsxs("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__style-trigger",onClick:()=>r(s=>!s),"aria-haspopup":"dialog","aria-expanded":a,"aria-label":n("canvas.toolbar.style"),title:n("canvas.toolbar.style"),children:[o.jsx("span",{className:"canvas-style-trigger__swatch",style:{background:e.color},"aria-hidden":"true"}),o.jsx("span",{className:"canvas-style-trigger__width",style:{height:`${Math.min(8,Math.max(2,e.strokeWidth))}px`},"aria-hidden":"true"})]}),a?o.jsxs("div",{className:"canvas-style-popover",role:"dialog","aria-label":n("canvas.toolbar.style"),children:[o.jsx("div",{className:"canvas-style-popover__row",role:"group","aria-label":n("canvas.toolbar.color"),children:It.map(s=>o.jsx("button",{type:"button",className:`canvas-style-swatch${e.color===s?" canvas-style-swatch--active":""}`,style:{background:s},onClick:()=>t({...e,color:s}),"aria-pressed":e.color===s,"aria-label":s,title:s},s))}),o.jsx("div",{className:"canvas-style-popover__row",role:"group","aria-label":n("canvas.toolbar.strokeWidth"),children:Nt.map(s=>o.jsx("button",{type:"button",className:`canvas-style-width${e.strokeWidth===s?" canvas-style-width--active":""}`,onClick:()=>t({...e,strokeWidth:s}),"aria-pressed":e.strokeWidth===s,"aria-label":`${s}px`,title:`${s}px`,children:o.jsx("span",{style:{height:`${s}px`,background:e.color}})},s))})]}):null]})}function Fn({tools:e,activeTool:t,onToolChange:n}){const[a,r]=c.useState(!1),l=c.useRef(null),s=e.find(d=>d.id===t)??e[0],i=s.icon;return c.useEffect(()=>{if(!a)return;const d=u=>{l.current?.contains(u.target)||r(!1)};return window.addEventListener("pointerdown",d),()=>window.removeEventListener("pointerdown",d)},[a]),o.jsxs("div",{ref:l,className:"canvas-tool-picker",children:[o.jsxs("button",{type:"button",className:`canvas-toolbar__button canvas-tool-picker__trigger${t!=="eraser"?" canvas-toolbar__button--active":""}`,onClick:()=>r(d=>!d),"aria-label":`${s.label} (${s.shortcut})`,"aria-pressed":t===s.id,"aria-haspopup":"menu","aria-expanded":a,title:`${s.label} (${s.shortcut})`,children:[o.jsx(i,{}),o.jsx("span",{className:"canvas-toolbar__shortcut","aria-hidden":"true",children:s.shortcut})]}),a?o.jsx("div",{className:"canvas-tool-picker__menu",role:"menu",children:e.map(d=>{const u=d.icon,b=t===d.id;return o.jsxs("button",{type:"button",className:`canvas-tool-picker__item${b?" active":""}`,role:"menuitemradio","aria-checked":b,onClick:()=>{n(d.id),r(!1)},children:[o.jsx(u,{}),o.jsx("span",{children:d.label}),o.jsx("kbd",{children:d.shortcut})]},d.id)})}):null]})}function Vn({activeTool:e,hasAnnotations:t,hasExportableContent:n,onToolChange:a,eraserMode:r="object",onEraserModeChange:l,style:s,onStyleChange:i,onClear:d,onApply:u,onExport:b,onUndo:f,onRedo:_,canUndo:B,canRedo:A,onDeleteSelected:O,selectedCount:T=0,onEditWithMask:N,canEditWithMask:m,isEditingWithMask:C,isApplying:E,isExporting:y,exportBackground:v="alpha",exportMatteColor:Z="#ffffff",onExportBackgroundChange:I,onExportMatteColorChange:U,cleanupTolerance:g=28,cleanupSeedCount:S=0,cleanupStats:D=null,cleanupHasPreview:P=!1,isCleanupPickingSeed:V=!1,isCleanupActive:Y=!1,cleanupIntent:te="remove",cleanupTool:ne="click",cleanupBrushRadius:se=.018,isCleanupPreviewing:ue=!1,isCleanupApplying:L=!1,onCleanupAutoSample:p,onCleanupPickSeed:R,onCleanupIntentChange:J,onCleanupToolChange:ae,onCleanupBrushRadiusChange:le,onCleanupToleranceChange:K,onCleanupPreview:q,onCleanupApply:G,onCleanupReset:z}){const{t:w}=ye(),[$,ee]=c.useState(!1),W=c.useRef(null),ce=n??t??!1,X=w(r==="object"?"canvas.toolbar.objectEraser":"canvas.toolbar.brushEraser"),F=[{id:"select",shortcut:"1",label:w("canvas.toolbar.select"),icon:Kn},{id:"pen",shortcut:"2",label:w("canvas.toolbar.pen"),icon:zn},{id:"box",shortcut:"3",label:w("canvas.toolbar.box"),icon:Xn},{id:"arrow",shortcut:"4",label:w("canvas.toolbar.arrow"),icon:qn},{id:"memo",shortcut:"5",label:w("canvas.toolbar.memo"),icon:Yn}];c.useEffect(()=>{if(!$)return;const re=we=>{W.current?.contains(we.target)||ee(!1)};return window.addEventListener("pointerdown",re),()=>window.removeEventListener("pointerdown",re)},[$]);const de=re=>{l?.(re),a("eraser"),ee(!1)};return o.jsxs("div",{className:"canvas-toolbar","aria-label":w("canvas.toolbar.label"),children:[o.jsx(Fn,{tools:F,activeTool:e,onToolChange:a}),o.jsx(Hn,{style:s,onStyleChange:i}),o.jsxs("div",{ref:W,className:`canvas-toolbar__split-button${e==="eraser"?" canvas-toolbar__split-button--active":""}`,onKeyDown:re=>{re.key==="Escape"&&$&&(re.preventDefault(),ee(!1))},children:[o.jsxs("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--split-main${e==="eraser"?" canvas-toolbar__button--active":""}`,onClick:()=>a("eraser"),"aria-label":`${X} (6)`,"aria-pressed":e==="eraser",title:`${X} (6)`,children:[o.jsx(Gn,{}),o.jsx("span",{className:"canvas-toolbar__shortcut","aria-hidden":"true",children:"6"})]}),o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--split-menu",onClick:()=>ee(re=>!re),"aria-label":w("canvas.toolbar.eraserMenu"),"aria-haspopup":"menu","aria-expanded":$,"aria-controls":"canvas-eraser-menu",title:w("canvas.toolbar.eraserMenu"),children:o.jsx(Zn,{})}),$?o.jsxs("div",{id:"canvas-eraser-menu",className:"canvas-toolbar__eraser-menu",role:"menu",children:[o.jsx("button",{type:"button",className:`canvas-toolbar__eraser-menu-item${r==="object"?" canvas-toolbar__eraser-menu-item--active":""}`,role:"menuitemradio","aria-checked":r==="object",onClick:()=>de("object"),children:w("canvas.toolbar.objectEraser")}),o.jsx("button",{type:"button",className:`canvas-toolbar__eraser-menu-item${r==="brush"?" canvas-toolbar__eraser-menu-item--active":""}`,role:"menuitemradio","aria-checked":r==="brush",onClick:()=>de("brush"),children:w("canvas.toolbar.brushEraser")})]}):null]}),o.jsx("span",{className:"canvas-toolbar__divider","aria-hidden":"true"}),u?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--primary${E?" canvas-toolbar__button--busy":""}`,onClick:u,disabled:!ce||E,"aria-label":w("canvas.toolbar.apply"),title:w("canvas.toolbar.apply"),children:o.jsx(Jn,{})}):null,N?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--primary canvas-toolbar__button--mask${C?" canvas-toolbar__button--busy":""}`,onClick:N,disabled:!m||C,"aria-label":w(m?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),title:w(m?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),children:o.jsx(na,{})}):null,f?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:f,disabled:!B,"aria-label":w("canvas.toolbar.undo"),title:w("canvas.toolbar.undo"),children:o.jsx(ea,{})}):null,_?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:_,disabled:!A,"aria-label":w("canvas.toolbar.redo"),title:w("canvas.toolbar.redo"),children:o.jsx(ta,{})}):null,O?o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:O,disabled:T===0,"aria-label":w("canvas.toolbar.deleteSelected"),title:w("canvas.toolbar.deleteSelected"),children:o.jsx(gt,{})}):null,b&&I&&U?o.jsx($n,{mode:v,matteColor:Z,onModeChange:I,onMatteColorChange:U}):null,p&&R&&J&&ae&&le&&K&&q&&G&&z?o.jsx(Un,{seedCount:S,tolerance:g,stats:D,hasPreview:P,isPickingSeed:V,intent:te,tool:ne,brushRadius:se,isPreviewing:ue,isApplying:L,keepOpen:Y,disabled:E||y,onAutoSample:p,onPickSeed:R,onIntentChange:J,onToolChange:ae,onBrushRadiusChange:le,onToleranceChange:K,onPreview:q,onApply:G,onReset:z}):null,b?o.jsx("button",{type:"button",className:`canvas-toolbar__button${y?" canvas-toolbar__button--busy":""}`,onClick:b,disabled:!ce||y,"aria-label":w("canvas.toolbar.export"),title:w("canvas.toolbar.export"),children:o.jsx(Qn,{})}):null,o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:d,disabled:!ce,"aria-label":w("canvas.toolbar.clear"),title:w("canvas.toolbar.clear"),children:o.jsx(gt,{})})]})}function Kn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M8 12.5V7a2 2 0 0 1 4 0v4"}),o.jsx("path",{d:"M12 11V5a2 2 0 0 1 4 0v7"}),o.jsx("path",{d:"M16 12V8a2 2 0 0 1 4 0v5.5A6.5 6.5 0 0 1 13.5 20H12a6 6 0 0 1-4.24-1.76L4.7 15.18a1.7 1.7 0 0 1 2.4-2.4L9 14.68"})]})}function zn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"m4 20 4.2-1.1L19.5 7.6a2.2 2.2 0 0 0-3.1-3.1L5.1 15.8 4 20Z"}),o.jsx("path",{d:"m14.5 6.5 3 3"})]})}function Xn(){return o.jsx("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:o.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"2"})})}function qn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M5 19 19 5"}),o.jsx("path",{d:"M10 5h9v9"})]})}function Yn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M6 4h12v16H6z"}),o.jsx("path",{d:"M9 8h6"}),o.jsx("path",{d:"M9 12h5"}),o.jsx("path",{d:"M9 16h3"})]})}function Gn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"m4 15 8.5-8.5a2.1 2.1 0 0 1 3 0l2 2a2.1 2.1 0 0 1 0 3L10 19H6.5L4 16.5V15Z"}),o.jsx("path",{d:"M10 19h10"}),o.jsx("path",{d:"m8.5 10.5 5 5"})]})}function Zn(){return o.jsx("svg",{className:"canvas-toolbar__icon canvas-toolbar__icon--small",viewBox:"0 0 24 24","aria-hidden":"true",children:o.jsx("path",{d:"m7 14 5-5 5 5"})})}function Jn(){return o.jsx("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:o.jsx("path",{d:"M5 12.5 10 17 19 7"})})}function Qn(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M12 4v11"}),o.jsx("path",{d:"m8 11 4 4 4-4"}),o.jsx("path",{d:"M5 20h14"})]})}function gt(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M4 7h16"}),o.jsx("path",{d:"M9 7V5h6v2"}),o.jsx("path",{d:"M7 7l1 13h8l1-13"}),o.jsx("path",{d:"M10 11v5"}),o.jsx("path",{d:"M14 11v5"})]})}function ea(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M9 7 5 11l4 4"}),o.jsx("path",{d:"M5 11h9a5 5 0 0 1 0 10h-2"})]})}function ta(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"m15 7 4 4-4 4"}),o.jsx("path",{d:"M19 11h-9a5 5 0 0 0 0 10h2"})]})}function na(){return o.jsxs("svg",{className:"canvas-toolbar__icon",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"2"}),o.jsx("path",{d:"M9 9h6v6H9z"})]})}function aa({annotations:e,backgroundCleanup:t,backgroundCleanupPreview:n,canvasState:a,actions:r}){return o.jsx(Vn,{activeTool:e.activeTool,eraserMode:e.eraserMode,onEraserModeChange:e.setEraserMode,style:{color:e.toolColor,strokeWidth:e.strokeWidth},onStyleChange:e.setStyle,hasExportableContent:e.hasAnnotations,onToolChange:e.setTool,onClear:e.clear,onApply:()=>{r.handleApplyCanvas()},onExport:()=>{r.handleExportCanvas()},onUndo:e.undo,onRedo:e.redo,canUndo:e.canUndo,canRedo:e.canRedo,onDeleteSelected:e.deleteSelected,selectedCount:e.selectedIds.length,onEditWithMask:()=>{r.handleEditWithMask()},canEditWithMask:e.boxes.length>0,isEditingWithMask:a.isEditingWithMask,isApplying:a.isApplying,isExporting:a.isExporting,exportBackground:a.exportBackground,exportMatteColor:a.exportMatteColor,onExportBackgroundChange:r.setExportBackground,onExportMatteColorChange:r.setExportMatteColor,cleanupTolerance:t.backgroundCleanupTolerance,cleanupSeedCount:t.backgroundCleanupSeeds.length,cleanupStats:t.backgroundCleanupStats,cleanupHasPreview:!!n,isCleanupPickingSeed:t.isBackgroundCleanupPickingSeed,isCleanupActive:t.isBackgroundCleanupActive,cleanupIntent:t.cleanupIntent,cleanupTool:t.cleanupTool,cleanupBrushRadius:t.cleanupBrushRadius,isCleanupPreviewing:t.isBackgroundCleanupPreviewing,isCleanupApplying:t.isBackgroundCleanupApplying,onCleanupAutoSample:t.handleBackgroundCleanupAutoSample,onCleanupPickSeed:t.handleBackgroundCleanupPickSeed,onCleanupIntentChange:t.setCleanupIntent,onCleanupToolChange:l=>{t.setCleanupTool(l),t.setIsBackgroundCleanupActive(!0)},onCleanupBrushRadiusChange:t.setCleanupBrushRadius,onCleanupToleranceChange:t.handleBackgroundCleanupToleranceChange,onCleanupPreview:()=>{t.runBackgroundCleanupPreview()},onCleanupApply:()=>{t.handleBackgroundCleanupApply()},onCleanupReset:t.handleBackgroundCleanupReset})}function ra({currentImage:e,canvasDisplayImage:t,canvasOpen:n,displayQuality:a,displaySize:r,displayModel:l,onAfterDeleteFocus:s,onCopyPrompt:i}){const{t:d}=ye(),u=[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?d("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,on(e.reasoningEffort),a,r,l].filter(b=>!!b).join(" · ");return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"result-meta",children:u}),o.jsx(sn,{imageOverride:n?t:null,onAfterDeleteFocus:s}),e.prompt?o.jsx(ln,{prompt:e.prompt,onCopy:i}):null]})}function oa({zoom:e,onZoomIn:t,onZoomOut:n,onZoomReset:a}){const{t:r}=ye(),l=Math.round(e*100);return o.jsxs("div",{className:"canvas-toolbar__zoom",role:"group","aria-label":r("canvas.toolbar.zoomGroup"),children:[o.jsx("button",{type:"button",className:"canvas-toolbar__zoom-button",onClick:n,"aria-label":r("canvas.toolbar.zoomOut"),title:r("canvas.toolbar.zoomOut"),children:o.jsx(sa,{})}),o.jsxs("button",{type:"button",className:"canvas-toolbar__zoom-value",onClick:a,"aria-label":r("canvas.toolbar.zoomReset"),title:r("canvas.toolbar.zoomReset"),children:[l,"%"]}),o.jsx("button",{type:"button",className:"canvas-toolbar__zoom-button",onClick:t,"aria-label":r("canvas.toolbar.zoomIn"),title:r("canvas.toolbar.zoomIn"),children:o.jsx(la,{})})]})}function sa(){return o.jsx("svg",{className:"canvas-toolbar__icon canvas-toolbar__icon--small",viewBox:"0 0 24 24","aria-hidden":"true",children:o.jsx("path",{d:"M5 12h14"})})}function la(){return o.jsxs("svg",{className:"canvas-toolbar__icon canvas-toolbar__icon--small",viewBox:"0 0 24 24","aria-hidden":"true",children:[o.jsx("path",{d:"M12 5v14"}),o.jsx("path",{d:"M5 12h14"})]})}function ca({zoom:e,closeLabel:t,blankCanvasLabel:n,blankCanvasAriaLabel:a,blankCanvasShortcut:r,blankCanvasBusy:l,shortcutHint:s,onZoomIn:i,onZoomOut:d,onZoomReset:u,onCreateBlankCanvas:b,onClose:f}){return o.jsxs("div",{className:"canvas-mode-topbar",children:[o.jsxs("div",{className:"canvas-mode-topbar__stack",children:[o.jsx("span",{className:"canvas-mode-topbar__label",children:"Canvas Mode"}),o.jsx(oa,{zoom:e,onZoomIn:i,onZoomOut:d,onZoomReset:u}),o.jsx("span",{className:"canvas-mode-topbar__shortcuts",children:s})]}),o.jsx("div",{className:"canvas-mode-topbar__center",children:o.jsxs("button",{type:"button",className:"canvas-mode-blank",onClick:b,disabled:l,"aria-label":a,title:a,children:[o.jsx("span",{"aria-hidden":"true",children:"+"}),o.jsx("span",{children:n}),o.jsx("kbd",{children:r})]})}),o.jsxs("button",{type:"button",className:"canvas-mode-close",onClick:f,"aria-label":t,children:[o.jsx("kbd",{children:"ESC"}),o.jsx("span",{children:t})]})]})}function Je(e,t,n){return Math.max(t,Math.min(n,e))}function ia({zoom:e,panX:t,panY:n}){const a=Je(100/Math.max(1,e),18,100),r=a/2,l=Je(50-t/40,r,100-r),s=Je(50-n/40,r,100-r);return{width:`${a}%`,height:`${a}%`,left:`${l}%`,top:`${s}%`}}function ua({imageSrc:e,zoom:t,panX:n,panY:a,resetLabel:r,onReset:l}){return o.jsxs("button",{type:"button",className:"canvas-viewport-minimap",onClick:l,"aria-label":r,title:r,children:[o.jsx("img",{src:e,alt:"","aria-hidden":"true"}),o.jsx("span",{className:"canvas-viewport-minimap__window",style:ia({zoom:t,panX:n,panY:a}),"aria-hidden":"true"})]})}function Ne(e){return Math.min(1,Math.max(0,e))}function da(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("mask_blob_unavailable"))},"image/png")})}async function ha(e){const t=e.imageElement.naturalWidth,n=e.imageElement.naturalHeight;if(!t||!n)throw new Error("mask_source_size_unavailable");if(e.boxes.length===0)throw new Error("mask_boxes_required");const a=document.createElement("canvas");a.width=t,a.height=n;const r=a.getContext("2d");if(!r)throw new Error("mask_context_unavailable");r.fillStyle="rgba(0, 0, 0, 1)",r.fillRect(0,0,t,n),r.globalCompositeOperation="destination-out";for(const l of e.boxes){const s=Ne(l.x)*t,i=Ne(l.y)*n,d=Ne(l.width)*t,u=Ne(l.height)*n;d>0&&u>0&&r.fillRect(s,i,d,u)}return da(a)}async function fa(e){const t=e.naturalWidth,n=e.naturalHeight;if(!t||!n)throw new Error("image_source_size_unavailable");const a=document.createElement("canvas");a.width=t,a.height=n;const r=a.getContext("2d");if(!r)throw new Error("image_context_unavailable");return r.drawImage(e,0,0,t,n),a.toDataURL("image/png")}function ct(e){return new Promise((t,n)=>{const a=new FileReader;a.onerror=()=>n(new Error("mask_blob_read_failed")),a.onload=()=>t(String(a.result)),a.readAsDataURL(e)})}const pa=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='28' height='28' viewBox='0 0 28 28'%3E%3Ccircle cx='14' cy='14' r='8' fill='white' fill-opacity='0.16' stroke='black' stroke-width='3'/%3E%3Ccircle cx='14' cy='14' r='8' fill='none' stroke='white' stroke-width='1.5'/%3E%3Ccircle cx='14' cy='14' r='2' fill='white' stroke='black' stroke-width='1'/%3E%3C/svg%3E") 14 14, auto`,ma=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='28' height='28' viewBox='0 0 28 28'%3E%3Ccircle cx='14' cy='14' r='8' fill='white' fill-opacity='0.18' stroke='black' stroke-width='3'/%3E%3Ccircle cx='14' cy='14' r='8' fill='none' stroke='white' stroke-width='1.5'/%3E%3C/svg%3E") 14 14, auto`;function va(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function ba(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function ga(e){const t=e.url??e.image;if(!e.canvasVersion||!e.canvasMergedAt||t.startsWith("data:"))return t;const n=t.includes("?")?"&":"?";return`${t}${n}canvasMergedAt=${e.canvasMergedAt}`}function xa(e){const t=e.canvasSourceFilename??e.filename;return t?`/generated/${encodeURIComponent(t)}`:e.url??e.image}async function xt(e){const t=xa(e);if(t.startsWith("data:image/png;"))return t;const n=new Image;return await new Promise((a,r)=>{n.onload=()=>a(),n.onerror=()=>r(new Error("clean_source_load_failed")),n.src=t}),fa(n)}function it(e,t){return!e.canvasVersion||e.prompt||!t?.prompt?e:{...e,prompt:t.prompt}}function ya(e,t){if(!t?.filename)return null;const n=e.find(a=>a.canvasVersion&&(a.canvasSourceFilename===t.filename||a.canvasEditableFilename===t.filename))??null;return n?it(n,t):null}function ka(e,t){if(cn(e)){const n=e.images[0];if(!n)throw new Error("edit_empty_response");return{...n,prompt:t,reasoningEffort:e.reasoningEffort,provider:e.provider,quality:e.quality,size:e.size,moderation:e.moderation,model:e.model,usage:e.usage,kind:"edit",createdAt:Date.now()}}return{image:e.image,url:e.filename?`/generated/${e.filename}`:e.image,thumb:e.image,filename:e.filename,prompt:t,elapsed:e.elapsed,reasoningEffort:e.reasoningEffort,provider:e.provider,quality:e.quality,size:e.size,moderation:e.moderation,model:e.model,usage:e.usage,revisedPrompt:e.revisedPrompt??null,promptMode:e.promptMode??null,kind:"edit",createdAt:Date.now()}}const Qe=new WeakMap;function wa(e){if(!e.complete||!e.naturalWidth||!e.naturalHeight)return!1;const t=Qe.get(e);if(t&&t.src===e.currentSrc&&t.width===e.naturalWidth&&t.height===e.naturalHeight)return t.result;const n=64,a=Math.min(n,e.naturalWidth),r=Math.min(n,e.naturalHeight),l=document.createElement("canvas");l.width=a,l.height=r;const s=l.getContext("2d",{willReadFrequently:!0});if(!s)return!1;try{s.drawImage(e,0,0,a,r);const i=s.getImageData(0,0,a,r).data;for(let d=3;d<i.length;d+=4)if(i[d]<250)return Qe.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!0}),!0;return Qe.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!1}),!1}catch{return!1}}function Ca(e,t){if(e.width!==t.width||e.height!==t.height||e.data.length!==t.data.length)throw new Error("cleanup_mask_size_mismatch")}function yt(e,t){return{width:e,height:t,data:new Uint8Array(e*t)}}function rt(e){return{width:e.width,height:e.height,data:new Uint8Array(e.data)}}function _a(e,t){Ca(e,t);for(let n=0;n<e.data.length;n+=1)(t.data[n]??0)>0&&(e.data[n]=0)}function Se(e,t){if(!e)return null;const n=rt(e);return t&&_a(n,t),n}function Ma(e,t){if(e.width!==t.width||e.height!==t.height)throw new Error("cleanup_mask_size_mismatch");const n=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);for(let a=0;a<t.data.length;a+=1)(t.data[a]??0)>0&&(n.data[a*4+3]=0);return n}const ut=[{x:0,y:0},{x:1,y:0},{x:0,y:1},{x:1,y:1}],Ea=1024;function Sa(e){return Math.max(0,Math.min(255,Math.round(e)))}function Rt(e,t,n){const a=Math.max(0,Math.min(t-1,Math.round(e.x*(t-1))));return Math.max(0,Math.min(n-1,Math.round(e.y*(n-1))))*t+a}function Ba(e,t){return(t.length>0?t:ut).map(a=>{const r=Rt(a,e.width,e.height)*4;return{r:e.data[r]??0,g:e.data[r+1]??0,b:e.data[r+2]??0}})}function ja(e,t,n,a){for(const r of n)if(Math.max(Math.abs((e[t]??0)-r.r),Math.abs((e[t+1]??0)-r.g),Math.abs((e[t+2]??0)-r.b))<=a)return!0;return!1}function Be(e,t,n,a,r,l,s){if(e<0||e>=a.length||a[e])return r;const i=e*4;return(t.data[i+3]??0)===0?(a[e]=1,r):ja(t.data,i,l,s)?(a[e]=1,n[r]=e,r+1):r}function et(){return ut.map(e=>({...e}))}function kt(e,t,n,a){if(e.width!==t.width||e.height!==t.height)throw new Error("cleanup_mask_size_mismatch");const{width:r,height:l}=t,s=r*l,i=new Uint8Array(s),d=new Int32Array(s),u=Ba(t,n),b=Sa(a);let f=0;for(const _ of n.length>0?n:ut)f=Be(Rt(_,r,l),t,d,i,f,u,b);for(;f>0;){const _=d[--f];e.data[_]=255;const B=_%r;B>0&&(f=Be(_-1,t,d,i,f,u,b)),B<r-1&&(f=Be(_+1,t,d,i,f,u,b)),_>=r&&(f=Be(_-r,t,d,i,f,u,b)),_<s-r&&(f=Be(_+r,t,d,i,f,u,b))}}function Ta(e,t){const n=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),a=Ma(n,t),r=t.data.reduce((l,s)=>l+(s>0?1:0),0);return{imageData:{width:e.width,height:e.height,data:a.data},stats:{width:e.width,height:e.height,removedPixels:r,removedPercent:t.data.length>0?r/t.data.length:0}}}function Lt(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("background_cleanup_blob_failed"))},"image/png")})}function Ot(e,t){const n=e.naturalWidth,a=e.naturalHeight;if(n<=0||a<=0)throw new Error("background_cleanup_image_not_ready");const r=t&&t>0?Math.min(1,t/Math.max(n,a)):1,l=Math.max(1,Math.round(n*r)),s=Math.max(1,Math.round(a*r)),i=document.createElement("canvas");i.width=l,i.height=s;const d=i.getContext("2d",{willReadFrequently:!0});if(!d)throw new Error("background_cleanup_context_failed");return d.drawImage(e,0,0,l,s),{canvas:i,context:d,width:l,height:s}}async function wt({imageElement:e,mask:t}){try{const{canvas:n,context:a,width:r,height:l}=Ot(e),s=a.getImageData(0,0,r,l),i=Ta({width:r,height:l,data:s.data},t),d=a.createImageData(r,l);d.data.set(i.imageData.data),a.putImageData(d,0,0);const u=await Lt(n);return{blob:u,dataUrl:await ct(u),stats:i.stats}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}async function Pa({imageElement:e,mask:t}){try{const{width:n,height:a}=Ot(e,Ea),r=document.createElement("canvas");r.width=n,r.height=a;const l=r.getContext("2d");if(!l)throw new Error("background_cleanup_context_failed");const s=l.createImageData(n,a);let i=0;for(let u=0;u<a;u+=1)for(let b=0;b<n;b+=1){const f=Math.min(t.width-1,Math.floor(b/n*t.width)),_=Math.min(t.height-1,Math.floor(u/a*t.height));if((t.data[_*t.width+f]??0)===0)continue;const B=(u*n+b)*4;s.data[B]=168,s.data[B+1]=85,s.data[B+2]=247,s.data[B+3]=150,i+=1}l.putImageData(s,0,0);const d=await Lt(r);return{dataUrl:await ct(d),stats:{width:t.width,height:t.height,removedPixels:t.data.reduce((u,b)=>u+(b>0?1:0),0),removedPercent:t.data.length>0?i/(n*a):0}}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}function Ct(e){return{...e,seeds:e.seeds.map(t=>({intent:t.intent,point:{...t.point}})),brushStrokes:e.brushStrokes.map(t=>({...t,points:t.points.map(n=>({...n}))})),brushCursor:e.brushCursor?{...e.brushCursor}:null,removeMask:e.removeMask?rt(e.removeMask):null,preserveMask:e.preserveMask?rt(e.preserveMask):null}}function Da(){return`cleanup_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function Re(e){return Math.max(0,Math.min(1,e))}function Aa(e){const t=[],n=Math.max(0,e.radius*.55);for(const a of e.points)t.push({...a}),!(n<=0)&&t.push({x:Re(a.x-n),y:a.y},{x:Re(a.x+n),y:a.y},{x:a.x,y:Re(a.y-n)},{x:a.x,y:Re(a.y+n)});return t}function Ia(e){const t=e.naturalWidth,n=e.naturalHeight;if(t<=0||n<=0)throw new Error("background_cleanup_image_not_ready");const a=document.createElement("canvas");a.width=t,a.height=n;const r=a.getContext("2d",{willReadFrequently:!0});if(!r)throw new Error("background_cleanup_context_failed");r.drawImage(e,0,0,t,n);const l=r.getImageData(0,0,t,n);return{width:t,height:n,data:l.data}}function Na({canvasOpen:e,currentImage:t,canvasDisplayImage:n,imageElementRef:a,canvasSourceImageRef:r,lastMergedDataUrlRef:l,setCanvasSaveState:s,setCanvasVersionItem:i,applyMergedCanvasImage:d,attachCanvasVersionReference:u,showToast:b,t:f}){const[_,B]=c.useState(!1),[A,O]=c.useState("remove"),[T,N]=c.useState("click"),[m,C]=c.useState("flat-flood-fill"),[E,y]=c.useState([]),[v,Z]=c.useState([]),[I,U]=c.useState(28),[g,S]=c.useState(null),[D,P]=c.useState(null),[V,Y]=c.useState(null),[te,ne]=c.useState(!1),[se,ue]=c.useState(.018),[L,p]=c.useState(null),[R,J]=c.useState(!1),[ae,le]=c.useState(!1),K=c.useRef(null),q=c.useRef(null),G=c.useRef(null),z=c.useRef({past:[],future:[]}),w=c.useRef(0),$=c.useRef(null),ee=c.useCallback(()=>Ct({intent:A,tool:T,engine:m,seeds:E,brushStrokes:v,brushRadius:se,tolerance:I,removeMask:K.current,preserveMask:q.current,preview:g,maskOverlay:D,stats:V,active:te,brushCursor:L}),[v,D,g,E,V,I,L,se,m,A,T,te]),W=c.useCallback(()=>{z.current={past:[...z.current.past.slice(-19),ee()],future:[]}},[ee]),ce=c.useCallback(x=>{const k=Ct(x);K.current=k.removeMask,q.current=k.preserveMask,G.current=null,O(k.intent),N(k.tool),C(k.engine),y(k.seeds),Z(k.brushStrokes),ue(k.brushRadius),U(k.tolerance),S(k.preview),P(k.maskOverlay),Y(k.stats),ne(k.active),p(k.brushCursor),J(!1),le(!1)},[]),X=c.useCallback(async()=>{if(!a.current||!t)return;const x=Se(K.current,q.current);if(!x){P(null),Y(null);return}const k=w.current+1;w.current=k,J(!0);try{const M=await Pa({imageElement:a.current,mask:x});if(w.current!==k)return;P(M),Y(M.stats)}catch{if(w.current!==k)return;b(f("canvas.toolbar.cleanupFailed"),!0)}finally{w.current===k&&J(!1)}},[t,a,b,f]),F=c.useCallback(async(x,k,M)=>{if(!a.current)return;const Q=Ia(a.current),ie=yt(Q.width,Q.height),ke=yt(Q.width,Q.height);for(const fe of x){const Ce=fe.intent==="remove"?ie:ke;kt(Ce,Q,[fe.point],M)}for(const fe of k){const Ce=fe.intent==="remove"?ie:ke;kt(Ce,Q,Aa(fe),M)}K.current=ie,q.current=ke},[a]),de=c.useCallback(()=>{w.current+=1,$.current!=null&&(window.clearTimeout($.current),$.current=null),K.current=null,q.current=null,G.current=null,z.current={past:[],future:[]},y([]),Z([]),S(null),P(null),Y(null),ne(!1),p(null),J(!1),le(!1)},[]),re=c.useCallback(()=>{const x=z.current.past.pop();return x?(z.current.future=[ee(),...z.current.future.slice(0,19)],ce(x),!0):!1},[ee,ce]),we=c.useCallback(()=>{const x=z.current.future.shift();return x?(z.current.past=[...z.current.past.slice(-19),ee()],ce(x),!0):!1},[ee,ce]),Pe=c.useCallback(x=>{W();const k=[...E,{point:x,intent:A}];y(k),S(null),F(k,v,I).then(X)},[v,E,I,A,W,F,X]),Oe=c.useCallback(()=>{W();const x=et().map(k=>({point:k,intent:"remove"}));y(x),S(null),ne(!1),F(x,v,I).then(X)},[v,I,W,F,X]),$e=c.useCallback(()=>{W(),N("click"),ne(x=>!x)},[W]),Ue=c.useCallback(x=>{W(),$.current!=null&&window.clearTimeout($.current),U(x),S(null),$.current=window.setTimeout(()=>{$.current=null,F(E,v,x).then(X)},180)},[v,E,W,F,X]),H=c.useCallback(async()=>{if(!a.current||!t)return null;let x=Se(K.current,q.current);if(!x){const M=et().map(Q=>({point:Q,intent:"remove"}));y(M),await F(M,v,I),x=Se(K.current,q.current)}if(!x)return null;W();const k=w.current+1;w.current=k,J(!0);try{const M=await wt({imageElement:a.current,mask:x});return w.current!==k?null:(S(M),P(null),Y(M.stats),M)}catch{return w.current!==k||b(f("canvas.toolbar.cleanupFailed"),!0),null}finally{w.current===k&&J(!1)}},[v,I,t,a,W,F,b,f]),We=c.useCallback(()=>{W(),de()},[W,de]),He=c.useCallback(x=>{W();const k={id:Da(),intent:A,points:[{...x}],radius:se};G.current=k,p(x),Z(M=>[...M,k])},[se,A,W]),Fe=c.useCallback(x=>{const k=G.current;if(!k){p(x);return}k.points=[...k.points,{...x}],p(x),Z(M=>M.map(Q=>Q.id===k.id?{...k,points:k.points.map(ie=>({...ie}))}:Q)),F(E,v.map(M=>M.id===k.id?k:M),I).then(X)},[v,E,I,F,X]),Ve=c.useCallback(()=>{G.current=null,F(E,v,I).then(X)},[v,E,I,F,X]),ve=c.useCallback(async()=>{if(!t||!a.current)return;const x=r.current??t;if(!x?.filename){b(f("canvas.toolbar.cleanupFailed"),!0);return}let k=Se(K.current,q.current);if(!k){const M=et().map(Q=>({point:Q,intent:"remove"}));y(M),await F(M,v,I),k=Se(K.current,q.current)}if(k){le(!0),s("saving");try{W();const M=await wt({imageElement:a.current,mask:k}),Q=await Bt({sourceFilename:x.canvasSourceFilename??x.filename,image:M.blob,prompt:x.prompt}),ie=it(Q.item,x);l.current=M.dataUrl,i(ie),d(ie),await u(ie),s("saved"),S(null),P(null),Y(M.stats),ne(!1),b(f("canvas.toolbar.cleanupApplied"))}catch{s("error"),b(f("canvas.toolbar.cleanupFailed"),!0)}finally{le(!1)}}},[d,u,v,I,r,t,a,l,W,F,s,i,b,f]),he=c.useCallback(()=>te?(G.current=null,ne(!1),p(null),!0):!1,[te]);return c.useEffect(()=>{const x=a.current;if(!x||!e){B(!1);return}const k=()=>B(wa(x));if(x.complete)k();else return x.addEventListener("load",k),()=>x.removeEventListener("load",k)},[e,n?.canvasMergedAt,n?.filename,n?.image,n?.url,g?.dataUrl,a]),{imageHasAlpha:_,backgroundCleanupSeeds:E,backgroundCleanupBrushStrokes:v,backgroundCleanupTolerance:I,backgroundCleanupPreview:g,backgroundCleanupMaskOverlay:D,backgroundCleanupStats:V,cleanupIntent:A,setCleanupIntent:O,cleanupTool:T,setCleanupTool:N,cleanupClickEngine:m,setCleanupClickEngine:C,cleanupBrushRadius:se,setCleanupBrushRadius:ue,cleanupBrushCursor:L,setCleanupBrushCursor:p,isBackgroundCleanupActive:te,setIsBackgroundCleanupActive:ne,isBackgroundCleanupPickingSeed:te&&T==="click",isBackgroundCleanupPreviewing:R,isBackgroundCleanupApplying:ae,hasActiveCleanupStroke:!!G.current,canUndoBackgroundCleanup:z.current.past.length>0,canRedoBackgroundCleanup:z.current.future.length>0,resetBackgroundCleanup:de,undoBackgroundCleanup:re,redoBackgroundCleanup:we,addBackgroundCleanupClick:Pe,addBackgroundCleanupSeed:Pe,runBackgroundCleanupPreview:H,handleBackgroundCleanupAutoSample:Oe,handleBackgroundCleanupPickSeed:$e,handleBackgroundCleanupToleranceChange:Ue,handleBackgroundCleanupReset:We,handleBackgroundCleanupApply:ve,handleBackgroundCleanupEscape:he,startBackgroundCleanupBrushStroke:He,updateBackgroundCleanupBrushStroke:Fe,endBackgroundCleanupBrushStroke:Ve}}function _t(e){return Math.min(1,Math.max(0,e))}function Mt(e,t){const n=t.getBoundingClientRect();return{x:_t((e.clientX-n.left)/n.width),y:_t((e.clientY-n.top)/n.height)}}const Ra=.18,La=.12;function Oa(e){return{id:"selection-box",x:Math.min(e.start.x,e.current.x),y:Math.min(e.start.y,e.current.y),width:Math.abs(e.current.x-e.start.x),height:Math.abs(e.current.y-e.start.y),color:"#64c8ff",strokeWidth:2}}function ot(e,t,n=0){return e.x>=t.x-n&&e.x<=t.x+t.width+n&&e.y>=t.y-n&&e.y<=t.y+t.height+n}function $t(e){return{id:e.id,x:e.x,y:e.y,width:Ra,height:La,color:e.color,strokeWidth:1}}function $a(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,i=a*a+r*r;if(i===0)return Math.hypot(e.x-t.x,e.y-t.y);const d=Math.max(0,Math.min(1,(l*a+s*r)/i));return Math.hypot(e.x-(t.x+d*a),e.y-(t.y+d*r))}function Ua(e,t,n){for(let a=1;a<t.points.length;a+=1)if($a(e,t.points[a-1],t.points[a])<=n)return!0;return!1}function Et(e,t){return e.x<=t.x+t.width&&e.x+e.width>=t.x&&e.y<=t.y+t.height&&e.y+e.height>=t.y}function Wa(e,t){return e.points.some(n=>ot(n,t))}function St(e){const t=e.tolerance??.015;for(const n of[...e.memos].reverse())if(ot(e.point,$t(n),t))return Dt(n);for(const n of[...e.boxes].reverse())if(ot(e.point,n,t))return Pt(n);for(const n of[...e.paths].reverse())if(Ua(e.point,n,t))return Tt(n);return null}function Ha(e){const t=[];for(const n of e.annotations.paths)Wa(n,e.box)&&t.push(Tt(n));for(const n of e.annotations.boxes)Et(n,e.box)&&t.push(Pt(n));for(const n of e.annotations.memos)Et($t(n),e.box)&&t.push(Dt(n));return t}function Fa({canvasOpen:e,canvasZoom:t,canvasPanX:n,canvasPanY:a,spaceHeld:r,canDragViewportWithSelect:l,isBackgroundCleanupActive:s,cleanupTool:i,annotationFrameRef:d,annotations:u,setCanvasPan:b,addBackgroundCleanupClick:f,startBackgroundCleanupBrushStroke:_,updateBackgroundCleanupBrushStroke:B,endBackgroundCleanupBrushStroke:A,setCleanupBrushCursor:O}){const T=c.useRef({mode:null,lastPoint:null,didMove:!1}),N=c.useRef({active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null}),[m,C]=c.useState(!1),E=g=>{g.currentTarget.setPointerCapture(g.pointerId),N.current={active:!0,startX:g.clientX,startY:g.clientY,basePanX:n,basePanY:a,pointerId:g.pointerId},C(!0)};return{viewportPanActive:m,resetPointerSession:()=>{T.current={mode:null,lastPoint:null,didMove:!1},N.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},C(!1)},handleAnnotationPointerDown:g=>{if(!e||me(g.target)||!d.current)return;const S=g.button===1;if(r||S){g.preventDefault(),E(g);return}g.preventDefault();const D=Mt(g,d.current);if(s){i==="click"?f(D):(g.currentTarget.setPointerCapture(g.pointerId),_(D));return}if(u.activeTool==="select"){const P=St({point:D,paths:u.paths,boxes:u.boxes,memos:u.memos});if(P)g.shiftKey?u.toggleSelected(P):u.selectOne(P),u.startSelectedMove(),T.current={mode:"move",lastPoint:D,didMove:!1};else if(l&&t>1.01){E(g);return}else u.clearSelection(),u.startSelectionBox(D),T.current={mode:"box",lastPoint:D,didMove:!1};g.currentTarget.setPointerCapture(g.pointerId);return}if(u.activeTool==="memo"){u.createMemo(D),requestAnimationFrame(()=>{d.current?.querySelector(".canvas-memo--active")?.focus()});return}if(u.activeTool==="eraser"){if(u.eraserMode==="object"){const P=St({point:D,paths:u.paths,boxes:u.boxes,memos:u.memos});P&&u.eraseObjectAtPoint(P);return}g.currentTarget.setPointerCapture(g.pointerId),u.startEraserStroke(D);return}g.currentTarget.setPointerCapture(g.pointerId),u.startDrawing(D)},handleAnnotationPointerMove:g=>{if(!e||me(g.target)||!d.current)return;if(N.current.active){const D=g.clientX-N.current.startX,P=g.clientY-N.current.startY;b(N.current.basePanX+D,N.current.basePanY+P);return}const S=Mt(g,d.current);if(s){i==="brush"?B(S):O(S);return}if(u.activeTool==="select"){if(T.current.mode==="move"&&T.current.lastPoint){const D={x:S.x-T.current.lastPoint.x,y:S.y-T.current.lastPoint.y};(Math.abs(D.x)>5e-4||Math.abs(D.y)>5e-4)&&(u.moveSelected(D),T.current.didMove=!0),T.current.lastPoint=S}else T.current.mode==="box"&&u.updateSelectionBox(S);return}if(u.activeTool!=="memo"){if(u.activeTool==="eraser"){u.eraserMode==="brush"&&u.updateEraserStroke(S);return}u.moveDrawing(S)}},handleAnnotationPointerUp:g=>{if(e&&!me(g.target)){if(N.current.active&&N.current.pointerId===g.pointerId){g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),N.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},C(!1);return}if(g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),s){i==="brush"&&A();return}if(u.activeTool==="select"){T.current.mode==="move"&&T.current.didMove&&u.commitSelectedMove(),T.current.mode==="box"&&u.selectionBox&&u.endSelectionBox(Ha({box:Oa(u.selectionBox),annotations:u.toPayload()})),T.current={mode:null,lastPoint:null,didMove:!1};return}if(u.activeTool!=="memo"){if(u.activeTool==="eraser"){u.eraserMode==="brush"&&u.endEraserStroke();return}u.endDrawing()}}},handleAnnotationPointerLeave:()=>{s&&O(null)}}}function Va({canvasOpen:e,canvasZoom:t,currentImage:n,annotations:a,undoBackgroundCleanup:r,redoBackgroundCleanup:l,handleBackgroundCleanupEscape:s,handleCloseCanvas:i,selectHistoryShortcutTarget:d,trashHistoryItem:u,permanentlyDeleteHistoryItemByShortcut:b,setCanvasZoom:f,resetCanvasZoom:_,onCreateBlankCanvas:B,isCreatingBlankCanvas:A}){const[O,T]=c.useState(!1);return c.useEffect(()=>{if(!e)return;const m=v=>{v.preventDefault()},C=v=>{v.ctrlKey&&v.preventDefault()},E={passive:!1,capture:!0},y={passive:!1};return window.addEventListener("wheel",C,E),window.addEventListener("gesturestart",m,y),window.addEventListener("gesturechange",m,y),window.addEventListener("gestureend",m,y),()=>{window.removeEventListener("wheel",C,E),window.removeEventListener("gesturestart",m,y),window.removeEventListener("gesturechange",m,y),window.removeEventListener("gestureend",m,y)}},[e]),c.useEffect(()=>{if(!e)return;const m=E=>{E.code==="Space"&&(me(E.target)||(O||T(!0),E.preventDefault()))},C=E=>{E.code==="Space"&&T(!1)};return window.addEventListener("keydown",m),window.addEventListener("keyup",C),()=>{window.removeEventListener("keydown",m),window.removeEventListener("keyup",C)}},[e,O]),c.useEffect(()=>{if(!e)return;const m=C=>{if(!C.defaultPrevented){if(me(C.target)){C.key==="Escape"&&(C.preventDefault(),C.target.blur(),a.focusMemo(null));return}if(C.key==="Escape"){if(C.preventDefault(),s())return;i();return}if(C.shiftKey&&!C.metaKey&&!C.ctrlKey&&!C.altKey&&C.key.toLowerCase()==="b"){C.preventDefault(),!A&&!C.repeat&&B();return}if((C.metaKey||C.ctrlKey)&&C.key.toLowerCase()==="z"){if(C.preventDefault(),C.shiftKey){if(l())return;a.redo();return}if(r())return;a.undo()}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[a,a.focusMemo,a.redo,a.undo,e,i,s,A,B,l,r]),{spaceHeld:O,handleViewerKeyDown:m=>{if(me(m.target)){m.key==="Escape"&&(m.preventDefault(),m.target.blur(),a.focusMemo(null));return}if(e&&["1","2","3","4","5","6"].includes(m.key)){m.preventDefault();const C=["select","pen","box","arrow","memo","eraser"];a.setTool(C[Number(m.key)-1]);return}if(e&&m.key==="Escape"){if(m.preventDefault(),m.stopPropagation(),s())return;i();return}if(e&&m.key==="]"){m.preventDefault(),f(t+.1);return}if(e&&m.key==="["){m.preventDefault(),f(t-.1);return}if(e&&m.key==="0"){m.preventDefault(),_();return}if(m.key==="Delete"||m.key==="Backspace"){if(!n||m.target!==m.currentTarget)return;if(m.preventDefault(),m.shiftKey){b(n);return}u(n);return}m.key!=="ArrowLeft"&&m.key!=="ArrowRight"&&m.key!=="Home"&&m.key!=="End"||m.target===m.currentTarget&&(me(m.target)||(m.preventDefault(),m.key==="ArrowLeft"?d("previous"):m.key==="ArrowRight"?d("next"):m.key==="Home"?d("first"):m.key==="End"&&d("last")))}}}function Ka(e,t){return new Promise((n,a)=>{e.toBlob(r=>{if(r){n(r);return}a(new Error("canvas_blob_unavailable"))},t)})}async function Ut(e){const t=document.createElement("canvas");t.width=e.imageElement.naturalWidth,t.height=e.imageElement.naturalHeight;const n=t.getContext("2d");if(!n)throw new Error("canvas_context_unavailable");e.background?.mode==="matte"&&(n.fillStyle=e.background.color,n.fillRect(0,0,t.width,t.height)),n.drawImage(e.imageElement,0,0,t.width,t.height);const a={width:t.width,height:t.height};for(const l of e.paths)nt(n,l,a);for(const l of e.boxes)at(n,l,a,"committed");for(const l of e.memos)Bn(n,l,a);return{blob:await Ka(t,"image/png"),dataUrl:t.toDataURL("image/png")}}const za=["left","center","right"],Xa=["top","middle","bottom"];function qa(e,t){const n=za[Math.min(2,Math.max(0,Math.floor(e*3)))],a=Xa[Math.min(2,Math.max(0,Math.floor(t*3)))];return`${a==="middle"&&n==="center"?"center":`${a} ${n}`} area (x: ${Math.round(e*100)}%, y: ${Math.round(t*100)}% from top-left)`}function Ya(e){const t=e.map(n=>({...n,text:n.text.trim()})).filter(n=>n.text.length>0);return t.length===0?"":["Apply the following annotation instructions at the specified image locations (percentages are relative to image width and height):",...t.map((n,a)=>`${a+1}. At the ${qa(n.x,n.y)}: ${n.text}`),"Do not render any annotation text, sticky notes, boxes, arrows, or markup in the output image."].join(`
2
+ `)}async function Ga(e){return(await Ut(e)).blob}function Za(e={},t=new Date){const n=t.toISOString().slice(0,19).replace(/[-:T]/g,""),a=e.matte?"-flat":"";return`canvas-export-${n}${a}.png`}function Ja(e,t){const n=URL.createObjectURL(e);try{const a=document.createElement("a");a.href=n,a.download=t,a.click()}finally{URL.revokeObjectURL(n)}}function Qa({imageElementRef:e,currentImage:t,canvasDisplayImage:n,canvasSourceImageRef:a,lastMergedDataUrlRef:r,lastCleanDataUrlRef:l,canvasVersionItem:s,annotations:i,exportBackground:d,exportMatteColor:u,quality:b,format:f,moderation:_,provider:B,imageModel:A,reasoningEffort:O,promptMode:T,webSearchEnabled:N,getResolvedSize:m,setCanvasVersionItem:C,setCanvasSaveState:E,setIsApplying:y,setIsExporting:v,setIsEditingWithMask:Z,applyMergedCanvasImage:I,addGeneratedHistoryItem:U,attachCanvasVersionReference:g,closeCanvas:S,resetCanvasSession:D,showToast:P,t:V}){const Y=c.useCallback(async()=>{if(!e.current||!t)return null;const L=a.current??t;if(!L?.filename)return P(V("canvas.version.failed"),!0),null;y(!0),E("saving");try{const p=await Ut({imageElement:e.current,paths:i.paths,boxes:i.boxes,memos:i.memos});r.current=p.dataUrl;const R=await xt(L);l.current=R;const J=s?.filename?await un(s.filename,{image:p.blob,sourceFilename:L.canvasSourceFilename??L.filename,prompt:L.prompt}):await Bt({sourceFilename:L.filename,image:p.blob,prompt:L.prompt}),ae=it(J.item,L);return C(ae),I(ae),await g(ae,R),await jt(L.filename).catch(()=>{}),i.resetLocal(),i.markSaved(),E("saved"),P(V("canvas.version.saved")),ae}catch{return E("error"),P(V("canvas.version.failed"),!0),null}finally{y(!1)}},[i,I,g,a,s?.filename,t,e,r,l,E,C,y,P,V]);return{saveCanvasVersionAndUseReference:Y,handleApplyCanvas:async()=>{await Y()},handleCloseCanvas:async()=>{(i.hasAnnotations||i.isDirty)&&!await Y()||(S(),D())},handleExportCanvas:async()=>{if(!(!e.current||!t)){v(!0);try{const L=d==="matte",p=await Ga({imageElement:e.current,paths:i.paths,boxes:i.boxes,memos:i.memos,background:L?{mode:"matte",color:u}:{mode:"alpha"}});Ja(p,Za({matte:L}))}catch{P(V("canvas.toolbar.exportFailed"),!0)}finally{v(!1)}}},handleEditWithMask:async()=>{if(!(!e.current||!n||i.boxes.length===0)){Z(!0);try{const L=i.memos;let p=l.current;if(i.isDirty||i.hasAnnotations){if(!await Y())return;p=l.current}p||(p=await xt(a.current??n));const R=i.boxes.filter(w=>i.selectedIds.some($=>pe($,"box",w.id))),J=await ha({imageElement:e.current,boxes:R.length>0?R:i.boxes}),ae=Ya(L),K=[(n.prompt??t?.prompt??"").trim(),ae].filter(Boolean).join(`
3
+
4
+ `);if(!K.trim()){P(V("toast.noPromptToFork"),!0);return}const q=n.size??t?.size??null,G=q&&/^\d+x\d+$/.test(q)?q:m(),z=await dn({image:p,mask:await ct(J),prompt:K,quality:b,size:G,format:f,moderation:_,provider:B,n:1,model:A,reasoningEffort:O,mode:T,webSearchEnabled:N});await U(ka(z,K))}catch(L){const p=L.code;P(V(p==="EDIT_MASK_NOT_SUPPORTED"?"canvas.toolbar.editMaskUnsupported":"canvas.toolbar.editMaskFailed"),!0)}finally{Z(!1)}}}}}function tr(e){const t=j(h=>h.currentImage),n=j(h=>h.history),a=j(h=>h.importLocalImageToHistory),[r,l]=c.useState(!1),s=j(h=>{const oe=h.multimodePreviewFlightId;return oe?h.multimodeSequences[oe]??null:null}),i=j(h=>h.selectHistoryShortcutTarget),d=j(h=>h.trashHistoryItem),u=j(h=>h.permanentlyDeleteHistoryItemByShortcut),b=j(h=>h.markGeneratedResultsSeen),f=j(h=>h.activeGenerations),_=j(h=>h.quality),B=j(h=>h.format),A=j(h=>h.moderation),O=j(h=>h.provider),T=j(h=>h.imageModel),N=j(h=>h.reasoningEffort),m=j(h=>h.promptMode),C=j(h=>h.webSearchEnabled),E=j(h=>h.getResolvedSize),y=j(h=>h.showToast),v=j(h=>h.canvasOpen),Z=j(h=>h.openCanvas),I=j(h=>h.closeCanvas),U=j(h=>h.canvasZoom),g=j(h=>h.canvasPanX),S=j(h=>h.canvasPanY),D=j(h=>h.setCanvasPan),P=j(h=>h.setCanvasZoom),V=j(h=>h.resetCanvasZoom),Y=j(h=>h.canvasExportBackground),te=j(h=>h.canvasExportMatteColor),ne=j(h=>h.setCanvasExportBackground),se=j(h=>h.setCanvasExportMatteColor),ue=j(h=>h.applyMergedCanvasImage),L=j(h=>h.addGeneratedHistoryItem),p=j(h=>h.attachCanvasVersionReference),{t:R}=ye(),{creatingBlankCanvas:J,createBlankCanvas:ae}=hn(),le=c.useRef(null),K=c.useRef(null),q=c.useRef(null),G=c.useRef(null),z=c.useRef(null),w=c.useRef(null),$=c.useRef(null),ee=c.useRef(null),W=c.useRef(null),[ce,X]=c.useState(null),[F,de]=c.useState("idle"),[re,we]=c.useState(!1),[Pe,Oe]=c.useState(!1),[$e,Ue]=c.useState(!1),H=Sn(),We=()=>{t?.prompt&&(navigator.clipboard.writeText(t.prompt),y(R("toast.promptCopied")))},He=va(t?.quality),Fe=ba(t?.size),Ve=fn(t?.model),ve=t?.filename??t?.url??t?.image??null,he=ya(n,t),x=v?ce??he??t:t,k=x?ga(x):null,M=Na({canvasOpen:v,currentImage:t,canvasDisplayImage:x,imageElementRef:K,canvasSourceImageRef:$,lastMergedDataUrlRef:ee,setCanvasSaveState:de,setCanvasVersionItem:X,applyMergedCanvasImage:ue,attachCanvasVersionReference:p,showToast:y,t:R}),{imageHasAlpha:Q,backgroundCleanupSeeds:ie,backgroundCleanupPreview:ke,backgroundCleanupMaskOverlay:fe,backgroundCleanupBrushStrokes:Ce,cleanupTool:Wt,cleanupBrushRadius:Ht,cleanupBrushCursor:Ft,isBackgroundCleanupActive:_e}=M,Ke=M.backgroundCleanupPreview?.dataUrl??k,ze=()=>{$.current=null,z.current=null,w.current!=null&&(window.clearTimeout(w.current),w.current=null),X(null),de("idle"),M.resetBackgroundCleanup(),ee.current=null,W.current=null,en()};c.useEffect(()=>{if(!v){G.current=ve,ze();return}if(G.current===null){G.current=ve,$.current=t,X(he);return}G.current!==ve&&(H.resetLocal(),ze(),$.current=t,X(he),G.current=ve)},[H.resetLocal,v,t,ve,he]),c.useEffect(()=>{!v||!t||$.current||($.current=t,X(he))},[v,t,he]),c.useEffect(()=>{if(!v||!t?.filename||t.canvasVersion)return;const h=t.filename;if(z.current===h)return;z.current=h;let oe=!1;return pn(h).then(Me=>{!oe&&Me.annotations&&H.load(Me.annotations)}).catch(()=>{}),()=>{oe=!0}},[H.load,v,t?.canvasVersion,t?.filename]),c.useEffect(()=>{if(!v||!t?.filename||t.canvasVersion||!H.isDirty)return;const h=t.filename;return w.current!=null&&window.clearTimeout(w.current),w.current=window.setTimeout(()=>{const oe=H.toPayload();(H.hasAnnotations?mn(h,oe):jt(h)).then(()=>H.markSaved()).catch(()=>{})},500),()=>{w.current!=null&&(window.clearTimeout(w.current),w.current=null)}},[H,H.hasAnnotations,H.isDirty,v,t?.canvasVersion,t?.filename]);const Vt=h=>{me(h.target)||(b(),h.currentTarget.focus())},Kt=c.useCallback(()=>{window.requestAnimationFrame(()=>q.current?.focus())},[]),zt=h=>{if(v){if(h.preventDefault(),h.ctrlKey){P(U-h.deltaY*.01);return}D(g-h.deltaX,S-h.deltaY)}},Xt=c.useCallback(h=>{Array.from(h.dataTransfer.types).includes("Files")&&(h.preventDefault(),l(oe=>oe||!0))},[]),qt=c.useCallback(h=>{h.currentTarget.contains(h.relatedTarget)||l(!1)},[]),Yt=c.useCallback(async h=>{if(!Array.from(h.dataTransfer.types).includes("Files"))return;h.preventDefault(),l(!1);const oe=Array.from(h.dataTransfer.files).filter(Me=>/^image\/(png|jpeg|webp)$/.test(Me.type));oe.length!==0&&await a(oe[0])},[a]),{handleApplyCanvas:Gt,handleCloseCanvas:dt,handleExportCanvas:Zt,handleEditWithMask:Jt}=Qa({imageElementRef:K,currentImage:t,canvasDisplayImage:x,canvasSourceImageRef:$,lastMergedDataUrlRef:ee,lastCleanDataUrlRef:W,canvasVersionItem:ce,annotations:H,exportBackground:Y,exportMatteColor:te,quality:_,format:B,moderation:A,provider:O,imageModel:T,reasoningEffort:N,promptMode:m,webSearchEnabled:C,getResolvedSize:E,setCanvasVersionItem:X,setCanvasSaveState:de,setIsApplying:we,setIsExporting:Oe,setIsEditingWithMask:Ue,applyMergedCanvasImage:ue,addGeneratedHistoryItem:L,attachCanvasVersionReference:p,closeCanvas:I,resetCanvasSession:ze,showToast:y,t:R}),{spaceHeld:Xe,handleViewerKeyDown:Qt}=Va({canvasOpen:v,canvasZoom:U,currentImage:t,annotations:H,undoBackgroundCleanup:M.undoBackgroundCleanup,redoBackgroundCleanup:M.redoBackgroundCleanup,handleBackgroundCleanupEscape:M.handleBackgroundCleanupEscape,handleCloseCanvas:dt,selectHistoryShortcutTarget:i,trashHistoryItem:d,permanentlyDeleteHistoryItemByShortcut:u,setCanvasZoom:P,resetCanvasZoom:V,onCreateBlankCanvas:ae,isCreatingBlankCanvas:J}),qe=v&&U>1.01&&H.activeTool==="select"&&!_e,{viewportPanActive:Ye,resetPointerSession:en,handleAnnotationPointerDown:tn,handleAnnotationPointerMove:nn,handleAnnotationPointerUp:an,handleAnnotationPointerLeave:rn}=Fa({canvasOpen:v,canvasZoom:U,canvasPanX:g,canvasPanY:S,spaceHeld:Xe,canDragViewportWithSelect:qe,isBackgroundCleanupActive:_e,cleanupTool:Wt,annotationFrameRef:le,annotations:H,setCanvasPan:D,addBackgroundCleanupClick:M.addBackgroundCleanupClick,startBackgroundCleanupBrushStroke:M.startBackgroundCleanupBrushStroke,updateBackgroundCleanupBrushStroke:M.updateBackgroundCleanupBrushStroke,endBackgroundCleanupBrushStroke:M.endBackgroundCleanupBrushStroke,setCleanupBrushCursor:M.setCleanupBrushCursor});return o.jsxs("main",{className:`canvas${v?" canvas--mode-open":""}${r?" canvas--drop-active":""}${Xe?" canvas--space-held":""}${Ye?" canvas--pan-active":""}${qe?" canvas--zoom-hand":""}`,onDragOver:Xt,onDragLeave:qt,onDrop:Yt,children:[r?o.jsx("div",{className:"canvas__drop-overlay","aria-hidden":!0,children:o.jsx("span",{className:"canvas__drop-hint",children:R("canvas.drop.hint")})}):null,v&&o.jsx(ca,{zoom:U,closeLabel:R("canvas.close"),blankCanvasLabel:R("canvas.blank.title"),blankCanvasAriaLabel:`${R(J?"canvas.blank.creating":"canvas.blank.create")} (Shift+B)`,blankCanvasShortcut:"Shift+B",blankCanvasBusy:J,shortcutHint:R("canvas.toolbar.zoomShortcutHint"),onZoomIn:()=>P(U+.1),onZoomOut:()=>P(U-.1),onZoomReset:V,onCreateBlankCanvas:()=>{ae()},onClose:()=>{dt()}}),o.jsx("div",{className:`progress-bar${f>0?" active":""}`}),s?o.jsx(vn,{}):t?o.jsxs("div",{ref:q,className:"result-container visible",tabIndex:0,onMouseDown:Vt,onWheel:zt,onKeyDown:Qt,"aria-label":R("canvas.imageViewerAria"),children:[o.jsx(Nn,{annotationFrameRef:le,imageElementRef:K,frameClassName:`canvas-annotation-frame${(Q||ke)&&v?" canvas-annotation-frame--alpha":""}${_e&&v?" canvas-annotation-frame--cleanup-picking":""}${fe&&v?" canvas-annotation-frame--cleanup-mask":""}`,frameStyle:{cursor:Ye?"grabbing":Xe||qe?"grab":v?_e?"crosshair":H.activeTool==="select"?"default":H.activeTool==="eraser"?H.eraserMode==="object"?pa:ma:"crosshair":"zoom-in",transform:v?`translate(${g}px, ${S}px) scale(${U})`:void 0,transition:v&&!Ye?"transform 0.2s ease":void 0},imageKey:`${x?.filename??x?.url??x?.image}:${x?.canvasMergedAt??""}`,imageSrc:Ke??t.image,fallbackImage:t.image,alt:R("canvas.resultAlt"),canvasOpen:v,maskOverlayUrl:fe?.dataUrl??null,cleanupLayer:o.jsx(On,{seeds:ie,brushStrokes:Ce,brushCursor:Ft,brushRadius:Ht,active:_e}),annotations:H,onOpenCanvas:Z,onPointerDown:tn,onPointerMove:nn,onPointerUp:an,onPointerLeave:rn}),v&&Ke?o.jsx(ua,{imageSrc:Ke,zoom:U,panX:g,panY:S,resetLabel:R("canvas.toolbar.zoomReset"),onReset:V}):null,v&&o.jsx(aa,{annotations:H,backgroundCleanup:M,backgroundCleanupPreview:ke,canvasState:{exportBackground:Y,exportMatteColor:te,isApplying:re,isExporting:Pe,isEditingWithMask:$e},actions:{handleApplyCanvas:Gt,handleExportCanvas:Zt,handleEditWithMask:Jt,setExportBackground:ne,setExportMatteColor:se}}),v&&F!=="idle"?o.jsx("div",{className:`canvas-save-state canvas-save-state--${F}`,children:R(F==="saving"?"canvas.version.saving":F==="saved"?"canvas.version.saved":"canvas.version.failed")}):null,o.jsx(ra,{currentImage:t,canvasDisplayImage:x,canvasOpen:v,displayQuality:He,displaySize:Fe,displayModel:Ve,onAfterDeleteFocus:Kt,onCopyPrompt:We})]}):null]})}export{tr as CanvasModeWorkspace};