ima2-gen 2.0.15 → 2.0.16

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 (125) hide show
  1. package/README.md +30 -0
  2. package/bin/commands/skill.js +336 -17
  3. package/bin/ima2.js +22 -2
  4. package/bin/lib/doctor-checks.js +6 -4
  5. package/config.js +1 -0
  6. package/docs/CLI.md +25 -3
  7. package/docs/PROMPT_STUDIO.ko.md +29 -0
  8. package/docs/PROMPT_STUDIO.md +31 -0
  9. package/docs/migration/runtime-test-inventory.md +7 -1
  10. package/lib/agentImageVideoGen.js +8 -0
  11. package/lib/agentQueueStore.js +36 -10
  12. package/lib/agentQueueWorker.js +79 -7
  13. package/lib/agentRuntime.js +2 -0
  14. package/lib/assetLifecycle.js +40 -8
  15. package/lib/canvasVersionStore.js +86 -0
  16. package/lib/cardNewsGenerator.js +37 -3
  17. package/lib/cardNewsJobStore.js +10 -0
  18. package/lib/cardNewsManifestStore.js +6 -12
  19. package/lib/cardNewsPath.js +25 -0
  20. package/lib/db.js +2 -0
  21. package/lib/generatePipeline.js +474 -0
  22. package/lib/generationInputValidation.js +32 -0
  23. package/lib/grokImageCore.js +18 -1
  24. package/lib/historyIndex.js +11 -4
  25. package/lib/historyList.js +3 -0
  26. package/lib/imageMetadata.js +3 -0
  27. package/lib/inflight.js +30 -3
  28. package/lib/multimodePipeline.js +462 -0
  29. package/lib/nodeGeneration.js +440 -0
  30. package/lib/nodeValidation.js +23 -0
  31. package/lib/oauthProxy/generators.js +3 -246
  32. package/lib/oauthProxy/multimodeGenerators.js +251 -0
  33. package/lib/routeHelpers.js +9 -2
  34. package/package.json +2 -2
  35. package/routes/agent.js +4 -4
  36. package/routes/canvasVersions.js +21 -1
  37. package/routes/cardNews.js +2 -1
  38. package/routes/edit.js +25 -9
  39. package/routes/events.js +5 -1
  40. package/routes/generate.js +2 -481
  41. package/routes/keys.js +31 -39
  42. package/routes/multimode.js +2 -502
  43. package/routes/nodes.js +3 -448
  44. package/routes/video.js +12 -3
  45. package/routes/videoExtended.js +19 -4
  46. package/server.js +53 -1
  47. package/skills/ima2/SKILL.md +204 -0
  48. package/skills/ima2-front/SKILL.md +611 -0
  49. package/skills/ima2-front/references/a11y-patterns.md +134 -0
  50. package/skills/ima2-front/references/aesthetics.md +327 -0
  51. package/skills/ima2-front/references/anti-slop.md +241 -0
  52. package/skills/ima2-front/references/asset-requirements.md +431 -0
  53. package/skills/ima2-front/references/brand-asset-sourcing.md +122 -0
  54. package/skills/ima2-front/references/color-system.md +132 -0
  55. package/skills/ima2-front/references/consistency-locks.md +20 -0
  56. package/skills/ima2-front/references/crud-ui.md +53 -0
  57. package/skills/ima2-front/references/dropdown-layer.md +110 -0
  58. package/skills/ima2-front/references/i18n-global.md +104 -0
  59. package/skills/ima2-front/references/iterative-design.md +90 -0
  60. package/skills/ima2-front/references/korea-2026.md +174 -0
  61. package/skills/ima2-front/references/layout-discipline.md +161 -0
  62. package/skills/ima2-front/references/liquid-glass.md +181 -0
  63. package/skills/ima2-front/references/logo-sections.md +194 -0
  64. package/skills/ima2-front/references/mobile-ux.md +144 -0
  65. package/skills/ima2-front/references/performance-budget.md +106 -0
  66. package/skills/ima2-front/references/preflight-full.md +58 -0
  67. package/skills/ima2-front/references/product-density.md +53 -0
  68. package/skills/ima2-front/references/prototype-variants.md +54 -0
  69. package/skills/ima2-front/references/reference-capture.md +120 -0
  70. package/skills/ima2-front/references/responsive-viewport.md +139 -0
  71. package/skills/ima2-front/references/seo-baseline.md +123 -0
  72. package/skills/ima2-front/references/soft-3d-asset-gates.md +70 -0
  73. package/skills/ima2-front/references/stacks/astro.md +204 -0
  74. package/skills/ima2-front/references/stacks/mobile-native.md +281 -0
  75. package/skills/ima2-front/references/stacks/nextjs.md +219 -0
  76. package/skills/ima2-front/references/stacks/react.md +264 -0
  77. package/skills/ima2-front/references/stacks/svelte.md +235 -0
  78. package/skills/ima2-front/references/stacks/vanilla.md +226 -0
  79. package/skills/ima2-front/references/theme-switching.md +82 -0
  80. package/skills/ima2-front/references/top-bar.md +126 -0
  81. package/skills/ima2-front/references/typography-wrapping.md +270 -0
  82. package/skills/ima2-front/references/ux-writing-ko.md +62 -0
  83. package/skills/ima2-front/references/visual-verification.md +102 -0
  84. package/skills/ima2-uiux/SKILL.md +477 -0
  85. package/skills/ima2-uiux/references/anti-slop-judgment.md +39 -0
  86. package/skills/ima2-uiux/references/color-system.md +80 -0
  87. package/skills/ima2-uiux/references/design-isms.md +194 -0
  88. package/skills/ima2-uiux/references/design-read-example.md +33 -0
  89. package/skills/ima2-uiux/references/design-system-bootstrap.md +133 -0
  90. package/skills/ima2-uiux/references/favicon-logo.md +355 -0
  91. package/skills/ima2-uiux/references/form-patterns.md +118 -0
  92. package/skills/ima2-uiux/references/intent-discovery-ladder.md +86 -0
  93. package/skills/ima2-uiux/references/korean-design-vocabulary.md +52 -0
  94. package/skills/ima2-uiux/references/layout-macrostructures.md +54 -0
  95. package/skills/ima2-uiux/references/logo-trust-sections.md +96 -0
  96. package/skills/ima2-uiux/references/mobile-native-ux.md +207 -0
  97. package/skills/ima2-uiux/references/product-personalities.md +118 -0
  98. package/skills/ima2-uiux/references/responsive-nav.md +66 -0
  99. package/skills/ima2-uiux/references/typography-line-breaks.md +193 -0
  100. package/skills/ima2-uiux/references/ux-preflight.md +65 -0
  101. package/skills/ima2-uiux/references/ux-states.md +197 -0
  102. package/skills/ima2-uiux/references/visual-hierarchy.md +115 -0
  103. package/ui/dist/.vite/manifest.json +13 -13
  104. package/ui/dist/assets/AgentWorkspace-CtYt4SF5.js +3 -0
  105. package/ui/dist/assets/{CardNewsWorkspace-Cdxn1ohU.js → CardNewsWorkspace-DN5cVqG5.js} +1 -1
  106. package/ui/dist/assets/GenerationRequestLogPanel-DnmUQdKR.js +1 -0
  107. package/ui/dist/assets/{NodeCanvas-C67sLboA.js → NodeCanvas-CxpfIBI0.js} +1 -1
  108. package/ui/dist/assets/PromptBuilderPanel-C2R3ObtR.js +2 -0
  109. package/ui/dist/assets/{PromptImportDialog-DeQXsEEv.js → PromptImportDialog-BIxz_yEx.js} +2 -2
  110. package/ui/dist/assets/PromptImportDiscoverySection-BQTlPMME.js +1 -0
  111. package/ui/dist/assets/PromptImportFolderSection-Ds_Th9O3.js +1 -0
  112. package/ui/dist/assets/{PromptLibraryPanel-Db3xEPM_.js → PromptLibraryPanel-Rs4l45pV.js} +2 -2
  113. package/ui/dist/assets/{SettingsWorkspace-BDk_1W-V.js → SettingsWorkspace-p1AZ6uT9.js} +1 -1
  114. package/ui/dist/assets/index-0-_vgFGs.js +4 -0
  115. package/ui/dist/assets/index-Dm3pFxV4.js +23 -0
  116. package/ui/dist/assets/index-J8yDF3Ch.css +1 -0
  117. package/ui/dist/index.html +2 -2
  118. package/ui/dist/assets/AgentWorkspace-DAg_7zpY.js +0 -3
  119. package/ui/dist/assets/GenerationRequestLogPanel-C_qvEUi2.js +0 -1
  120. package/ui/dist/assets/PromptBuilderPanel-DjvVdAie.js +0 -2
  121. package/ui/dist/assets/PromptImportDiscoverySection-CrwyUKYI.js +0 -1
  122. package/ui/dist/assets/PromptImportFolderSection-CToGMqYE.js +0 -1
  123. package/ui/dist/assets/index-2oG6in1i.css +0 -1
  124. package/ui/dist/assets/index-CoxMOXAU.js +0 -23
  125. package/ui/dist/assets/index-p8egnGHk.js +0 -4
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PromptImportDiscoverySection-CrwyUKYI.js","assets/index-CoxMOXAU.js","assets/index-2oG6in1i.css","assets/PromptImportFolderSection-CToGMqYE.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-CoxMOXAU.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-CrwyUKYI.js"),__vite__mapDeps([0,1,2])).then(i=>({default:i.PromptImportDiscoverySection}))),je=o.lazy(()=>J(()=>import("./PromptImportFolderSection-CToGMqYE.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-BQTlPMME.js","assets/index-Dm3pFxV4.js","assets/index-J8yDF3Ch.css","assets/PromptImportFolderSection-Ds_Th9O3.js"])))=>i.map(i=>d[i]);
2
+ import{u as V,j as e,b as ce,a as o,V as K,X as M,Y as pe,Z as de,$ as me,_ as X}from"./index-Dm3pFxV4.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(()=>X(()=>import("./PromptImportDiscoverySection-BQTlPMME.js"),__vite__mapDeps([0,1,2])).then(i=>({default:i.PromptImportDiscoverySection}))),je=o.lazy(()=>X(()=>import("./PromptImportFolderSection-Ds_Th9O3.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),[Y,N]=o.useState(!1),[Z,$]=o.useState([]),[A,J]=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();$(r.sources),z(new Set)},[]);o.useEffect(()=>{if(!i)return;let r=!1;return K().then(a=>{r||($(a.sources),z(new Set))}).catch(()=>{r||$([])}),()=>{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:A.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,A,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${Y?" 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:Z.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:A,onChange:r=>J(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};
@@ -0,0 +1 @@
1
+ import{u as L,a as t,a0 as S,a1 as C,a2 as P,j as r}from"./index-Dm3pFxV4.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,a3 as S,a4 as _,j as t}from"./index-Dm3pFxV4.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-DeQXsEEv.js","assets/index-CoxMOXAU.js","assets/index-2oG6in1i.css"])))=>i.map(i=>d[i]);
2
- import{u,j as r,a as n,b as s,S as E,_ as $}from"./index-CoxMOXAU.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-DeQXsEEv.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-BIxz_yEx.js","assets/index-Dm3pFxV4.js","assets/index-J8yDF3Ch.css"])))=>i.map(i=>d[i]);
2
+ import{u,j as r,a as n,b as s,S as E,_ as $}from"./index-Dm3pFxV4.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-BIxz_yEx.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 +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-CoxMOXAU.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};
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-Dm3pFxV4.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 i,j as o,u as ye,f as dn,x as hn,y as fn,z as pn,B as Tt,C as Pt,D as me,E as mn,b as T,F as At,G as vn,H as bn,J as Dt,K as gn,c as xn,L as yn,N as kn}from"./index-Dm3pFxV4.js";const Ae=2,Oe=1e-6;function wn({paths:e,points:t,radius:n,makeId:a=()=>crypto.randomUUID()}){if(e.length===0||t.length===0||n<=0)return{paths:e,changed:!1};let r=!1;const l=[];for(const s of e){const c=Cn(s,t,n,a);(c.length!==1||c[0]!==s)&&(r=!0),l.push(...c)}return{paths:l,changed:r}}function Cn(e,t,n,a=()=>crypto.randomUUID()){if(e.points.length<Ae||t.length===0||n<=0)return[e];const r=[];let l=Te(e.points[0],t,n)?[]:[e.points[0]];for(let c=1;c<e.points.length;c+=1){const d=e.points[c-1],u=e.points[c],b=Te(u,t,n),f=_n(d,u,t,n);if(f){l.length===0&&!Te(d,t,n)&&(l=[d]),l.length>0&&f.leftT>Oe&&ft(l,Pe(d,u,f.leftT)),l.length>=Ae&&r.push(l),l=[],f.rightT<1-Oe&&!b&&(l=[Pe(d,u,f.rightT),u]);continue}if(b){l.length>=Ae&&r.push(l),l=[];continue}l.length===0&&!Te(d,t,n)&&(l=[d]),ft(l,u)}if(l.length>=Ae&&r.push(l),r.length===0)return[];if(r.length===1&&r[0].length===e.points.length)return[e];const s=e.tool==="arrow"?r.length-1:-1;return r.map((c,d)=>({...e,id:d===0?e.id:a(),tool:e.tool==="arrow"&&d!==s?"pen":e.tool,points:c}))}function Te(e,t,n){if(t.length===1)return xe(e,t[0])<=n;for(let a=1;a<t.length;a+=1)if(Mn(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 _n(e,t,n,a){const r=xe(e,t);if(r<=Oe)return Te(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=Pe(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=Pe(n[d-1],n[d],b),_=ht(f,e,t),j=Pe(e,t,_),R=xe(f,j);R<s&&(s=R,l=_)}}if(l===null||s>a)return null;const c=Math.max(a/r,.01);return{leftT:Math.max(0,l-c),rightT:Math.min(1,l+c)}}function 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,c=a*a+r*r;return c===0?0:Math.max(0,Math.min(1,(l*a+s*r)/c))}function Pe(e,t,n){return{x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}}function ft(e,t){const n=e.at(-1);(!n||xe(n,t)>Oe)&&e.push(t)}function Mn(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,c=a*a+r*r;if(c===0)return xe(e,t);const d=Math.max(0,Math.min(1,(l*a+s*r)/c));return xe(e,{x:t.x+d*a,y:t.y+d*r})}function lt(e,t){return`${e}:${t}`}function ct(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 Rt(e){return lt("path",e.id)}function It(e){return lt("box",e.id)}function Nt(e){return lt("memo",e.id)}function pe(e,t,n){const a=ct(e);return a?.kind===t&&a.id===n}const Ot="ima2.canvas.annotationStyle.v1",Lt=["#ef4444","#f97316","#eab308","#22c55e","#38bdf8","#6366f1","#a855f7","#111827","#ffffff"],$t=[2,3,5,8],Se={color:"#ef4444",strokeWidth:3};function En(){if(typeof window>"u")return Se;try{const e=window.localStorage.getItem(Ot);if(!e)return Se;const t=JSON.parse(e),n=typeof t.color=="string"&&Lt.includes(t.color)?t.color:Se.color,a=typeof t.strokeWidth=="number"&&$t.includes(t.strokeWidth)?t.strokeWidth:Se.strokeWidth;return{color:n,strokeWidth:a}}catch{return Se}}function Sn(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Ot,JSON.stringify(e))}catch{}}const pt=En(),nt={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 Ze(e,t){return{...e,past:[...e.past.slice(-49),t],future:[]}}function Bn(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 jn(e,t,n){const{start:a,current:r}=e,l=Math.min(a.x,r.x),s=Math.min(a.y,r.y),c=Math.abs(r.x-a.x),d=Math.abs(r.y-a.y);return c<.01||d<.01?null:{id:crypto.randomUUID(),x:l,y:s,width:c,height:d,color:t,strokeWidth:n}}function Tn(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 Je(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 Pn(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=jn(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?Bn(e.memoBaseline,ge(e))?{...e,memoBaseline:null,activeMemoId:null}:{...Ze(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{...nt,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{...nt,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=>Je(a,t.delta))}:n),boxes:e.boxes.map(n=>e.selectedIds.some(a=>pe(a,"box",n.id))?Tn(n,t.delta):n),memos:e.memos.map(n=>e.selectedIds.some(a=>pe(a,"memo",n.id))?{...n,x:Je(n,t.delta).x,y:Je(n,t.delta).y}:n)};case"START_SELECTED_MOVE":return{...e,moveBaseline:ge(e)};case"COMMIT_SELECTED_MOVE":return e.moveBaseline?{...Ze(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=ct(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=wn({paths:e.paths,points:e.activeEraserStroke.points,radius:e.activeEraserStroke.radius});return n.changed?{...Ze(e,e.eraserBaseline),paths:n.paths,activeEraserStroke:null,eraserBaseline:null,selectedIds:[],isDirty:!0}:{...e,activeEraserStroke:null,eraserBaseline:null}}default:return e}}function An(){const[e,t]=i.useReducer(Pn,nt),n=i.useMemo(()=>e.paths.length>0||e.boxes.length>0||e.memos.length>0,[e.paths.length,e.boxes.length,e.memos.length]),a=e.past.length>0,r=e.future.length>0,l=i.useCallback(p=>t({type:"SET_TOOL",tool:p}),[]),s=i.useCallback(p=>{Sn(p),t({type:"SET_STYLE",style:p})},[]),c=i.useCallback(()=>t({type:"CLEAR"}),[]),d=i.useCallback(p=>t({type:"LOAD",payload:p}),[]),u=i.useCallback(()=>t({type:"MARK_SAVED"}),[]),b=i.useCallback(()=>t({type:"RESET_LOCAL"}),[]),f=i.useCallback(()=>t({type:"UNDO"}),[]),_=i.useCallback(()=>t({type:"REDO"}),[]),j=i.useCallback(()=>t({type:"COMMIT_MEMO_EDIT"}),[]),R=i.useCallback(()=>t({type:"START_SELECTED_MOVE"}),[]),H=i.useCallback(()=>t({type:"COMMIT_SELECTED_MOVE"}),[]),P=i.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]),O=i.useCallback(p=>{e.activePath?t({type:"ADD_POINT",point:p}):e.activeBox&&t({type:"UPDATE_BOX",point:p})},[e.activePath,e.activeBox]),v=i.useCallback(()=>{e.activePath?t({type:"END_PATH"}):e.activeBox&&t({type:"END_BOX"})},[e.activePath,e.activeBox]),C=i.useCallback(p=>t({type:"CREATE_MEMO",point:p}),[]),M=i.useCallback((p,B)=>t({type:"UPDATE_MEMO",id:p,text:B}),[]),y=i.useCallback(p=>t({type:"DELETE_MEMO",id:p}),[]),m=i.useCallback(p=>t({type:"FOCUS_MEMO",id:p}),[]),J=i.useCallback(p=>t({type:"SET_ERASER_MODE",mode:p}),[]),I=i.useCallback(p=>t({type:"SELECT_ONE",id:p}),[]),K=i.useCallback(p=>t({type:"TOGGLE_SELECTED",id:p}),[]),g=i.useCallback(()=>t({type:"CLEAR_SELECTION"}),[]),S=i.useCallback(()=>t({type:"DELETE_SELECTED"}),[]),D=i.useCallback(p=>t({type:"MOVE_SELECTED",delta:p}),[]),A=i.useCallback(p=>t({type:"START_SELECTION_BOX",point:p}),[]),L=i.useCallback(p=>t({type:"UPDATE_SELECTION_BOX",point:p}),[]),Z=i.useCallback(p=>t({type:"END_SELECTION_BOX",ids:p}),[]),ee=i.useCallback(p=>t({type:"ERASE_OBJECT",id:p}),[]),te=i.useCallback(p=>t({type:"START_ERASER_STROKE",point:p}),[]),se=i.useCallback(p=>t({type:"UPDATE_ERASER_STROKE",point:p}),[]),ie=i.useCallback(()=>t({type:"END_ERASER_STROKE"}),[]),ue=i.useCallback(()=>({paths:e.paths,boxes:e.boxes,memos:e.memos}),[e.paths,e.boxes,e.memos]);return{...e,canUndo:a,canRedo:r,hasAnnotations:n,setTool:l,setStyle:s,setEraserMode:J,startDrawing:P,moveDrawing:O,endDrawing:v,createMemo:C,updateMemo:M,commitMemoEdit:j,deleteMemo:y,focusMemo:m,clear:c,load:d,toPayload:ue,markSaved:u,resetLocal:b,undo:f,redo:_,selectOne:I,toggleSelected:K,clearSelection:g,deleteSelected:S,moveSelected:D,startSelectedMove:R,commitSelectedMove:H,startSelectionBox:A,updateSelectionBox:L,endSelectionBox:Z,eraseObjectAtPoint:ee,startEraserStroke:te,updateEraserStroke:se,endEraserStroke:ie}}function De(e,t){return{x:e.x*t.width,y:e.y*t.height}}function at(e,t,n){if(t.points.length<2)return;const a=De(t.points[0],n);e.save(),e.beginPath(),e.strokeStyle=t.color,e.lineWidth=t.strokeWidth,e.lineCap="round",e.lineJoin="round",e.moveTo(a.x,a.y);for(const r of t.points.slice(1)){const l=De(r,n);e.lineTo(l.x,l.y)}if(e.stroke(),t.tool==="arrow"){const r=De(t.points[t.points.length-1],n),l=De(t.points[t.points.length-2],n);In(e,l,r,t.color,t.strokeWidth)}e.restore()}function rt(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 Dn(e,t,n){const a=t.x*n.width,r=t.y*n.height,l=Math.min(260,Math.max(150,n.width*.22)),s=12,c=18;e.save(),e.font="14px sans-serif";const d=Nn(e,t.text.trim()||" ",l-s*2),u=Math.max(52,s*2+d.length*c);e.fillStyle="rgba(255, 246, 179, 0.96)",e.strokeStyle="rgba(44, 37, 12, 0.28)",e.lineWidth=1,On(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*c)}),e.restore()}function Rn(e,t){const n=ct(e);if(!n)return null;if(n.kind==="box")return t.boxes.find(u=>u.id===n.id)??null;const a=n.kind==="memo"?t.memos.find(u=>u.id===n.id):null;if(a)return{id:a.id,x:a.x,y:a.y,width:.18,height:.12,color:a.color,strokeWidth:1};if(n.kind!=="path")return null;const r=t.paths.find(u=>u.id===n.id);if(!r||r.points.length===0)return null;const l=r.points.map(u=>u.x),s=r.points.map(u=>u.y),c=Math.min(...l),d=Math.min(...s);return{id:r.id,x:c,y:d,width:Math.max(.01,Math.max(...l)-c),height:Math.max(.01,Math.max(...s)-d),color:r.color,strokeWidth:r.strokeWidth}}function 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 In(e,t,n,a,r){const l=Math.atan2(n.y-t.y,n.x-t.x),s=Math.max(12,r*4),c=Math.PI/7;e.save(),e.fillStyle=a,e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x-s*Math.cos(l-c),n.y-s*Math.sin(l-c)),e.lineTo(n.x-s*Math.cos(l+c),n.y-s*Math.sin(l+c)),e.closePath(),e.fill(),e.restore()}function Nn(e,t,n){const a=t.split(/\s+/).filter(Boolean);if(a.length===0)return[""];const r=[];let l="";for(const s of a){const c=l?`${l} ${s}`:s;if(e.measureText(c).width<=n||l===""){l=c;continue}r.push(l),l=s}return l&&r.push(l),r}function On(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 Ln({paths:e,boxes:t,memos:n=[],selectedIds:a=[],selectionBox:r=null,activePath:l,activeBox:s}){const c=i.useRef(null);return i.useEffect(()=>{const d=c.current;if(!d)return;const u=d.getBoundingClientRect(),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 j of e)at(f,j,_);for(const j of t)rt(f,j,_,"committed");for(const j of a){const R=Rn(j,{paths:e,boxes:t,memos:n});R&&vt(f,R,_)}r&&vt(f,r,_),l&&at(f,l,_),s&&rt(f,s,_,"active")},[e,t,n,a,r,l,s]),o.jsx("canvas",{ref:c,className:"canvas-annotation-layer","aria-hidden":"true"})}function Re(e){e.stopPropagation()}function $n({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:Re,onPointerMove:Re,onPointerUp:Re,onPointerCancel:Re,onChange:c=>n(s.id,c.currentTarget.value),onBlur:()=>{l?.(),s.text.trim()===""&&a(s.id)},"aria-label":"Canvas memo"},s.id))})}function Un({annotationFrameRef:e,imageElementRef:t,frameClassName:n,frameStyle:a,imageKey:r,imageSrc:l,fallbackImage:s,alt:c,canvasOpen:d,maskOverlayUrl:u,cleanupLayer:b,annotations:f,onOpenCanvas:_,onPointerDown:j,onPointerMove:R,onPointerUp:H,onPointerLeave:P}){return o.jsxs("div",{ref:e,className:n,onPointerDown:j,onPointerMove:R,onPointerUp:H,onPointerCancel:H,onPointerLeave:P,style:a,children:[o.jsx("img",{ref:t,className:"result-img",src:l??s,alt:c,decoding:"async",onDoubleClick:O=>{O.stopPropagation(),_()}},r),d&&u?o.jsx("img",{className:"canvas-background-cleanup-mask",src:u,alt:"","aria-hidden":"true",decoding:"async"}):null,d?b:null,d&&o.jsxs(o.Fragment,{children:[o.jsx(Ln,{paths:f.paths,boxes:f.boxes,memos:f.memos,selectedIds:f.selectedIds,selectionBox:f.selectionBox,activePath:f.activePath,activeBox:f.activeBox}),o.jsx($n,{memos:f.memos,activeMemoId:f.activeMemoId,onUpdate:f.updateMemo,onDelete:f.deleteMemo,onFocus:f.focusMemo,onCommit:f.commitMemoEdit})]})]})}function Wn(e){return`${e.x*100} ${e.y*100}`}function Fn(e){return e.map(Wn).join(" ")}function Hn({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:Fn(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 Kn({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 zn({seedCount:e,tolerance:t,stats:n,hasPreview:a,isPickingSeed:r,intent:l,tool:s,brushRadius:c,isPreviewing:d,isApplying:u,keepOpen:b,disabled:f,onAutoSample:_,onPickSeed:j,onIntentChange:R,onToolChange:H,onBrushRadiusChange:P,onToleranceChange:O,onPreview:v,onApply:C,onReset:M}){const{t:y}=ye(),[m,J]=i.useState(!1),I=i.useRef(null),K=n?Math.round(n.removedPercent*1e3)/10:0,g=r||s==="brush";return i.useEffect(()=>{if(!m)return;const S=D=>{b||I.current?.contains(D.target)||J(!1)};return window.addEventListener("pointerdown",S),()=>window.removeEventListener("pointerdown",S)},[b,m]),o.jsxs("div",{className:"canvas-toolbar__cleanup",ref:I,children:[o.jsx("button",{type:"button",className:`canvas-toolbar__button${m||a?" canvas-toolbar__button--active":""}`,onClick:()=>J(S=>!S),disabled:f,"aria-expanded":m,"aria-label":y("canvas.toolbar.cleanup"),title:y("canvas.toolbar.cleanup"),children:o.jsx(Vn,{})}),m?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:R}),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:H}),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=>O(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:c,onChange:S=>P(Number(S.target.value))}),o.jsx("output",{children:Math.round(c*1e3)})]}):null,o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:_,children:y("canvas.toolbar.cleanupAutoSample")}),o.jsx("button",{type:"button",className:r?"active":"",onClick:j,children:y(g?"canvas.toolbar.cleanupActive":"canvas.toolbar.cleanupPickSeed")})]}),o.jsxs("div",{className:"canvas-toolbar__cleanup-actions",children:[o.jsx("button",{type:"button",onClick:v,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:M,disabled:!a&&e===0,children:y("canvas.toolbar.cleanupReset")})]}),g?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:y(s==="brush"?"canvas.toolbar.cleanupBrushHint":"canvas.toolbar.cleanupPickHint")}):n&&!a?o.jsx("div",{className:"canvas-toolbar__cleanup-status canvas-toolbar__cleanup-status--active",children:y("canvas.toolbar.cleanupMaskHint")}):null,n?o.jsx("div",{className:"canvas-toolbar__cleanup-status",children:y("canvas.toolbar.cleanupRemoved",{n:K})}):null]}):null]})}function Vn(){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 Xn({style:e,onStyleChange:t}){const{t:n}=ye(),[a,r]=i.useState(!1),l=i.useRef(null);return i.useEffect(()=>{if(!a)return;const s=c=>{l.current?.contains(c.target)||r(!1)};return window.addEventListener("pointerdown",s),()=>window.removeEventListener("pointerdown",s)},[a]),o.jsxs("div",{ref:l,className:`canvas-toolbar__split-button${a?" canvas-toolbar__split-button--active":""}`,onKeyDown:s=>{s.key==="Escape"&&a&&(s.preventDefault(),s.stopPropagation(),r(!1))},children:[o.jsxs("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__style-trigger",onClick:()=>r(s=>!s),"aria-haspopup":"dialog","aria-expanded":a,"aria-label":n("canvas.toolbar.style"),title:n("canvas.toolbar.style"),children:[o.jsx("span",{className:"canvas-style-trigger__swatch",style:{background:e.color},"aria-hidden":"true"}),o.jsx("span",{className:"canvas-style-trigger__width",style:{height:`${Math.min(8,Math.max(2,e.strokeWidth))}px`},"aria-hidden":"true"})]}),a?o.jsxs("div",{className:"canvas-style-popover",role:"dialog","aria-label":n("canvas.toolbar.style"),children:[o.jsx("div",{className:"canvas-style-popover__row",role:"group","aria-label":n("canvas.toolbar.color"),children:Lt.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:$t.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 qn({tools:e,activeTool:t,onToolChange:n}){const[a,r]=i.useState(!1),l=i.useRef(null),s=e.find(d=>d.id===t)??e[0],c=s.icon;return i.useEffect(()=>{if(!a)return;const d=u=>{l.current?.contains(u.target)||r(!1)};return window.addEventListener("pointerdown",d),()=>window.removeEventListener("pointerdown",d)},[a]),o.jsxs("div",{ref:l,className:"canvas-tool-picker",children:[o.jsxs("button",{type:"button",className:`canvas-toolbar__button canvas-tool-picker__trigger${t!=="eraser"?" canvas-toolbar__button--active":""}`,onClick:()=>r(d=>!d),"aria-label":`${s.label} (${s.shortcut})`,"aria-pressed":t===s.id,"aria-haspopup":"menu","aria-expanded":a,title:`${s.label} (${s.shortcut})`,children:[o.jsx(c,{}),o.jsx("span",{className:"canvas-toolbar__shortcut","aria-hidden":"true",children:s.shortcut})]}),a?o.jsx("div",{className:"canvas-tool-picker__menu",role:"menu",children:e.map(d=>{const u=d.icon,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 Yn({activeTool:e,hasAnnotations:t,hasExportableContent:n,onToolChange:a,eraserMode:r="object",onEraserModeChange:l,style:s,onStyleChange:c,onClear:d,onApply:u,onRevertAnnotations:b,onExport:f,onUndo:_,onRedo:j,canUndo:R,canRedo:H,onDeleteSelected:P,selectedCount:O=0,onEditWithMask:v,canEditWithMask:C,isEditingWithMask:M,isApplying:y,isExporting:m,exportBackground:J="alpha",exportMatteColor:I="#ffffff",onExportBackgroundChange:K,onExportMatteColorChange:g,cleanupTolerance:S=28,cleanupSeedCount:D=0,cleanupStats:A=null,cleanupHasPreview:L=!1,isCleanupPickingSeed:Z=!1,isCleanupActive:ee=!1,cleanupIntent:te="remove",cleanupTool:se="click",cleanupBrushRadius:ie=.018,isCleanupPreviewing:ue=!1,isCleanupApplying:p=!1,onCleanupAutoSample:B,onCleanupPickSeed:W,onCleanupIntentChange:ne,onCleanupToolChange:ae,onCleanupBrushRadiusChange:G,onCleanupToleranceChange:X,onCleanupPreview:$,onCleanupApply:F,onCleanupReset:N}){const{t:w}=ye(),[Y,U]=i.useState(!1),le=i.useRef(null),q=n??t??!1,z=w(r==="object"?"canvas.toolbar.objectEraser":"canvas.toolbar.brushEraser"),de=[{id:"select",shortcut:"1",label:w("canvas.toolbar.select"),icon:Gn},{id:"pen",shortcut:"2",label:w("canvas.toolbar.pen"),icon:Zn},{id:"box",shortcut:"3",label:w("canvas.toolbar.box"),icon:Jn},{id:"arrow",shortcut:"4",label:w("canvas.toolbar.arrow"),icon:Qn},{id:"memo",shortcut:"5",label:w("canvas.toolbar.memo"),icon:ea}];i.useEffect(()=>{if(!Y)return;const re=we=>{le.current?.contains(we.target)||U(!1)};return window.addEventListener("pointerdown",re),()=>window.removeEventListener("pointerdown",re)},[Y]);const ke=re=>{l?.(re),a("eraser"),U(!1)};return o.jsxs("div",{className:"canvas-toolbar","aria-label":w("canvas.toolbar.label"),children:[o.jsx(qn,{tools:de,activeTool:e,onToolChange:a}),o.jsx(Xn,{style:s,onStyleChange:c}),o.jsxs("div",{ref:le,className:`canvas-toolbar__split-button${e==="eraser"?" canvas-toolbar__split-button--active":""}`,onKeyDown:re=>{re.key==="Escape"&&Y&&(re.preventDefault(),U(!1))},children:[o.jsxs("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--split-main${e==="eraser"?" canvas-toolbar__button--active":""}`,onClick:()=>a("eraser"),"aria-label":`${z} (6)`,"aria-pressed":e==="eraser",title:`${z} (6)`,children:[o.jsx(ta,{}),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:()=>U(re=>!re),"aria-label":w("canvas.toolbar.eraserMenu"),"aria-haspopup":"menu","aria-expanded":Y,"aria-controls":"canvas-eraser-menu",title:w("canvas.toolbar.eraserMenu"),children:o.jsx(na,{})}),Y?o.jsxs("div",{id:"canvas-eraser-menu",className:"canvas-toolbar__eraser-menu",role:"menu",children:[o.jsx("button",{type:"button",className:`canvas-toolbar__eraser-menu-item${r==="object"?" canvas-toolbar__eraser-menu-item--active":""}`,role:"menuitemradio","aria-checked":r==="object",onClick:()=>ke("object"),children: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:()=>ke("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${y?" canvas-toolbar__button--busy":""}`,onClick:u,disabled:!q||y,"aria-label":w("canvas.toolbar.apply"),title:w("canvas.toolbar.apply"),children:o.jsx(aa,{})}):null,b?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:b,disabled:y,"aria-label":w("canvas.revert.action"),title:w("canvas.revert.action"),children:o.jsx(xt,{})}):null,v?o.jsx("button",{type:"button",className:`canvas-toolbar__button canvas-toolbar__button--primary canvas-toolbar__button--mask${M?" canvas-toolbar__button--busy":""}`,onClick:v,disabled:!C||M,"aria-label":w(C?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),title:w(C?"canvas.toolbar.editMask":"canvas.toolbar.editMaskDisabled"),children:o.jsx(sa,{})}):null,_?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:_,disabled:!R,"aria-label":w("canvas.toolbar.undo"),title:w("canvas.toolbar.undo"),children:o.jsx(xt,{})}):null,j?o.jsx("button",{type:"button",className:"canvas-toolbar__button",onClick:j,disabled:!H,"aria-label":w("canvas.toolbar.redo"),title:w("canvas.toolbar.redo"),children:o.jsx(oa,{})}):null,P?o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:P,disabled:O===0,"aria-label":w("canvas.toolbar.deleteSelected"),title:w("canvas.toolbar.deleteSelected"),children:o.jsx(gt,{})}):null,f&&K&&g?o.jsx(Kn,{mode:J,matteColor:I,onModeChange:K,onMatteColorChange:g}):null,B&&W&&ne&&ae&&G&&X&&$&&F&&N?o.jsx(zn,{seedCount:D,tolerance:S,stats:A,hasPreview:L,isPickingSeed:Z,intent:te,tool:se,brushRadius:ie,isPreviewing:ue,isApplying:p,keepOpen:ee,disabled:y||m,onAutoSample:B,onPickSeed:W,onIntentChange:ne,onToolChange:ae,onBrushRadiusChange:G,onToleranceChange:X,onPreview:$,onApply:F,onReset:N}):null,f?o.jsx("button",{type:"button",className:`canvas-toolbar__button${m?" canvas-toolbar__button--busy":""}`,onClick:f,disabled:!q||m,"aria-label":w("canvas.toolbar.export"),title:w("canvas.toolbar.export"),children:o.jsx(ra,{})}):null,o.jsx("button",{type:"button",className:"canvas-toolbar__button canvas-toolbar__button--danger",onClick:d,disabled:!q,"aria-label":w("canvas.toolbar.clear"),title:w("canvas.toolbar.clear"),children:o.jsx(gt,{})})]})}function Gn(){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 Jn(){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 ea(){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 ta(){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 na(){return o.jsx("svg",{className:"canvas-toolbar__icon canvas-toolbar__icon--small",viewBox:"0 0 24 24","aria-hidden":"true",children:o.jsx("path",{d:"m7 14 5-5 5 5"})})}function aa(){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 ra(){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 xt(){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 oa(){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 sa(){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 la({annotations:e,backgroundCleanup:t,backgroundCleanupPreview:n,canvasState:a,actions:r}){return o.jsx(Yn,{activeTool:e.activeTool,eraserMode:e.eraserMode,onEraserModeChange:e.setEraserMode,style:{color:e.toolColor,strokeWidth:e.strokeWidth},onStyleChange:e.setStyle,hasExportableContent:e.hasAnnotations,onToolChange:e.setTool,onClear:e.clear,onApply:()=>{r.handleApplyCanvas()},onRevertAnnotations:a.canRevertAnnotations?()=>{r.handleRevertAnnotations()}:void 0,onExport:()=>{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 ca({currentImage:e,canvasDisplayImage:t,canvasOpen:n,displayQuality:a,displaySize:r,displayModel:l,onAfterDeleteFocus:s,onCopyPrompt:c}){const{t:d}=ye(),u=[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?d("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,dn(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(hn,{imageOverride:n?t:null,onAfterDeleteFocus:s}),e.prompt?o.jsx(fn,{prompt:e.prompt,onCopy:c}):null]})}function ia({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(ua,{})}),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(da,{})})]})}function ua(){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 da(){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 ha({zoom:e,closeLabel:t,blankCanvasLabel:n,blankCanvasAriaLabel:a,blankCanvasShortcut:r,blankCanvasBusy:l,shortcutHint:s,onZoomIn:c,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(ia,{zoom:e,onZoomIn:c,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 Qe(e,t,n){return Math.max(t,Math.min(n,e))}function fa({zoom:e,panX:t,panY:n}){const a=Qe(100/Math.max(1,e),18,100),r=a/2,l=Qe(50-t/40,r,100-r),s=Qe(50-n/40,r,100-r);return{width:`${a}%`,height:`${a}%`,left:`${l}%`,top:`${s}%`}}function pa({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:fa({zoom:t,panX:n,panY:a}),"aria-hidden":"true"})]})}function Ie(e){return Math.min(1,Math.max(0,e))}function ma(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("mask_blob_unavailable"))},"image/png")})}async function va(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=Ie(l.x)*t,c=Ie(l.y)*n,d=Ie(l.width)*t,u=Ie(l.height)*n;d>0&&u>0&&r.fillRect(s,c,d,u)}return ma(a)}async function ba(e){const t=e.naturalWidth,n=e.naturalHeight;if(!t||!n)throw new Error("image_source_size_unavailable");const a=document.createElement("canvas");a.width=t,a.height=n;const r=a.getContext("2d");if(!r)throw new Error("image_context_unavailable");return r.drawImage(e,0,0,t,n),a.toDataURL("image/png")}function it(e){return new Promise((t,n)=>{const a=new FileReader;a.onerror=()=>n(new Error("mask_blob_read_failed")),a.onload=()=>t(String(a.result)),a.readAsDataURL(e)})}const ga=`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`,xa=`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 ya(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function ka(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function wa(e){const t=e.url??e.image;if(!e.canvasVersion||!e.canvasMergedAt||t.startsWith("data:"))return t;const n=t.includes("?")?"&":"?";return`${t}${n}canvasMergedAt=${e.canvasMergedAt}`}function Ca(e){const t=e.canvasSourceFilename??e.filename;return t?`/generated/${encodeURIComponent(t)}`:e.url??e.image}async function yt(e){const t=Ca(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}),ba(n)}function Le(e,t){return!e.canvasVersion||e.prompt||!t?.prompt?e:{...e,prompt:t.prompt}}function _a(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?Le(n,t):null}function Ma(e,t){if(pn(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 et=new WeakMap;function Ea(e){if(!e.complete||!e.naturalWidth||!e.naturalHeight)return!1;const t=et.get(e);if(t&&t.src===e.currentSrc&&t.width===e.naturalWidth&&t.height===e.naturalHeight)return t.result;const n=64,a=Math.min(n,e.naturalWidth),r=Math.min(n,e.naturalHeight),l=document.createElement("canvas");l.width=a,l.height=r;const s=l.getContext("2d",{willReadFrequently:!0});if(!s)return!1;try{s.drawImage(e,0,0,a,r);const c=s.getImageData(0,0,a,r).data;for(let d=3;d<c.length;d+=4)if(c[d]<250)return et.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!0}),!0;return et.set(e,{src:e.currentSrc,width:e.naturalWidth,height:e.naturalHeight,result:!1}),!1}catch{return!1}}function Sa(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 kt(e,t){return{width:e,height:t,data:new Uint8Array(e*t)}}function ot(e){return{width:e.width,height:e.height,data:new Uint8Array(e.data)}}function Ba(e,t){Sa(e,t);for(let n=0;n<e.data.length;n+=1)(t.data[n]??0)>0&&(e.data[n]=0)}function Be(e,t){if(!e)return null;const n=ot(e);return t&&Ba(n,t),n}function ja(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}],Ta=1024;function Pa(e){return Math.max(0,Math.min(255,Math.round(e)))}function Ut(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 Aa(e,t){return(t.length>0?t:ut).map(a=>{const r=Ut(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 Da(e,t,n,a){for(const r of n)if(Math.max(Math.abs((e[t]??0)-r.r),Math.abs((e[t+1]??0)-r.g),Math.abs((e[t+2]??0)-r.b))<=a)return!0;return!1}function je(e,t,n,a,r,l,s){if(e<0||e>=a.length||a[e])return r;const c=e*4;return(t.data[c+3]??0)===0?(a[e]=1,r):Da(t.data,c,l,s)?(a[e]=1,n[r]=e,r+1):r}function tt(){return ut.map(e=>({...e}))}function wt(e,t,n,a){if(e.width!==t.width||e.height!==t.height)throw new Error("cleanup_mask_size_mismatch");const{width:r,height:l}=t,s=r*l,c=new Uint8Array(s),d=new Int32Array(s),u=Aa(t,n),b=Pa(a);let f=0;for(const _ of n.length>0?n:ut)f=je(Ut(_,r,l),t,d,c,f,u,b);for(;f>0;){const _=d[--f];e.data[_]=255;const j=_%r;j>0&&(f=je(_-1,t,d,c,f,u,b)),j<r-1&&(f=je(_+1,t,d,c,f,u,b)),_>=r&&(f=je(_-r,t,d,c,f,u,b)),_<s-r&&(f=je(_+r,t,d,c,f,u,b))}}function Ra(e,t){const n=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),a=ja(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 Wt(e){return new Promise((t,n)=>{e.toBlob(a=>{a?t(a):n(new Error("background_cleanup_blob_failed"))},"image/png")})}function Ft(e,t){const n=e.naturalWidth,a=e.naturalHeight;if(n<=0||a<=0)throw new Error("background_cleanup_image_not_ready");const r=t&&t>0?Math.min(1,t/Math.max(n,a)):1,l=Math.max(1,Math.round(n*r)),s=Math.max(1,Math.round(a*r)),c=document.createElement("canvas");c.width=l,c.height=s;const d=c.getContext("2d",{willReadFrequently:!0});if(!d)throw new Error("background_cleanup_context_failed");return d.drawImage(e,0,0,l,s),{canvas:c,context:d,width:l,height:s}}async function Ct({imageElement:e,mask:t}){try{const{canvas:n,context:a,width:r,height:l}=Ft(e),s=a.getImageData(0,0,r,l),c=Ra({width:r,height:l,data:s.data},t),d=a.createImageData(r,l);d.data.set(c.imageData.data),a.putImageData(d,0,0);const u=await Wt(n);return{blob:u,dataUrl:await it(u),stats:c.stats}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}async function Ia({imageElement:e,mask:t}){try{const{width:n,height:a}=Ft(e,Ta),r=document.createElement("canvas");r.width=n,r.height=a;const l=r.getContext("2d");if(!l)throw new Error("background_cleanup_context_failed");const s=l.createImageData(n,a);let c=0;for(let u=0;u<a;u+=1)for(let 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 j=(u*n+b)*4;s.data[j]=168,s.data[j+1]=85,s.data[j+2]=247,s.data[j+3]=150,c+=1}l.putImageData(s,0,0);const d=await Wt(r);return{dataUrl:await it(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?c/(n*a):0}}}catch(n){throw n instanceof Error?n:new Error("background_cleanup_failed")}}function _t(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?ot(e.removeMask):null,preserveMask:e.preserveMask?ot(e.preserveMask):null}}function Na(){return`cleanup_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function Ne(e){return Math.max(0,Math.min(1,e))}function Oa(e){const t=[],n=Math.max(0,e.radius*.55);for(const a of e.points)t.push({...a}),!(n<=0)&&t.push({x:Ne(a.x-n),y:a.y},{x:Ne(a.x+n),y:a.y},{x:a.x,y:Ne(a.y-n)},{x:a.x,y:Ne(a.y+n)});return t}function La(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 $a({canvasOpen:e,currentImage:t,canvasDisplayImage:n,imageElementRef:a,canvasSourceImageRef:r,lastMergedDataUrlRef:l,setCanvasSaveState:s,setCanvasVersionItem:c,applyMergedCanvasImage:d,attachCanvasVersionReference:u,showToast:b,t:f}){const[_,j]=i.useState(!1),[R,H]=i.useState("remove"),[P,O]=i.useState("click"),[v,C]=i.useState("flat-flood-fill"),[M,y]=i.useState([]),[m,J]=i.useState([]),[I,K]=i.useState(28),[g,S]=i.useState(null),[D,A]=i.useState(null),[L,Z]=i.useState(null),[ee,te]=i.useState(!1),[se,ie]=i.useState(.018),[ue,p]=i.useState(null),[B,W]=i.useState(!1),[ne,ae]=i.useState(!1),G=i.useRef(null),X=i.useRef(null),$=i.useRef(null),F=i.useRef({past:[],future:[]}),N=i.useRef(0),w=i.useRef(null),Y=i.useCallback(()=>_t({intent:R,tool:P,engine:v,seeds:M,brushStrokes:m,brushRadius:se,tolerance:I,removeMask:G.current,preserveMask:X.current,preview:g,maskOverlay:D,stats:L,active:ee,brushCursor:ue}),[m,D,g,M,L,I,ue,se,v,R,P,ee]),U=i.useCallback(()=>{F.current={past:[...F.current.past.slice(-19),Y()],future:[]}},[Y]),le=i.useCallback(x=>{const k=_t(x);G.current=k.removeMask,X.current=k.preserveMask,$.current=null,H(k.intent),O(k.tool),C(k.engine),y(k.seeds),J(k.brushStrokes),ie(k.brushRadius),K(k.tolerance),S(k.preview),A(k.maskOverlay),Z(k.stats),te(k.active),p(k.brushCursor),W(!1),ae(!1)},[]),q=i.useCallback(async()=>{if(!a.current||!t)return;const x=Be(G.current,X.current);if(!x){A(null),Z(null);return}const k=N.current+1;N.current=k,W(!0);try{const E=await Ia({imageElement:a.current,mask:x});if(N.current!==k)return;A(E),Z(E.stats)}catch{if(N.current!==k)return;b(f("canvas.toolbar.cleanupFailed"),!0)}finally{N.current===k&&W(!1)}},[t,a,b,f]),z=i.useCallback(async(x,k,E)=>{if(!a.current)return;const Q=La(a.current),ce=kt(Q.width,Q.height),Ce=kt(Q.width,Q.height);for(const fe of x){const _e=fe.intent==="remove"?ce:Ce;wt(_e,Q,[fe.point],E)}for(const fe of k){const _e=fe.intent==="remove"?ce:Ce;wt(_e,Q,Oa(fe),E)}G.current=ce,X.current=Ce},[a]),de=i.useCallback(()=>{N.current+=1,w.current!=null&&(window.clearTimeout(w.current),w.current=null),G.current=null,X.current=null,$.current=null,F.current={past:[],future:[]},y([]),J([]),S(null),A(null),Z(null),te(!1),p(null),W(!1),ae(!1)},[]),ke=i.useCallback(()=>{const x=F.current.past.pop();return x?(F.current.future=[Y(),...F.current.future.slice(0,19)],le(x),!0):!1},[Y,le]),re=i.useCallback(()=>{const x=F.current.future.shift();return x?(F.current.past=[...F.current.past.slice(-19),Y()],le(x),!0):!1},[Y,le]),we=i.useCallback(x=>{U();const k=[...M,{point:x,intent:R}];y(k),S(null),z(k,m,I).then(q)},[m,M,I,R,U,z,q]),$e=i.useCallback(()=>{U();const x=tt().map(k=>({point:k,intent:"remove"}));y(x),S(null),te(!1),z(x,m,I).then(q)},[m,I,U,z,q]),Ue=i.useCallback(()=>{U(),O("click"),te(x=>!x)},[U]),We=i.useCallback(x=>{U(),w.current!=null&&window.clearTimeout(w.current),K(x),S(null),w.current=window.setTimeout(()=>{w.current=null,z(M,m,x).then(q)},180)},[m,M,U,z,q]),V=i.useCallback(async()=>{if(!a.current||!t)return null;let x=Be(G.current,X.current);if(!x){const E=tt().map(Q=>({point:Q,intent:"remove"}));y(E),await z(E,m,I),x=Be(G.current,X.current)}if(!x)return null;U();const k=N.current+1;N.current=k,W(!0);try{const E=await Ct({imageElement:a.current,mask:x});return N.current!==k?null:(S(E),A(null),Z(E.stats),E)}catch{return N.current!==k||b(f("canvas.toolbar.cleanupFailed"),!0),null}finally{N.current===k&&W(!1)}},[m,I,t,a,U,z,b,f]),Fe=i.useCallback(()=>{U(),de()},[U,de]),He=i.useCallback(x=>{U();const k={id:Na(),intent:R,points:[{...x}],radius:se};$.current=k,p(x),J(E=>[...E,k])},[se,R,U]),Ke=i.useCallback(x=>{const k=$.current;if(!k){p(x);return}k.points=[...k.points,{...x}],p(x),J(E=>E.map(Q=>Q.id===k.id?{...k,points:k.points.map(ce=>({...ce}))}:Q)),z(M,m.map(E=>E.id===k.id?k:E),I).then(q)},[m,M,I,z,q]),ze=i.useCallback(()=>{$.current=null,z(M,m,I).then(q)},[m,M,I,z,q]),ve=i.useCallback(async()=>{if(!t||!a.current)return;const x=r.current??t;if(!x?.filename){b(f("canvas.toolbar.cleanupFailed"),!0);return}let k=Be(G.current,X.current);if(!k){const E=tt().map(Q=>({point:Q,intent:"remove"}));y(E),await z(E,m,I),k=Be(G.current,X.current)}if(k){ae(!0),s("saving");try{U();const E=await Ct({imageElement:a.current,mask:k}),Q=n?.canvasVersion&&n.filename?await Tt(n.filename,{sourceFilename:x.canvasSourceFilename??x.filename,image:E.blob,prompt:x.prompt,pixelEdited:!0}):await Pt({sourceFilename:x.canvasSourceFilename??x.filename,image:E.blob,prompt:x.prompt}),ce=Le(Q.item,x);l.current=E.dataUrl,c(ce),d(ce),await u(ce),s("saved"),S(null),A(null),Z(E.stats),te(!1),b(f("canvas.toolbar.cleanupApplied"))}catch{s("error"),b(f("canvas.toolbar.cleanupFailed"),!0)}finally{ae(!1)}}},[d,u,m,I,n,r,t,a,l,U,z,s,c,b,f]),he=i.useCallback(()=>ee?($.current=null,te(!1),p(null),!0):!1,[ee]);return i.useEffect(()=>{const x=a.current;if(!x||!e){j(!1);return}const k=()=>j(Ea(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:M,backgroundCleanupBrushStrokes:m,backgroundCleanupTolerance:I,backgroundCleanupPreview:g,backgroundCleanupMaskOverlay:D,backgroundCleanupStats:L,cleanupIntent:R,setCleanupIntent:H,cleanupTool:P,setCleanupTool:O,cleanupClickEngine:v,setCleanupClickEngine:C,cleanupBrushRadius:se,setCleanupBrushRadius:ie,cleanupBrushCursor:ue,setCleanupBrushCursor:p,isBackgroundCleanupActive:ee,setIsBackgroundCleanupActive:te,isBackgroundCleanupPickingSeed:ee&&P==="click",isBackgroundCleanupPreviewing:B,isBackgroundCleanupApplying:ne,hasActiveCleanupStroke:!!$.current,canUndoBackgroundCleanup:F.current.past.length>0,canRedoBackgroundCleanup:F.current.future.length>0,resetBackgroundCleanup:de,undoBackgroundCleanup:ke,redoBackgroundCleanup:re,addBackgroundCleanupClick:we,addBackgroundCleanupSeed:we,runBackgroundCleanupPreview:V,handleBackgroundCleanupAutoSample:$e,handleBackgroundCleanupPickSeed:Ue,handleBackgroundCleanupToleranceChange:We,handleBackgroundCleanupReset:Fe,handleBackgroundCleanupApply:ve,handleBackgroundCleanupEscape:he,startBackgroundCleanupBrushStroke:He,updateBackgroundCleanupBrushStroke:Ke,endBackgroundCleanupBrushStroke:ze}}function Mt(e){return Math.min(1,Math.max(0,e))}function Et(e,t){const n=t.getBoundingClientRect();return{x:Mt((e.clientX-n.left)/n.width),y:Mt((e.clientY-n.top)/n.height)}}const Ua=.18,Wa=.12;function Fa(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 st(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 Ht(e){return{id:e.id,x:e.x,y:e.y,width:Ua,height:Wa,color:e.color,strokeWidth:1}}function Ha(e,t,n){const a=n.x-t.x,r=n.y-t.y,l=e.x-t.x,s=e.y-t.y,c=a*a+r*r;if(c===0)return Math.hypot(e.x-t.x,e.y-t.y);const d=Math.max(0,Math.min(1,(l*a+s*r)/c));return Math.hypot(e.x-(t.x+d*a),e.y-(t.y+d*r))}function Ka(e,t,n){for(let a=1;a<t.points.length;a+=1)if(Ha(e,t.points[a-1],t.points[a])<=n)return!0;return!1}function St(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 za(e,t){return e.points.some(n=>st(n,t))}function Bt(e){const t=e.tolerance??.015;for(const n of[...e.memos].reverse())if(st(e.point,Ht(n),t))return Nt(n);for(const n of[...e.boxes].reverse())if(st(e.point,n,t))return It(n);for(const n of[...e.paths].reverse())if(Ka(e.point,n,t))return Rt(n);return null}function Va(e){const t=[];for(const n of e.annotations.paths)za(n,e.box)&&t.push(Rt(n));for(const n of e.annotations.boxes)St(n,e.box)&&t.push(It(n));for(const n of e.annotations.memos)St(Ht(n),e.box)&&t.push(Nt(n));return t}function Xa({canvasOpen:e,canvasZoom:t,canvasPanX:n,canvasPanY:a,spaceHeld:r,canDragViewportWithSelect:l,isBackgroundCleanupActive:s,cleanupTool:c,annotationFrameRef:d,annotations:u,setCanvasPan:b,addBackgroundCleanupClick:f,startBackgroundCleanupBrushStroke:_,updateBackgroundCleanupBrushStroke:j,endBackgroundCleanupBrushStroke:R,setCleanupBrushCursor:H}){const P=i.useRef({mode:null,lastPoint:null,didMove:!1}),O=i.useRef({active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null}),[v,C]=i.useState(!1),M=g=>{g.currentTarget.setPointerCapture(g.pointerId),O.current={active:!0,startX:g.clientX,startY:g.clientY,basePanX:n,basePanY:a,pointerId:g.pointerId},C(!0)};return{viewportPanActive:v,resetPointerSession:()=>{P.current={mode:null,lastPoint:null,didMove:!1},O.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},C(!1)},handleAnnotationPointerDown:g=>{if(!e||me(g.target)||!d.current)return;const S=g.button===1;if(r||S){g.preventDefault(),M(g);return}g.preventDefault();const D=Et(g,d.current);if(s){c==="click"?f(D):(g.currentTarget.setPointerCapture(g.pointerId),_(D));return}if(u.activeTool==="select"){const A=Bt({point:D,paths:u.paths,boxes:u.boxes,memos:u.memos});if(A)g.shiftKey?u.toggleSelected(A):u.selectOne(A),u.startSelectedMove(),P.current={mode:"move",lastPoint:D,didMove:!1};else if(l&&t>1.01){M(g);return}else u.clearSelection(),u.startSelectionBox(D),P.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 A=Bt({point:D,paths:u.paths,boxes:u.boxes,memos:u.memos});A&&u.eraseObjectAtPoint(A);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(O.current.active){const D=g.clientX-O.current.startX,A=g.clientY-O.current.startY;b(O.current.basePanX+D,O.current.basePanY+A);return}const S=Et(g,d.current);if(s){c==="brush"?j(S):H(S);return}if(u.activeTool==="select"){if(P.current.mode==="move"&&P.current.lastPoint){const D={x:S.x-P.current.lastPoint.x,y:S.y-P.current.lastPoint.y};(Math.abs(D.x)>5e-4||Math.abs(D.y)>5e-4)&&(u.moveSelected(D),P.current.didMove=!0),P.current.lastPoint=S}else P.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(O.current.active&&O.current.pointerId===g.pointerId){g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),O.current={active:!1,startX:0,startY:0,basePanX:0,basePanY:0,pointerId:null},C(!1);return}if(g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),s){c==="brush"&&R();return}if(u.activeTool==="select"){P.current.mode==="move"&&P.current.didMove&&u.commitSelectedMove(),P.current.mode==="box"&&u.selectionBox&&u.endSelectionBox(Va({box:Fa(u.selectionBox),annotations:u.toPayload()})),P.current={mode:null,lastPoint:null,didMove:!1};return}if(u.activeTool!=="memo"){if(u.activeTool==="eraser"){u.eraserMode==="brush"&&u.endEraserStroke();return}u.endDrawing()}}},handleAnnotationPointerLeave:()=>{s&&H(null)}}}function qa({canvasOpen:e,canvasZoom:t,currentImage:n,annotations:a,undoBackgroundCleanup:r,redoBackgroundCleanup:l,handleBackgroundCleanupEscape:s,handleCloseCanvas:c,selectHistoryShortcutTarget:d,trashHistoryItem:u,permanentlyDeleteHistoryItemByShortcut:b,setCanvasZoom:f,resetCanvasZoom:_,onCreateBlankCanvas:j,isCreatingBlankCanvas:R}){const[H,P]=i.useState(!1);return i.useEffect(()=>{if(!e)return;const v=m=>{m.preventDefault()},C=m=>{m.ctrlKey&&m.preventDefault()},M={passive:!1,capture:!0},y={passive:!1};return window.addEventListener("wheel",C,M),window.addEventListener("gesturestart",v,y),window.addEventListener("gesturechange",v,y),window.addEventListener("gestureend",v,y),()=>{window.removeEventListener("wheel",C,M),window.removeEventListener("gesturestart",v,y),window.removeEventListener("gesturechange",v,y),window.removeEventListener("gestureend",v,y)}},[e]),i.useEffect(()=>{if(!e)return;const v=M=>{M.code==="Space"&&(me(M.target)||(H||P(!0),M.preventDefault()))},C=M=>{M.code==="Space"&&P(!1)};return window.addEventListener("keydown",v),window.addEventListener("keyup",C),()=>{window.removeEventListener("keydown",v),window.removeEventListener("keyup",C)}},[e,H]),i.useEffect(()=>{if(!e)return;const v=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;c();return}if(C.shiftKey&&!C.metaKey&&!C.ctrlKey&&!C.altKey&&C.key.toLowerCase()==="b"){C.preventDefault(),!R&&!C.repeat&&j();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",v),()=>window.removeEventListener("keydown",v)},[a,a.focusMemo,a.redo,a.undo,e,c,s,R,j,l,r]),{spaceHeld:H,handleViewerKeyDown:v=>{if(me(v.target)){v.key==="Escape"&&(v.preventDefault(),v.target.blur(),a.focusMemo(null));return}if(e&&["1","2","3","4","5","6"].includes(v.key)){v.preventDefault();const C=["select","pen","box","arrow","memo","eraser"];a.setTool(C[Number(v.key)-1]);return}if(e&&v.key==="Escape"){if(v.preventDefault(),v.stopPropagation(),s())return;c();return}if(e&&v.key==="]"){v.preventDefault(),f(t+.1);return}if(e&&v.key==="["){v.preventDefault(),f(t-.1);return}if(e&&v.key==="0"){v.preventDefault(),_();return}if(v.key==="Delete"||v.key==="Backspace"){if(!n||v.target!==v.currentTarget)return;if(v.preventDefault(),v.shiftKey){b(n);return}u(n);return}v.key!=="ArrowLeft"&&v.key!=="ArrowRight"&&v.key!=="Home"&&v.key!=="End"||v.target===v.currentTarget&&(me(v.target)||(v.preventDefault(),v.key==="ArrowLeft"?d("previous"):v.key==="ArrowRight"?d("next"):v.key==="Home"?d("first"):v.key==="End"&&d("last")))}}}function Ya(e,t){return new Promise((n,a)=>{e.toBlob(r=>{if(r){n(r);return}a(new Error("canvas_blob_unavailable"))},t)})}async function Kt(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)at(n,l,a);for(const l of e.boxes)rt(n,l,a,"committed");for(const l of e.memos)Dn(n,l,a);return{blob:await Ya(t,"image/png"),dataUrl:t.toDataURL("image/png")}}const Ga=["left","center","right"],Za=["top","middle","bottom"];function Ja(e,t){const n=Ga[Math.min(2,Math.max(0,Math.floor(e*3)))],a=Za[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 jt(e){const t=e.map(n=>({...n,text:n.text.trim()})).filter(n=>n.text.length>0);return t.length===0?"":["The numbered notes below are temporary editing instructions written on the image. They are not image content: interpret each one to locate and apply the requested change (percentages are relative to image width and height).",...t.map((n,a)=>`${a+1}. At the ${Ja(n.x,n.y)}: ${n.text}`),"After applying every numbered instruction, remove all annotation markup. Do not render any annotation text, sticky notes, boxes, arrows, or markup in the output image. Where markup covered the image, show the underlying content reconstructed to match the surrounding texture, lighting, and perspective, with no residue, outline, or discoloration.","Keep everything not named in the numbered instructions exactly the same as the source image: composition, subjects, lighting, colors, and background."].join(`
2
+ `)}async function Qa(e){return(await Kt(e)).blob}function er(e={},t=new Date){const n=t.toISOString().slice(0,19).replace(/[-:T]/g,""),a=e.matte?"-flat":"";return`canvas-export-${n}${a}.png`}function tr(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 nr({imageElementRef:e,currentImage:t,canvasDisplayImage:n,canvasSourceImageRef:a,lastMergedDataUrlRef:r,lastCleanDataUrlRef:l,canvasVersionItem:s,annotations:c,exportBackground:d,exportMatteColor:u,quality:b,format:f,moderation:_,provider:j,imageModel:R,reasoningEffort:H,promptMode:P,webSearchEnabled:O,getResolvedSize:v,setCanvasVersionItem:C,setCanvasSaveState:M,setIsApplying:y,setIsExporting:m,setIsEditingWithMask:J,applyMergedCanvasImage:I,addGeneratedHistoryItem:K,attachCanvasVersionReference:g,closeCanvas:S,resetCanvasSession:D,showToast:A,t:L}){const Z=i.useCallback(async()=>{if(!e.current||!t)return null;const p=a.current??t;if(!p?.filename)return A(L("canvas.version.failed"),!0),null;y(!0),M("saving");try{const B=await Kt({imageElement:e.current,paths:c.paths,boxes:c.boxes,memos:c.memos});r.current=B.dataUrl;const W=await yt(p);l.current=W;const ne=s?.filename?await Tt(s.filename,{image:B.blob,sourceFilename:p.canvasSourceFilename??p.filename,prompt:p.prompt}):await Pt({sourceFilename:p.filename,image:B.blob,prompt:p.prompt}),ae=c.toPayload(),G=!s||!!s.annotationOnly,X=await mn(ne.item.filename,ae,G),$=Le(X.item,p);C($),I($),await g($,W);const F=jt(c.memos),N=`canvas-annotations:${p.canvasSourceFilename??p.filename}`,{insertPromptToComposer:w,removeInsertedPromptFromComposer:Y}=T.getState();return Y(N),F&&w({id:N,name:L("canvas.annotationInstructionsChip"),text:F,placement:"after"}),await At(p.filename).catch(()=>{}),c.resetLocal(),c.markSaved(),M("saved"),A(L("canvas.version.saved")),$}catch{return M("error"),A(L("canvas.version.failed"),!0),null}finally{y(!1)}},[c,I,g,a,s?.filename,t,e,r,l,M,C,y,A,L]);return{saveCanvasVersionAndUseReference:Z,handleApplyCanvas:async()=>{await Z()},handleRevertAnnotations:async()=>{if(!(!s?.filename||!s.annotationsBaked)&&!(!s.annotationOnly&&!window.confirm(L("canvas.revert.mixedConfirm")))){y(!0),M("saving");try{const p=await bn(s.filename),B=a.current??t??s,W=Le(p.item,B);if(C(W),I(W),r.current=null,p.annotationOnly&&p.snapshot){c.load(p.snapshot);const ne=W.canvasSourceFilename??B.filename;ne&&await Dt(ne,p.snapshot),A(L("canvas.revert.restored"))}else c.resetLocal(),A(L("canvas.revert.completed"));M("saved")}catch{M("error"),A(L("canvas.revert.failed"),!0)}finally{y(!1)}}},handleCloseCanvas:async()=>{(c.hasAnnotations||c.isDirty)&&!await Z()||(S(),D())},handleExportCanvas:async()=>{if(!(!e.current||!t)){m(!0);try{const p=d==="matte",B=await Qa({imageElement:e.current,paths:c.paths,boxes:c.boxes,memos:c.memos,background:p?{mode:"matte",color:u}:{mode:"alpha"}});tr(B,er({matte:p}))}catch{A(L("canvas.toolbar.exportFailed"),!0)}finally{m(!1)}}},handleEditWithMask:async()=>{if(!(!e.current||!n||c.boxes.length===0)){J(!0);try{const p=c.memos;let B=l.current;if(c.isDirty||c.hasAnnotations){if(!await Z())return;B=l.current}B||(B=await yt(a.current??n));const W=c.boxes.filter(w=>c.selectedIds.some(Y=>pe(Y,"box",w.id))),ne=await va({imageElement:e.current,boxes:W.length>0?W:c.boxes}),ae=jt(p),X=[(n.prompt??t?.prompt??"").trim(),ae].filter(Boolean).join(`
3
+
4
+ `);if(!X.trim()){A(L("toast.noPromptToFork"),!0);return}const $=n.size??t?.size??null,F=$&&/^\d+x\d+$/.test($)?$:v(),N=await vn({image:B,mask:await it(ne),prompt:X,quality:b,size:F,format:f,moderation:_,provider:j,n:1,model:R,reasoningEffort:H,mode:P,webSearchEnabled:O});await K(Ma(N,X))}catch(p){const B=p.code;A(L(B==="EDIT_MASK_NOT_SUPPORTED"?"canvas.toolbar.editMaskUnsupported":"canvas.toolbar.editMaskFailed"),!0)}finally{J(!1)}}}}}function rr(e){const t=T(h=>h.currentImage),n=T(h=>h.history),a=T(h=>h.importLocalImageToHistory),[r,l]=i.useState(!1),s=T(h=>{const oe=h.multimodePreviewFlightId;return oe?h.multimodeSequences[oe]??null:null}),c=T(h=>h.selectHistoryShortcutTarget),d=T(h=>h.trashHistoryItem),u=T(h=>h.permanentlyDeleteHistoryItemByShortcut),b=T(h=>h.markGeneratedResultsSeen),f=T(h=>h.activeGenerations),_=T(h=>h.quality),j=T(h=>h.format),R=T(h=>h.moderation),H=T(h=>h.provider),P=T(h=>h.imageModel),O=T(h=>h.reasoningEffort),v=T(h=>h.promptMode),C=T(h=>h.webSearchEnabled),M=T(h=>h.getResolvedSize),y=T(h=>h.showToast),m=T(h=>h.canvasOpen),J=T(h=>h.openCanvas),I=T(h=>h.closeCanvas),K=T(h=>h.canvasZoom),g=T(h=>h.canvasPanX),S=T(h=>h.canvasPanY),D=T(h=>h.setCanvasPan),A=T(h=>h.setCanvasZoom),L=T(h=>h.resetCanvasZoom),Z=T(h=>h.canvasExportBackground),ee=T(h=>h.canvasExportMatteColor),te=T(h=>h.setCanvasExportBackground),se=T(h=>h.setCanvasExportMatteColor),ie=T(h=>h.applyMergedCanvasImage),ue=T(h=>h.addGeneratedHistoryItem),p=T(h=>h.attachCanvasVersionReference),{t:B}=ye(),{creatingBlankCanvas:W,createBlankCanvas:ne}=gn(),ae=i.useRef(null),G=i.useRef(null),X=i.useRef(null),$=i.useRef(null),F=i.useRef(null),N=i.useRef(null),w=i.useRef(null),Y=i.useRef(null),U=i.useRef(null),[le,q]=i.useState(null),[z,de]=i.useState("idle"),[ke,re]=i.useState(!1),[we,$e]=i.useState(!1),[Ue,We]=i.useState(!1),V=An(),Fe=()=>{t?.prompt&&(navigator.clipboard.writeText(t.prompt),y(B("toast.promptCopied")))},He=ya(t?.quality),Ke=ka(t?.size),ze=xn(t?.model),ve=t?.filename??t?.url??t?.image??null,he=_a(n,t),x=m?le??he??t:t,k=x?wa(x):null,E=$a({canvasOpen:m,currentImage:t,canvasDisplayImage:x,imageElementRef:G,canvasSourceImageRef:w,lastMergedDataUrlRef:Y,setCanvasSaveState:de,setCanvasVersionItem:q,applyMergedCanvasImage:ie,attachCanvasVersionReference:p,showToast:y,t:B}),{imageHasAlpha:Q,backgroundCleanupSeeds:ce,backgroundCleanupPreview:Ce,backgroundCleanupMaskOverlay:fe,backgroundCleanupBrushStrokes:_e,cleanupTool:zt,cleanupBrushRadius:Vt,cleanupBrushCursor:Xt,isBackgroundCleanupActive:Me}=E,Ve=E.backgroundCleanupPreview?.dataUrl??k,Xe=()=>{w.current=null,F.current=null,N.current!=null&&(window.clearTimeout(N.current),N.current=null),q(null),de("idle"),E.resetBackgroundCleanup(),Y.current=null,U.current=null,on()};i.useEffect(()=>{if(!m){$.current=ve,Xe();return}if($.current===null){$.current=ve,w.current=t,q(he);return}$.current!==ve&&(V.resetLocal(),Xe(),w.current=t,q(he),$.current=ve)},[V.resetLocal,m,t,ve,he]),i.useEffect(()=>{!m||!t||w.current||(w.current=t,q(he))},[m,t,he]),i.useEffect(()=>{if(!m||!t?.filename||t.canvasVersion)return;const h=t.filename;if(F.current===h)return;F.current=h;let oe=!1;return yn(h).then(Ee=>{!oe&&Ee.annotations&&V.load(Ee.annotations)}).catch(()=>{}),()=>{oe=!0}},[V.load,m,t?.canvasVersion,t?.filename]),i.useEffect(()=>{if(!m||!t?.filename||t.canvasVersion||!V.isDirty)return;const h=t.filename;return N.current!=null&&window.clearTimeout(N.current),N.current=window.setTimeout(()=>{const oe=V.toPayload();(V.hasAnnotations?Dt(h,oe):At(h)).then(()=>V.markSaved()).catch(()=>{})},500),()=>{N.current!=null&&(window.clearTimeout(N.current),N.current=null)}},[V,V.hasAnnotations,V.isDirty,m,t?.canvasVersion,t?.filename]);const qt=h=>{me(h.target)||(b(),h.currentTarget.focus())},Yt=i.useCallback(()=>{window.requestAnimationFrame(()=>X.current?.focus())},[]),Gt=h=>{if(m){if(h.preventDefault(),h.ctrlKey){A(K-h.deltaY*.01);return}D(g-h.deltaX,S-h.deltaY)}},Zt=i.useCallback(h=>{Array.from(h.dataTransfer.types).includes("Files")&&(h.preventDefault(),l(oe=>oe||!0))},[]),Jt=i.useCallback(h=>{h.currentTarget.contains(h.relatedTarget)||l(!1)},[]),Qt=i.useCallback(async h=>{if(!Array.from(h.dataTransfer.types).includes("Files"))return;h.preventDefault(),l(!1);const oe=Array.from(h.dataTransfer.files).filter(Ee=>/^image\/(png|jpeg|webp)$/.test(Ee.type));oe.length!==0&&await a(oe[0])},[a]),{handleApplyCanvas:en,handleRevertAnnotations:tn,handleCloseCanvas:dt,handleExportCanvas:nn,handleEditWithMask:an}=nr({imageElementRef:G,currentImage:t,canvasDisplayImage:x,canvasSourceImageRef:w,lastMergedDataUrlRef:Y,lastCleanDataUrlRef:U,canvasVersionItem:le,annotations:V,exportBackground:Z,exportMatteColor:ee,quality:_,format:j,moderation:R,provider:H,imageModel:P,reasoningEffort:O,promptMode:v,webSearchEnabled:C,getResolvedSize:M,setCanvasVersionItem:q,setCanvasSaveState:de,setIsApplying:re,setIsExporting:$e,setIsEditingWithMask:We,applyMergedCanvasImage:ie,addGeneratedHistoryItem:ue,attachCanvasVersionReference:p,closeCanvas:I,resetCanvasSession:Xe,showToast:y,t:B}),{spaceHeld:qe,handleViewerKeyDown:rn}=qa({canvasOpen:m,canvasZoom:K,currentImage:t,annotations:V,undoBackgroundCleanup:E.undoBackgroundCleanup,redoBackgroundCleanup:E.redoBackgroundCleanup,handleBackgroundCleanupEscape:E.handleBackgroundCleanupEscape,handleCloseCanvas:dt,selectHistoryShortcutTarget:c,trashHistoryItem:d,permanentlyDeleteHistoryItemByShortcut:u,setCanvasZoom:A,resetCanvasZoom:L,onCreateBlankCanvas:ne,isCreatingBlankCanvas:W}),Ye=m&&K>1.01&&V.activeTool==="select"&&!Me,{viewportPanActive:Ge,resetPointerSession:on,handleAnnotationPointerDown:sn,handleAnnotationPointerMove:ln,handleAnnotationPointerUp:cn,handleAnnotationPointerLeave:un}=Xa({canvasOpen:m,canvasZoom:K,canvasPanX:g,canvasPanY:S,spaceHeld:qe,canDragViewportWithSelect:Ye,isBackgroundCleanupActive:Me,cleanupTool:zt,annotationFrameRef:ae,annotations:V,setCanvasPan:D,addBackgroundCleanupClick:E.addBackgroundCleanupClick,startBackgroundCleanupBrushStroke:E.startBackgroundCleanupBrushStroke,updateBackgroundCleanupBrushStroke:E.updateBackgroundCleanupBrushStroke,endBackgroundCleanupBrushStroke:E.endBackgroundCleanupBrushStroke,setCleanupBrushCursor:E.setCleanupBrushCursor});return o.jsxs("main",{className:`canvas${m?" canvas--mode-open":""}${r?" canvas--drop-active":""}${qe?" canvas--space-held":""}${Ge?" canvas--pan-active":""}${Ye?" canvas--zoom-hand":""}`,onDragOver:Zt,onDragLeave:Jt,onDrop:Qt,children:[r?o.jsx("div",{className:"canvas__drop-overlay","aria-hidden":!0,children:o.jsx("span",{className:"canvas__drop-hint",children:B("canvas.drop.hint")})}):null,m&&o.jsx(ha,{zoom:K,closeLabel:B("canvas.close"),blankCanvasLabel:B("canvas.blank.title"),blankCanvasAriaLabel:`${B(W?"canvas.blank.creating":"canvas.blank.create")} (Shift+B)`,blankCanvasShortcut:"Shift+B",blankCanvasBusy:W,shortcutHint:B("canvas.toolbar.zoomShortcutHint"),onZoomIn:()=>A(K+.1),onZoomOut:()=>A(K-.1),onZoomReset:L,onCreateBlankCanvas:()=>{ne()},onClose:()=>{dt()}}),o.jsx("div",{className:`progress-bar${f>0?" active":""}`}),s?o.jsx(kn,{}):t?o.jsxs("div",{ref:X,className:"result-container visible",tabIndex:0,onMouseDown:qt,onWheel:Gt,onKeyDown:rn,"aria-label":B("canvas.imageViewerAria"),children:[o.jsx(Un,{annotationFrameRef:ae,imageElementRef:G,frameClassName:`canvas-annotation-frame${(Q||Ce)&&m?" canvas-annotation-frame--alpha":""}${Me&&m?" canvas-annotation-frame--cleanup-picking":""}${fe&&m?" canvas-annotation-frame--cleanup-mask":""}`,frameStyle:{cursor:Ge?"grabbing":qe||Ye?"grab":m?Me?"crosshair":V.activeTool==="select"?"default":V.activeTool==="eraser"?V.eraserMode==="object"?ga:xa:"crosshair":"zoom-in",transform:m?`translate(${g}px, ${S}px) scale(${K})`:void 0,transition:m&&!Ge?"transform 0.2s ease":void 0},imageKey:`${x?.filename??x?.url??x?.image}:${x?.canvasMergedAt??""}`,imageSrc:Ve??t.image,fallbackImage:t.image,alt:B("canvas.resultAlt"),canvasOpen:m,maskOverlayUrl:fe?.dataUrl??null,cleanupLayer:o.jsx(Hn,{seeds:ce,brushStrokes:_e,brushCursor:Xt,brushRadius:Vt,active:Me}),annotations:V,onOpenCanvas:J,onPointerDown:sn,onPointerMove:ln,onPointerUp:cn,onPointerLeave:un}),m&&Ve?o.jsx(pa,{imageSrc:Ve,zoom:K,panX:g,panY:S,resetLabel:B("canvas.toolbar.zoomReset"),onReset:L}):null,m&&o.jsx(la,{annotations:V,backgroundCleanup:E,backgroundCleanupPreview:Ce,canvasState:{exportBackground:Z,exportMatteColor:ee,isApplying:ke,isExporting:we,isEditingWithMask:Ue,canRevertAnnotations:!!le?.annotationsBaked},actions:{handleApplyCanvas:en,handleRevertAnnotations:tn,handleExportCanvas:nn,handleEditWithMask:an,setExportBackground:te,setExportMatteColor:se}}),m&&z!=="idle"?o.jsx("div",{className:`canvas-save-state canvas-save-state--${z}`,children:B(z==="saving"?"canvas.version.saving":z==="saved"?"canvas.version.saved":"canvas.version.failed")}):null,o.jsx(ca,{currentImage:t,canvasDisplayImage:x,canvasOpen:m,displayQuality:He,displaySize:Ke,displayModel:ze,onAfterDeleteFocus:Yt,onCopyPrompt:Fe})]}):null]})}export{rr as CanvasModeWorkspace};