tide-commander 1.110.4 → 1.111.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/assets/{BossLogsModal-BBO4P4qG.js → BossLogsModal-CWgY8sCg.js} +1 -1
  2. package/dist/assets/{BossSpawnModal-DJ1DmEWp.js → BossSpawnModal-FqRpqBcy.js} +1 -1
  3. package/dist/assets/{ControlsModal-DeRColMt.js → ControlsModal-BytmCa_F.js} +1 -1
  4. package/dist/assets/{DockerLogsModal-DGpatLiw.js → DockerLogsModal-cgbuzWq6.js} +1 -1
  5. package/dist/assets/{EmbeddedEditor-Dsgf6hMF.js → EmbeddedEditor-x0-x_VZN.js} +1 -1
  6. package/dist/assets/{GmailOAuthSetup-CGis0yjA.js → GmailOAuthSetup-PBbSgHHz.js} +1 -1
  7. package/dist/assets/{GoogleOAuthSetup-Bnhf_nts.js → GoogleOAuthSetup-BTMT26MQ.js} +1 -1
  8. package/dist/assets/{IframeModal-BahnrxAm.js → IframeModal-CQWRHjMj.js} +1 -1
  9. package/dist/assets/{IntegrationsPanel-BUs_7XBA.js → IntegrationsPanel-DurGaUXT.js} +2 -2
  10. package/dist/assets/{LogViewerModal-DXxjS8NR.js → LogViewerModal-DA0thQR1.js} +1 -1
  11. package/dist/assets/{MonitoringModal-DPeyASIV.js → MonitoringModal-BR3H7QWp.js} +1 -1
  12. package/dist/assets/{PM2LogsModal-kNNjOmdB.js → PM2LogsModal-8OCVhfh2.js} +1 -1
  13. package/dist/assets/{RestoreArchivedAreaModal-CVHj28LX.js → RestoreArchivedAreaModal-dFjRSRLv.js} +1 -1
  14. package/dist/assets/{Scene2DCanvas-BShs3yx7.js → Scene2DCanvas-B-R3VS-A.js} +1 -1
  15. package/dist/assets/{SceneManager-CF89Ktyf.js → SceneManager-BdlbWXX_.js} +1 -1
  16. package/dist/assets/{SkillsPanel-BVRP74vV.js → SkillsPanel-BdjWXZR_.js} +1 -1
  17. package/dist/assets/{SlackMultiInstanceSetup-f6boDwm1.js → SlackMultiInstanceSetup-zKg6uBlN.js} +1 -1
  18. package/dist/assets/{SpawnModal-Bm8rg45q.js → SpawnModal-DjIL4lqU.js} +1 -1
  19. package/dist/assets/{StatisticsModal-DuNj8UzS.js → StatisticsModal-vNiEk-nb.js} +1 -1
  20. package/dist/assets/{SubordinateAssignmentModal-Cn3e2lNE.js → SubordinateAssignmentModal-5uQWItJR.js} +1 -1
  21. package/dist/assets/{TriggerManagerPanel-Deo2dE4T.js → TriggerManagerPanel-BQW0K0b-.js} +1 -1
  22. package/dist/assets/{WorkflowEditorPanel-D-_duRlu.js → WorkflowEditorPanel-BScrIOTs.js} +1 -1
  23. package/dist/assets/{index-BFJmgmOF.css → index-BHB6qrT0.css} +1 -1
  24. package/dist/assets/index-BoE8DsSC.js +2 -0
  25. package/dist/assets/{index-C9A7qvBF.js → index-CGhaTkiM.js} +2 -2
  26. package/dist/assets/index-CSNgpO8m.js +1 -0
  27. package/dist/assets/{index-BsykE0PB.js → index-D76_Hnti.js} +1 -1
  28. package/dist/assets/index-DYa5qtk2.js +19 -0
  29. package/dist/assets/{index-DeeuvLUM.js → index-Dzjjm9nN.js} +1 -1
  30. package/dist/assets/{index-Bb-7Dvp1.js → index-EYFKOKSV.js} +3 -3
  31. package/dist/assets/{index-v1ImDk7h.js → index-QD32wJ7v.js} +1 -1
  32. package/dist/assets/{index-zphXsHhS.js → index-iJa_ZaEs.js} +4 -4
  33. package/dist/assets/main-BUSv52j9.css +1 -0
  34. package/dist/assets/main-ViFk-kY8.js +214 -0
  35. package/dist/assets/{web-VEWFSkZI.js → web-5CCgdfq2.js} +1 -1
  36. package/dist/assets/{web-BZcyP_IR.js → web-B9FA2zSi.js} +1 -1
  37. package/dist/assets/{web-BKgFBlgl.js → web-nOakqhE0.js} +1 -1
  38. package/dist/index.html +2 -2
  39. package/dist/locales/de/terminal.json +4 -0
  40. package/dist/locales/en/terminal.json +4 -0
  41. package/dist/locales/es/terminal.json +4 -0
  42. package/dist/locales/fr/terminal.json +4 -0
  43. package/dist/locales/hi/terminal.json +4 -0
  44. package/dist/locales/it/terminal.json +4 -0
  45. package/dist/locales/ja/terminal.json +4 -0
  46. package/dist/locales/pt/terminal.json +4 -0
  47. package/dist/locales/ru/terminal.json +4 -0
  48. package/dist/locales/zh-CN/terminal.json +4 -0
  49. package/dist/src/packages/server/services/claude-usage-service.js +82 -19
  50. package/package.json +1 -1
  51. package/dist/assets/index-CZGINGY-.js +0 -1
  52. package/dist/assets/index-DZu9t3BI.js +0 -2
  53. package/dist/assets/index-y3mA_lBK.js +0 -19
  54. package/dist/assets/main-CyZg1kKu.js +0 -214
  55. package/dist/assets/main-VciFPjA1.css +0 -1
@@ -0,0 +1,19 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/EmbeddedEditor-x0-x_VZN.js","assets/main-ViFk-kY8.js","assets/vendor-react--Eh9ivFN.js","assets/vendor-three-Chj50gSY.js","assets/main-BUSv52j9.css","assets/EmbeddedEditor-O_u2UVA4.css"])))=>i.map(i=>d[i]);
2
+ import{r as s,aM as Y,l as K,a_ as Kt,M as $s,S as Rt,N as Hs,s as mt,u as le,j as e,I as M,bB as Ft,f as zs,bC as As,bD as Rn,bE as Os,bF as Gs,bG as Fn,bH as In,bI as Tt,bJ as Pn,bK as Ln,bL as $n,bM as Xt,bN as Hn,bO as Us,bP as Mt,bQ as Dt,ac as it,bR as ft,bS as pt,bT as Es,bU as zn,b6 as An,bV as Jt,bW as On,bX as Gn,bY as Ss,C as Un,n as Bn}from"./main-ViFk-kY8.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function _n(t){const[n,o]=s.useState(null),[c,r]=s.useState(!1),i=s.useCallback(async()=>{if(t){r(!0);try{const f=await Y(K(`/api/files/git-status?path=${encodeURIComponent(t)}`)),l=await f.json();f.ok?o(l):o({isGitRepo:!1,files:[]})}catch(f){console.error("[FileExplorer] Failed to load git status:",f),o({isGitRepo:!1,files:[]})}finally{r(!1)}}},[t]);return{gitStatus:n,loading:c,loadGitStatus:i}}async function Vn(t){try{const n=await Y(K(`/api/files/git-original?path=${encodeURIComponent(t)}`)),o=await n.json();return n.ok&&!o.isNew?{content:o.content,isNew:!1}:{content:null,isNew:!0}}catch(n){return console.error("[FileExplorer] Failed to load original file:",n),{content:null,isNew:!0}}}const Kn=new Set([".txt",".md",".markdown",".json",".yaml",".yml",".xml",".html",".htm",".css",".scss",".sass",".less",".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".rb",".c",".cpp",".h",".hpp",".cs",".go",".rs",".swift",".kt",".scala",".clj",".ex",".exs",".erl",".hs",".ml",".fs",".sql",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".toml",".ini",".cfg",".conf",".env",".gitignore",".dockerignore",".editorconfig",".prettierrc",".eslintrc",".babelrc",".log",".csv",".tsv",".svg",""]),Wn=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".svg"]),Yn=new Set([".pdf"]),qn=new Set([".xlsx",".xls",".docx",".doc",".pptx",".ppt",".zip",".tar",".gz",".rar",".7z",".exe",".dmg",".app",".deb",".rpm",".apk",".aab",".ipa",".msi",".mp3",".mp4",".wav",".avi",".mov",".mkv",".flac",".ogg",".webm",".ttf",".otf",".woff",".woff2",".eot",".sqlite",".db",".so",".dll",".dylib",".a",".o",".obj",".bin",".dat",".iso",".img",".jar",".war",".ear",".class"]);function Jn(t){const n=t.toLowerCase();return Wn.has(n)?"image":Yn.has(n)?"pdf":qn.has(n)?"binary":(Kn.has(n),"text")}function Xn(){const[t,n]=s.useState(null),[o,c]=s.useState(!1),[r,i]=s.useState(null),f=s.useCallback(async u=>{var g,j;c(!0),i(null);try{const p=u.substring(u.lastIndexOf(".")).toLowerCase(),y=Jn(p),C=u.substring(u.lastIndexOf("/")+1);if(y==="image"){const N=await Y(K(`/api/files/binary?path=${encodeURIComponent(u)}`));if(!N.ok){const w=await N.json().catch(()=>({error:"Failed to load image"}));i(w.error||"Failed to load image"),n(null);return}const d=await N.blob(),v=URL.createObjectURL(d);n({path:u,filename:C,extension:p,content:"",size:d.size,modified:new Date().toISOString(),fileType:"image",dataUrl:v});return}if(y==="pdf"){const N=await Y(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await N.json();if(!N.ok){i(d.error||"Failed to load PDF info"),n(null);return}n({path:u,filename:C,extension:p,content:"",size:d.size,modified:d.modified,fileType:"pdf",dataUrl:K(`/api/files/binary?path=${encodeURIComponent(u)}&token=${encodeURIComponent(Kt())}`)});return}if(y==="binary"){const N=await Y(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await N.json();if(!N.ok){i(d.error||"Failed to load file info"),n(null);return}n({path:u,filename:C,extension:p,content:"",size:d.size,modified:d.modified,fileType:"binary",dataUrl:K(`/api/files/binary?path=${encodeURIComponent(u)}&download=true&token=${encodeURIComponent(Kt())}`)});return}const R=await Y(K(`/api/files/read?path=${encodeURIComponent(u)}`)),x=await R.json();if(!R.ok){if((g=x.error)!=null&&g.includes("too large")||(j=x.error)!=null&&j.includes("binary")){const N=await Y(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await N.json();if(N.ok){n({path:u,filename:C,extension:p,content:"",size:d.size,modified:d.modified,fileType:"binary",dataUrl:K(`/api/files/binary?path=${encodeURIComponent(u)}&download=true&token=${encodeURIComponent(Kt())}`)});return}}i(x.error||"Failed to load file"),n(null);return}n({...x,fileType:"text"})}catch(p){const y=p instanceof Error?p.message:"Failed to load file";i(y),n(null)}finally{c(!1)}},[]),l=s.useCallback(()=>{n(u=>(u!=null&&u.dataUrl&&u.dataUrl.startsWith("blob:")&&URL.revokeObjectURL(u.dataUrl),null)),i(null)},[]);return{file:t,loading:o,error:r,loadFile:f,clearFile:l,setFile:n}}const Wt="file-explorer-state",Qn=10080*60*1e3;function Zn(t,n){return n?`${Wt}-folder-${n}`:t?`${Wt}-area-${t}`:`${Wt}-default`}async function ea(t){try{const n=await Y(K(`/api/files/exists?path=${encodeURIComponent(t)}`));return n.ok?(await n.json()).exists===!0:!1}catch{return!1}}function ta({areaId:t,folderPath:n,isOpen:o}){const c=Zn(t,n),r=s.useRef(!1);s.useEffect(()=>{r.current=!1},[t,n]);const i=s.useCallback(async()=>{if(r.current)return null;r.current=!0;try{const l=localStorage.getItem(c);if(!l)return null;const u=JSON.parse(l);if(Date.now()-u.timestamp>Qn)return localStorage.removeItem(c),null;const j=(await Promise.all(u.tabs.map(async y=>({tab:y,exists:await ea(y.path)})))).filter(({exists:y})=>y).map(({tab:y})=>y);let p=u.activeTabPath;return p&&!j.some(y=>y.path===p)&&(p=j.length>0?j[0].path:null),{tabs:j,activeTabPath:p,viewMode:u.viewMode||"files",selectedFolderIndex:u.selectedFolderIndex||0,expandedPaths:new Set(u.expandedPaths||[])}}catch(l){return console.error("[FileExplorerStorage] Failed to load state:",l),null}},[c]),f=s.useCallback(l=>{if(o)try{const u={tabs:l.tabs,activeTabPath:l.activeTabPath,viewMode:l.viewMode,selectedFolderIndex:l.selectedFolderIndex,expandedPaths:Array.from(l.expandedPaths),timestamp:Date.now()};localStorage.setItem(c,JSON.stringify(u))}catch(u){console.error("[FileExplorerStorage] Failed to save state:",u)}},[c,o]);return{loadStoredState:i,saveState:f}}const Ts=280,Ms=150,Ds=1200;function sa(){const[t,n]=s.useState(()=>{const g=$s(Rt.TREE_PANEL_WIDTH,Ts);return g>=Ms&&g<=Ds?g:Ts}),o=s.useRef(!1),[c,r]=s.useState(!1),i=s.useRef(0),f=s.useRef(0),l=s.useRef(t);l.current=t;const u=s.useCallback(g=>{g.preventDefault(),o.current=!0,r(!0),i.current=g.clientX,f.current=t,document.body.style.cursor="ew-resize",document.body.style.userSelect="none"},[t]);return s.useEffect(()=>{const g=p=>{if(!o.current)return;const y=p.clientX-i.current,C=Math.min(Ds,Math.max(Ms,f.current+y));n(C)},j=()=>{o.current&&(o.current=!1,r(!1),document.body.style.cursor="",document.body.style.userSelect="",Hs(Rt.TREE_PANEL_WIDTH,l.current))};return document.addEventListener("mousemove",g),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",j)}},[]),{treePanelWidth:t,handleResizeStart:u,isResizing:c}}const na=100,aa=.65,ra=36;function ia(){const[t,n]=s.useState(()=>$s(Rt.MOBILE_TREE_PANEL_HEIGHT,0)),o=s.useRef(t);o.current=t;const c=s.useRef(0),r=s.useRef(0),i=()=>Math.floor((window.innerHeight-ra)*aa),f=p=>Math.min(i(),Math.max(na,p)),l=s.useCallback(p=>{n(p);const y=document.querySelector(".file-explorer-main");y&&y.style.setProperty("--fe-mobile-tree-height",`${p}px`)},[]),u=s.useCallback(()=>{document.body.style.cursor="",document.body.style.userSelect="",Hs(Rt.MOBILE_TREE_PANEL_HEIGHT,o.current),mt.setTerminalResizing(!1)},[]),g=s.useCallback(p=>{p.preventDefault();const y=document.querySelector(".file-explorer-tree-panel"),C=o.current>0?o.current:(y==null?void 0:y.getBoundingClientRect().height)??240;c.current=p.clientY,r.current=C,document.body.style.cursor="ns-resize",document.body.style.userSelect="none",mt.setTerminalResizing(!0);const R=N=>{const d=N.clientY-c.current;l(f(r.current+d))},x=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",x),u()};document.addEventListener("mousemove",R),document.addEventListener("mouseup",x)},[l,u]),j=s.useCallback(p=>{if(p.touches.length!==1)return;const y=document.querySelector(".file-explorer-tree-panel"),C=o.current>0?o.current:(y==null?void 0:y.getBoundingClientRect().height)??240;c.current=p.touches[0].clientY,r.current=C,document.body.style.cursor="ns-resize",document.body.style.userSelect="none",mt.setTerminalResizing(!0);const R=N=>{if(N.touches.length!==1)return;N.preventDefault();const d=N.touches[0].clientY-c.current;l(f(r.current+d))},x=()=>{document.removeEventListener("touchmove",R),document.removeEventListener("touchend",x),document.removeEventListener("touchcancel",x),u()};document.addEventListener("touchmove",R,{passive:!1}),document.addEventListener("touchend",x),document.addEventListener("touchcancel",x)},[l,u]);return{mobileTreeHeight:t,handleResizeMouseDown:g,handleResizeTouchStart:j}}function Qt(){const[t,n]=s.useState([]),[o,c]=s.useState(!1),[r,i]=s.useState(null),[f,l]=s.useState(null),u=s.useCallback(async N=>{c(!0),i(null);try{const d=await Y(K(`/api/files/git-branches?path=${encodeURIComponent(N)}`)),v=await d.json();d.ok?n(v.branches||[]):(i(v.error||"Failed to load branches"),n([]))}catch(d){console.error("[GitBranches] Failed to load branches:",d),i("Failed to load branches"),n([])}finally{c(!1)}},[]),g=s.useCallback(async(N,d)=>{l("checkout"),i(null);try{const v=await Y(K("/api/files/git-checkout"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,branch:d})}),w=await v.json();return v.ok||i(w.error||"Checkout failed"),w}catch(v){console.error("[GitBranches] Checkout failed:",v);const w={success:!1,error:"Checkout failed"};return i(w.error),w}finally{l(null)}},[]),j=s.useCallback(async(N,d,v)=>{l("create"),i(null);try{const w=await Y(K("/api/files/git-branch-create"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,name:d,startPoint:v})}),S=await w.json();return w.ok||i(S.error||"Failed to create branch"),S}catch(w){console.error("[GitBranches] Create branch failed:",w);const S={success:!1,error:"Failed to create branch"};return i(S.error),S}finally{l(null)}},[]),p=s.useCallback(async N=>{l("pull"),i(null);try{const d=await Y(K("/api/files/git-pull"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return!d.ok&&!v.conflicts&&i(v.error||"Pull failed"),v}catch(d){console.error("[GitBranches] Pull failed:",d);const v={success:!1,error:"Pull failed"};return i(v.error),v}finally{l(null)}},[]),y=s.useCallback(async N=>{l("push"),i(null);try{const d=await Y(K("/api/files/git-push"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return d.ok||i(v.error||"Push failed"),v}catch(d){console.error("[GitBranches] Push failed:",d);const v={success:!1,error:"Push failed"};return i(v.error),v}finally{l(null)}},[]),C=s.useCallback(async(N,d)=>{l("merge"),i(null);try{const v=await Y(K("/api/files/git-merge"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N,branch:d})}),w=await v.json();return!v.ok&&!w.conflicts&&i(w.error||"Merge failed"),w}catch(v){console.error("[GitBranches] Merge failed:",v);const w={success:!1,error:"Merge failed"};return i(w.error),w}finally{l(null)}},[]),R=s.useCallback(async N=>{l("merge-abort"),i(null);try{const d=await Y(K("/api/files/git-merge-abort"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return d.ok||i(v.error||"Merge abort failed"),v}catch(d){console.error("[GitBranches] Merge abort failed:",d);const v={success:!1,error:"Merge abort failed"};return i(v.error),v}finally{l(null)}},[]),x=s.useCallback(async N=>{l("merge-continue"),i(null);try{const d=await Y(K("/api/files/git-merge-continue"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:N})}),v=await d.json();return d.ok||i(v.error||"Merge continue failed"),v}catch(d){console.error("[GitBranches] Merge continue failed:",d);const v={success:!1,error:"Merge continue failed"};return i(v.error),v}finally{l(null)}},[]);return{branches:t,loading:o,error:r,operationInProgress:f,loadBranches:u,checkoutBranch:g,createBranch:j,pullFromRemote:p,pushToRemote:y,mergeBranch:C,mergeAbort:R,mergeContinue:x}}const la=50,oa=400,Rs={branch:"",author:"",since:"",until:"",searchPath:"",search:""};function ca(){const[t,n]=s.useState([]),[o,c]=s.useState(!1),[r,i]=s.useState(!1),[f,l]=s.useState(null),[u,g]=s.useState(!1),[j,p]=s.useState(0),[y,C]=s.useState({...Rs}),[R,x]=s.useState(null),[N,d]=s.useState([]),[v,w]=s.useState(!1),[S,A]=s.useState([]),[H,G]=s.useState(!1),z=s.useRef(null),ae=s.useRef(""),ee=s.useCallback((O,Z,L)=>{const T=L||y,W=new URLSearchParams;return W.set("path",O),W.set("limit",String(la)),W.set("offset",String(Z)),T.branch&&W.set("branch",T.branch),T.author&&W.set("author",T.author),T.since&&W.set("since",T.since),T.until&&W.set("until",T.until),T.searchPath&&W.set("searchPath",T.searchPath),T.search&&W.set("search",T.search),W.toString()},[y]),D=s.useCallback(async O=>{ae.current=O,c(!0),l(null),x(null),d([]);try{const Z=ee(O,0),L=await Y(K(`/api/files/git-log?${Z}`)),T=await L.json();L.ok?(n(T.commits||[]),p(T.total||0),g(T.hasMore||!1)):(l(T.error||"Failed to load git history"),n([]))}catch(Z){console.error("[useGitHistory] loadHistory error:",Z),l("Failed to load git history"),n([])}finally{c(!1)}},[ee]),F=s.useCallback(async O=>{if(!(r||!u)){i(!0);try{const Z=ee(O,t.length),L=await Y(K(`/api/files/git-log?${Z}`)),T=await L.json();L.ok&&(n(W=>[...W,...T.commits||[]]),p(T.total||0),g(T.hasMore||!1))}catch(Z){console.error("[useGitHistory] loadMore error:",Z)}finally{i(!1)}}},[ee,t.length,u,r]),I=s.useCallback(async O=>{if(x(O),!O){d([]);return}w(!0);try{const Z=ae.current,L=new URLSearchParams({path:Z,hash:O.hash}),T=await Y(K(`/api/files/git-commit-files?${L}`)),W=await T.json();T.ok?d(W.files||[]):d([])}catch(Z){console.error("[useGitHistory] selectCommit files error:",Z),d([])}finally{w(!1)}},[]),re=s.useCallback((O,Z)=>{C(L=>({...L,[O]:Z}))},[]),_=s.useCallback(()=>{C({...Rs})},[]);s.useEffect(()=>{const O=ae.current;if(O)return z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{D(O)},oa),()=>{z.current&&clearTimeout(z.current)}},[y]);const ge=s.useCallback(async O=>{G(!0);try{const Z=new URLSearchParams({path:O}),L=await Y(K(`/api/files/git-authors?${Z}`)),T=await L.json();L.ok&&A(T.authors||[])}catch(Z){console.error("[useGitHistory] loadAuthors error:",Z)}finally{G(!1)}},[]);return{commits:t,loading:o,loadingMore:r,error:f,hasMore:u,total:j,filters:y,setFilter:re,resetFilters:_,selectedCommit:R,selectCommit:I,commitFiles:N,commitFilesLoading:v,loadHistory:D,loadMore:F,authors:S,authorsLoading:H,loadAuthors:ge}}function da(t){if(!t.current)return null;const n=[".file-viewer-code-with-lines",".file-viewer-markdown-wrapper",".file-viewer-code-wrapper",".file-viewer-diagram-wrapper",".file-viewer-image-wrapper",".file-viewer-pdf-wrapper"];for(const o of n){const c=t.current.querySelector(o);if(c&&Fs(c))return c}return Fs(t.current)?t.current:null}function Fs(t){const n=["auto","scroll"].includes(getComputedStyle(t).overflowY),o=t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth;return n&&o}function Bs(t){if(!t)return 19.5;const n=parseFloat(getComputedStyle(t).lineHeight);return isNaN(n)?19.5:n}function Yt(t,n=!0){const o=n?t.scrollHeight:0;t.scrollTo({top:o,behavior:"smooth"})}function ua(t){const{scrollTop:n,scrollHeight:o,clientHeight:c}=t;return o<=c?100:Math.round(n/(o-c)*100)}function ha(t,n){const o=Bs(t),c=t.scrollTop,r=Math.floor(c/o)+1,i=n.split(`
3
+ `).length;return Math.min(r,i)}function ma(t,n,o=!1){if(!n)return[];o||t.toLowerCase();const c=o?n:n.toLowerCase(),r=[];let i=0;const f=t.split(`
4
+ `);let l=0;for(let u=0;u<f.length;u++){const g=f[u],j=o?g:g.toLowerCase();let p=0,y=j.indexOf(c);for(;y!==-1;){const C=l+y;r.push({index:i++,line:u+1,column:y,length:c.length,charIndex:C}),p=y+c.length,y=j.indexOf(c,p)}l+=g.length+1}return r}function lt(t){return/[\w]/.test(t)}function Ge(t){return/\s/.test(t)}function fa(t,n,o){let c=n-1,r=o;const i=t.length,f=t[c]||"";if(r<f.length){const g=lt(f[r]);if(!Ge(f[r]))for(;r<f.length&&!Ge(f[r])&&lt(f[r])===g;)r++}for(;c<i;){const g=t[c]||"";for(;r<g.length&&Ge(g[r]);)r++;if(r<g.length)return{line:c+1,col:r};c++,r=0}const l=i,u=Math.max(0,(t[i-1]||"").length-1);return{line:l,col:u}}function pa(t,n,o){let c=n-1,r=o+1;const i=t.length;for(;c<i;){const u=t[c]||"";for(;r<u.length&&Ge(u[r]);)r++;if(r<u.length)break;c++,r=0}if(c>=i)return{line:i,col:Math.max(0,(t[i-1]||"").length-1)};const f=t[c]||"",l=lt(f[r]);for(;r+1<f.length&&!Ge(f[r+1])&&lt(f[r+1])===l;)r++;return{line:c+1,col:r}}function ga(t,n,o){let c=n-1,r=o-1;for(;c>=0;){const l=t[c]||"";for(;r>=0&&Ge(l[r]);)r--;if(r>=0)break;c--,c>=0&&(r=(t[c]||"").length-1)}if(c<0)return{line:1,col:0};const i=t[c]||"",f=lt(i[r]);for(;r>0&&!Ge(i[r-1])&&lt(i[r-1])===f;)r--;return{line:c+1,col:r}}function xa(t,n,o,c){if(c==="none")return"";const{anchorLine:r,anchorCol:i,headLine:f,headCol:l}=o;if(c==="line"){const C=Math.min(r,f),R=Math.max(r,f);return n.slice(C-1,R).join(`
5
+ `)}let u,g,j,p;if(r<f||r===f&&i<=l?(u=r,g=i,j=f,p=l):(u=f,g=l,j=r,p=i),u===j)return(n[u-1]||"").substring(g,p+1);const y=[];y.push((n[u-1]||"").substring(g));for(let C=u;C<j-1;C++)y.push(n[C]||"");return y.push((n[j-1]||"").substring(0,p+1)),y.join(`
6
+ `)}function _s(t){const{containerRef:n,isEnabled:o=!0,content:c="",onClose:r,onSearchOpen:i}=t,f=s.useRef({percentage:0,line:1,column:1}),l=s.useRef(null),u=s.useRef(19.5),g=s.useMemo(()=>c.split(`
7
+ `),[c]),j=g.length,[p,y]=s.useState(1),[C,R]=s.useState(0),[x,N]=s.useState(!1),[d,v]=s.useState("none"),[w,S]=s.useState(null),[A,H]=s.useState(!1),[G,z]=s.useState(""),[ae,ee]=s.useState(0),[D,F]=s.useState(!1),I=s.useMemo(()=>ma(c,G,!1),[c,G]),re=s.useCallback(()=>{const m=l.current;if(!m)return;const q=ua(m),ie=ha(m,c),V=Math.max(1,Math.round(m.scrollLeft/7.8)+1);f.current={percentage:q,line:ie,column:V}},[c]),_=s.useCallback(()=>{H(!0),z(""),ee(0),i==null||i()},[i]),ge=s.useCallback(()=>{H(!1),z(""),ee(0)},[]),O=s.useCallback(()=>{F(m=>!m)},[]),Z=s.useCallback(m=>{const q=l.current;if(!q)return;const ie=q.querySelector(".file-viewer-pre"),ue=ie&&parseFloat(getComputedStyle(ie).lineHeight)||u.current,V=ie&&parseFloat(getComputedStyle(ie).paddingTop)||0,Q=(ie?ie.offsetTop:0)+V+(m-1)*ue,te=ue*3;q.scrollTo({top:Math.max(0,Q-te),behavior:"smooth"})},[]);s.useEffect(()=>{!A||I.length===0||ee(0)},[I,A]),s.useEffect(()=>{if(!A||I.length===0)return;const m=I[ae];m&&(y(m.line),R(m.column),Z(m.line))},[A,I,ae,Z]);const L=s.useCallback(()=>{I.length!==0&&ee(m=>(m+1)%I.length)},[I]),T=s.useCallback(()=>{I.length!==0&&ee(m=>(m-1+I.length)%I.length)},[I]),W=s.useCallback(m=>{const q=l.current;if(!q)return;const ie=q.querySelector(".file-viewer-pre");if(!ie)return;const ue=parseFloat(getComputedStyle(ie).lineHeight),V=isNaN(ue)?u.current:ue,E=parseFloat(getComputedStyle(ie).paddingTop)||0,te=ie.offsetTop+E+(m-1)*V,Ne=te+V,xe=q.scrollTop,U=xe+q.clientHeight;te<xe?q.scrollTo({top:Math.max(0,te),behavior:"auto"}):Ne>U&&q.scrollTo({top:Ne-q.clientHeight,behavior:"auto"})},[]),ne=s.useCallback((m,q)=>{y(m),R(q),W(m),d!=="none"&&S(ie=>ie?{...ie,headLine:m,headCol:q}:null)},[d,W]),be=s.useCallback(()=>{if(d==="none"||!w)return;const m=xa(c,g,w,d);m&&navigator.clipboard.writeText(m).catch(()=>{const q=document.createElement("textarea");q.value=m,q.style.position="fixed",q.style.left="-9999px",document.body.appendChild(q),q.select(),document.execCommand("copy"),document.body.removeChild(q)}),v("none"),S(null)},[d,w,c,g]),de=s.useCallback(m=>{const q=m.target;if((q.tagName==="INPUT"||q.tagName==="TEXTAREA")&&m.key!=="Escape")return;const ue=l.current;if(!ue)return;let V=!1;const E=u.current,Q=Math.max(1,Math.floor(ue.clientHeight/E)),te=Math.max(1,Math.floor(Q/2)),Ne=(U,se)=>{const pe=Math.max(0,(g[U-1]||"").length-1);return Math.min(se,Math.max(0,pe))},xe=(U,se)=>{const pe=Ne(U,se);ne(U,pe)};if(m.key==="v"&&!m.shiftKey&&!m.ctrlKey&&!A)m.preventDefault(),m.stopPropagation(),d==="char"?(v("none"),S(null)):(v("char"),S({anchorLine:p,anchorCol:C,headLine:p,headCol:C})),V=!0;else if(m.key==="V"&&m.shiftKey&&!m.ctrlKey&&!A)m.preventDefault(),m.stopPropagation(),d==="line"?(v("none"),S(null)):(v("line"),S({anchorLine:p,anchorCol:0,headLine:p,headCol:0})),V=!0;else if(m.key==="y"&&!m.ctrlKey&&d!=="none")m.preventDefault(),m.stopPropagation(),be(),V=!0;else if(m.key==="j"||m.key==="ArrowDown"){m.preventDefault(),m.stopPropagation();const U=Math.min(p+1,j);xe(U,C),V=!0}else if(m.key==="k"||m.key==="ArrowUp"){m.preventDefault(),m.stopPropagation();const U=Math.max(p-1,1);xe(U,C),V=!0}else if(m.key==="d"&&m.ctrlKey||m.key==="d"&&d==="none"&&!A){m.preventDefault(),m.stopPropagation();const U=Math.min(p+te,j);xe(U,C),V=!0}else if(m.key==="u"&&m.ctrlKey||m.key==="u"&&d==="none"&&!A){m.preventDefault(),m.stopPropagation();const U=Math.max(p-te,1);xe(U,C),V=!0}else if((m.ctrlKey||m.metaKey)&&m.key==="f")m.preventDefault(),m.stopPropagation(),_(),V=!0;else if(m.key==="f"&&!m.ctrlKey&&!m.metaKey&&d==="none"&&!A){m.preventDefault(),m.stopPropagation();const U=Math.min(p+Q,j);xe(U,C),V=!0}else if(m.key===" "||m.key==="PageDown"){m.preventDefault(),m.stopPropagation();const U=Math.min(p+Q,j);xe(U,C),V=!0}else if(m.key==="b"&&!x&&d==="none"&&!A||m.key==="PageUp"){m.preventDefault(),m.stopPropagation();const U=Math.max(p-Q,1);xe(U,C),V=!0}else if(m.key==="g"&&!m.shiftKey&&d==="none"&&!A)m.preventDefault(),m.stopPropagation(),ne(1,0),Yt(ue,!1),V=!0;else if(m.key==="Home")m.preventDefault(),m.stopPropagation(),ne(1,0),Yt(ue,!1),V=!0;else if(m.key==="G"&&m.shiftKey||m.key==="End")m.preventDefault(),m.stopPropagation(),ne(j,0),Yt(ue,!0),V=!0;else if(m.key==="h"||m.key==="ArrowLeft")m.preventDefault(),m.stopPropagation(),ne(p,Math.max(0,C-1)),V=!0;else if(m.key==="l"||m.key==="ArrowRight"){m.preventDefault(),m.stopPropagation();const U=(g[p-1]||"").length;ne(p,Math.min(C+1,Math.max(0,U-1))),V=!0}else if(m.key==="w"&&!m.ctrlKey&&!A){m.preventDefault(),m.stopPropagation();const U=fa(g,p,C);ne(U.line,U.col),V=!0}else if(m.key==="e"&&!m.ctrlKey&&!A){m.preventDefault(),m.stopPropagation();const U=pa(g,p,C);ne(U.line,U.col),V=!0}else if(m.key==="b"&&!A){m.preventDefault(),m.stopPropagation();const U=ga(g,p,C);ne(U.line,U.col),V=!0}else if(m.key==="0")m.preventDefault(),m.stopPropagation(),ne(p,0),V=!0;else if(m.key==="$")m.preventDefault(),m.stopPropagation(),ne(p,Math.max(0,(g[p-1]||"").length-1)),V=!0;else if(m.key==="^"){m.preventDefault(),m.stopPropagation();const se=(g[p-1]||"").search(/\S/);ne(p,se>=0?se:0),V=!0}else m.key==="/"?(m.preventDefault(),m.stopPropagation(),_(),V=!0):m.key==="n"&&!A?(m.preventDefault(),m.stopPropagation(),L(),V=!0):m.key==="N"&&m.shiftKey&&!A?(m.preventDefault(),m.stopPropagation(),T(),V=!0):m.key==="?"&&d==="none"?(m.preventDefault(),m.stopPropagation(),O(),V=!0):m.key==="q"&&d==="none"?(m.preventDefault(),m.stopPropagation(),r==null||r(),V=!0):m.key==="Escape"&&(d!=="none"?(m.preventDefault(),m.stopPropagation(),v("none"),S(null),V=!0):A?(m.preventDefault(),m.stopPropagation(),ge(),V=!0):x&&(m.preventDefault(),m.stopPropagation(),N(!1),V=!0));V&&(m.key!=="Escape"&&!x&&N(!0),requestAnimationFrame(re))},[r,re,j,g,p,C,W,A,ge,d,x,ne,be,_,L,T,O]);return s.useEffect(()=>{if(!o)return;const m=da(n);if(l.current=m,!m){console.warn("[useLessNavigation] Could not find scrollable container");return}u.current=Bs(m);const q=()=>{re()};return window.addEventListener("keydown",de,{capture:!0}),m.addEventListener("scroll",q,{passive:!0}),re(),()=>{window.removeEventListener("keydown",de,{capture:!0}),m.removeEventListener("scroll",q)}},[o,de,re]),{scrollPercentage:f.current.percentage,currentLine:f.current.line,currentColumn:f.current.column,totalLines:j,cursorLine:p,cursorCol:C,cursorModeActive:x,visualMode:d,selection:w,searchActive:A,searchQuery:G,searchMatches:I,currentMatchIndex:ae,startSearch:_,setSearchQuery:z,nextMatch:L,prevMatch:T,clearSearch:ge,helpActive:D,toggleHelp:O}}const Zt=({query:t,onQueryChange:n,matchCount:o,currentIndex:c,onNext:r,onPrev:i,onClose:f})=>{const{t:l}=le(["terminal"]),u=s.useRef(null);s.useEffect(()=>{var p;(p=u.current)==null||p.focus()},[]);const g=s.useCallback(p=>{p.stopPropagation(),p.key==="Enter"||p.key==="ArrowDown"?(p.preventDefault(),r()):p.key==="ArrowUp"&&(p.preventDefault(),i())},[r,i]),j=o===0&&t?l("terminal:fileExplorer.noMatches"):o>0?`${c+1}/${o}`:"";return e.jsxs("div",{className:"file-viewer-search-bar",children:[e.jsxs("div",{className:"file-viewer-search-input-wrapper",children:[e.jsx("span",{className:"file-viewer-search-prefix",children:"/"}),e.jsx("input",{ref:u,type:"text",className:"file-viewer-search-input",placeholder:l("terminal:fileExplorer.searchInFile"),value:t,onChange:p=>n(p.target.value),onKeyDown:g,autoComplete:"off",spellCheck:"false"})]}),t&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"file-viewer-search-counter",children:j}),e.jsxs("div",{className:"file-viewer-search-nav",children:[e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-prev",onClick:i,disabled:o===0,title:l("terminal:fileExplorer.previousMatch"),"aria-label":l("terminal:fileExplorer.previousMatch"),children:e.jsx(M,{name:"caret-up",size:10})}),e.jsx("button",{className:"file-viewer-search-btn file-viewer-search-next",onClick:r,disabled:o===0,title:l("terminal:fileExplorer.nextMatch"),"aria-label":l("terminal:fileExplorer.nextMatch"),children:e.jsx(M,{name:"caret-down",size:10})})]})]}),e.jsx("button",{className:"file-viewer-search-close",onClick:f,title:l("terminal:fileExplorer.closeSearch"),"aria-label":l("terminal:fileExplorer.closeSearch"),children:e.jsx(M,{name:"close",size:12})})]})};Zt.displayName="SearchBar";const ya=[{keys:["j","↓"],description:"Move cursor down one line",category:"Navigation"},{keys:["k","↑"],description:"Move cursor up one line",category:"Navigation"},{keys:["h","←"],description:"Move cursor left",category:"Navigation"},{keys:["l","→"],description:"Move cursor right",category:"Navigation"},{keys:["0"],description:"Jump to start of line",category:"Navigation"},{keys:["$"],description:"Jump to end of line",category:"Navigation"},{keys:["^"],description:"First non-whitespace char",category:"Navigation"},{keys:["d","Ctrl+D"],description:"Half page down",category:"Navigation"},{keys:["u","Ctrl+U"],description:"Half page up",category:"Navigation"},{keys:["f","Space"],description:"Full page down",category:"Navigation"},{keys:["b","Page Up"],description:"Full page up",category:"Navigation"},{keys:["g","Home"],description:"Jump to top of file",category:"Navigation"},{keys:["G","End"],description:"Jump to bottom of file",category:"Navigation"},{keys:["w"],description:"Next word start",category:"Word Motion"},{keys:["e"],description:"Next word end",category:"Word Motion"},{keys:["b"],description:"Previous word start",category:"Word Motion"},{keys:["v"],description:"Character visual mode",category:"Visual Mode"},{keys:["V"],description:"Line visual mode",category:"Visual Mode"},{keys:["y"],description:"Yank (copy) selection",category:"Visual Mode"},{keys:["Escape"],description:"Exit visual mode",category:"Visual Mode"},{keys:["/"],description:"Open search bar",category:"Search"},{keys:["n"],description:"Next match",category:"Search"},{keys:["N"],description:"Previous match",category:"Search"},{keys:["?"],description:"Toggle this help overlay",category:"Help"},{keys:["Escape"],description:"Exit cursor mode (or visual/search)",category:"Help"},{keys:["Alt+E"],description:"Close file viewer",category:"Help"},{keys:["q"],description:"Close file viewer",category:"Help"}],es=({onClose:t})=>{const{t:n}=le(["terminal"]),o=s.useCallback(i=>{i.target===i.currentTarget&&t()},[t]),c=s.useCallback(i=>{(i.key==="Escape"||i.key==="?")&&(i.preventDefault(),i.stopPropagation(),t())},[t]),r=ya.reduce((i,f)=>(i[f.category]||(i[f.category]=[]),i[f.category].push(f),i),{});return e.jsx("div",{className:"keybindings-help-overlay",onClick:o,onKeyDown:c,tabIndex:0,role:"dialog","aria-label":n("terminal:fileExplorer.keybindingsHelp"),children:e.jsxs("div",{className:"keybindings-help-content",children:[e.jsx("button",{className:"keybindings-help-close",onClick:t,"aria-label":n("terminal:fileExplorer.closeHelp"),title:n("terminal:fileExplorer.pressEscapeToClose"),children:e.jsx(M,{name:"close",size:14})}),e.jsx("h2",{className:"keybindings-help-title",children:n("terminal:fileExplorer.keybindingsHelp")}),e.jsx("p",{className:"keybindings-help-subtitle",children:n("terminal:fileExplorer.keybindingsSubtitle")}),e.jsx("div",{className:"keybindings-help-categories",children:Object.entries(r).map(([i,f])=>e.jsxs("div",{className:"keybindings-help-category",children:[e.jsx("h3",{className:"keybindings-help-category-title",children:i}),e.jsx("div",{className:"keybindings-help-list",children:f.map((l,u)=>e.jsxs("div",{className:"keybindings-help-item",children:[e.jsx("div",{className:"keybindings-help-keys",children:l.keys.map((g,j)=>e.jsx("kbd",{className:"keybindings-help-key",children:g},j))}),e.jsx("div",{className:"keybindings-help-description",children:l.description})]},u))})]},i))}),e.jsx("p",{className:"keybindings-help-footer",children:n("terminal:fileExplorer.keybindingsFooter")})]})})};es.displayName="KeybindingsHelp";const Is=s.lazy(()=>Rn(()=>import("./EmbeddedEditor-x0-x_VZN.js"),__vite__mapDeps([0,1,2,3,4,5])).then(t=>({default:t.EmbeddedEditor}))),ba=[".md",".mdx",".markdown"],Ps="file-viewer-markdown-render",ja=[".puml",".plantuml",".iuml",".pu"],Ls="file-viewer-plantuml-render",va="https://kroki.io/plantuml/svg";function wa(t){return ba.includes(t.toLowerCase())}function Ca(t){return ja.includes(t.toLowerCase())}function Na(){const[t,n]=s.useState(()=>{try{const c=localStorage.getItem(Ps);return c===null?!0:c==="true"}catch{return!0}}),o=s.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ps,String(r))}catch{}return r})},[]);return[t,o]}function ka(){const[t,n]=s.useState(()=>{try{const c=localStorage.getItem(Ls);return c===null?!0:c==="true"}catch{return!0}}),o=s.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ls,String(r))}catch{}return r})},[]);return[t,o]}function Ea(t){const n=new TextEncoder().encode(t);let o="";for(const c of n)o+=String.fromCharCode(c);return`data:image/svg+xml;base64,${window.btoa(o)}`}function Ue({file:t,rightContent:n,onRevealInTree:o,editMode:c,onToggleEdit:r}){const{t:i}=le(["terminal","common"]),[f,l]=s.useState("idle"),[u,g]=s.useState("idle"),[j,p]=s.useState("idle"),y=t.fileType==="text"?Ft(t.extension):t.extension.slice(1).toUpperCase(),C=t.fileType==="text"&&t.content!=null,{settings:R}=zs(),x=async()=>{try{await Tt(t.content),p("copied"),setTimeout(()=>p("idle"),2e3)}catch{p("error"),setTimeout(()=>p("idle"),2e3)}},N=()=>{const S=new Blob([t.content],{type:"text/plain;charset=utf-8"}),A=URL.createObjectURL(S),H=document.createElement("a");H.href=A,H.download=t.filename,document.body.appendChild(H),H.click(),H.remove(),setTimeout(()=>URL.revokeObjectURL(A),1e3)},d=async()=>{l("loading");try{const S=await Y(K("/api/files/open-in-editor"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,...R.externalEditorCommand&&{editorCommand:R.externalEditorCommand}})});if(!S.ok){const A=await S.json().catch(()=>({error:"Unknown error"}));console.error("Failed to open in editor:",A),l("error"),setTimeout(()=>l("idle"),2e3);return}l("success"),setTimeout(()=>l("idle"),2e3)}catch(S){console.error("Error opening file in editor:",S),l("error"),setTimeout(()=>l("idle"),2e3)}},v=async()=>{if(t.path)try{await $n(t.path),g("success"),setTimeout(()=>g("idle"),2e3)}catch(S){console.error("Error opening file explorer:",S),g("error"),setTimeout(()=>g("idle"),2e3)}},w=i("terminal:fileExplorer.openInFileExplorer");return e.jsxs("div",{className:"file-viewer-header",children:[e.jsxs("div",{className:"file-viewer-header-left",children:[e.jsx("span",{className:"file-viewer-filename",children:t.filename}),e.jsxs("span",{className:"file-viewer-meta",children:[As(t.size)," • ",y,t.content&&` • ${t.content.split(`
8
+ `).length} lines`]})]}),e.jsxs("div",{className:"file-viewer-header-right",children:[r&&t.fileType==="text"&&e.jsx("button",{className:`file-viewer-edit-btn${c?" active":""}`,onClick:r,title:i(c?"terminal:fileExplorer.exitEdit":"terminal:fileExplorer.editFile"),children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M11.013 1.427a1.75 1.75 0 012.474 0l1.086 1.086a1.75 1.75 0 010 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 01-.927-.928l.929-3.25a1.75 1.75 0 01.445-.758l8.61-8.61zm1.414 1.06a.25.25 0 00-.354 0L3.463 11.1a.25.25 0 00-.064.108l-.558 1.953 1.953-.558a.25.25 0 00.108-.064l8.61-8.61a.25.25 0 000-.354l-1.086-1.086z"})})}),C&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:`file-viewer-copy-html-btn ${j}`,onClick:x,title:i("terminal:fileExplorer.copyAllTitle"),children:i(j==="copied"?"terminal:fileExplorer.copied":j==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyAll")}),e.jsx("button",{className:"file-viewer-download-btn",onClick:N,title:i("terminal:fileExplorer.downloadFileTitle"),children:i("common:buttons.download")})]}),e.jsx("button",{className:`file-viewer-reveal-explorer-btn ${u}`,onClick:v,disabled:!t.path,title:w,"aria-label":w,children:u==="success"?e.jsx(M,{name:"check",size:14}):u==="error"?e.jsx(M,{name:"cross",size:14}):e.jsx(M,{name:"folder-open",size:14})}),e.jsx("button",{className:`file-viewer-open-editor-btn ${f}`,onClick:d,disabled:f==="loading",title:i(f==="error"?"terminal:fileExplorer.failedToOpenEditor":f==="success"?"terminal:fileExplorer.openingInEditor":"terminal:fileExplorer.openInEditor"),children:f==="success"?e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 11-1.06-1.06l7.25-7.25a.75.75 0 011.06 0z"})}):f==="error"?e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"})}):e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M1.5 1h6v1.5h-5v11h11v-5H15v6.5H0V1h1.5zm8 0H15v5.5h-1.5V3.56L7.28 9.78l-1.06-1.06L12.44 2.5H9.5V1z"})})}),o&&e.jsx("button",{className:"file-viewer-locate-btn",onClick:()=>o(t.path),title:i("terminal:fileExplorer.locateInTree"),children:e.jsx(M,{name:"target",size:14})}),n]})]})}function Sa({file:t,onRevealInTree:n,renderMarkdown:o,onToggleRender:c,editMode:r,onToggleEdit:i}){const f=s.useRef(null),l=s.useRef(null),u=s.useRef(null),{t:g}=le(["terminal","common"]),[j,p]=s.useState("idle"),[y,C]=s.useState("idle"),[R,x]=s.useState("idle"),[N,d]=s.useState("idle"),v=_s({containerRef:u,isEnabled:!0,content:t.content});s.useEffect(()=>{if(!o&&f.current){const z=Ft(t.extension);Os(z).then(()=>{f.current&&Gs(f.current)})}},[t,o]);const w=s.useCallback(async()=>{if(!l.current){p("error"),setTimeout(()=>p("idle"),2e3);return}try{const z=l.current.innerHTML,ae=Fn(z),ee=l.current.innerText;await In(ae,ee),p("copied"),setTimeout(()=>p("idle"),2e3)}catch{p("error"),setTimeout(()=>p("idle"),2e3)}},[]),S=s.useCallback(async()=>{if(!l.current){C("error"),setTimeout(()=>C("idle"),2e3);return}try{const z=l.current.innerHTML;await Tt(z),C("copied"),setTimeout(()=>C("idle"),2e3)}catch{C("error"),setTimeout(()=>C("idle"),2e3)}},[]),A=s.useCallback(async()=>{try{await Tt(t.content),x("copied"),setTimeout(()=>x("idle"),2e3)}catch{x("error"),setTimeout(()=>x("idle"),2e3)}},[t.content]),H=s.useCallback(async()=>{try{await Tt(t.content),d("copied"),setTimeout(()=>d("idle"),2e3)}catch{d("error"),setTimeout(()=>d("idle"),2e3)}},[t.content]),G=e.jsxs("div",{className:"file-viewer-header-buttons",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:`file-viewer-copy-html-btn ${j}`,onClick:w,title:g("terminal:fileExplorer.copyRichTextTitle"),children:g(j==="copied"?"terminal:fileExplorer.copied":j==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyRichText")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${y}`,onClick:S,title:g("terminal:fileExplorer.copyHtmlTitle"),children:g(y==="copied"?"terminal:fileExplorer.copied":y==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyHtml")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${R}`,onClick:A,title:g("terminal:fileExplorer.copyMarkdownTitle"),children:g(R==="copied"?"terminal:fileExplorer.copied":R==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyMarkdown")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${N}`,onClick:H,title:g("terminal:fileExplorer.copyOriginalTitle"),children:g(N==="copied"?"terminal:fileExplorer.copied":N==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyOriginal")})]}),e.jsx("button",{className:`file-viewer-render-toggle ${o?"active":""}`,onClick:c,title:g(o?"terminal:fileExplorer.showSource":"terminal:fileExplorer.renderMarkdown"),children:o?"</>":"Aa"})]});return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{file:t,onRevealInTree:n,rightContent:G,editMode:r,onToggleEdit:i}),e.jsxs("div",{className:"file-viewer-content-wrapper",ref:u,children:[o?e.jsx("div",{className:"file-viewer-markdown-wrapper",children:e.jsx("div",{className:"markdown-content",ref:l,children:e.jsx(Pn,{remarkPlugins:[Ln],children:t.content})})}):e.jsx("div",{className:"file-viewer-code-wrapper",children:e.jsx("pre",{className:"file-viewer-pre",children:e.jsx("code",{ref:f,className:"language-markdown",children:t.content})})}),e.jsx("div",{className:"file-viewer-scroll-indicator",title:`Line ${v.currentLine}/${v.totalLines}`,children:v.scrollPercentage===100?"END":v.scrollPercentage===0?"TOP":`${v.scrollPercentage}%`}),v.searchActive&&e.jsx(Zt,{query:v.searchQuery,onQueryChange:v.setSearchQuery,matchCount:v.searchMatches.length,currentIndex:v.currentMatchIndex,onNext:v.nextMatch,onPrev:v.prevMatch,onClose:v.clearSearch})]}),v.helpActive&&e.jsx(es,{onClose:v.toggleHelp})]})}function Ta({file:t,onRevealInTree:n,renderPlantUml:o,onToggleRender:c,editMode:r,onToggleEdit:i}){const{t:f}=le(["terminal"]),l=s.useRef(null),u=s.useRef(null),[g,j]=s.useState(null),[p,y]=s.useState(!1),[C,R]=s.useState(null),x=_s({containerRef:u,isEnabled:!0,content:t.content});s.useEffect(()=>{if(!o&&l.current){const d=Ft(t.extension);Os(d).then(()=>{l.current&&Gs(l.current)})}},[t,o]),s.useEffect(()=>{if(!o)return;if(!t.content.trim()){j(null),R("Diagram is empty");return}const d=new AbortController;return y(!0),R(null),(async()=>{try{const w=await fetch(va,{method:"POST",headers:{"Content-Type":"text/plain; charset=utf-8",Accept:"image/svg+xml"},body:t.content,signal:d.signal});if(!w.ok)throw new Error(`Render failed (${w.status})`);const S=await w.text();if(!S.includes("<svg"))throw new Error("Invalid SVG output");j(Ea(S))}catch(w){if(d.signal.aborted)return;const S=w instanceof Error?w.message:"Failed to render diagram";R(S),j(null)}finally{d.signal.aborted||y(!1)}})(),()=>d.abort()},[t.path,t.content,o]);const N=e.jsx("div",{className:"file-viewer-header-buttons",children:e.jsx("button",{className:`file-viewer-render-toggle ${o?"active":""}`,onClick:c,title:f(o?"terminal:fileExplorer.showSource":"terminal:fileExplorer.renderDiagram"),children:o?"</>":f("terminal:fileExplorer.diagram")})});return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{file:t,onRevealInTree:n,rightContent:N,editMode:r,onToggleEdit:i}),e.jsxs("div",{className:"file-viewer-content-wrapper",ref:u,children:[o?e.jsxs("div",{className:"file-viewer-diagram-wrapper",children:[p&&e.jsx("div",{className:"file-viewer-placeholder",children:f("terminal:fileExplorer.renderingDiagram")}),!p&&g&&e.jsx("img",{src:g,alt:t.filename,className:"file-viewer-diagram-image"}),!p&&C&&e.jsxs("div",{className:"file-viewer-diagram-error",children:[e.jsxs("div",{children:[f("terminal:fileExplorer.couldNotRender"),": ",C]}),e.jsx("button",{className:"file-viewer-render-toggle",onClick:c,children:f("terminal:fileExplorer.showSource")})]})]}):e.jsx("div",{className:"file-viewer-code-wrapper",children:e.jsx("pre",{className:"file-viewer-pre",children:e.jsx("code",{ref:l,className:"language-plaintext",children:t.content})})}),e.jsx("div",{className:"file-viewer-scroll-indicator",title:`Line ${x.currentLine}/${x.totalLines}`,children:x.scrollPercentage===100?"END":x.scrollPercentage===0?"TOP":`${x.scrollPercentage}%`}),x.searchActive&&e.jsx(Zt,{query:x.searchQuery,onQueryChange:x.setSearchQuery,matchCount:x.searchMatches.length,currentIndex:x.currentMatchIndex,onNext:x.nextMatch,onPrev:x.prevMatch,onClose:x.clearSearch})]}),x.helpActive&&e.jsx(es,{onClose:x.toggleHelp})]})}function Ma({file:t,onRevealInTree:n}){const{t:o}=le(["common","terminal"]),c=()=>{if(t.dataUrl){const r=document.createElement("a");r.href=t.dataUrl,r.download=t.filename,r.click()}};return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{file:t,onRevealInTree:n,rightContent:e.jsx("button",{className:"file-viewer-download-btn",onClick:c,title:o("common:buttons.download"),children:o("common:buttons.download")})}),e.jsx("div",{className:"file-viewer-image-wrapper",children:t.dataUrl?e.jsx("img",{src:t.dataUrl,alt:t.filename,className:"file-viewer-image"}):e.jsx("div",{className:"file-viewer-placeholder",children:o("terminal:fileExplorer.failedToLoadImage")})})]})}function Da({file:t,onRevealInTree:n}){const{t:o}=le(["common","terminal"]),c=()=>{if(t.dataUrl){const r=document.createElement("a");r.href=t.dataUrl,r.download=t.filename,r.click()}};return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{file:t,onRevealInTree:n,rightContent:e.jsx("button",{className:"file-viewer-download-btn",onClick:c,title:o("common:buttons.download"),children:o("common:buttons.download")})}),e.jsx("div",{className:"file-viewer-pdf-wrapper",children:t.dataUrl?e.jsx("iframe",{src:t.dataUrl,title:t.filename,className:"file-viewer-pdf"}):e.jsx("div",{className:"file-viewer-placeholder",children:o("terminal:fileExplorer.failedToLoadPdf")})})]})}function Ra({file:t,onRevealInTree:n}){const{t:o}=le(["terminal","common"]),c=()=>{if(t.dataUrl){const i=document.createElement("a");i.href=t.dataUrl,i.download=t.filename,i.click()}},r=()=>{const i=t.extension.toLowerCase();return[".xlsx",".xls"].includes(i)?e.jsx(M,{name:"dashboard",size:48}):[".docx",".doc"].includes(i)?e.jsx(M,{name:"edit",size:48}):[".pptx",".ppt"].includes(i)?e.jsx(M,{name:"film",size:48}):[".zip",".tar",".gz",".rar",".7z"].includes(i)?e.jsx(M,{name:"file-zip",size:48}):[".mp3",".wav",".flac",".ogg"].includes(i)?e.jsx(M,{name:"music-note",size:48}):[".mp4",".avi",".mov",".mkv",".webm"].includes(i)?e.jsx(M,{name:"film",size:48}):[".exe",".dmg",".app",".msi"].includes(i)?e.jsx(M,{name:"gear",size:48}):[".apk",".aab",".ipa"].includes(i)?e.jsx(M,{name:"mobile",size:48}):[".jar",".war",".ear"].includes(i)?e.jsx(M,{name:"coffee",size:48}):[".iso",".img"].includes(i)?e.jsx(M,{name:"disc",size:48}):[".so",".dll",".dylib"].includes(i)?e.jsx(M,{name:"wrench",size:48}):e.jsx(M,{name:"folder",size:48})};return e.jsxs(e.Fragment,{children:[e.jsx(Ue,{file:t,onRevealInTree:n}),e.jsxs("div",{className:"file-viewer-binary",children:[e.jsx("div",{className:"file-viewer-binary-icon",children:r()}),e.jsx("div",{className:"file-viewer-binary-name",children:t.filename}),e.jsx("div",{className:"file-viewer-binary-size",children:As(t.size)}),e.jsx("div",{className:"file-viewer-binary-message",children:o("terminal:fileExplorer.cannotPreview")}),e.jsx("button",{className:"file-viewer-download-btn large",onClick:c,children:o("terminal:fileExplorer.downloadFile")})]})]})}function Fa({file:t,loading:n,error:o,onRevealInTree:c,onFileEdited:r}){const{t:i}=le(["terminal","common"]),[f,l]=Na(),[u,g]=ka(),[j,p]=s.useState(!1);s.useEffect(()=>{p(!1)},[t==null?void 0:t.path]);const y=s.useCallback(async w=>{if(!t)return;const S=await Y(K("/api/files/write"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,content:w})});if(!S.ok){const A=await S.json().catch(()=>({error:"Save failed"}));throw new Error(A.error||"Save failed")}},[t]),C=s.useCallback(()=>{p(w=>(w&&t&&(r==null||r(t.path)),!w))},[t,r]),R=s.useCallback(()=>{t&&(r==null||r(t.path))},[t,r]);if(n)return e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")});if(o)return e.jsx("div",{className:"file-viewer-placeholder error",children:o});if(!t)return e.jsxs("div",{className:"file-viewer-placeholder",children:[e.jsx("div",{className:"placeholder-icon",children:e.jsx(M,{name:"folder-open",size:32})}),e.jsx("div",{className:"placeholder-text",children:i("terminal:fileExplorer.selectFileToView")})]});const x=t.fileType||"text",N=x==="text"&&wa(t.extension),d=x==="text"&&Ca(t.extension),v=N||d;return v&&j&&t.content!=null?e.jsxs("div",{className:"file-viewer-content",children:[e.jsx(Ue,{file:t,onRevealInTree:c,editMode:!0,onToggleEdit:C}),e.jsx(s.Suspense,{fallback:e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")}),children:e.jsx(Is,{content:t.content,extension:t.extension,onSave:y,onCancel:C},t.path)})]}):x==="text"&&!v&&t.content!=null?e.jsxs("div",{className:"file-viewer-content",children:[e.jsx(Ue,{file:t,onRevealInTree:c}),e.jsx(s.Suspense,{fallback:e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")}),children:e.jsx(Is,{content:t.content,extension:t.extension,onSave:y,onCancel:R},t.path)})]}):e.jsxs("div",{className:"file-viewer-content",children:[N&&e.jsx(Sa,{file:t,onRevealInTree:c,renderMarkdown:f,onToggleRender:l,editMode:j,onToggleEdit:C}),d&&!N&&e.jsx(Ta,{file:t,onRevealInTree:c,renderPlantUml:u,onToggleRender:g,editMode:j,onToggleEdit:C}),x==="image"&&e.jsx(Ma,{file:t,onRevealInTree:c}),x==="pdf"&&e.jsx(Da,{file:t,onRevealInTree:c}),x==="binary"&&e.jsx(Ra,{file:t,onRevealInTree:c})]})}const Vs=s.memo(Fa,(t,n)=>t.loading!==n.loading||t.error!==n.error?!1:t.file===null&&n.file===null?!0:t.file===null||n.file===null?!1:t.file.path===n.file.path&&t.file.content===n.file.content&&t.file.modified===n.file.modified);Vs.displayName="FileViewer";function Ks({text:t,query:n}){if(!n)return e.jsx(e.Fragment,{children:t});const o=Hn(t,n);if(o)return e.jsxs(e.Fragment,{children:[t.slice(0,o.start),e.jsx("mark",{className:"search-highlight",children:t.slice(o.start,o.end)}),t.slice(o.end)]});const c=n.toLowerCase(),i=t.toLowerCase().indexOf(c);return i===-1?e.jsx(e.Fragment,{children:t}):e.jsxs(e.Fragment,{children:[t.slice(0,i),e.jsx("mark",{className:"search-highlight",children:t.slice(i,i+n.length)}),t.slice(i+n.length)]})}const Ia=s.memo(function({node:n,query:o,isSelected:c,onSelect:r,lineNumber:i}){const f=n.isDirectory?null:Xt(n),l=n.path.split("/");l[l.length-1];const u=l.slice(0,-1).join("/");return e.jsxs("div",{className:`search-result-item ${c?"selected":""}`,onClick:()=>r(n),children:[n.isDirectory?e.jsx("span",{className:"search-result-icon",children:e.jsx(M,{name:"folder",size:14})}):f?e.jsx("span",{className:"search-result-icon",style:{backgroundImage:`url('${f}')`},role:"img","aria-label":"file icon"}):e.jsx("span",{className:"search-result-icon",children:e.jsx(M,{name:"file-text",size:14})}),e.jsxs("div",{className:"search-result-info",children:[e.jsxs("span",{className:"search-result-name",children:[e.jsx(Ks,{text:n.name,query:o}),i&&e.jsxs("span",{className:"search-result-line-badge",children:[":",i]})]}),e.jsx("span",{className:"search-result-path",children:u})]})]})}),Pa=s.memo(function({match:n,query:o,isSelected:c,onSelect:r}){const{t:i}=le(["terminal"]),f={name:n.name,path:n.path,isDirectory:!1,extension:n.extension},l=Xt(f),u=n.path.split("/"),g=u[u.length-1],j=u.slice(0,-1).join("/");return e.jsxs("div",{className:`content-search-item ${c?"selected":""}`,children:[e.jsxs("div",{className:`content-search-header ${c?"selected":""}`,onClick:()=>r(n.path),children:[l?e.jsx("span",{className:"content-search-icon",style:{backgroundImage:`url('${l}')`},role:"img","aria-label":"file icon"}):e.jsx("span",{className:"content-search-icon",children:e.jsx(M,{name:"file-text",size:14})}),e.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:"2px"},children:[e.jsx("span",{className:"content-search-name",children:g}),e.jsx("span",{className:"search-result-path",style:{fontSize:"10px"},children:j})]}),e.jsx("span",{className:"content-search-count",children:n.matches.length})]}),e.jsxs("div",{className:"content-search-matches",children:[n.matches.slice(0,5).map((p,y)=>e.jsxs("div",{className:"content-search-match",onClick:()=>r(n.path,p.line),children:[e.jsx("span",{className:"content-search-line-num",children:p.line}),e.jsx("span",{className:"content-search-line-content",children:e.jsx(Ks,{text:p.content.trim(),query:o})})]},`${n.path}-${p.line}-${y}`)),n.matches.length>5&&e.jsxs("div",{className:"content-search-match",style:{opacity:.6,cursor:"default"},children:[e.jsx("span",{className:"content-search-line-num",children:"..."}),e.jsx("span",{className:"content-search-line-content",children:i("terminal:fileExplorer.moreMatches",{count:n.matches.length-5})})]})]})]})});function La({filenameResults:t,contentResults:n,onSelectFile:o,onSelectContent:c,selectedPath:r,query:i,lineNumber:f}){const{t:l}=le(["terminal"]),u=t.length>0,g=n.length>0;return!u&&!g?e.jsx("div",{className:"search-no-results",children:l("terminal:fileExplorer.noMatchesFound")}):e.jsxs("div",{className:"unified-search-results",children:[u&&e.jsxs("div",{className:"unified-search-section",children:[e.jsxs("div",{className:"unified-search-section-header",children:[e.jsx("span",{className:"unified-search-section-icon",children:e.jsx(M,{name:"file-text",size:14})}),e.jsx("span",{className:"unified-search-section-title",children:l("terminal:fileExplorer.files")}),e.jsx("span",{className:"unified-search-section-count",children:t.length})]}),e.jsx("div",{className:"unified-search-section-content",children:t.map(j=>e.jsx(Ia,{node:j,query:i,isSelected:r===j.path,onSelect:o,lineNumber:f},j.path))})]}),g&&e.jsxs("div",{className:"unified-search-section",children:[e.jsxs("div",{className:"unified-search-section-header",children:[e.jsx("span",{className:"unified-search-section-icon",children:e.jsx(M,{name:"edit",size:14})}),e.jsx("span",{className:"unified-search-section-title",children:l("terminal:fileExplorer.content")}),e.jsx("span",{className:"unified-search-section-count",children:l("terminal:fileExplorer.matchesInFiles",{matches:n.reduce((j,p)=>j+p.matches.length,0),files:n.length})})]}),e.jsx("div",{className:"unified-search-section-content",children:n.map(j=>e.jsx(Pa,{match:j,query:i,isSelected:r===j.path,onSelect:c},j.path))})]})]})}const Ws=s.memo(La,(t,n)=>!(t.query!==n.query||t.selectedPath!==n.selectedPath||t.filenameResults.length!==n.filenameResults.length||t.contentResults.length!==n.contentResults.length));Ws.displayName="UnifiedSearchResults";const $a=s.memo(function({file:n,isSelected:o,onSelect:c,onStage:r,isStaging:i,showDirPath:f,isChecked:l,onToggleCheck:u,onContextMenu:g,onDiscard:j}){const{t:p}=le(["terminal"]),y=n.status,C=pt[y],R=y==="deleted",x=y==="untracked"&&r,N=n.name.includes(".")?"."+n.name.split(".").pop():"",d=f&&n.path.includes("/")?n.path.slice(0,n.path.lastIndexOf("/")):"";return e.jsxs("div",{className:`git-file-item ${o?"selected":""}`,onClick:()=>!R&&c(n.path,y),onContextMenu:v=>{v.preventDefault(),g==null||g(v,n,y)},style:{cursor:R?"not-allowed":"pointer"},title:n.path,children:[u&&e.jsx("input",{type:"checkbox",className:"git-file-checkbox",checked:l||!1,onChange:v=>{v.stopPropagation(),u(n.path)},onClick:v=>v.stopPropagation()}),e.jsx("img",{className:"tree-icon",src:ft(N),alt:"file"}),e.jsxs("span",{className:"git-file-name",children:[n.name,d&&e.jsx("span",{className:"git-file-dir",children:d})]}),e.jsx("span",{className:"git-file-status",style:{color:C.color},children:C.icon}),n.oldPath&&e.jsxs("span",{className:"git-file-renamed",children:[e.jsx(M,{name:"subitem",size:10,style:{transform:"rotate(180deg)"}})," ",n.oldPath.split("/").pop()]}),x&&e.jsx("button",{className:`git-stage-btn ${i?"staging":""}`,onClick:v=>{v.stopPropagation(),i||r(n.path)},title:p("terminal:fileExplorer.stageFile"),disabled:i,children:i?"...":"+"}),j&&e.jsx("button",{className:"git-discard-btn",onClick:v=>{v.stopPropagation(),j(n,y)},title:y==="untracked"||y==="added"?"Delete file":"Discard changes",children:e.jsx(M,{name:"revert",size:12})})]})}),Ha=16,za=22,Aa=s.memo(function t({node:n,depth:o,expandedDirs:c,onToggleDir:r,selectedPath:i,onSelect:f,onStage:l,stagingPaths:u,checkedFiles:g,onToggleCheck:j,onContextMenu:p,onDirContextMenu:y,onDiscard:C}){const{t:R}=le(["terminal"]),x=o*Ha;if(!n.isDirectory){const d=n.file.status,v=pt[d];return e.jsxs("div",{className:`git-file-item ${i===n.path?"selected":""}`,onClick:()=>d!=="deleted"&&f(n.file.path,d),onContextMenu:w=>{w.preventDefault(),p==null||p(w,n.file,d)},style:{paddingLeft:`${x+za}px`,cursor:d==="deleted"?"not-allowed":"pointer"},title:n.file.path,children:[j&&e.jsx("input",{type:"checkbox",className:"git-file-checkbox",checked:(g==null?void 0:g.has(n.file.path))||!1,onChange:w=>{w.stopPropagation(),j(n.file.path)},onClick:w=>w.stopPropagation()}),e.jsx("img",{className:"tree-icon",src:ft(n.file.name.includes(".")?"."+n.file.name.split(".").pop():""),alt:"file"}),e.jsx("span",{className:"git-file-name",children:n.file.name}),e.jsx("span",{className:"git-file-status",style:{color:v.color},children:v.icon}),n.file.oldPath&&e.jsxs("span",{className:"git-file-renamed",children:[e.jsx(M,{name:"subitem",size:10,style:{transform:"rotate(180deg)"}})," ",n.file.oldPath.split("/").pop()]}),d==="untracked"&&l&&e.jsx("button",{className:`git-stage-btn ${u!=null&&u.has(n.path)?"staging":""}`,onClick:w=>{w.stopPropagation(),u!=null&&u.has(n.path)||l(n.file.path)},title:R("terminal:fileExplorer.stageFile"),disabled:u==null?void 0:u.has(n.path),children:u!=null&&u.has(n.path)?"...":"+"}),C&&e.jsx("button",{className:"git-discard-btn",onClick:w=>{w.stopPropagation(),C(n.file,d)},title:d==="untracked"||d==="added"?"Delete file":"Discard changes",children:e.jsx(M,{name:"revert",size:12})})]})}const N=c.has(n.path);return e.jsxs("div",{className:"tree-node-wrapper",children:[e.jsxs("div",{className:`tree-node directory ${N?"expanded":""}`,style:{paddingLeft:`${x}px`},onClick:()=>r(n.path),onContextMenu:d=>{d.preventDefault(),d.stopPropagation(),y==null||y(d,n)},children:[e.jsx("span",{className:`tree-arrow ${N?"expanded":""}`,children:e.jsx(M,{name:"caret-right",size:10})}),e.jsx("img",{className:"tree-folder-icon",src:N?"/assets/vscode-icons/default_folder_opened.svg":"/assets/vscode-icons/default_folder.svg",alt:"folder"}),e.jsx("span",{className:"tree-name",children:n.name}),e.jsx("span",{className:"git-tree-file-count",children:R("terminal:fileExplorer.fileCount",{count:n.fileCount})})]}),N&&e.jsx("div",{className:"tree-children",children:n.children.map(d=>e.jsx(t,{node:d,depth:o+1,expandedDirs:c,onToggleDir:r,selectedPath:i,onSelect:f,onStage:l,stagingPaths:u,checkedFiles:g,onToggleCheck:j,onContextMenu:p,onDirContextMenu:y,onDiscard:C},d.path))})]})}),qt=s.memo(function({groupLabel:n,groupIcon:o,groupColor:c,files:r,treeNodes:i,viewMode:f,selectedPath:l,expandedDirs:u,onToggleDir:g,onFileSelect:j,onStageFile:p,onStageAll:y,stagingPaths:C,checkedFiles:R,onToggleCheck:x,onContextMenu:N,onDirContextMenu:d,onDiscardFile:v,onDiscardAll:w}){const{t:S}=le(["terminal"]);if(r.length===0)return null;const A=r.some(z=>z.status==="untracked"),H=A&&y&&r.length>0,G=C?r.every(z=>C.has(z.path)):!1;return e.jsxs("div",{className:"git-status-group",children:[e.jsxs("div",{className:"git-status-group-header",style:{color:c},children:[e.jsx("span",{className:"git-status-badge",style:{background:c},children:o}),n," (",r.length,")",H&&e.jsx("button",{className:`git-stage-all-btn ${G?"staging":""}`,onClick:z=>{z.stopPropagation(),G||y()},title:S("terminal:fileExplorer.stageAllUntracked"),disabled:G,children:G?"...":S("terminal:fileExplorer.stageAll")}),w&&e.jsxs("button",{className:"git-discard-all-btn",onClick:z=>{z.stopPropagation(),w()},title:A?`Delete all ${r.length} files`:`Discard all ${r.length} changes`,children:[e.jsx(M,{name:"revert",size:12})," All"]})]}),f==="tree"?e.jsx("div",{className:"git-tree-content",children:i.map(z=>e.jsx(Aa,{node:z,depth:0,expandedDirs:u,onToggleDir:g,selectedPath:l,onSelect:j,onStage:p,stagingPaths:C,checkedFiles:R,onToggleCheck:x,onContextMenu:N,onDirContextMenu:d,onDiscard:v},z.path))}):e.jsx("div",{className:"git-flat-content",children:r.map(z=>e.jsx($a,{file:z,isSelected:l===z.path,onSelect:j,onStage:z.status==="untracked"?p:void 0,isStaging:C==null?void 0:C.has(z.path),showDirPath:!0,isChecked:R==null?void 0:R.has(z.path),onToggleCheck:x,onContextMenu:N,onDiscard:v},z.path))})]})});function Oa({gitStatus:t,loading:n,onFileSelect:o,selectedPath:c,onRefresh:r,onStageFiles:i,stagingPaths:f,currentFolder:l,onCommitComplete:u,mergeInProgress:g,mergingBranch:j,onMergeContinue:p,onMergeAbort:y,onConflictOpen:C,onRevealInTree:R}){const{t:x}=le(["terminal","common"]),[N,d]=s.useState("tree"),[v,w]=s.useState(new Set),[S,A]=s.useState(""),[H,G]=s.useState(""),[z,ae]=s.useState(!1),[ee,D]=s.useState(new Set),[F,I]=s.useState(!1),[re,_]=s.useState(null),ge=s.useRef(null),{showToast:O}=Us(),[Z,L]=s.useState(null),[T,W]=s.useState(null),[ne,be]=s.useState(null),de=s.useCallback((k,P)=>{be({files:[k],label:k.name})},[]),m=s.useCallback(async()=>{if(!(!ne||!l))try{const k=await Y(K("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:ne.files.map(B=>({path:B.path,status:B.status})),directory:l})}),P=await k.json();k.ok&&P.success?(O("success","Discarded",`Reverted ${ne.files.length} file(s)`),r()):O("error","Discard Failed",P.error||"Could not discard changes")}catch{O("error","Discard Failed","Network error")}finally{be(null)}},[ne,l,r,O]),q=s.useCallback((k,P,B)=>{k.preventDefault(),k.stopPropagation(),L({isOpen:!0,position:{x:k.clientX,y:k.clientY},file:P,status:B})},[]),ie=s.useCallback(async(k,P)=>{if(l)try{const B=await Y(K("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:[{path:k.path,status:P}],directory:l})}),ke=await B.json();B.ok&&ke.success?(O("success","Discarded",`Restored ${k.name}`),r()):O("error","Discard Failed",ke.error||"Could not discard changes")}catch{O("error","Discard Failed","Network error")}},[l,r,O]),ue=s.useCallback(async k=>{try{await navigator.clipboard.writeText(k),O("success","Copied","Full path copied")}catch{O("error","Copy Failed","Could not copy path")}},[O]),V=s.useCallback(async k=>{const P=l&&k.startsWith(l+"/")?k.slice(l.length+1):k;try{await navigator.clipboard.writeText(P),O("success","Copied","Relative path copied")}catch{O("error","Copy Failed","Could not copy path")}},[l,O]),E=s.useMemo(()=>{if(!Z)return[];const{file:k,status:P}=Z,B=[];return P==="conflict"&&C?B.push({id:"open-conflict",label:x("terminal:fileExplorer.gitContextMenu.openConflictResolver"),icon:e.jsx(M,{name:"warn",size:14}),onClick:()=>C(k.path)}):P!=="deleted"&&B.push({id:"open-file",label:x("terminal:fileExplorer.gitContextMenu.openFile"),icon:e.jsx(M,{name:"file-text",size:14}),onClick:()=>o(k.path,P)}),P!=="conflict"&&B.push({id:"stage-file",label:x("terminal:fileExplorer.gitContextMenu.stageFile"),icon:e.jsx(M,{name:"plus",size:14}),onClick:()=>{i([k.path])}}),B.push({id:"divider-1",label:"",divider:!0,onClick:()=>{}}),(P==="modified"||P==="deleted"||P==="renamed"||P==="conflict")&&B.push({id:"discard-changes",label:x("terminal:fileExplorer.gitContextMenu.discardChanges"),icon:e.jsx(M,{name:"revert",size:14}),danger:!0,onClick:()=>{ie(k,P)}}),(P==="untracked"||P==="added")&&B.push({id:"delete-file",label:x("terminal:fileExplorer.gitContextMenu.deleteFile"),icon:e.jsx(M,{name:"trash",size:14}),danger:!0,onClick:()=>{ie(k,P)}}),B.push({id:"divider-2",label:"",divider:!0,onClick:()=>{}}),B.push({id:"copy-full-path",label:x("terminal:fileExplorer.gitContextMenu.copyFullPath"),icon:e.jsx(M,{name:"pin",size:14}),onClick:()=>{ue(k.path)}}),B.push({id:"copy-relative-path",label:x("terminal:fileExplorer.gitContextMenu.copyRelativePath"),icon:e.jsx(M,{name:"clipboard",size:14}),onClick:()=>{V(k.path)}}),R&&P!=="deleted"&&B.push({id:"reveal-in-tree",label:x("terminal:fileExplorer.gitContextMenu.revealInTree"),icon:e.jsx(M,{name:"target",size:14}),onClick:()=>R(k.path)}),B},[Z,o,i,C,R,ie,ue,V,x]),Q=s.useCallback((k,P)=>{k.preventDefault(),k.stopPropagation(),W({isOpen:!0,position:{x:k.clientX,y:k.clientY},node:P})},[]),te=s.useCallback(k=>!k.isDirectory&&k.file?[k.file]:k.children.flatMap(P=>te(P)),[]),Ne=s.useCallback(async k=>{if(!l)return;const P=te(k);if(P.length!==0)try{const B=await Y(K("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:P.map(Te=>({path:Te.path,status:Te.status})),directory:l})}),ke=await B.json();B.ok&&ke.success?(O("success","Discarded",`Reverted ${P.length} file(s) in ${k.name}`),r()):O("error","Discard Failed",ke.error||"Could not discard changes")}catch{O("error","Discard Failed","Network error")}},[l,te,r,O]),xe=s.useMemo(()=>{if(!T)return[];const{node:k}=T,P=te(k);return[{id:"discard-dir",label:`Discard Changes (${P.length} files)`,icon:e.jsx(M,{name:"revert",size:14}),danger:!0,onClick:()=>{Ne(k)}},{id:"stage-dir",label:`Stage All (${P.length} files)`,icon:e.jsx(M,{name:"plus",size:14}),onClick:()=>{i(P.map(B=>B.path))}}]},[T,te,Ne,i]),U=s.useCallback(k=>{w(P=>{const B=new Set(P);return B.has(k)?B.delete(k):B.add(k),B})},[]),{conflictFiles:se,conflictTree:pe,changesFiles:me,changesTree:Be,untrackedFiles:Se,untrackedTree:It,allDirPaths:He}=s.useMemo(()=>{if(!t||!t.isGitRepo||t.files.length===0)return{conflictFiles:[],conflictTree:[],changesFiles:[],changesTree:[],untrackedFiles:[],untrackedTree:[],allDirPaths:new Set};const k=new Set,P=t.files.filter(Re=>Re.status==="conflict"),B=Mt(P);Dt(B,k);const ke=t.files.filter(Re=>Re.status==="modified"||Re.status==="added"||Re.status==="deleted"||Re.status==="renamed"),Te=Mt(ke);Dt(Te,k);const ot=t.files.filter(Re=>Re.status==="untracked"),We=Mt(ot);return Dt(We,k),{conflictFiles:P,conflictTree:B,changesFiles:ke,changesTree:Te,untrackedFiles:ot,untrackedTree:We,allDirPaths:k}},[t]);s.useEffect(()=>{w(He)},[He]),s.useEffect(()=>{t!=null&&t.files&&D(new Set(t.files.map(k=>k.path)))},[t==null?void 0:t.files]);const Pt=s.useCallback(()=>{me.length!==0&&be({files:me,label:`${me.length} changed files`})},[me]),_e=s.useCallback(()=>{Se.length!==0&&be({files:Se,label:`${Se.length} unversioned files`})},[Se]),Lt=s.useCallback(()=>{se.length!==0&&be({files:se,label:`${se.length} conflicted files`})},[se]),Ve=se.length>0;s.useEffect(()=>{if(re){const k=re.type==="error"?8e3:4e3,P=setTimeout(()=>_(null),k);return()=>clearTimeout(P)}},[re]);const gt=s.useCallback(async()=>{const k=!z;if(ae(k),k&&l){G(S);try{const B=await(await Y(K(`/api/files/git-log-message?path=${encodeURIComponent(l)}`))).json();B.message&&A(B.message)}catch{}}else A(H)},[z,l,S,H]),je=s.useCallback(k=>{D(P=>{const B=new Set(P);return B.has(k)?B.delete(k):B.add(k),B})},[]),$t=s.useCallback(()=>{if(!(t!=null&&t.files))return;const k=t.files.map(B=>B.path),P=k.every(B=>ee.has(B));D(P?new Set:new Set(k))},[t==null?void 0:t.files,ee]),ve=s.useCallback(async k=>{if(!(!l||!S.trim()||ee.size===0||F)){I(!0),_(null);try{const P=await Y(K("/api/files/git-commit"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:l,message:S.trim(),amend:z,paths:Array.from(ee)})}),B=await P.json();if(!P.ok||!B.success){_({type:"error",text:B.error||"Commit failed"}),I(!1);return}if(k)try{const ke=await Y(K("/api/files/git-push"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:l})}),Te=await ke.json();ke.ok&&Te.success?_({type:"success",text:x("terminal:fileExplorer.committedAndPushed")}):_({type:"error",text:x("terminal:fileExplorer.committedButPushFailed",{error:Te.error||"Unknown error"})})}catch{_({type:"error",text:x("terminal:fileExplorer.committedButPushFailed",{error:"Network error"})})}else _({type:"success",text:x("terminal:fileExplorer.committedSuccessfully")});A(""),G(""),ae(!1),r(),u==null||u()}catch(P){_({type:"error",text:P.message||"Commit failed"})}finally{I(!1)}}},[l,S,z,ee,F,r,u]);if(n)return e.jsx("div",{className:"git-changes-loading",children:x("terminal:fileExplorer.loadingGitStatus")});if(!t||!t.isGitRepo)return e.jsxs("div",{className:"git-changes-empty",children:[e.jsx("div",{className:"git-empty-icon",children:e.jsx(M,{name:"package",size:32})}),e.jsx("div",{className:"git-empty-text",children:x("terminal:fileExplorer.notGitRepo")})]});if(t.files.length===0)return e.jsxs("div",{className:"git-changes-empty",children:[e.jsx("div",{className:"git-empty-icon",children:e.jsx(M,{name:"sparkle",size:32})}),e.jsx("div",{className:"git-empty-text",children:x("terminal:fileExplorer.workingTreeClean")}),e.jsx("div",{className:"git-empty-branch",children:x("terminal:fileExplorer.onBranch",{branch:t.branch})})]});const xt=k=>{i([k])},Ke=()=>{const k=Se.map(P=>P.path);k.length>0&&i(k)},De=(k,P)=>{P==="conflict"&&C?C(k):o(k,P)};return e.jsxs("div",{className:"git-changes",children:[e.jsxs("div",{className:"git-changes-header",children:[e.jsxs("span",{className:"git-branch",children:[e.jsx("span",{className:"git-branch-icon",children:e.jsx(M,{name:"git-branch",size:12})}),t.branch]}),t.counts&&e.jsxs("div",{className:"git-changes-summary",children:[(t.counts.conflict??0)>0&&e.jsxs("span",{className:"git-count conflict",children:[t.counts.conflict,"C"]}),t.counts.modified>0&&e.jsxs("span",{className:"git-count modified",children:[t.counts.modified,"M"]}),t.counts.added>0&&e.jsxs("span",{className:"git-count added",children:[t.counts.added,"A"]}),t.counts.deleted>0&&e.jsxs("span",{className:"git-count deleted",children:[t.counts.deleted,"D"]}),t.counts.untracked>0&&e.jsxs("span",{className:"git-count untracked",children:[t.counts.untracked,"?"]})]}),e.jsxs("div",{className:"git-view-toggle",children:[e.jsx("button",{className:`git-view-toggle-btn ${N==="flat"?"active":""}`,onClick:()=>d("flat"),title:x("terminal:fileExplorer.flatList"),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:[e.jsx("rect",{x:"2",y:"3",width:"12",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"2",y:"7",width:"12",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"2",y:"11",width:"12",height:"1.5",rx:"0.5"})]})}),e.jsx("button",{className:`git-view-toggle-btn ${N==="tree"?"active":""}`,onClick:()=>d("tree"),title:x("terminal:fileExplorer.directoryTree"),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:[e.jsx("rect",{x:"1",y:"2",width:"6",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"4",y:"5.5",width:"8",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"4",y:"9",width:"8",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"7",y:"12.5",width:"7",height:"1.5",rx:"0.5"})]})})]}),e.jsx("button",{className:"git-refresh-btn",onClick:r,title:x("common:buttons.refresh"),children:e.jsx(M,{name:"refresh",size:12})})]}),g&&e.jsxs("div",{className:"git-merge-banner",children:[e.jsx("span",{className:"git-merge-banner-icon",children:"⚠"}),e.jsx("span",{className:"git-merge-banner-text",children:x("terminal:fileExplorer.mergeInProgress",{branch:j?` (${j})`:""})}),e.jsxs("div",{className:"git-merge-actions",children:[e.jsx("button",{className:"git-merge-continue-btn",onClick:p,disabled:Ve,title:x(Ve?"terminal:fileExplorer.resolveAllConflictsFirst":"terminal:fileExplorer.continueMerge"),children:x("terminal:fileExplorer.continue")}),e.jsx("button",{className:"git-merge-abort-btn",onClick:y,title:x("terminal:fileExplorer.abortMerge"),children:x("terminal:fileExplorer.abort")})]})]}),e.jsxs("div",{className:"git-changes-list",children:[e.jsx(qt,{groupLabel:x("terminal:fileExplorer.gitGroups.conflicts"),groupIcon:"C",groupColor:"#ff5555",files:se,treeNodes:pe,viewMode:N,selectedPath:c,expandedDirs:v,onToggleDir:U,onFileSelect:De,checkedFiles:ee,onToggleCheck:je,onContextMenu:q,onDirContextMenu:Q,onDiscardFile:de,onDiscardAll:Lt}),e.jsx(qt,{groupLabel:x("terminal:fileExplorer.gitGroups.changes"),groupIcon:"~",groupColor:"#c89a5a",files:me,treeNodes:Be,viewMode:N,selectedPath:c,expandedDirs:v,onToggleDir:U,onFileSelect:De,checkedFiles:ee,onToggleCheck:je,onContextMenu:q,onDirContextMenu:Q,onDiscardFile:de,onDiscardAll:Pt}),e.jsx(qt,{groupLabel:x("terminal:fileExplorer.gitGroups.unversioned"),groupIcon:"?",groupColor:"#6ab8c8",files:Se,treeNodes:It,viewMode:N,selectedPath:c,expandedDirs:v,onToggleDir:U,onFileSelect:De,onStageFile:xt,onStageAll:Ke,stagingPaths:f,checkedFiles:ee,onToggleCheck:je,onContextMenu:q,onDirContextMenu:Q,onDiscardFile:de,onDiscardAll:_e})]}),e.jsxs("div",{className:"git-commit-panel",children:[e.jsxs("div",{className:"git-commit-options",children:[e.jsxs("label",{className:"git-commit-amend-label",children:[e.jsx("input",{type:"checkbox",className:"git-commit-amend-checkbox",checked:z,onChange:gt}),x("terminal:fileExplorer.amend")]}),e.jsx("span",{className:"git-commit-file-count",children:x("terminal:fileExplorer.fileCount",{count:ee.size})}),e.jsx("button",{className:"git-commit-select-toggle",onClick:$t,title:ee.size===t.files.length?x("terminal:fileExplorer.deselectAll"):x("terminal:fileExplorer.selectAll"),children:ee.size===t.files.length?x("terminal:fileExplorer.deselectAll"):x("terminal:fileExplorer.selectAll")})]}),e.jsx("textarea",{ref:ge,className:"git-commit-message",placeholder:x("terminal:fileExplorer.commitMessagePlaceholder"),value:S,onChange:k=>A(k.target.value),onKeyDown:k=>{(k.metaKey||k.ctrlKey)&&k.key==="Enter"&&(k.preventDefault(),ve(!1)),(k.metaKey||k.ctrlKey)&&k.shiftKey&&k.key==="Enter"&&(k.preventDefault(),ve(!0)),k.stopPropagation()},rows:3,disabled:F}),re&&e.jsx("div",{className:`git-commit-status ${re.type}`,children:re.text}),e.jsxs("div",{className:"git-commit-actions",children:[e.jsx("button",{className:"git-commit-btn",onClick:()=>ve(!1),disabled:!S.trim()||ee.size===0||F,title:x("terminal:fileExplorer.commitCtrlEnter"),children:x(F?"terminal:fileExplorer.committing":"terminal:fileExplorer.commitAction")}),e.jsx("button",{className:"git-commit-push-btn",onClick:()=>ve(!0),disabled:!S.trim()||ee.size===0||F,title:x("terminal:fileExplorer.commitAndPushCtrlShiftEnter"),children:F?"...":x("terminal:fileExplorer.commitAndPush")})]})]}),Z&&e.jsx(it,{isOpen:Z.isOpen,position:Z.position,worldPosition:{x:0,z:0},actions:E,onClose:()=>L(null)}),T&&e.jsx(it,{isOpen:T.isOpen,position:T.position,worldPosition:{x:0,z:0},actions:xe,onClose:()=>W(null)}),ne&&e.jsx("div",{className:"git-discard-confirm-overlay",onClick:()=>be(null),children:e.jsxs("div",{className:"git-discard-confirm",onClick:k=>k.stopPropagation(),children:[e.jsx("p",{children:ne.files.some(k=>k.status==="untracked"||k.status==="added")?e.jsxs(e.Fragment,{children:["Delete ",e.jsx("strong",{children:ne.label}),"?"]}):e.jsxs(e.Fragment,{children:["Discard changes to ",e.jsx("strong",{children:ne.label}),"?"]})}),e.jsx("p",{className:"git-discard-confirm-hint",children:"This cannot be undone."}),e.jsxs("div",{className:"git-discard-confirm-actions",children:[e.jsx("button",{className:"git-discard-confirm-cancel",onClick:()=>be(null),children:"Cancel"}),e.jsx("button",{className:"git-discard-confirm-btn",onClick:m,children:ne.files.some(k=>k.status==="untracked"||k.status==="added")?"Delete":"Discard"})]})]})})]})}const Ys=s.memo(Oa,(t,n)=>t.loading!==n.loading||t.selectedPath!==n.selectedPath||t.stagingPaths!==n.stagingPaths||t.currentFolder!==n.currentFolder||t.mergeInProgress!==n.mergeInProgress||t.mergingBranch!==n.mergingBranch?!1:t.gitStatus===null&&n.gitStatus===null?!0:!(t.gitStatus===null||n.gitStatus===null||t.gitStatus.isGitRepo!==n.gitStatus.isGitRepo||t.gitStatus.branch!==n.gitStatus.branch||t.gitStatus.files.length!==n.gitStatus.files.length||t.gitStatus.mergeInProgress!==n.gitStatus.mergeInProgress));Ys.displayName="GitChanges";const Ga=s.memo(function({tab:n,isActive:o,onSelect:c,onClose:r,onContextMenu:i}){const{t:f}=le(["terminal"]),l={name:n.filename,path:n.path,isDirectory:!1,extension:n.extension},u=s.useCallback(()=>{c(n.path)},[c,n.path]),g=s.useCallback(y=>{y.button===1&&(y.preventDefault(),y.stopPropagation(),r(n.path))},[r,n.path]),j=s.useCallback(y=>{y.preventDefault(),y.stopPropagation(),r(n.path)},[r,n.path]),p=s.useCallback(y=>{y.preventDefault(),y.stopPropagation(),i(y,n)},[i,n]);return e.jsxs("div",{className:`file-tab ${o?"active":""}`,onClick:u,onMouseDown:g,onContextMenu:p,title:n.path,children:[e.jsx("img",{className:"file-tab-icon",src:Xt(l),alt:"file"}),e.jsx("span",{className:"file-tab-name",children:n.filename}),e.jsx("button",{className:"file-tab-close",onClick:j,title:f("terminal:fileExplorer.closeMiddleClick"),children:"×"})]})});function Ua(t){return typeof t.path=="string"&&t.path.startsWith("/")}function Ba({tabs:t,activeTabPath:n,onSelectTab:o,onCloseTab:c,onCloseAllTabs:r,onShowGitHistory:i}){const{t:f}=le(["terminal"]),[l,u]=s.useState(null),g=s.useCallback((y,C)=>{u({isOpen:!0,position:{x:y.clientX,y:y.clientY},tab:C})},[]),j=s.useCallback(()=>u(null),[]),p=s.useMemo(()=>{if(!l)return[];const y=l.tab,C=!!i&&Ua(y),R=[{id:"git-history",label:f("terminal:fileExplorer.showGitHistory")??"Show Git History",icon:e.jsx(M,{name:"git-commit",size:14}),disabled:!C,onClick:()=>{C&&i(y.path)}}];return r&&R.push({id:"divider-close-all",label:"",divider:!0,onClick:()=>{}},{id:"close-all-tabs",label:f("terminal:fileExplorer.closeAllTabs")??"Close all tabs",icon:e.jsx(M,{name:"cross",size:14}),danger:!0,onClick:()=>r()}),R},[l,i,r,f]);return t.length===0?null:e.jsxs("div",{className:"file-tabs-bar",children:[e.jsx("div",{className:"file-tabs-container",children:t.map(y=>e.jsx(Ga,{tab:y,isActive:n===y.path,onSelect:o,onClose:c,onContextMenu:g},y.path))}),l&&e.jsx(it,{isOpen:l.isOpen,position:l.position,worldPosition:{x:0,z:0},actions:p,onClose:j})]})}const qs=s.memo(Ba,(t,n)=>{if(t.activeTabPath!==n.activeTabPath||t.tabs.length!==n.tabs.length||t.onShowGitHistory!==n.onShowGitHistory||t.onCloseAllTabs!==n.onCloseAllTabs)return!1;for(let o=0;o<t.tabs.length;o++)if(t.tabs[o].path!==n.tabs[o].path)return!1;return!0});qs.displayName="FileTabs";const _a=s.memo(function({currentFolder:n,gitStatus:o,onBranchChanged:c,onMerge:r,onCompare:i,onPullConflicts:f}){const{t:l}=le(["terminal","common"]),[u,g]=s.useState(!1),[j,p]=s.useState(""),[y,C]=s.useState(!1),[R,x]=s.useState(""),[N,d]=s.useState(!1),[v,w]=s.useState(null),[S,A]=s.useState(null),H=s.useRef(null),G=s.useRef(null),z=s.useRef(null),{branches:ae,loading:ee,operationInProgress:D,loadBranches:F,checkoutBranch:I,createBranch:re,pullFromRemote:_,pushToRemote:ge}=Qt();s.useEffect(()=>{u&&n&&(F(n),setTimeout(()=>{var E;return(E=G.current)==null?void 0:E.focus()},50)),u||(p(""),C(!1),x(""),w(null))},[u,n,F]),s.useEffect(()=>{if(v){const E=v.type==="error"?8e3:3e3,Q=setTimeout(()=>w(null),E);return()=>clearTimeout(Q)}},[v]),s.useEffect(()=>{y&&setTimeout(()=>{var E;return(E=z.current)==null?void 0:E.focus()},50)},[y]),s.useEffect(()=>{if(!u)return;const E=te=>{const Ne=te.target;!Ne.closest(".branch-widget-selector")&&!Ne.closest(".branch-widget-dropdown")&&g(!1)},Q=te=>{te.key==="Escape"&&(te.preventDefault(),te.stopPropagation(),g(!1))};return document.addEventListener("click",E),document.addEventListener("keydown",Q,!0),()=>{document.removeEventListener("click",E),document.removeEventListener("keydown",Q,!0)}},[u]);const O=s.useCallback(async E=>{if(!n||D||E.isCurrent)return;const Q=await I(n,E.name);Q.success?(w({type:"success",text:l("terminal:fileExplorer.switchedToBranch",{branch:Q.branch||E.name})}),c(),F(n)):w({type:"error",text:Q.error||l("terminal:fileExplorer.checkoutFailed")})},[n,D,I,c,F]),Z=s.useCallback(async()=>{if(!n||!R.trim()||D)return;const E=await re(n,R.trim());E.success?(w({type:"success",text:l("terminal:fileExplorer.createdBranch",{branch:E.branch})}),C(!1),x(""),c(),F(n)):w({type:"error",text:E.error||l("terminal:fileExplorer.createBranchFailed")})},[n,R,D,re,c,F]),L=s.useCallback(async()=>{if(!n||D)return;const E=await _(n);E.success?(E.stashConflicts&&E.stashConflicts.length>0?(w({type:"error",text:`Pull succeeded but stash pop had conflicts: ${E.stashConflicts.length} file(s). Resolve manually.`}),f==null||f(E.stashConflicts),g(!1)):E.stashed?w({type:"success",text:"Pull complete. Local changes were auto-stashed and restored."}):w({type:"success",text:l("terminal:fileExplorer.pullComplete")}),c(),F(n)):E.conflicts&&E.conflicts.length>0?(w({type:"error",text:`Pull conflicts: ${E.conflicts.length} file(s)`}),f==null||f(E.conflicts),g(!1)):w({type:"error",text:E.error||l("terminal:fileExplorer.pullFailed")})},[n,D,_,c,F,f]),T=s.useCallback(async()=>{if(!n||D)return;const E=await ge(n);E.success?w({type:"success",text:l("terminal:fileExplorer.pushComplete")}):w({type:"error",text:E.error||l("terminal:fileExplorer.pushFailed")})},[n,D,ge]),[W,ne]=s.useState(!1),be=s.useCallback(async()=>{if(!(!n||D||W)){ne(!0);try{const E=await Y(K("/api/files/git-fetch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})});if(E.ok)w({type:"success",text:"Fetch complete"}),c(),F(n);else{const Q=await E.json().catch(()=>({error:"Fetch failed"}));w({type:"error",text:Q.error||"Fetch failed"})}}catch{w({type:"error",text:"Fetch failed"})}finally{ne(!1)}}},[n,D,W,c,F]),de=(o==null?void 0:o.branch)||"unknown",m=!!D,q=s.useCallback((E,Q)=>{Q.isCurrent||(E.preventDefault(),E.stopPropagation(),A({isOpen:!0,position:{x:E.clientX,y:E.clientY},branch:Q.name}))},[]),ie=s.useMemo(()=>{if(!S)return[];const E=!!D||(o==null?void 0:o.mergeInProgress);return[{id:"compare",label:l("terminal:fileExplorer.showDiffWith",{branch:S.branch}),icon:e.jsx(M,{name:"arrows-horizontal",size:14}),disabled:!!D,onClick:()=>{i==null||i(S.branch),g(!1)}},{id:"merge",label:l("terminal:fileExplorer.mergeInto",{source:S.branch,target:de}),icon:"⤵",disabled:!!E,onClick:()=>{r&&r(S.branch),g(!1)}},{id:"divider-1",label:"",divider:!0,onClick:()=>{}},{id:"checkout",label:l("terminal:fileExplorer.checkoutBranch",{branch:S.branch}),icon:e.jsx(M,{name:"git-branch",size:14}),disabled:!!D,onClick:()=>{const Q=ae.find(te=>te.name===S.branch);Q&&O(Q)}}]},[S,D,o==null?void 0:o.mergeInProgress,de,r,i,ae,O]),ue=s.useMemo(()=>{const E=ae.filter(te=>!te.isRemote);if(!j)return E;const Q=j.toLowerCase();return E.filter(te=>te.name.toLowerCase().includes(Q))},[ae,j]),V=s.useMemo(()=>{const E=ae.filter(te=>te.isRemote);if(!j)return E;const Q=j.toLowerCase();return E.filter(te=>te.name.toLowerCase().includes(Q))},[ae,j]);return e.jsxs("div",{className:"branch-widget",style:{position:"relative"},children:[e.jsxs("div",{className:"branch-widget-selector",onClick:E=>{E.stopPropagation(),g(!u)},title:`Branch: ${de}`,children:[e.jsx("svg",{className:"branch-widget-icon",width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M5 3.25a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Zm0 2.122a2.25 2.25 0 1 0-1 0v1.836A2.25 2.25 0 0 0 5.75 9.5h1.378a2.251 2.251 0 1 0 0-1H5.75a1.25 1.25 0 0 1-1.25-1.25V5.372Zm7.75 4.878a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3-8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"})}),e.jsx("span",{className:"branch-widget-name",children:de}),e.jsx("span",{className:"branch-widget-arrow",children:"▼"})]}),u&&e.jsxs("div",{className:"branch-widget-dropdown",ref:H,children:[e.jsx("div",{className:"branch-widget-search",children:e.jsx("input",{ref:G,type:"text",className:"branch-widget-search-input",placeholder:l("terminal:fileExplorer.searchBranches"),value:j,onChange:E=>p(E.target.value),onKeyDown:E=>E.stopPropagation()})}),v&&e.jsx("div",{className:`branch-widget-status ${v.type}`,children:v.text}),e.jsx("div",{className:"branch-widget-section-header",children:l("terminal:fileExplorer.actions")}),e.jsxs("div",{className:"branch-widget-actions",children:[e.jsxs("div",{className:`branch-widget-action-item ${m||W?"disabled":""}`,onClick:be,children:[e.jsx("span",{className:"branch-widget-action-icon",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M8 13l-3-3h2V6h2v4h2l-3 3zM8 3l3 3h-2v4H7V6H5l3-3z"})})}),e.jsx("span",{className:"branch-widget-action-label",children:W?"Fetching...":"Fetch"})]}),e.jsxs("div",{className:`branch-widget-action-item ${m?"disabled":""}`,onClick:L,children:[e.jsx("span",{className:"branch-widget-action-icon",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M8 12l-4-4h2.5V3h3v5H12L8 12z"})})}),e.jsx("span",{className:"branch-widget-action-label",children:l(D==="pull"?"terminal:fileExplorer.pulling":"terminal:fileExplorer.pull")})]}),e.jsxs("div",{className:`branch-widget-action-item ${m?"disabled":""}`,onClick:T,children:[e.jsx("span",{className:"branch-widget-action-icon",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M8 4l4 4h-2.5v5h-3V8H4l4-4z"})})}),e.jsx("span",{className:"branch-widget-action-label",children:l(D==="push"?"terminal:fileExplorer.pushing":"terminal:fileExplorer.push")})]}),e.jsxs("div",{className:`branch-widget-action-item ${m?"disabled":""}`,onClick:()=>{m||C(!y)},children:[e.jsx("span",{className:"branch-widget-action-icon",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:e.jsx("path",{d:"M8 2v5H3v2h5v5h2V9h5V7H10V2H8z"})})}),e.jsx("span",{className:"branch-widget-action-label",children:l("terminal:fileExplorer.newBranch")})]})]}),y&&e.jsxs("div",{className:"branch-widget-new-branch",children:[e.jsx("input",{ref:z,type:"text",className:"branch-widget-new-branch-input",placeholder:l("terminal:fileExplorer.branchNamePlaceholder"),value:R,onChange:E=>x(E.target.value),onKeyDown:E=>{E.stopPropagation(),E.key==="Enter"&&Z(),E.key==="Escape"&&(C(!1),x(""))}}),e.jsx("button",{className:"branch-widget-new-branch-confirm",onClick:Z,disabled:!R.trim()||m,children:D==="create"?"...":l("common:buttons.create")})]}),e.jsxs("div",{className:"branch-widget-section-header",children:[l("terminal:fileExplorer.localBranches"),ee&&e.jsxs("span",{className:"branch-widget-loading-hint",children:[" ",l("terminal:fileExplorer.loading")]})]}),e.jsxs("div",{className:"branch-widget-branch-list",children:[ue.length===0&&!ee&&e.jsx("div",{className:"branch-widget-empty",children:l("terminal:fileExplorer.noBranchesFound")}),ue.map(E=>e.jsxs("div",{className:`branch-widget-branch-item ${E.isCurrent?"current":""} ${m?"disabled":""}`,onClick:()=>O(E),onContextMenu:Q=>q(Q,E),title:E.lastMessage||E.name,children:[e.jsxs("span",{className:"branch-widget-branch-name",children:[E.isCurrent&&e.jsx("span",{className:"branch-widget-current-marker",children:"*"}),E.name]}),E.lastCommit&&e.jsx("span",{className:"branch-widget-branch-commit",children:E.lastCommit})]},E.name))]}),V.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"branch-widget-section-header clickable",onClick:()=>d(!N),children:[e.jsx("span",{className:"branch-widget-section-toggle",children:N?"▾":"▸"}),l("terminal:fileExplorer.remoteBranches",{count:V.length})]}),N&&e.jsx("div",{className:"branch-widget-branch-list",children:V.map(E=>e.jsxs("div",{className:`branch-widget-branch-item remote ${m?"disabled":""}`,onClick:()=>O(E),onContextMenu:Q=>q(Q,E),title:E.lastMessage||E.name,children:[e.jsx("span",{className:"branch-widget-branch-name",children:E.name}),E.lastCommit&&e.jsx("span",{className:"branch-widget-branch-commit",children:E.lastCommit})]},E.name))})]})]}),S&&e.jsx(it,{isOpen:S.isOpen,position:S.position,worldPosition:{x:0,z:0},actions:ie,onClose:()=>A(null)})]})});function Va(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function St(t,n){if(!t)return"";const o=Es.languages[n];return o?Es.highlight(t,o,n):Va(t)}function Ka(t){const n=[],o=t.split(`
9
+ `);let c=[],r=!1,i=[],f=[],l=!1;for(const u of o)u.startsWith("<<<<<<<")?(c.length>0&&(n.push({type:"unchanged",content:c.join(`
10
+ `)}),c=[]),r=!0,l=!1,i=[],f=[]):u.startsWith("=======")&&r?l=!0:u.startsWith(">>>>>>>")&&r?(n.push({type:"conflict",ours:i.join(`
11
+ `),theirs:f.join(`
12
+ `),resolved:null}),r=!1,l=!1):r?l?f.push(u):i.push(u):c.push(u);return c.length>0&&n.push({type:"unchanged",content:c.join(`
13
+ `)}),n}const Wa=s.memo(function({file:n,versions:o,loading:c,onResolve:r,onClose:i,currentBranch:f,mergingBranch:l}){const{t:u}=le(["terminal"]),g=s.useMemo(()=>{var F;if(!(o!=null&&o.filename))return"plaintext";const D="."+((F=o.filename.split(".").pop())==null?void 0:F.toLowerCase());return Ft(D)},[o==null?void 0:o.filename]),j=s.useMemo(()=>o!=null&&o.merged?Ka(o.merged):[],[o==null?void 0:o.merged]),[p,y]=s.useState(j),[C,R]=s.useState(!1);s.useMemo(()=>{y(j)},[j]);const x=s.useRef(null),[N,d]=s.useState(0),v=s.useMemo(()=>p.map((D,F)=>D.type==="conflict"?F:-1).filter(D=>D!==-1),[p]),w=v.length,S=s.useCallback(D=>{const F=x.current;if(!F||D<0||D>=v.length)return;const I=v[D],re=F.querySelector(`[data-section-idx="${I}"]`);re&&(re.scrollIntoView({behavior:"smooth",block:"center"}),d(D))},[v]),A=s.useCallback(()=>{S(N>0?N-1:v.length-1)},[N,v.length,S]),H=s.useCallback(()=>{S(N<v.length-1?N+1:0)},[N,v.length,S]);s.useEffect(()=>{if(v.length>0&&x.current){const D=setTimeout(()=>S(0),100);return()=>clearTimeout(D)}},[v.length,S]);const G=s.useMemo(()=>{const D=p.filter(F=>F.type==="conflict");return D.length>0&&D.every(F=>F.resolved!==null)},[p]),z=s.useCallback((D,F)=>{y(I=>I.map((re,_)=>_!==D||re.type!=="conflict"?re:{...re,resolved:F}))},[]),ae=s.useCallback(D=>{y(F=>F.map(I=>I.type!=="conflict"?I:{...I,resolved:D}))},[]),ee=s.useCallback(async()=>{R(!0);try{const D=p.map(F=>F.type==="unchanged"?F.content:F.resolved==="ours"?F.ours:F.resolved==="theirs"?F.theirs:F.resolved==="both"?F.ours+`
14
+ `+F.theirs:`<<<<<<< ${f}
15
+ ${F.ours}
16
+ =======
17
+ ${F.theirs}
18
+ >>>>>>> ${l}`).join(`
19
+ `);await r(D)}finally{R(!1)}},[p,r,f,l]);return e.jsxs("div",{className:"conflict-resolver",children:[e.jsxs("div",{className:"conflict-header",children:[e.jsx("span",{className:"conflict-header-title",children:u("terminal:fileExplorer.resolveFile",{filename:o==null?void 0:o.filename})}),w>0&&e.jsxs("div",{className:"conflict-nav",children:[e.jsx("button",{className:"conflict-nav-btn",onClick:A,title:u("terminal:fileExplorer.prevConflict"),children:e.jsx(M,{name:"caret-up",size:10})}),e.jsxs("span",{className:"conflict-nav-counter",children:[N+1," / ",w]}),e.jsx("button",{className:"conflict-nav-btn",onClick:H,title:u("terminal:fileExplorer.nextConflict"),children:e.jsx(M,{name:"caret-down",size:10})})]}),e.jsx("button",{className:"conflict-close-btn",onClick:i,children:"×"})]}),c||!o?e.jsx("div",{className:"conflict-loading",children:u("terminal:fileExplorer.loadingConflictData")}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"conflict-pane-headers",children:[e.jsx("div",{className:"conflict-pane-header current",children:u("terminal:fileExplorer.currentBranchLabel",{branch:f})}),e.jsx("div",{className:"conflict-pane-header incoming",children:u("terminal:fileExplorer.incomingBranchLabel",{branch:l})})]}),e.jsx("div",{className:"conflict-content",ref:x,children:p.map((D,F)=>D.type==="unchanged"?e.jsx("div",{className:"conflict-section-unchanged",children:e.jsxs("div",{className:"conflict-panes",children:[e.jsx("div",{className:"conflict-pane ours",children:e.jsx("pre",{dangerouslySetInnerHTML:{__html:St(D.content,g)}})}),e.jsx("div",{className:"conflict-pane theirs",children:e.jsx("pre",{dangerouslySetInnerHTML:{__html:St(D.content,g)}})})]})},F):e.jsxs("div",{"data-section-idx":F,className:`conflict-section-conflict ${D.resolved?"resolved":""}`,children:[e.jsxs("div",{className:"conflict-panes",children:[e.jsxs("div",{className:`conflict-pane ours ${D.resolved==="ours"||D.resolved==="both"?"accepted":""}`,children:[e.jsx("pre",{dangerouslySetInnerHTML:{__html:St(D.ours,g)}}),e.jsx("button",{className:"conflict-accept-btn ours",onClick:()=>z(F,"ours"),disabled:D.resolved==="ours",children:D.resolved==="ours"?u("terminal:fileExplorer.accepted"):u("terminal:fileExplorer.acceptCurrent")})]}),e.jsxs("div",{className:`conflict-pane theirs ${D.resolved==="theirs"||D.resolved==="both"?"accepted":""}`,children:[e.jsx("pre",{dangerouslySetInnerHTML:{__html:St(D.theirs,g)}}),e.jsx("button",{className:"conflict-accept-btn theirs",onClick:()=>z(F,"theirs"),disabled:D.resolved==="theirs",children:D.resolved==="theirs"?u("terminal:fileExplorer.accepted"):u("terminal:fileExplorer.acceptIncoming")})]})]}),e.jsx("button",{className:`conflict-accept-both-btn ${D.resolved==="both"?"accepted":""}`,onClick:()=>z(F,"both"),disabled:D.resolved==="both",children:D.resolved==="both"?u("terminal:fileExplorer.accepted"):u("terminal:fileExplorer.acceptBoth")})]},F))}),e.jsxs("div",{className:"conflict-actions",children:[e.jsx("button",{className:"conflict-action-btn accept-all-current",onClick:()=>ae("ours"),children:u("terminal:fileExplorer.acceptAllCurrent")}),e.jsx("button",{className:"conflict-action-btn accept-all-incoming",onClick:()=>ae("theirs"),children:u("terminal:fileExplorer.acceptAllIncoming")}),e.jsx("button",{className:"conflict-action-btn accept-all-both",onClick:()=>ae("both"),children:u("terminal:fileExplorer.acceptAllBoth")}),e.jsx("button",{className:"conflict-action-btn save-resolved",onClick:ee,disabled:!G||C,children:u(C?"terminal:fileExplorer.saving":"terminal:fileExplorer.saveAndResolve")})]})]})]})}),Ya=16,qa=s.memo(function t({node:n,depth:o,expandedDirs:c,onToggleDir:r,selectedPath:i,onSelect:f}){const{t:l}=le(["terminal"]),u=o*Ya;if(!n.isDirectory){const j=n.file.status,p=pt[j],y=j==="deleted",C=n.file.name.includes(".")?"."+n.file.name.split(".").pop():"";return e.jsxs("div",{className:`git-file-item ${i===n.path?"selected":""}`,onClick:()=>!y&&f(n.file.path,j),style:{paddingLeft:`${u+4}px`,cursor:y?"not-allowed":"pointer"},title:n.file.path,children:[e.jsx("span",{className:"tree-arrow-spacer"}),e.jsx("img",{className:"tree-icon",src:ft(C),alt:"file"}),e.jsx("span",{className:"git-file-name",children:n.file.name}),e.jsx("span",{className:"git-file-status",style:{color:p.color},children:p.icon}),n.file.oldPath&&e.jsxs("span",{className:"git-file-renamed",children:["← ",n.file.oldPath.split("/").pop()]})]})}const g=c.has(n.path);return e.jsxs("div",{className:"tree-node-wrapper",children:[e.jsxs("div",{className:`tree-node directory ${g?"expanded":""}`,style:{paddingLeft:`${u+4}px`},onClick:()=>r(n.path),children:[e.jsx("span",{className:`tree-arrow ${g?"expanded":""}`,children:"►"}),e.jsx("img",{className:"tree-folder-icon",src:g?"/assets/vscode-icons/default_folder_opened.svg":"/assets/vscode-icons/default_folder.svg",alt:"folder"}),e.jsx("span",{className:"tree-name",children:n.name}),e.jsx("span",{className:"git-tree-file-count",children:l("terminal:fileExplorer.fileCount",{count:n.fileCount})})]}),g&&e.jsx("div",{className:"tree-children",children:n.children.map(j=>e.jsx(t,{node:j,depth:o+1,expandedDirs:c,onToggleDir:r,selectedPath:i,onSelect:f},j.path))})]})}),Ja=s.memo(function({file:n,isSelected:o,onSelect:c}){const r=pt[n.status],i=n.status==="deleted",f=n.name.includes(".")?"."+n.name.split(".").pop():"",l=n.path.includes("/")?n.path.slice(0,n.path.lastIndexOf("/")):"";return e.jsxs("div",{className:`git-file-item ${o?"selected":""}`,onClick:()=>!i&&c(n.path,n.status),style:{cursor:i?"not-allowed":"pointer"},title:n.path,children:[e.jsx("span",{className:"tree-arrow-spacer"}),e.jsx("img",{className:"tree-icon",src:ft(f),alt:"file"}),e.jsxs("span",{className:"git-file-name",children:[n.name,l&&e.jsx("span",{className:"git-file-dir",children:l})]}),e.jsx("span",{className:"git-file-status",style:{color:r.color},children:r.icon}),n.oldPath&&e.jsxs("span",{className:"git-file-renamed",children:["← ",n.oldPath.split("/").pop()]})]})});function Xa({compareResult:t,loading:n,onFileSelect:o,selectedPath:c,onClose:r}){const{t:i}=le(["terminal"]),[f,l]=s.useState("tree"),[u,g]=s.useState(new Set),j=s.useMemo(()=>!t||t.files.length===0?[]:Mt(t.files),[t]),p=s.useMemo(()=>{const w=new Set;return Dt(j,w),w},[j]);s.useEffect(()=>{g(p)},[p]);const y=s.useCallback(w=>{g(S=>{const A=new Set(S);return A.has(w)?A.delete(w):A.add(w),A})},[]),C=s.useMemo(()=>t?[...t.files].sort((w,S)=>w.path.toLowerCase().localeCompare(S.path.toLowerCase())):[],[t]);if(n)return e.jsxs("div",{className:"branch-comparison",children:[e.jsxs("div",{className:"branch-comparison-header",children:[e.jsx("span",{className:"branch-comparison-title",children:i("terminal:fileExplorer.comparingBranches")}),e.jsx("button",{className:"branch-comparison-close",onClick:r,title:i("terminal:fileExplorer.closeComparison"),children:"×"})]}),e.jsx("div",{className:"branch-comparison-empty",children:e.jsx("div",{className:"branch-comparison-empty-text",children:i("terminal:fileExplorer.comparingBranches")})})]});if(!t)return null;const{files:R,counts:x,baseBranch:N,currentBranch:d}=t,v=R.length;return v===0?e.jsxs("div",{className:"branch-comparison",children:[e.jsxs("div",{className:"branch-comparison-header",children:[e.jsxs("span",{className:"branch-comparison-title",children:[d," vs ",N]}),e.jsx("button",{className:"branch-comparison-close",onClick:r,title:i("terminal:fileExplorer.closeComparison"),children:"×"})]}),e.jsxs("div",{className:"branch-comparison-empty",children:[e.jsx("div",{className:"branch-comparison-empty-icon",children:"✨"}),e.jsx("div",{className:"branch-comparison-empty-text",children:i("terminal:fileExplorer.noDifferences")})]})]}):e.jsxs("div",{className:"branch-comparison",children:[e.jsxs("div",{className:"branch-comparison-header",children:[e.jsxs("span",{className:"branch-comparison-title",children:["⇔ ",d," vs ",N]}),e.jsx("span",{className:"branch-comparison-file-count",children:i("terminal:fileExplorer.fileCount",{count:v})}),e.jsxs("div",{className:"git-changes-summary",children:[x.modified>0&&e.jsxs("span",{className:"git-count modified",children:[x.modified,"M"]}),x.added>0&&e.jsxs("span",{className:"git-count added",children:[x.added,"A"]}),x.deleted>0&&e.jsxs("span",{className:"git-count deleted",children:[x.deleted,"D"]}),x.renamed>0&&e.jsxs("span",{className:"git-count renamed",children:[x.renamed,"R"]}),(x.conflict??0)>0&&e.jsxs("span",{className:"git-count conflict",children:[x.conflict,"C"]})]}),e.jsxs("div",{className:"git-view-toggle",children:[e.jsx("button",{className:`git-view-toggle-btn ${f==="flat"?"active":""}`,onClick:()=>l("flat"),title:i("terminal:fileExplorer.flatList"),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:[e.jsx("rect",{x:"2",y:"3",width:"12",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"2",y:"7",width:"12",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"2",y:"11",width:"12",height:"1.5",rx:"0.5"})]})}),e.jsx("button",{className:`git-view-toggle-btn ${f==="tree"?"active":""}`,onClick:()=>l("tree"),title:i("terminal:fileExplorer.directoryTree"),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor",children:[e.jsx("rect",{x:"1",y:"2",width:"6",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"4",y:"5.5",width:"8",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"4",y:"9",width:"8",height:"1.5",rx:"0.5"}),e.jsx("rect",{x:"7",y:"12.5",width:"7",height:"1.5",rx:"0.5"})]})})]}),e.jsx("button",{className:"branch-comparison-close",onClick:r,title:i("terminal:fileExplorer.closeComparison"),children:"×"})]}),e.jsx("div",{className:"branch-comparison-list",children:f==="tree"?j.map(w=>e.jsx(qa,{node:w,depth:0,expandedDirs:u,onToggleDir:y,selectedPath:c,onSelect:o},w.path)):C.map(w=>e.jsx(Ja,{file:w,isSelected:c===w.path,onSelect:o},w.path))})]})}const Js=s.memo(Xa);Js.displayName="BranchComparison";function Qa(t){const n=new Date(t);if(isNaN(n.getTime()))return t||"—";const c=Date.now()-n.getTime(),r=Math.floor(c/6e4),i=Math.floor(r/60),f=Math.floor(i/24);if(f<4)return r<1?"just now":r<60?`${r}m ago`:i<24?`${i}h ago`:`${f}d ago`;const l=n.getFullYear(),u=String(n.getMonth()+1).padStart(2,"0"),g=String(n.getDate()).padStart(2,"0"),j=String(n.getHours()).padStart(2,"0"),p=String(n.getMinutes()).padStart(2,"0");return`${l}-${u}-${g} ${j}:${p}`}const Za=s.memo(function({commit:n,isSelected:o,onSelect:c}){return e.jsxs("div",{className:`gh-row ${o?"selected":""}`,onClick:()=>c(n),children:[e.jsx("span",{className:"gh-col-hash",children:n.shortHash}),e.jsxs("span",{className:"gh-col-message",children:[e.jsx("span",{className:"gh-subject",children:n.subject}),n.refs.isHead&&e.jsx("span",{className:"gh-badge gh-badge-head",children:"HEAD"}),n.refs.branches.map(r=>e.jsx("span",{className:"gh-badge gh-badge-branch",children:r},r)),n.refs.tags.map(r=>e.jsx("span",{className:"gh-badge gh-badge-tag",children:r},r))]}),e.jsx("span",{className:"gh-col-author",children:n.author}),e.jsx("span",{className:"gh-col-date",children:Qa(n.date)})]})}),er=s.memo(function({files:n,loading:o,selectedFilePath:c,onSelectFile:r}){const{t:i}=le(["common"]);return o?e.jsx("div",{className:"gh-files-loading",children:i("common:status.loading")}):n.length===0?e.jsx("div",{className:"gh-files-empty",children:"No changed files"}):e.jsx("div",{className:"gh-files-list",children:n.map(f=>{const l=f.path.split("/").pop()||f.path,u=f.path.includes("/")?f.path.substring(0,f.path.lastIndexOf("/")):"",g=pt[f.status],j=l.includes(".")?"."+l.split(".").pop():"";return e.jsxs("div",{className:`gh-file-row ${c===f.path?"selected":""}`,onClick:()=>r==null?void 0:r(f.path),title:f.path,children:[e.jsx("span",{className:"gh-file-status",style:{color:g.color},children:g.icon}),e.jsx("img",{className:"gh-file-icon",src:ft(j),alt:""}),e.jsx("span",{className:"gh-file-name",children:l}),u&&e.jsx("span",{className:"gh-file-dir",children:u})]},f.path)})})}),tr=s.memo(function({history:n,currentFolder:o,onFileSelect:c}){const{t:r}=le(["terminal","common"]),i=s.useRef(null),[f,l]=s.useState(null),[u,g]=s.useState(!1),{commits:j,loading:p,loadingMore:y,error:C,hasMore:R,total:x,filters:N,setFilter:d,resetFilters:v,selectedCommit:w,selectCommit:S,commitFiles:A,commitFilesLoading:H,loadHistory:G,loadMore:z,authors:ae,loadAuthors:ee}=n,{branches:D,loadBranches:F}=Qt();s.useEffect(()=>{o&&(G(o),ee(o),F(o))},[o,G,ee,F]);const I=zn({count:j.length,getScrollElement:()=>i.current,estimateSize:()=>28,overscan:20}),re=s.useCallback(()=>{const L=i.current;if(!L||y||!R||!o)return;const{scrollTop:T,scrollHeight:W,clientHeight:ne}=L;W-T-ne<200&&z(o)},[y,R,o,z]),_=s.useCallback(L=>{l(L),c&&w&&c(L,w.hash)},[c,w]),ge=s.useMemo(()=>D.filter(L=>!L.isRemote).map(L=>L.name),[D]),O=!!(N.branch||N.author||N.since||N.until||N.searchPath||N.search),Z=I.getVirtualItems();return e.jsxs("div",{className:"gh-panel",children:[e.jsxs("div",{className:"gh-toolbar",children:[e.jsx("span",{className:"gh-toolbar-title",children:r("terminal:fileExplorer.gitHistory.title")}),e.jsx("span",{className:"gh-toolbar-count",children:p?"...":x>0?x:j.length}),e.jsx("input",{type:"text",className:"gh-search-input",placeholder:r("terminal:fileExplorer.gitHistory.searchPlaceholder"),value:N.search,onChange:L=>d("search",L.target.value)}),e.jsx("button",{className:`gh-filter-toggle ${u?"active":""} ${O?"has-filters":""}`,onClick:()=>g(!u),title:"Filters",children:e.jsx(M,{name:"gear",size:12})}),O&&e.jsx("button",{className:"gh-reset-btn",onClick:v,children:r("terminal:fileExplorer.gitHistory.resetFilters")})]}),u&&e.jsxs("div",{className:"gh-filters-row",children:[e.jsxs("select",{className:"gh-filter-select",value:N.branch,onChange:L=>d("branch",L.target.value),children:[e.jsx("option",{value:"",children:r("terminal:fileExplorer.gitHistory.allBranches")}),ge.map(L=>e.jsx("option",{value:L,children:L},L))]}),e.jsxs("select",{className:"gh-filter-select",value:N.author,onChange:L=>d("author",L.target.value),children:[e.jsx("option",{value:"",children:r("terminal:fileExplorer.gitHistory.allAuthors")}),ae.map(L=>e.jsx("option",{value:L,children:L},L))]}),e.jsx("input",{type:"date",className:"gh-filter-input gh-date-input",value:N.since,onChange:L=>d("since",L.target.value),title:r("terminal:fileExplorer.gitHistory.since")}),e.jsx("input",{type:"date",className:"gh-filter-input gh-date-input",value:N.until,onChange:L=>d("until",L.target.value),title:r("terminal:fileExplorer.gitHistory.until")}),e.jsx("input",{type:"text",className:"gh-filter-input",placeholder:r("terminal:fileExplorer.gitHistory.pathFilter"),value:N.searchPath,onChange:L=>d("searchPath",L.target.value)})]}),e.jsxs("div",{className:"gh-body",children:[e.jsxs("div",{className:"gh-commits-section",children:[e.jsxs("div",{className:"gh-header-row",children:[e.jsx("span",{className:"gh-col-hash",children:"Hash"}),e.jsx("span",{className:"gh-col-message",children:"Message"}),e.jsx("span",{className:"gh-col-author",children:"Author"}),e.jsx("span",{className:"gh-col-date",children:"Date"})]}),p&&j.length===0?e.jsx("div",{className:"gh-state-msg",children:r("common:status.loading")}):C?e.jsx("div",{className:"gh-state-msg gh-error",children:C}):j.length===0?e.jsx("div",{className:"gh-state-msg",children:r("terminal:fileExplorer.gitHistory.noCommits")}):e.jsxs("div",{className:"gh-commit-scroll",ref:i,onScroll:re,children:[e.jsx("div",{style:{height:`${I.getTotalSize()}px`,width:"100%",position:"relative"},children:Z.map(L=>e.jsx("div",{"data-index":L.index,ref:I.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${L.start}px)`},children:e.jsx(Za,{commit:j[L.index],isSelected:(w==null?void 0:w.hash)===j[L.index].hash,onSelect:S})},L.key))}),y&&e.jsx("div",{className:"gh-loading-more",children:r("common:status.loading")})]})]}),w&&e.jsxs("div",{className:"gh-files-section",children:[e.jsxs("div",{className:"gh-files-header",children:[e.jsxs("span",{className:"gh-files-title",children:[A.length," ",A.length===1?"file":"files"]}),e.jsx("span",{className:"gh-files-commit-info",children:w.shortHash})]}),e.jsx(er,{files:A,loading:H,selectedFilePath:f,onSelectFile:_})]})]})]})});async function sr({path:t,cwd:n,limit:o}){const c=new URLSearchParams({path:t,cwd:n});Number.isFinite(o)&&c.set("limit",String(o));const r=await Y(K(`/api/files/git-file-history?${c.toString()}`));if(!r.ok){const f=await r.json().catch(()=>({}));throw new Error(f.error||`Failed to load file git history: ${r.statusText}`)}const i=await r.json();return{commits:Array.isArray(i.commits)?i.commits:[]}}async function nr({path:t,cwd:n,sha:o}){const c=new URLSearchParams({path:t,cwd:n,sha:o}),r=await Y(K(`/api/files/git-file-commit-diff?${c.toString()}`));if(!r.ok){const f=await r.json().catch(()=>({}));throw new Error(f.error||`Failed to load commit diff: ${r.statusText}`)}const i=await r.json();return i.binary===!0?{binary:!0,filename:i.filename??"",changeType:i.changeType??"modified"}:{binary:!1,filename:i.filename??"",language:i.language??"plaintext",changeType:i.changeType??"modified",originalContent:typeof i.originalContent=="string"?i.originalContent:"",modifiedContent:typeof i.modifiedContent=="string"?i.modifiedContent:""}}const ar=100;function rr(t){if(!t)return"";const n=Date.parse(t);if(Number.isNaN(n))return t;const o=Date.now()-n,c=Math.round(o/1e3);if(c<60)return`${c}s ago`;const r=Math.round(c/60);if(r<60)return`${r}m ago`;const i=Math.round(r/60);if(i<24)return`${i}h ago`;const f=Math.round(i/24);if(f<30)return`${f}d ago`;const l=Math.round(f/30);return l<12?`${l}mo ago`:`${Math.round(l/12)}y ago`}function ir(t){if(!t)return"";const n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function lr({isOpen:t,onClose:n,filePath:o,cwd:c}){const{t:r}=le(["terminal","common"]),[i,f]=s.useState([]),[l,u]=s.useState(!1),[g,j]=s.useState(null),[p,y]=s.useState(null),[C,R]=s.useState(null),[x,N]=s.useState(!1),[d,v]=s.useState(null);s.useEffect(()=>{if(!t)return;let H=!1;return f([]),y(null),R(null),v(null),j(null),u(!0),(async()=>{try{const G=await sr({path:o,cwd:c,limit:ar});if(H)return;f(G.commits),G.commits.length>0&&y(G.commits[0].sha)}catch(G){if(H)return;j(G instanceof Error?G.message:r("terminal:fileGitHistory.error"))}finally{H||u(!1)}})(),()=>{H=!0}},[t,o,c,r]),s.useEffect(()=>{if(!t||!p){R(null);return}let H=!1;return N(!0),v(null),R(null),(async()=>{try{const G=await nr({path:o,cwd:c,sha:p});if(H)return;R(G)}catch(G){if(H)return;v(G instanceof Error?G.message:r("terminal:fileGitHistory.error"))}finally{H||N(!1)}})(),()=>{H=!0}},[t,p,o,c,r]);const w=s.useCallback(H=>{H.key==="Escape"&&(H.preventDefault(),n())},[n]),S=s.useMemo(()=>ir(o),[o]),A=()=>x?e.jsxs("div",{className:"git-file-history-loading",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:r("terminal:fileGitHistory.loading")})]}):d?e.jsxs("div",{className:"git-file-history-empty",children:[e.jsx(M,{name:"warn",size:20}),e.jsx("p",{children:d})]}):C?C.binary?e.jsxs("div",{className:"git-file-history-empty",children:[e.jsx(M,{name:"file",size:20}),e.jsx("p",{children:r("terminal:fileGitHistory.binaryFile")})]}):e.jsx(Jt,{originalContent:C.originalContent,modifiedContent:C.modifiedContent,filename:C.filename||S,filePath:o,language:C.language}):e.jsx("div",{className:"git-file-history-empty",children:e.jsx("p",{children:r("terminal:fileGitHistory.selectCommit")})});return t?e.jsx(An,{children:e.jsx("div",{className:"modal-overlay visible",onClick:n,children:e.jsxs("div",{className:"git-file-history-modal",onClick:H=>H.stopPropagation(),onKeyDown:w,tabIndex:-1,children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{className:"git-file-history-title",children:[e.jsx("h2",{children:r("terminal:fileGitHistory.title")}),e.jsx("span",{className:"git-file-history-filepath",title:o,children:S})]}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:e.jsx(M,{name:"close",size:16})})]}),e.jsxs("div",{className:"git-file-history-body",children:[e.jsx("aside",{className:"git-file-history-commit-list","aria-label":r("terminal:fileGitHistory.title"),children:l?e.jsxs("div",{className:"git-file-history-loading",children:[e.jsx("div",{className:"spinner"}),e.jsx("p",{children:r("terminal:fileGitHistory.loading")})]}):g?e.jsxs("div",{className:"git-file-history-empty",children:[e.jsx(M,{name:"warn",size:18}),e.jsx("p",{children:g})]}):i.length===0?e.jsx("div",{className:"git-file-history-empty",children:e.jsx("p",{children:r("terminal:fileGitHistory.empty")})}):e.jsx("ul",{className:"git-file-history-commits",role:"listbox",children:i.map(H=>{const G=H.sha===p;return e.jsxs("li",{className:`git-file-history-commit ${G?"selected":""}`,role:"option","aria-selected":G,onClick:()=>y(H.sha),children:[e.jsxs("div",{className:"git-file-history-commit-row",children:[e.jsx("span",{className:"git-file-history-sha",children:H.shortSha}),e.jsx("span",{className:"git-file-history-date",title:H.date,children:rr(H.date)})]}),e.jsx("div",{className:"git-file-history-subject",title:H.subject,children:H.subject}),e.jsx("div",{className:"git-file-history-author",title:H.email,children:H.author})]},H.sha)})})}),e.jsx("section",{className:"git-file-history-diff","aria-live":"polite",children:A()})]})]})})}):null}function ur({isOpen:t,areaId:n,onClose:o,onChangeArea:c,folderPath:r}){const{t:i}=le(["terminal","common"]),f=zs(),l=!!r&&!n,u=!l&&n?f.areas.get(n):null,g=l?[r]:(u==null?void 0:u.directories)||[],j=Array.from(f.areas.values()),[p,y]=s.useState(0),[C,R]=s.useState(null),[x,N]=s.useState(!1),d=g[p]||g[0]||null,v=(d==null?void 0:d.split("/").pop())||d||"";s.useEffect(()=>{y(0)},[r,l]),s.useEffect(()=>{!l&&r&&R(r)},[l,r]),s.useEffect(()=>{if(t)try{l&&r?localStorage.setItem("file-explorer-last-opened",JSON.stringify({type:"folder",path:r})):n&&localStorage.setItem("file-explorer-last-opened",JSON.stringify({type:"area",areaId:n}))}catch{}},[t,l,r,n]);const w=s.useMemo(()=>{const a=[];for(const h of j)for(const b of h.directories)a.push({path:b,areaId:h.id,areaName:h.name,areaColor:h.color});return a},[j]),{tree:S,loading:A,expandedPaths:H,loadTree:G,reloadDirectory:z,renamePathInTree:ae,togglePath:ee,expandToPath:D,setExpandedPaths:F}=On(d),{gitStatus:I,loading:re,loadGitStatus:_}=_n(d),{mergeBranch:ge,mergeAbort:O,mergeContinue:Z}=Qt(),L=ca(),{showToast:T}=Us(),{file:W,loading:ne,error:be,loadFile:de,clearFile:m,setFile:q}=Xn(),{treePanelWidth:ie,handleResizeStart:ue,isResizing:V}=sa(),{mobileTreeHeight:E,handleResizeMouseDown:Q,handleResizeTouchStart:te}=ia(),{loadStoredState:Ne,saveState:xe}=ta({areaId:n||null,folderPath:r||null,isOpen:t}),[U,se]=s.useState(null),[pe,me]=s.useState("files"),[Be,Se]=s.useState(""),[It,He]=s.useState([]),[Pt,_e]=s.useState([]),[Lt,Ve]=s.useState(!1),[gt,je]=s.useState(null),[$t,ve]=s.useState(null),[xt,Ke]=s.useState(!1),[De,k]=s.useState(!1),[P,B]=s.useState(!1),[ke,Te]=s.useState(new Set),[ot]=s.useState(!1),[We,Re]=s.useState(!1),[Ht,Xs]=s.useState(250),ct=s.useRef(null),[$e,yt]=s.useState(null),[Qs,ts]=s.useState(!1),[Ye,ss]=s.useState(null),[qe,ns]=s.useState(null),[Je,Zs]=s.useState(null),[zt,At]=s.useState({open:!1,path:"",cwd:""}),[he,ze]=s.useState({isOpen:!1,node:null,value:"",submitting:!1}),[ye,Xe]=s.useState({isOpen:!1,parentDir:"",isDirectory:!1,value:"",submitting:!1}),[Ee,as]=s.useState(null),[Fe,Ae]=s.useState([]),[oe,Ie]=s.useState(null),dt=s.useRef([]),Qe=s.useRef(-1),Ot=s.useRef(!1),[en,tn]=s.useState(!1),[sn,nn]=s.useState(!1),[,Gt]=s.useState(void 0),[rs,Ze]=s.useState(null),[ut,ht]=s.useState(null),[an,et]=s.useState(null),[rn,is]=s.useState(!1),[bt,Ut]=s.useState(null),[ls,Bt]=s.useState(!1),[jt,vt]=s.useState(null),os=s.useRef(null),_t=s.useRef(null),cs=s.useRef(null),wt=s.useRef(null);s.useEffect(()=>{if(!t||De)return;(async()=>{const h=await Ne();if(h){let b=h.selectedFolderIndex;if(C){const $=g.indexOf(C);b=$>=0?$:0,R(null)}else{const $=Math.max(0,g.length-1);b=Math.min(Math.max(0,b),$)}Ae(h.tabs),Ie(h.activeTabPath),me(h.viewMode),y(b),F(h.expandedPaths),wt.current=h.expandedPaths,Ke(!0),h.activeTabPath&&(se(h.activeTabPath),de(h.activeTabPath))}k(!0)})()},[t,De,Ne,F,de,C,g]),s.useEffect(()=>{wt.current&&!A&&S.length>0&&(F(wt.current),wt.current=null)},[A,S,F]),s.useEffect(()=>{if(!t||!De)return;const a=setTimeout(()=>{xe({tabs:Fe,activeTabPath:oe,viewMode:pe,selectedFolderIndex:p,expandedPaths:H})},500);return()=>clearTimeout(a)},[t,De,Fe,oe,pe,p,H,xe]),s.useEffect(()=>{k(!1)},[n,r]),s.useEffect(()=>{if(!he.isOpen)return;const a=window.setTimeout(()=>{var h,b;(h=_t.current)==null||h.focus(),(b=_t.current)==null||b.select()},0);return()=>window.clearTimeout(a)},[he.isOpen]),s.useEffect(()=>{if(!ye.isOpen)return;const a=window.setTimeout(()=>{var h;(h=cs.current)==null||h.focus()},0);return()=>window.clearTimeout(a)},[ye.isOpen]);const Pe=s.useMemo(()=>{const a=Be.trim(),h=a.match(/^(.+):(\d+)$/);return h?{query:h[1],lineNumber:parseInt(h[2],10)}:{query:a,lineNumber:void 0}},[Be]);s.useEffect(()=>{if(!Pe.query||!d){He([]),_e([]),Ve(!1);return}Ve(!0);const a=setTimeout(async()=>{try{const h=Pe.query,b=Y(K(`/api/files/search?path=${encodeURIComponent(d)}&q=${encodeURIComponent(h)}&limit=200`)).then(fe=>fe.json()).catch(()=>({results:[]})),$=h.length>=2&&!Pe.lineNumber?Y(K(`/api/files/search-content?path=${encodeURIComponent(d)}&q=${encodeURIComponent(h)}&limit=200`)).then(fe=>fe.json()).catch(()=>({results:[]})):Promise.resolve({results:[]}),[J,X]=await Promise.all([b,$]);He(J.results||[]),_e(X.results||[])}catch(h){console.error("[FileExplorer] Search failed:",h),He([]),_e([])}Ve(!1)},300);return()=>clearTimeout(a)},[Pe.query,Pe.lineNumber,d]),s.useEffect(()=>{t&&d&&(m(),se(null),je(null),ve(null),Ke(!1),G(),_())},[t,d,G,_,m]),s.useEffect(()=>{if(f.fileViewerPath&&t){const a=f.fileViewerPath;if(f.fileViewerRevealInTree){const h=a.split("/").pop()||a,b=a.substring(a.lastIndexOf(".")).toLowerCase();Ct(a,h,b),kt(a)}else de(a),se(a);mt.clearFileViewerPath()}},[f.fileViewerPath,f.fileViewerRevealInTree,t,de]),s.useEffect(()=>{De&&!xt&&I&&Ke(!0)},[I,xt,De,pe]),s.useEffect(()=>{if(n&&(m(),se(null),Se(""),_e([]),He([]),je(null),ve(null),Ke(!1),k(!1),C)){const a=f.areas.get(n);a!=null&&a.directories.includes(C)||R(null)}},[n,C,f.areas,m]),s.useEffect(()=>{const a=b=>{var J;if(!t)return;if(b.altKey&&b.key==="e"){b.preventDefault(),b.stopPropagation(),o();return}if(b.key==="Escape"){if(he.isOpen){b.preventDefault(),b.stopPropagation(),he.submitting||ze({isOpen:!1,node:null,value:"",submitting:!1});return}if(ot)return;if(x){b.preventDefault(),b.stopPropagation(),N(!1);return}b.preventDefault(),b.stopPropagation(),o();return}(b.metaKey||b.ctrlKey)&&b.key==="p"&&(b.preventDefault(),(J=os.current)==null||J.focus());const $=mt.getShortcuts().find(X=>X.id==="file-explorer-close-tab");if(Bn(b,$)){if(b.repeat)return;b.preventDefault(),b.stopPropagation(),oe&&fs(oe)}},h=b=>{const $=b.target;x&&!$.closest(".file-explorer-folder-selector")&&!$.closest(".file-explorer-folder-dropdown")&&N(!1)};return document.addEventListener("keydown",a,!0),document.addEventListener("click",h),()=>{document.removeEventListener("keydown",a,!0),document.removeEventListener("click",h)}},[t,o,x,oe,ot,he]);const ds=s.useMemo(()=>{const a=new Map;if(I!=null&&I.files)for(const h of I.files)a.set(h.path,h.status);return a},[I==null?void 0:I.files]),Vt=s.useMemo(()=>{const a=new Map;if(!(I!=null&&I.files))return a;const h={conflict:0,modified:1,added:2,deleted:3,untracked:4,renamed:5};for(const b of I.files){let $=b.path;for(;;){const J=$.lastIndexOf("/");if(J<=0)break;$=$.substring(0,J);const X=a.get($);X?h[b.status]<h[X]&&a.set($,b.status):a.set($,b.status)}}return a},[I==null?void 0:I.files]),us=s.useMemo(()=>{const a=h=>({...h,gitStatus:h.isDirectory?Vt.get(h.path):ds.get(h.path),hasGitChanges:h.isDirectory&&Vt.has(h.path)||void 0,children:h.children?h.children.map(a):void 0});return S.map(a)},[S,ds,Vt]),Ct=(a,h,b,$)=>{if(!Fe.find(X=>X.path===a)){const X={path:a,filename:h,extension:b};Ae(fe=>[...fe,X])}Ie(a),se(a),Gt($),de(a)},hs=async a=>{if(a.isDirectory){me("files"),Se(""),await D(a.path),se(a.path),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let h=a.path,b=document.querySelector(`[data-path="${h}"]`);for(;!b&&h.includes("/");)h=h.substring(0,h.lastIndexOf("/")),b=document.querySelector(`[data-path="${h}"]`);b instanceof HTMLElement&&b.scrollIntoView({behavior:"smooth",block:"center"})})});return}ve(null),je(null),Ct(a.path,a.name,a.extension,Pe.lineNumber)},ln=(a,h)=>{ve(null),je(null);const b=a.split("/").pop()||a,$=a.substring(a.lastIndexOf(".")).toLowerCase();Ct(a,b,$,h)},on=async(a,h)=>{ve(h),je(null);const b=a.split("/").pop()||a,$=a.substring(a.lastIndexOf(".")).toLowerCase();if(Ct(a,b,$),h==="modified"){const{content:J}=await Vn(a);J!==null&&je(J)}},Oe=s.useCallback(()=>{const a=dt.current,h=Qe.current;tn(h>0),nn(h>=0&&h<a.length-1)},[]);s.useEffect(()=>{if(!oe){dt.current=[],Qe.current=-1,Oe();return}if(Ot.current){Ot.current=!1,Oe();return}const a=dt.current,h=Qe.current;if(h>=0&&a[h]===oe){Oe();return}const b=h<a.length-1?a.slice(0,h+1):a.slice();b.push(oe),b.length>100&&b.shift(),dt.current=b,Qe.current=b.length-1,Oe()},[oe,Oe]);const ms=a=>{Ie(a),se(a),ve(null),je(null),Gt(void 0);const h=Fe.find(b=>b.path===a);h!=null&&h.data||de(a)},Nt=s.useCallback(a=>{const h=dt.current;if(h.length===0)return;let b=Qe.current+a;for(;b>=0&&b<h.length;){const $=h[b];if(Fe.some(J=>J.path===$)){Ot.current=!0,Qe.current=b,Oe(),ms($);return}b+=a}},[Fe,Oe]),cn=s.useCallback(()=>Nt(-1),[Nt]),dn=s.useCallback(()=>Nt(1),[Nt]),fs=a=>{Ae(h=>{var J;const b=h.filter(X=>X.path!==a),$=h.findIndex(X=>X.path===a);if($!==-1&&((J=h[$])==null?void 0:J.path)===a&&(oe===a||h.find(X=>X.path===oe)),b.length>0){if(!b.some(fe=>fe.path===oe)){const fe=h.findIndex(Ce=>Ce.path===a),ce=Math.max(0,Math.min(fe,b.length-1)),we=b[ce];we&&(Ie(we.path),se(we.path),de(we.path))}}else Ie(null),se(null),m();return b})},un=s.useCallback(()=>{Ae([]),Ie(null),se(null),m()},[m]),hn=a=>{if(N(!1),a.areaId!==n)R(a.path),c&&c(a.areaId);else{const h=g.indexOf(a.path);y(h>=0?h:0)}},Le=s.useCallback(a=>{const h=a.lastIndexOf("/");return h<=0?"/":a.slice(0,h)},[]),tt=s.useCallback((a,h,b)=>a===h?b:a.startsWith(`${h}/`)?`${b}${a.slice(h.length)}`:a,[]),mn=s.useCallback((a,h)=>{se(h.path),ss({isOpen:!0,position:{x:a.clientX,y:a.clientY},node:h})},[]),fn=s.useCallback(a=>{a.defaultPrevented||d&&(a.preventDefault(),ns({isOpen:!0,position:{x:a.clientX,y:a.clientY},parentDir:d}))},[d]),ps=s.useCallback(a=>{ze({isOpen:!0,node:a,value:a.name,submitting:!1})},[]),st=s.useCallback(()=>{ze({isOpen:!1,node:null,value:"",submitting:!1})},[]),nt=s.useCallback((a,h)=>{a&&Xe({isOpen:!0,parentDir:a,isDirectory:h,value:"",submitting:!1})},[]),at=s.useCallback(()=>{Xe({isOpen:!1,parentDir:"",isDirectory:!1,value:"",submitting:!1})},[]),gs=s.useCallback(a=>{as({node:a})},[]),pn=s.useCallback(async()=>{const a=Ee==null?void 0:Ee.node;if(a)try{const h=await Y(K("/api/files/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:a.path,recursive:a.isDirectory})}),b=await h.json().catch(()=>({}));if(!h.ok){T("error","Delete Failed",b.error||"Unable to delete item");return}Ae(J=>J.filter(X=>X.path!==a.path&&!X.path.startsWith(`${a.path}/`))),(oe===a.path||oe!=null&&oe.startsWith(`${a.path}/`))&&(Ie(null),m()),(U===a.path||U!=null&&U.startsWith(`${a.path}/`))&&se(null);const $=Le(a.path);await z($),await _(),T("success",a.isDirectory?"Folder Deleted":"File Deleted",a.name)}catch(h){console.error("[FileExplorer] Delete failed:",h),T("error","Delete Failed","Unable to delete item")}},[Ee,oe,U,Le,z,_,T,m]),xs=s.useCallback(async()=>{const{parentDir:a,isDirectory:h,value:b}=ye,$=b.trim();if(!a||!$){at();return}if($.includes("/")||$.includes("\\")){T("error","Invalid Name","Name must not contain path separators");return}Xe(J=>({...J,submitting:!0}));try{const J=await Y(K("/api/files/create"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parentDir:a,name:$,isDirectory:h})}),X=await J.json();if(!J.ok){T("error","Create Failed",X.error||"Unable to create item"),Xe(we=>({...we,submitting:!1}));return}const fe=X.path,ce=new Set(H);ce.add(a),await z(a),F(ce),await _(),se(fe),T("success",h?"Folder Created":"File Created",$),at()}catch(J){console.error("[FileExplorer] Create failed:",J),T("error","Create Failed","Unable to create item"),Xe(X=>({...X,submitting:!1}))}},[ye,H,z,F,_,T,at]),ys=s.useCallback(async()=>{const a=he.node;if(!a)return;const h=he.value.trim();if(!h||h===a.name){st();return}ze(b=>({...b,submitting:!0}));try{const b=await Y(K("/api/files/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:a.path,newName:h})}),$=await b.json();if(!b.ok){T("error","Rename Failed",$.error||"Unable to rename item"),ze(Ce=>({...Ce,submitting:!1}));return}const J=$.newPath,X=a.path,fe=new Set(Array.from(H).map(Ce=>tt(Ce,X,J))),ce=Le(X),we=Le(J);if(Ae(Ce=>Ce.map(Me=>{if(!Me.path.startsWith(X))return Me;const rt=tt(Me.path,X,J),Et=rt.split("/").pop()||rt,ks=Et.includes(".")?`.${Et.split(".").pop()}`:"";return{...Me,path:rt,filename:Et,extension:ks.toLowerCase(),data:Me.data?{...Me.data,path:rt,filename:Et,extension:ks.toLowerCase()}:Me.data}})),oe&&Ie(tt(oe,X,J)),U&&se(tt(U,X,J)),W!=null&&W.path){const Ce=tt(W.path,X,J);if(Ce!==W.path){const Me=Ce.split("/").pop()||Ce,rt=Me.includes(".")?`.${Me.split(".").pop()}`:"";q({...W,path:Ce,filename:Me,extension:rt.toLowerCase()})}}ae(X,J),F(fe),await z(ce),we!==ce&&await z(we),await _(),T("success","Renamed",`${a.name} renamed`),st()}catch(b){console.error("[FileExplorer] Rename failed:",b),T("error","Rename Failed","Unable to rename item"),ze($=>({...$,submitting:!1}))}},[he,st,oe,U,W,H,tt,Le,ae,F,z,_,T,q]),bs=s.useCallback(a=>{Zs({sourcePath:a.path,isDirectory:a.isDirectory,name:a.name}),T("info","Copied",`${a.name} ready to paste`)},[T]),js=s.useCallback(async a=>{if(!Je)return;const h=a.isDirectory?a.path:Le(a.path),b=new Set(H);b.add(h);try{const $=await Y(K("/api/files/paste"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourcePath:Je.sourcePath,targetDir:h})}),J=await $.json();if(!$.ok){T("error","Paste Failed",J.error||"Unable to paste item");return}await z(h),F(b),await _(),J.destinationPath&&se(J.destinationPath),T("success","Pasted",`${Je.name} pasted`)}catch($){console.error("[FileExplorer] Paste failed:",$),T("error","Paste Failed","Unable to paste item")}},[Je,Le,H,z,F,_,T]),vs=s.useCallback(async a=>{try{await navigator.clipboard.writeText(a.path),T("success","Copied","Full path copied")}catch(h){console.error("[FileExplorer] Copy path failed:",h),T("error","Copy Failed","Could not copy path")}},[T]),ws=s.useCallback(a=>{a.isDirectory||!d||At({open:!0,path:a.path,cwd:d})},[d]),gn=s.useCallback(a=>{!d||!a||At({open:!0,path:a,cwd:d})},[d]),xn=s.useMemo(()=>{if(!Ye)return[];const a=Ye.node,h=a.isDirectory?a.path:Le(a.path),b=[{id:"create-file",label:a.isDirectory?"New File...":"New File Here...",icon:e.jsx(M,{name:"file-text",size:14}),onClick:()=>nt(h,!1)},{id:"create-folder",label:a.isDirectory?"New Folder...":"New Folder Here...",icon:e.jsx(M,{name:"folder",size:14}),onClick:()=>nt(h,!0)},{id:"divider-create",label:"",divider:!0,onClick:()=>{}},{id:"rename",label:a.isDirectory?"Rename Folder":"Rename File",icon:e.jsx(M,{name:"edit",size:14}),onClick:()=>ps(a)},{id:"copy",label:a.isDirectory?"Copy Folder":"Copy File",icon:e.jsx(M,{name:"file-text",size:14}),onClick:()=>bs(a)},{id:"paste",label:a.isDirectory?"Paste Into Folder":"Paste Here",icon:e.jsx(M,{name:"clipboard",size:14}),disabled:!Je,onClick:()=>{js(a)}},{id:"divider-1",label:"",divider:!0,onClick:()=>{}},{id:"copy-full-path",label:"Copy Full Path",icon:e.jsx(M,{name:"pin",size:14}),onClick:()=>{vs(a)}}];return a.isDirectory||b.push({id:"divider-git-history",label:"",divider:!0,onClick:()=>{}},{id:"git-history",label:i("terminal:fileExplorer.showGitHistory")??"Show Git History",icon:e.jsx(M,{name:"git-commit",size:14}),onClick:()=>ws(a)}),b.push({id:"divider-delete",label:"",divider:!0,onClick:()=>{}},{id:"delete",label:a.isDirectory?"Delete Folder":"Delete File",icon:e.jsx(M,{name:"trash",size:14}),danger:!0,onClick:()=>gs(a)}),b},[Ye,Je,Le,nt,ps,bs,js,vs,ws,gs,i]),yn=s.useMemo(()=>{if(!qe)return[];const a=qe.parentDir;return[{id:"create-file-root",label:"New File...",icon:e.jsx(M,{name:"file-text",size:14}),onClick:()=>nt(a,!1)},{id:"create-folder-root",label:"New Folder...",icon:e.jsx(M,{name:"folder",size:14}),onClick:()=>nt(a,!0)}]},[qe,nt]),kt=s.useCallback(async a=>{me("files"),Se(""),await D(a),se(a),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let h=a,b=document.querySelector(`[data-path="${h}"]`);for(;!b&&h.includes("/");)h=h.substring(0,h.lastIndexOf("/")),b=document.querySelector(`[data-path="${h}"]`);b instanceof HTMLElement&&b.scrollIntoView({behavior:"smooth",block:"center"})})})},[D]),bn=s.useCallback(async a=>{if(!(!d||a.length===0)){Te(h=>{const b=new Set(h);for(const $ of a)b.add($);return b});try{const h=await Y(K("/api/files/git-add"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:a,directory:d})});if(h.ok)await _();else{const b=await h.json();console.error("[FileExplorer] Git add failed:",b.error)}}catch(h){console.error("[FileExplorer] Git add failed:",h)}finally{Te(h=>{const b=new Set(h);for(const $ of a)b.delete($);return b})}}},[d,_]),jn=s.useCallback(async a=>{if(!d)return;Ze(a);const h=await ge(d,a);if(await _(),h.success)Ze(null),T("success","Merge Complete",`Merged '${a}' successfully`),G();else if(h.conflicts&&h.conflicts.length>0){const b=h.conflicts.length;T("warning","Merge Conflicts",`${b} conflict${b>1?"s":""} found — resolve to continue`),me("git")}else Ze(null),T("error","Merge Failed",h.error||"Merge failed")},[d,ge,_,G,T]),vn=s.useCallback(async a=>{Ze("remote"),await _();const h=a.length;T("warning","Pull Conflicts",`${h} conflict${h>1?"s":""} found — resolve to continue`),me("git")},[_,T]),wn=s.useCallback(async a=>{if(d){ht(a),is(!0),et(null);try{const h=await Y(K(`/api/files/git-conflict-file?path=${encodeURIComponent(d)}&file=${encodeURIComponent(a)}`)),b=await h.json();h.ok?et(b):console.error("[FileExplorer] Failed to load conflict file:",b.error)}catch(h){console.error("[FileExplorer] Failed to load conflict file:",h)}finally{is(!1)}}},[d]),Cn=s.useCallback(async a=>{if(!(!d||!ut))try{const h=await Y(K("/api/files/git-resolve-conflict"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:d,file:ut,content:a})}),b=await h.json();h.ok&&b.success?(ht(null),et(null),await _()):console.error("[FileExplorer] Failed to resolve conflict:",b.error)}catch(h){console.error("[FileExplorer] Failed to resolve conflict:",h)}},[d,ut,_]),Nn=s.useCallback(async()=>{if(!d)return;const a=await Z(d);a.success?(Ze(null),ht(null),et(null),T("success","Merge Complete","Merge completed successfully"),await _(),G()):T("error","Merge Failed",a.error||"Merge continue failed")},[d,Z,_,G,T]),kn=s.useCallback(async()=>{if(!d)return;const a=await O(d);a.success?(Ze(null),ht(null),et(null),T("info","Merge Aborted","Merge has been aborted"),await _(),G()):T("error","Abort Failed",a.error||"Failed to abort merge")},[d,O,_,G,T]),En=s.useCallback(async a=>{if(d){vt(a),Bt(!0),Ut(null),me("compare");try{const h=await Y(K(`/api/files/git-branch-compare?directory=${encodeURIComponent(d)}&branch=${encodeURIComponent(a)}`)),b=await h.json();h.ok?Ut(b):(T("error","Compare Failed",b.error||"Failed to compare branches"),me("files"),vt(null))}catch(h){console.error("[FileExplorer] Branch compare failed:",h),T("error","Compare Failed","Network error during comparison"),me("files"),vt(null)}finally{Bt(!1)}}},[d,T]),Sn=s.useCallback(async(a,h)=>{if(!d||!jt)return;const b=a.split("/").pop()||a,$=a.substring(a.lastIndexOf(".")).toLowerCase();Fe.find(ce=>ce.path===a)||Ae(ce=>[...ce,{path:a,filename:b,extension:$}]),Ie(a),se(a),Gt(void 0);const X=async ce=>{try{const we=await Y(K(`/api/files/git-show?path=${encodeURIComponent(a)}&ref=${encodeURIComponent(ce)}`)),Ce=await we.json();return we.ok?Ce.content??"":""}catch{return""}},fe=ce=>({path:a,filename:b,extension:$,content:ce,fileType:"text",size:ce.length,modified:""});if(h==="modified"||h==="renamed"){const[ce,we]=await Promise.all([X(jt),X("HEAD")]);je(ce),q(fe(we)),ve("modified")}else if(h==="deleted"){const ce=await X(jt);je(ce),q(fe("")),ve("modified")}else if(h==="added"){const ce=await X("HEAD");je(""),q(fe(ce)),ve("modified")}},[d,jt,Fe]),Cs=s.useCallback(()=>{me("files"),Ut(null),vt(null),Bt(!1)},[]),Tn=s.useCallback(async(a,h)=>{if(d){ts(!0);try{const b=new URLSearchParams({path:d,hash:h,file:a}),$=await Y(K(`/api/files/git-commit-file-diff?${b}`)),J=await $.json();$.ok?yt(J):yt(null)}catch(b){console.error("[FileExplorer] commit diff fetch error:",b),yt(null)}finally{ts(!1)}}},[d]),Mn=s.useCallback(()=>{yt(null)},[]),Dn=s.useCallback(a=>{a.preventDefault(),ct.current={startY:a.clientY,startHeight:Ht};const h=$=>{if(!ct.current)return;const J=ct.current.startY-$.clientY,X=Math.max(120,Math.min(600,ct.current.startHeight+J));Xs(X)},b=()=>{ct.current=null,document.removeEventListener("mousemove",h),document.removeEventListener("mouseup",b)};document.addEventListener("mousemove",h),document.addEventListener("mouseup",b)},[Ht]);if(!t||!u&&!l)return null;const Ns=(I==null?void 0:I.files.length)||0;return e.jsxs("div",{className:"file-explorer-panel ide-style",children:[e.jsxs("div",{className:"file-explorer-panel-header",children:[e.jsxs("div",{className:"file-explorer-panel-title",children:[e.jsxs("div",{className:"file-explorer-nav-group",role:"group","aria-label":"Tab history navigation",children:[e.jsx("button",{type:"button",className:"file-explorer-nav-btn",onClick:cn,disabled:!en,title:"Back to previous file","aria-label":"Back to previous file",children:e.jsx(M,{name:"arrow-left",size:14})}),e.jsx("button",{type:"button",className:"file-explorer-nav-btn",onClick:dn,disabled:!sn,title:"Forward to next file","aria-label":"Forward to next file",children:e.jsx(M,{name:"arrow-right",size:14})})]}),d&&e.jsxs("div",{className:"file-explorer-folder-selector",onClick:()=>!l&&w.length>0&&N(!x),style:{cursor:!l&&w.length>0?"pointer":"default"},title:d,children:[e.jsx("span",{className:"file-explorer-panel-dot",style:{background:(u==null?void 0:u.color)||"#ffd700"}}),e.jsx("span",{className:"file-explorer-folder-name",children:v}),e.jsx("span",{className:"file-explorer-folder-path-hint",children:d}),!l&&w.length>1&&e.jsx("span",{className:"file-explorer-folder-dropdown-icon",children:e.jsx(M,{name:"caret-down",size:10})})]}),(I==null?void 0:I.isGitRepo)&&d&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"file-explorer-path-separator",children:"/"}),e.jsx(_a,{currentFolder:d,gitStatus:I,onBranchChanged:()=>{_(),G()},onMerge:jn,onCompare:En,onPullConflicts:vn})]}),W&&e.jsxs("span",{className:"file-explorer-current-file",children:["/ ",W.filename]}),!l&&x&&w.length>0&&e.jsx("div",{className:"file-explorer-folder-dropdown",onWheel:a=>{a.preventDefault(),a.currentTarget.scrollTop+=a.deltaY*.35},children:w.map(a=>e.jsxs("div",{className:`file-explorer-folder-option ${a.path===d?"active":""}`,onClick:h=>{h.stopPropagation(),hn(a)},children:[e.jsxs("span",{className:"file-explorer-folder-option-name",children:[e.jsx("span",{className:"file-explorer-folder-option-dot",style:{background:a.areaColor}}),a.path.split("/").pop()||a.path]}),(a.path.split("/").pop()||a.path)!==a.path&&e.jsx("span",{className:"file-explorer-folder-option-path",children:a.path}),e.jsx("span",{className:"file-explorer-folder-option-area",children:a.areaName})]},`${a.areaId}-${a.path}`))})]}),(I==null?void 0:I.isGitRepo)&&e.jsx("button",{className:`file-explorer-history-toggle ${We?"active":""}`,onClick:()=>Re(!We),title:i("terminal:fileExplorer.gitHistory.title"),children:e.jsx(M,{name:"status-waiting-input",size:14})}),e.jsx("button",{className:"file-explorer-panel-close",onClick:o,children:"×"})]}),e.jsxs("div",{className:"file-explorer-main",style:E>0?{"--fe-mobile-tree-height":`${E}px`}:void 0,children:[e.jsxs("div",{className:`file-explorer-tree-panel ${P?"collapsed":""}`,style:{width:ie},children:[e.jsxs("div",{className:"file-explorer-tabs",children:[e.jsx("button",{className:"file-explorer-tree-toggle",onClick:()=>B(!P),title:i(P?"terminal:fileExplorer.expandTree":"terminal:fileExplorer.collapseTree"),children:e.jsx(M,{name:P?"caret-down":"caret-up",size:12})}),e.jsxs("button",{className:`file-explorer-tab ${pe==="files"?"active":""}`,onClick:()=>me("files"),children:[e.jsx("span",{className:"tab-icon",children:e.jsx(M,{name:"folder",size:14})}),i("terminal:spotlight.files")]}),e.jsxs("button",{className:`file-explorer-tab ${pe==="git"?"active":""}`,onClick:()=>me("git"),children:[e.jsx("span",{className:"tab-icon",children:e.jsx(M,{name:"git-branch",size:14})}),i("terminal:fileExplorer.gitChanges"),Ns>0&&e.jsx("span",{className:"tab-badge",children:Ns})]}),(bt||ls)&&e.jsxs("button",{className:`file-explorer-tab ${pe==="compare"?"active":""}`,onClick:()=>me("compare"),children:[e.jsx("span",{className:"tab-icon",children:e.jsx(M,{name:"arrows-horizontal",size:14})}),i("terminal:fileExplorer.diffView"),bt&&e.jsx("span",{className:"tab-badge",children:bt.files.length}),e.jsx("span",{className:"tab-close-btn",onClick:a=>{a.stopPropagation(),Cs()},children:"×"})]})]}),pe==="files"&&e.jsxs("div",{className:"file-explorer-toolbar",children:[e.jsxs("div",{className:"file-explorer-search",children:[e.jsx("span",{className:"file-explorer-search-icon",children:e.jsx(M,{name:"search",size:14})}),e.jsx("input",{ref:os,type:"text",className:"file-explorer-search-input",placeholder:i("terminal:fileExplorer.searchPlaceholder"),value:Be,onChange:a=>Se(a.target.value)}),Be&&e.jsx("button",{className:"file-explorer-search-clear",onClick:()=>Se(""),children:"×"})]}),e.jsxs("div",{className:"file-explorer-toolbar-buttons",children:[e.jsx("button",{className:"file-explorer-toolbar-btn",onClick:()=>F(new Set),title:i("terminal:fileExplorer.collapseAll"),children:"⊟"}),oe&&e.jsx("button",{className:"file-explorer-toolbar-btn",onClick:()=>kt(oe),title:i("terminal:fileExplorer.revealInTree"),children:e.jsx(M,{name:"target",size:14})})]})]}),e.jsx("div",{className:"file-explorer-tree-content",onContextMenu:pe==="files"?fn:void 0,children:pe==="compare"?e.jsx(Js,{compareResult:bt,loading:ls,onFileSelect:Sn,selectedPath:U,onClose:Cs}):pe==="files"?A?e.jsx("div",{className:"tree-loading",children:i("common:status.loading")}):Pe.query?Lt?e.jsx("div",{className:"tree-loading",children:i("terminal:fileExplorer.searching")}):e.jsx(Ws,{filenameResults:It,contentResults:Pt,onSelectFile:hs,onSelectContent:ln,selectedPath:U,query:Pe.query,lineNumber:Pe.lineNumber}):e.jsx("div",{className:"file-tree",children:us.length===0?e.jsx("div",{className:"tree-empty",children:i("terminal:fileExplorer.noDirectoriesLinked")}):us.map(a=>e.jsx(Gn,{node:a,depth:0,selectedPath:U,expandedPaths:H,onSelect:hs,onToggle:ee,onContextMenu:mn,searchQuery:""},a.path))}):e.jsx(Ys,{gitStatus:I,loading:re,onFileSelect:on,selectedPath:U,onRefresh:_,onStageFiles:bn,stagingPaths:ke,currentFolder:d,onCommitComplete:()=>{_(),G()},mergeInProgress:I==null?void 0:I.mergeInProgress,mergingBranch:rs,onMergeContinue:Nn,onMergeAbort:kn,onConflictOpen:wn,onRevealInTree:kt})})]}),e.jsx("div",{className:`file-explorer-resize-handle ${V?"active":""}`,onMouseDown:ue}),!P&&e.jsx("div",{className:"fe-mobile-resize-handle",onMouseDown:Q,onTouchStart:te}),e.jsx("div",{className:"file-explorer-viewer-panel",children:ut?e.jsx(Wa,{file:ut,versions:an,loading:rn,onResolve:Cn,onClose:()=>{ht(null),et(null)},currentBranch:(I==null?void 0:I.branch)||"HEAD",mergingBranch:rs||"incoming"}):$e?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"commit-diff-header",children:[e.jsx("span",{className:"commit-diff-file",children:$e.filePath}),e.jsx("span",{className:"commit-diff-hash",children:$e.hash.slice(0,8)}),e.jsx("button",{className:"commit-diff-close",onClick:Mn,children:"×"})]}),e.jsx(Jt,{originalContent:$e.beforeContent,modifiedContent:$e.afterContent,filename:$e.filename,filePath:$e.filePath,language:Ss[$e.extension]||"plaintext"})]}):Qs?e.jsx("div",{className:"commit-diff-loading",children:i("common:status.loading")}):e.jsxs(e.Fragment,{children:[e.jsx(qs,{tabs:Fe,activeTabPath:oe,onSelectTab:ms,onCloseTab:fs,onCloseAllTabs:un,onShowGitHistory:gn}),$t==="modified"&&gt!==null&&W?e.jsx(Jt,{originalContent:gt,modifiedContent:W.content,filename:W.filename,filePath:W.path,language:Ss[W.extension]||"plaintext"}):e.jsx(Vs,{file:W,loading:ne,error:be,onRevealInTree:kt,onFileEdited:de})]})})]}),We&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"git-history-resize-handle",onMouseDown:Dn}),e.jsx("div",{className:"git-history-bottom-panel",style:{height:Ht},children:e.jsx(tr,{history:L,currentFolder:d,onFileSelect:Tn})})]}),he.isOpen&&he.node&&e.jsx("div",{className:"file-explorer-rename-overlay",onClick:st,children:e.jsxs("div",{className:"file-explorer-rename-dialog",onClick:a=>a.stopPropagation(),children:[e.jsxs("div",{className:"file-explorer-rename-title",children:["Rename ",he.node.isDirectory?"Folder":"File"]}),e.jsx("div",{className:"file-explorer-rename-path",title:he.node.path,children:he.node.path}),e.jsx("input",{ref:_t,type:"text",className:"file-explorer-rename-input",value:he.value,onChange:a=>ze(h=>({...h,value:a.target.value})),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),ys()):a.key==="Escape"&&(a.preventDefault(),st())},disabled:he.submitting}),e.jsxs("div",{className:"file-explorer-rename-actions",children:[e.jsx("button",{className:"file-explorer-rename-btn",onClick:st,disabled:he.submitting,children:"Cancel"}),e.jsx("button",{className:"file-explorer-rename-btn primary",onClick:()=>{ys()},disabled:he.submitting||!he.value.trim(),children:he.submitting?"Renaming...":"Rename"})]})]})}),Ye&&e.jsx(it,{isOpen:Ye.isOpen,position:Ye.position,worldPosition:{x:0,z:0},actions:xn,onClose:()=>ss(null)}),qe&&e.jsx(it,{isOpen:qe.isOpen,position:qe.position,worldPosition:{x:0,z:0},actions:yn,onClose:()=>ns(null)}),ye.isOpen&&e.jsx("div",{className:"file-explorer-rename-overlay",onClick:at,children:e.jsxs("div",{className:"file-explorer-rename-dialog",onClick:a=>a.stopPropagation(),children:[e.jsxs("div",{className:"file-explorer-rename-title",children:["New ",ye.isDirectory?"Folder":"File"]}),e.jsx("div",{className:"file-explorer-rename-path",title:ye.parentDir,children:ye.parentDir}),e.jsx("input",{ref:cs,type:"text",className:"file-explorer-rename-input",placeholder:ye.isDirectory?"folder name":"file name",value:ye.value,onChange:a=>Xe(h=>({...h,value:a.target.value})),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),xs()):a.key==="Escape"&&(a.preventDefault(),at())},disabled:ye.submitting}),e.jsxs("div",{className:"file-explorer-rename-actions",children:[e.jsx("button",{className:"file-explorer-rename-btn",onClick:at,disabled:ye.submitting,children:"Cancel"}),e.jsx("button",{className:"file-explorer-rename-btn primary",onClick:()=>{xs()},disabled:ye.submitting||!ye.value.trim(),children:ye.submitting?"Creating...":"Create"})]})]})}),e.jsx(lr,{isOpen:zt.open,filePath:zt.path,cwd:zt.cwd,onClose:()=>At(a=>({...a,open:!1}))}),e.jsx(Un,{isOpen:!!Ee,title:Ee!=null&&Ee.node.isDirectory?"Delete Folder":"Delete File",message:Ee?e.jsxs(e.Fragment,{children:["Permanently delete ",e.jsx("strong",{children:Ee.node.name}),"?"]}):"",note:Ee!=null&&Ee.node.isDirectory?"The folder and everything inside it will be removed from disk.":"The file will be removed from disk.",confirmLabel:"Delete",cancelLabel:"Cancel",variant:"danger",onConfirm:()=>{pn()},onClose:()=>as(null)})]})}export{ur as FileExplorerPanel};
@@ -1 +1 @@
1
- import{u as J,a as Z,r,s as h,j as e,D as de,I as H,C as oe,b as me,c as be,d as ue,g as he,e as _e,Q as pe,R as xe}from"./main-CyZg1kKu.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const fe=({building:a,connections:x,activeConnectionId:l,activeDatabase:c,collapsed:y,onToggleCollapse:f,onConnectionChange:Q,onDatabaseChange:S,onInsertTable:L,onSelectTableQuery:P})=>{const{t:m}=J(["terminal"]),q=Z(a.id),[I,R]=r.useState(new Set),[k,n]=r.useState(""),[d,g]=r.useState(""),[$,w]=r.useState(!1),[U,F]=r.useState(null),K=r.useRef(null),C=r.useRef(null),O=r.useRef(null),N=l?q.databases.get(l)??[]:[],G=l&&c?`${l}:${c}`:"",j=G?q.tables.get(G)??[]:[],p=l?q.connectionStatus.get(l):void 0,D=r.useMemo(()=>{if(!k.trim())return N;const t=k.toLowerCase();return N.filter(o=>o.toLowerCase().includes(t))},[N,k]),b=r.useMemo(()=>{if(!d.trim())return j;const t=d.toLowerCase();return j.filter(o=>o.name.toLowerCase().includes(t))},[j,d]);r.useEffect(()=>{const t=o=>{C.current&&!C.current.contains(o.target)&&w(!1)};return $&&document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[$]),r.useEffect(()=>{l&&!p&&h.testDatabaseConnection(a.id,l)},[a.id,l,p]),r.useEffect(()=>{l&&(p!=null&&p.connected)&&N.length===0&&h.listDatabases(a.id,l)},[a.id,l,p==null?void 0:p.connected,N.length]),r.useEffect(()=>{l&&c&&j.length===0&&h.listTables(a.id,l,c)},[a.id,l,c,j.length]),r.useEffect(()=>{F(null),g("")},[l,c]);const _=r.useCallback(t=>{R(o=>{const T=new Set(o);if(T.has(t))T.delete(t);else if(T.add(t),l&&c){const v=`${l}:${c}:${t}`;q.tableSchemas.has(v)||h.getTableSchema(a.id,l,c,t)}return T})},[a.id,l,c,q.tableSchemas]),z=t=>{if(!l||!c)return null;const o=`${l}:${c}:${t}`;return q.tableSchemas.get(o)};return y?e.jsx("div",{className:"database-sidebar database-sidebar--collapsed",children:e.jsx("button",{className:"database-sidebar__toggle",onClick:f,title:m("terminal:database.expandSidebar"),children:"»"})}):e.jsxs("div",{className:"database-sidebar",children:[e.jsxs("div",{className:"database-sidebar__header",children:[e.jsx("span",{children:m("terminal:database.explorer")}),e.jsx("button",{className:"database-sidebar__toggle",onClick:f,title:m("terminal:database.collapseSidebar"),children:"«"})]}),e.jsxs("div",{className:"database-sidebar__section",children:[e.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.connection")}),e.jsx("select",{className:"database-sidebar__select",value:l||"",onChange:t=>Q(t.target.value),children:x.length===0?e.jsx("option",{value:"",children:m("terminal:database.noConnections")}):x.map(t=>{var o;return e.jsxs("option",{value:t.id,children:[((o=de[t.engine])==null?void 0:o.icon)??"🗄️"," ",t.name]},t.id)})}),p&&e.jsx("div",{className:`database-sidebar__status ${p.connected?"database-sidebar__status--connected":"database-sidebar__status--error"}`,children:p.connected?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"database-sidebar__status-icon",children:"✓"}),m("terminal:database.connected"),p.serverVersion&&e.jsxs("span",{className:"database-sidebar__version",children:["(",p.serverVersion,")"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"database-sidebar__status-icon",children:"✗"}),p.error||m("terminal:database.disconnected")]})})]}),N.length>0&&e.jsxs("div",{className:"database-sidebar__section",children:[e.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.databaseTitle")}),e.jsxs("div",{className:"database-sidebar__searchable-select",ref:C,children:[e.jsx("input",{ref:K,className:"database-sidebar__search-input",type:"text",value:$?k:c||"",placeholder:m("terminal:database.selectDatabase"),onChange:t=>{n(t.target.value),$||w(!0)},onFocus:()=>{w(!0),n("")},onKeyDown:t=>{var o,T;t.key==="Escape"?(w(!1),n(""),(o=K.current)==null||o.blur()):t.key==="Enter"&&D.length===1&&(S(D[0]),w(!1),n(""),(T=K.current)==null||T.blur())}}),$&&e.jsx("div",{className:"database-sidebar__dropdown",children:D.length===0?e.jsx("div",{className:"database-sidebar__dropdown-empty",children:"No matches"}):D.map(t=>e.jsx("div",{className:`database-sidebar__dropdown-item ${t===c?"database-sidebar__dropdown-item--active":""}`,onMouseDown:o=>{o.preventDefault(),S(t),w(!1),n("")},children:t},t))})]})]}),j.length>0&&e.jsxs("div",{className:"database-sidebar__section database-sidebar__section--tables",children:[e.jsx("div",{className:"database-sidebar__section-title",children:d.trim()?m("terminal:database.tablesCount",{count:b.length})+` / ${j.length}`:m("terminal:database.tablesCount",{count:j.length})}),e.jsxs("div",{className:"database-sidebar__table-filter",children:[e.jsx("input",{ref:O,className:"database-sidebar__table-filter-input",type:"text",value:d,placeholder:m("terminal:database.filterTables"),onChange:t=>g(t.target.value),onKeyDown:t=>{var o;t.key==="Escape"&&(d?g(""):(o=O.current)==null||o.blur(),t.stopPropagation())}}),d&&e.jsx("button",{className:"database-sidebar__table-filter-clear",onClick:()=>{var t;g(""),(t=O.current)==null||t.focus()},title:"Clear filter",children:"×"})]}),e.jsxs("div",{className:"database-sidebar__tables",children:[d.trim()&&b.length===0&&e.jsx("div",{className:"database-sidebar__tables-empty",children:m("terminal:database.noTablesMatch")}),b.map(t=>{const o=I.has(t.name),T=o?z(t.name):null;return e.jsxs("div",{className:"database-sidebar__table",children:[e.jsxs("div",{className:"database-sidebar__table-header",children:[e.jsx("button",{className:"database-sidebar__table-expand",onClick:()=>_(t.name),title:o?"Collapse table schema":"Expand table schema",children:e.jsx(H,{name:o?"caret-down":"caret-right",size:10})}),e.jsx("span",{className:"database-sidebar__table-icon",children:e.jsx(H,{name:t.type==="view"?"eye":"clipboard",size:12})}),e.jsx("span",{className:`database-sidebar__table-name ${U===t.name?"database-sidebar__table-name--selected":""}`,onClick:()=>F(t.name),onDoubleClick:()=>{F(t.name),P(t.name)},children:t.name}),e.jsx("button",{className:"database-sidebar__table-insert",onClick:v=>{v.stopPropagation(),L(t.name)},title:m("terminal:database.insertTableName"),children:"+"})]}),o&&T&&e.jsx("div",{className:"database-sidebar__table-columns",children:T.columns.map(v=>e.jsxs("div",{className:"database-sidebar__column",onClick:()=>L(v.name),title:`${v.type}${v.nullable?" NULL":" NOT NULL"}${v.primaryKey?" PK":""}`,children:[e.jsx("span",{className:"database-sidebar__column-icon",children:v.primaryKey?e.jsx(H,{name:"key",size:11}):null}),e.jsx("span",{className:"database-sidebar__column-name",children:v.name}),e.jsx("span",{className:"database-sidebar__column-type",children:v.type})]},v.name))})]},t.name)})]})]})]})},je=({buildingId:a,history:x,onLoadQuery:l})=>{const{t:c}=J(["terminal","common"]),[y,f]=r.useState(""),[Q,S]=r.useState(!1),[L,P]=r.useState(!1),m=r.useMemo(()=>{let n=x;if(Q&&(n=n.filter(d=>d.favorite)),y.trim()){const d=y.toLowerCase();n=n.filter(g=>g.query.toLowerCase().includes(d)||g.database.toLowerCase().includes(d))}return n},[x,Q,y]),q=n=>{const d=new Date(n),$=new Date().getTime()-d.getTime();return $<1440*60*1e3?d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):$<10080*60*1e3?d.toLocaleDateString([],{weekday:"short"})+" "+d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):d.toLocaleDateString([],{month:"short",day:"numeric"})},I=r.useCallback((n,d)=>{d.stopPropagation(),h.toggleQueryFavorite(a,n)},[a]),R=r.useCallback((n,d)=>{d.stopPropagation(),h.deleteQueryFromHistory(a,n)},[a]),k=r.useCallback(()=>{P(!0)},[]);return x.length===0?e.jsxs("div",{className:"query-history query-history--empty",children:[e.jsx("p",{children:c("terminal:database.noHistory")}),e.jsx("p",{children:c("terminal:database.queriesAppearHere")})]}):e.jsxs("div",{className:"query-history",children:[e.jsxs("div",{className:"query-history__toolbar",children:[e.jsx("input",{type:"text",className:"query-history__search",placeholder:c("terminal:database.searchQueries"),value:y,onChange:n=>f(n.target.value)}),e.jsxs("label",{className:"query-history__filter",children:[e.jsx("input",{type:"checkbox",checked:Q,onChange:n=>S(n.target.checked)}),c("terminal:database.favoritesOnly")]}),e.jsx("button",{className:"query-history__clear",onClick:k,title:c("terminal:database.clearAll"),children:c("terminal:database.clearAll")})]}),e.jsxs("div",{className:"query-history__list",children:[m.map(n=>e.jsxs("div",{className:`query-history__item ${n.status==="error"?"query-history__item--error":""}`,onClick:()=>l(n.query),children:[e.jsxs("div",{className:"query-history__item-header",children:[e.jsx("span",{className:`query-history__status ${n.status==="success"?"query-history__status--success":"query-history__status--error"}`,children:e.jsx(H,{name:n.status==="success"?"check":"cross",size:12})}),e.jsx("span",{className:"query-history__database",children:n.database}),e.jsx("span",{className:"query-history__date",children:q(n.executedAt)}),e.jsxs("span",{className:"query-history__duration",children:[n.duration,"ms"]}),n.rowCount!==void 0&&e.jsx("span",{className:"query-history__row-count",children:c("terminal:database.rowCount",{count:n.rowCount})})]}),e.jsx("div",{className:"query-history__query",children:e.jsx("code",{children:n.query.length>200?n.query.substring(0,200)+"...":n.query})}),n.error&&e.jsx("div",{className:"query-history__error",children:n.error}),e.jsxs("div",{className:"query-history__actions",children:[e.jsx("button",{className:`query-history__favorite ${n.favorite?"query-history__favorite--active":""}`,onClick:d=>I(n.id,d),title:n.favorite?c("terminal:database.removeFromFavorites"):c("terminal:database.addToFavorites"),children:e.jsx(H,{name:"star",size:12,weight:n.favorite?"fill":"regular",color:n.favorite?"#facc15":void 0})}),e.jsx("button",{className:"query-history__delete",onClick:d=>R(n.id,d),title:c("terminal:database.deleteFromHistory"),children:e.jsx(H,{name:"trash",size:12})})]})]},n.id)),m.length===0&&e.jsx("div",{className:"query-history__no-results",children:c("terminal:database.noQueriesMatch")})]}),e.jsx(oe,{isOpen:L,title:c("terminal:database.clearAll"),message:c("terminal:database.confirmClearHistory"),confirmLabel:c("terminal:database.clearAll"),cancelLabel:c("common:buttons.cancel"),variant:"danger",onConfirm:()=>h.clearQueryHistory(a),onClose:()=>P(!1)})]})},ye=({tabs:a,activeTabId:x,onTabClick:l,onTabClose:c})=>{const{t:y}=J(["terminal"]);return e.jsx("div",{className:"database-tabs",children:a.map(f=>e.jsxs("div",{className:`database-tabs__tab ${x===f.id?"database-tabs__tab--active":""}`,children:[e.jsxs("button",{className:"database-tabs__tab-label",onClick:()=>l(f),title:`${f.connectionName} / ${f.database}`,children:[f.database,e.jsx("span",{className:"database-tabs__tab-connection",children:f.connectionName})]}),e.jsx("button",{className:"database-tabs__tab-close",onClick:()=>c(f.id),title:y("terminal:database.closeTab"),"aria-label":`Close ${f.database} tab`,children:"×"})]},f.id))})},ee=a=>`db-panel-${a}`;function Ne(a){try{const x=localStorage.getItem(ee(a));return x?JSON.parse(x):{}}catch{return{}}}function ve(a,x){try{localStorage.setItem(ee(a),JSON.stringify(x))}catch{}}const ge=({building:a,onClose:x})=>{var B,W,Y,X;const{t:l}=J(["terminal","common"]),c=Z(a.id),y=me(a.id),f=be(a.id),Q=ue(a.id),S=r.useRef(Ne(a.id)),L=r.useRef(null),P=r.useRef(0),m=((B=a.database)==null?void 0:B.connections)??[],q=(s,i)=>`${s}:${i}`,I=s=>s?(S.current.queries??{})[s]??"":S.current.generalQuery??"",[R,k]=r.useState("results"),[n,d]=r.useState(0),[g,$]=r.useState(!1),[w,U]=r.useState(!1),[F,K]=r.useState(()=>(S.current.openTabs??[]).map(i=>{var u;return{id:`${i.connectionId}:${i.database}`,connectionId:i.connectionId,connectionName:((u=m.find(A=>A.id===i.connectionId))==null?void 0:u.name)??i.connectionId,database:i.database}})),[C,O]=r.useState(S.current.activeTabId??null),[N,G]=r.useState(()=>{const s=S.current.queries??{};return S.current.generalQuery,s}),[j,p]=r.useState(I(C)),D=r.useCallback(s=>{p(i=>{const u=typeof s=="function"?s(i):s;return G(A=>{const E={...A};return C&&(E[C]=u),E}),u})},[C]),b=c.activeConnectionId??S.current.connectionId??((W=a.database)==null?void 0:W.activeConnectionId)??((Y=m[0])==null?void 0:Y.id),_=c.activeDatabase??S.current.database??((X=a.database)==null?void 0:X.activeDatabase),z=m.find(s=>s.id===b),t=b&&_?`${b}:${_}`:"",o=t?c.tables.get(t)??[]:[],T=r.useMemo(()=>{const s=new Map;return!b||!_||o.forEach(i=>{const u=c.tableSchemas.get(`${b}:${_}:${i.name}`);u&&s.set(i.name,{columns:u.columns})}),s},[b,_,o,c.tableSchemas]),v=r.useCallback((s,i)=>{var E;const u=q(s,i),A=((E=m.find(M=>M.id===s))==null?void 0:E.name)??s;K(M=>{if(M.some(ie=>ie.id===u))return M;const ce={id:u,connectionId:s,connectionName:A,database:i};return[...M,ce]}),O(u),p(N[u]??""),h.setActiveConnection(a.id,s),h.setActiveDatabase(a.id,i)},[a.id,m,N]),ae=r.useCallback(s=>{K(i=>i.filter(u=>u.id!==s)),C===s&&K(i=>{if(i.length>0){const u=i[0];O(u.id),p(N[u.id]??""),h.setActiveConnection(a.id,u.connectionId),h.setActiveDatabase(a.id,u.database)}else O(null),p("");return i})},[C,a.id,N]),se=r.useCallback(s=>{O(s.id),p(N[s.id]??""),h.setActiveConnection(a.id,s.connectionId),h.setActiveDatabase(a.id,s.database)},[a.id,N]);r.useEffect(()=>{if(!w&&m.length>0){const s=S.current;s.connectionId&&m.some(i=>i.id===s.connectionId)&&(h.setActiveConnection(a.id,s.connectionId),h.listDatabases(a.id,s.connectionId),s.database&&(h.setActiveDatabase(a.id,s.database),h.listTables(a.id,s.connectionId,s.database))),U(!0)}},[a.id,m,w]),r.useEffect(()=>{h.requestQueryHistory(a.id)},[a.id]),r.useEffect(()=>{const s=i=>{i.key==="Escape"&&(i.preventDefault(),i.stopPropagation(),x())};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[x]),r.useEffect(()=>{w&&b&&ve(a.id,{connectionId:b,database:_,lastQuery:j,queries:N,generalQuery:"",openTabs:F.map(s=>({connectionId:s.connectionId,database:s.database})),activeTabId:C??void 0})},[a.id,b,_,j,w,F,C,N]);const te=r.useCallback(s=>{var i;if(!(!b||!_||!j.trim()||Q))if(s==="cursor"){const u=(i=L.current)==null?void 0:i.querySelector(".query-editor__textarea"),A=(u==null?void 0:u.selectionStart)??P.current,E=he(j,A);E&&h.executeQuery(a.id,b,_,E)}else{const u=_e(j);if(u.length<=1)h.executeQuery(a.id,b,_,j.trim());else{const A=b,E=_;(async()=>{for(const M of u)await h.executeQueryAndWait(a.id,A,E,M.sql)})()}}},[a.id,b,_,j,Q]),ne=r.useCallback(s=>{D(s),k("results")},[]),re=r.useCallback(s=>{h.setActiveConnection(a.id,s),h.listDatabases(a.id,s)},[a.id]),le=r.useCallback(s=>{b&&(v(b,s),h.listTables(a.id,b,s))},[a.id,b,v]),V=y[n];return m.length===0?e.jsxs("div",{className:"database-panel",ref:L,children:[e.jsxs("div",{className:"database-panel__header",children:[e.jsxs("div",{className:"database-panel__title",children:[e.jsx("span",{className:"database-panel__icon",children:e.jsx(H,{name:"database",size:16})}),e.jsx("span",{className:"database-panel__name",children:a.name})]}),e.jsx("button",{className:"database-panel__close",onClick:x,children:"×"})]}),e.jsx("div",{className:"database-panel__body",children:e.jsxs("div",{className:"database-panel__no-connections",children:[e.jsx("div",{className:"database-panel__no-connections-icon",children:e.jsx(H,{name:"plug",size:32})}),e.jsx("h3",{children:l("terminal:database.noConnections")}),e.jsx("p",{children:l("terminal:database.noConnectionsDesc")}),e.jsx("p",{children:l("terminal:database.toGetStarted")}),e.jsxs("ol",{children:[e.jsx("li",{children:l("terminal:database.step1Close")}),e.jsx("li",{children:l("terminal:database.step2Settings")}),e.jsx("li",{children:l("terminal:database.step3AddConnection")}),e.jsx("li",{children:l("terminal:database.step4Reopen")})]})]})})]}):e.jsxs("div",{className:"database-panel",ref:L,children:[e.jsxs("div",{className:"database-panel__header",children:[e.jsxs("div",{className:"database-panel__title",children:[e.jsx("span",{className:"database-panel__icon",children:(z==null?void 0:z.engine)==="mysql"?"🐬":"🐘"}),e.jsx("span",{className:"database-panel__name",children:a.name}),z&&e.jsxs("span",{className:"database-panel__connection-info",children:[z.name," / ",_||l("terminal:database.noDatabaseSelected")]})]}),e.jsx("button",{className:"database-panel__close",onClick:x,children:"×"})]}),e.jsxs("div",{className:"database-panel__body",children:[e.jsx(fe,{building:a,connections:m,activeConnectionId:b,activeDatabase:_,collapsed:g,onToggleCollapse:()=>$(!g),onConnectionChange:re,onDatabaseChange:le,onInsertTable:s=>D(i=>i+` ${s}`),onSelectTableQuery:s=>{const i=`SELECT * FROM ${s}`;D(i),b&&_&&h.executeQuery(a.id,b,_,i)}}),e.jsxs("div",{className:"database-panel__main",children:[F.length>0&&e.jsx(ye,{tabs:F,activeTabId:C,onTabClick:se,onTabClose:ae}),e.jsx(pe,{query:j,onChange:D,onExecute:te,isExecuting:Q,disabled:!b||!_,tables:o,tableSchemas:T,onRequestTableSchema:s=>{b&&_&&h.getTableSchema(a.id,b,_,s)}}),e.jsxs("div",{className:"database-panel__tabs",children:[e.jsxs("button",{className:`database-panel__tab ${R==="results"?"database-panel__tab--active":""}`,onClick:()=>k("results"),children:[l("terminal:database.results"),y.length>0&&e.jsx("span",{className:"database-panel__tab-badge",children:y.length})]}),e.jsxs("button",{className:`database-panel__tab ${R==="history"?"database-panel__tab--active":""}`,onClick:()=>k("history"),children:[l("terminal:database.history"),f.length>0&&e.jsx("span",{className:"database-panel__tab-badge",children:f.length})]}),R==="results"&&y.length>1&&e.jsxs("div",{className:"database-panel__result-nav",children:[e.jsxs("button",{disabled:n>=y.length-1,onClick:()=>d(s=>s+1),children:["← ",l("terminal:database.older")]}),e.jsxs("span",{children:[n+1," / ",y.length]}),e.jsxs("button",{disabled:n<=0,onClick:()=>d(s=>s-1),children:[l("terminal:database.newer")," →"]})]})]}),e.jsx("div",{className:"database-panel__tab-content",children:R==="results"?V?e.jsx(xe,{result:V,buildingId:a.id,building:a}):e.jsxs("div",{className:"database-panel__empty",children:[e.jsx("p",{children:l("terminal:database.noResultsYet")}),e.jsx("p",{children:l("terminal:database.selectDbAndRun")})]}):e.jsx(je,{buildingId:a.id,history:f,onLoadQuery:ne})})]})]})]})};export{ge as DatabasePanel,fe as DatabaseSidebar,ye as DatabaseTabs,pe as QueryEditor,je as QueryHistoryPanel,xe as ResultsTable};
1
+ import{u as J,a as Z,r,s as h,j as e,D as de,I as H,C as oe,b as me,c as be,d as ue,g as he,e as _e,Q as pe,R as xe}from"./main-ViFk-kY8.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";const fe=({building:a,connections:x,activeConnectionId:l,activeDatabase:c,collapsed:y,onToggleCollapse:f,onConnectionChange:Q,onDatabaseChange:S,onInsertTable:L,onSelectTableQuery:P})=>{const{t:m}=J(["terminal"]),q=Z(a.id),[I,R]=r.useState(new Set),[k,n]=r.useState(""),[d,g]=r.useState(""),[$,w]=r.useState(!1),[U,F]=r.useState(null),K=r.useRef(null),C=r.useRef(null),O=r.useRef(null),N=l?q.databases.get(l)??[]:[],G=l&&c?`${l}:${c}`:"",j=G?q.tables.get(G)??[]:[],p=l?q.connectionStatus.get(l):void 0,D=r.useMemo(()=>{if(!k.trim())return N;const t=k.toLowerCase();return N.filter(o=>o.toLowerCase().includes(t))},[N,k]),b=r.useMemo(()=>{if(!d.trim())return j;const t=d.toLowerCase();return j.filter(o=>o.name.toLowerCase().includes(t))},[j,d]);r.useEffect(()=>{const t=o=>{C.current&&!C.current.contains(o.target)&&w(!1)};return $&&document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[$]),r.useEffect(()=>{l&&!p&&h.testDatabaseConnection(a.id,l)},[a.id,l,p]),r.useEffect(()=>{l&&(p!=null&&p.connected)&&N.length===0&&h.listDatabases(a.id,l)},[a.id,l,p==null?void 0:p.connected,N.length]),r.useEffect(()=>{l&&c&&j.length===0&&h.listTables(a.id,l,c)},[a.id,l,c,j.length]),r.useEffect(()=>{F(null),g("")},[l,c]);const _=r.useCallback(t=>{R(o=>{const T=new Set(o);if(T.has(t))T.delete(t);else if(T.add(t),l&&c){const v=`${l}:${c}:${t}`;q.tableSchemas.has(v)||h.getTableSchema(a.id,l,c,t)}return T})},[a.id,l,c,q.tableSchemas]),z=t=>{if(!l||!c)return null;const o=`${l}:${c}:${t}`;return q.tableSchemas.get(o)};return y?e.jsx("div",{className:"database-sidebar database-sidebar--collapsed",children:e.jsx("button",{className:"database-sidebar__toggle",onClick:f,title:m("terminal:database.expandSidebar"),children:"»"})}):e.jsxs("div",{className:"database-sidebar",children:[e.jsxs("div",{className:"database-sidebar__header",children:[e.jsx("span",{children:m("terminal:database.explorer")}),e.jsx("button",{className:"database-sidebar__toggle",onClick:f,title:m("terminal:database.collapseSidebar"),children:"«"})]}),e.jsxs("div",{className:"database-sidebar__section",children:[e.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.connection")}),e.jsx("select",{className:"database-sidebar__select",value:l||"",onChange:t=>Q(t.target.value),children:x.length===0?e.jsx("option",{value:"",children:m("terminal:database.noConnections")}):x.map(t=>{var o;return e.jsxs("option",{value:t.id,children:[((o=de[t.engine])==null?void 0:o.icon)??"🗄️"," ",t.name]},t.id)})}),p&&e.jsx("div",{className:`database-sidebar__status ${p.connected?"database-sidebar__status--connected":"database-sidebar__status--error"}`,children:p.connected?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"database-sidebar__status-icon",children:"✓"}),m("terminal:database.connected"),p.serverVersion&&e.jsxs("span",{className:"database-sidebar__version",children:["(",p.serverVersion,")"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"database-sidebar__status-icon",children:"✗"}),p.error||m("terminal:database.disconnected")]})})]}),N.length>0&&e.jsxs("div",{className:"database-sidebar__section",children:[e.jsx("div",{className:"database-sidebar__section-title",children:m("terminal:database.databaseTitle")}),e.jsxs("div",{className:"database-sidebar__searchable-select",ref:C,children:[e.jsx("input",{ref:K,className:"database-sidebar__search-input",type:"text",value:$?k:c||"",placeholder:m("terminal:database.selectDatabase"),onChange:t=>{n(t.target.value),$||w(!0)},onFocus:()=>{w(!0),n("")},onKeyDown:t=>{var o,T;t.key==="Escape"?(w(!1),n(""),(o=K.current)==null||o.blur()):t.key==="Enter"&&D.length===1&&(S(D[0]),w(!1),n(""),(T=K.current)==null||T.blur())}}),$&&e.jsx("div",{className:"database-sidebar__dropdown",children:D.length===0?e.jsx("div",{className:"database-sidebar__dropdown-empty",children:"No matches"}):D.map(t=>e.jsx("div",{className:`database-sidebar__dropdown-item ${t===c?"database-sidebar__dropdown-item--active":""}`,onMouseDown:o=>{o.preventDefault(),S(t),w(!1),n("")},children:t},t))})]})]}),j.length>0&&e.jsxs("div",{className:"database-sidebar__section database-sidebar__section--tables",children:[e.jsx("div",{className:"database-sidebar__section-title",children:d.trim()?m("terminal:database.tablesCount",{count:b.length})+` / ${j.length}`:m("terminal:database.tablesCount",{count:j.length})}),e.jsxs("div",{className:"database-sidebar__table-filter",children:[e.jsx("input",{ref:O,className:"database-sidebar__table-filter-input",type:"text",value:d,placeholder:m("terminal:database.filterTables"),onChange:t=>g(t.target.value),onKeyDown:t=>{var o;t.key==="Escape"&&(d?g(""):(o=O.current)==null||o.blur(),t.stopPropagation())}}),d&&e.jsx("button",{className:"database-sidebar__table-filter-clear",onClick:()=>{var t;g(""),(t=O.current)==null||t.focus()},title:"Clear filter",children:"×"})]}),e.jsxs("div",{className:"database-sidebar__tables",children:[d.trim()&&b.length===0&&e.jsx("div",{className:"database-sidebar__tables-empty",children:m("terminal:database.noTablesMatch")}),b.map(t=>{const o=I.has(t.name),T=o?z(t.name):null;return e.jsxs("div",{className:"database-sidebar__table",children:[e.jsxs("div",{className:"database-sidebar__table-header",children:[e.jsx("button",{className:"database-sidebar__table-expand",onClick:()=>_(t.name),title:o?"Collapse table schema":"Expand table schema",children:e.jsx(H,{name:o?"caret-down":"caret-right",size:10})}),e.jsx("span",{className:"database-sidebar__table-icon",children:e.jsx(H,{name:t.type==="view"?"eye":"clipboard",size:12})}),e.jsx("span",{className:`database-sidebar__table-name ${U===t.name?"database-sidebar__table-name--selected":""}`,onClick:()=>F(t.name),onDoubleClick:()=>{F(t.name),P(t.name)},children:t.name}),e.jsx("button",{className:"database-sidebar__table-insert",onClick:v=>{v.stopPropagation(),L(t.name)},title:m("terminal:database.insertTableName"),children:"+"})]}),o&&T&&e.jsx("div",{className:"database-sidebar__table-columns",children:T.columns.map(v=>e.jsxs("div",{className:"database-sidebar__column",onClick:()=>L(v.name),title:`${v.type}${v.nullable?" NULL":" NOT NULL"}${v.primaryKey?" PK":""}`,children:[e.jsx("span",{className:"database-sidebar__column-icon",children:v.primaryKey?e.jsx(H,{name:"key",size:11}):null}),e.jsx("span",{className:"database-sidebar__column-name",children:v.name}),e.jsx("span",{className:"database-sidebar__column-type",children:v.type})]},v.name))})]},t.name)})]})]})]})},je=({buildingId:a,history:x,onLoadQuery:l})=>{const{t:c}=J(["terminal","common"]),[y,f]=r.useState(""),[Q,S]=r.useState(!1),[L,P]=r.useState(!1),m=r.useMemo(()=>{let n=x;if(Q&&(n=n.filter(d=>d.favorite)),y.trim()){const d=y.toLowerCase();n=n.filter(g=>g.query.toLowerCase().includes(d)||g.database.toLowerCase().includes(d))}return n},[x,Q,y]),q=n=>{const d=new Date(n),$=new Date().getTime()-d.getTime();return $<1440*60*1e3?d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):$<10080*60*1e3?d.toLocaleDateString([],{weekday:"short"})+" "+d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):d.toLocaleDateString([],{month:"short",day:"numeric"})},I=r.useCallback((n,d)=>{d.stopPropagation(),h.toggleQueryFavorite(a,n)},[a]),R=r.useCallback((n,d)=>{d.stopPropagation(),h.deleteQueryFromHistory(a,n)},[a]),k=r.useCallback(()=>{P(!0)},[]);return x.length===0?e.jsxs("div",{className:"query-history query-history--empty",children:[e.jsx("p",{children:c("terminal:database.noHistory")}),e.jsx("p",{children:c("terminal:database.queriesAppearHere")})]}):e.jsxs("div",{className:"query-history",children:[e.jsxs("div",{className:"query-history__toolbar",children:[e.jsx("input",{type:"text",className:"query-history__search",placeholder:c("terminal:database.searchQueries"),value:y,onChange:n=>f(n.target.value)}),e.jsxs("label",{className:"query-history__filter",children:[e.jsx("input",{type:"checkbox",checked:Q,onChange:n=>S(n.target.checked)}),c("terminal:database.favoritesOnly")]}),e.jsx("button",{className:"query-history__clear",onClick:k,title:c("terminal:database.clearAll"),children:c("terminal:database.clearAll")})]}),e.jsxs("div",{className:"query-history__list",children:[m.map(n=>e.jsxs("div",{className:`query-history__item ${n.status==="error"?"query-history__item--error":""}`,onClick:()=>l(n.query),children:[e.jsxs("div",{className:"query-history__item-header",children:[e.jsx("span",{className:`query-history__status ${n.status==="success"?"query-history__status--success":"query-history__status--error"}`,children:e.jsx(H,{name:n.status==="success"?"check":"cross",size:12})}),e.jsx("span",{className:"query-history__database",children:n.database}),e.jsx("span",{className:"query-history__date",children:q(n.executedAt)}),e.jsxs("span",{className:"query-history__duration",children:[n.duration,"ms"]}),n.rowCount!==void 0&&e.jsx("span",{className:"query-history__row-count",children:c("terminal:database.rowCount",{count:n.rowCount})})]}),e.jsx("div",{className:"query-history__query",children:e.jsx("code",{children:n.query.length>200?n.query.substring(0,200)+"...":n.query})}),n.error&&e.jsx("div",{className:"query-history__error",children:n.error}),e.jsxs("div",{className:"query-history__actions",children:[e.jsx("button",{className:`query-history__favorite ${n.favorite?"query-history__favorite--active":""}`,onClick:d=>I(n.id,d),title:n.favorite?c("terminal:database.removeFromFavorites"):c("terminal:database.addToFavorites"),children:e.jsx(H,{name:"star",size:12,weight:n.favorite?"fill":"regular",color:n.favorite?"#facc15":void 0})}),e.jsx("button",{className:"query-history__delete",onClick:d=>R(n.id,d),title:c("terminal:database.deleteFromHistory"),children:e.jsx(H,{name:"trash",size:12})})]})]},n.id)),m.length===0&&e.jsx("div",{className:"query-history__no-results",children:c("terminal:database.noQueriesMatch")})]}),e.jsx(oe,{isOpen:L,title:c("terminal:database.clearAll"),message:c("terminal:database.confirmClearHistory"),confirmLabel:c("terminal:database.clearAll"),cancelLabel:c("common:buttons.cancel"),variant:"danger",onConfirm:()=>h.clearQueryHistory(a),onClose:()=>P(!1)})]})},ye=({tabs:a,activeTabId:x,onTabClick:l,onTabClose:c})=>{const{t:y}=J(["terminal"]);return e.jsx("div",{className:"database-tabs",children:a.map(f=>e.jsxs("div",{className:`database-tabs__tab ${x===f.id?"database-tabs__tab--active":""}`,children:[e.jsxs("button",{className:"database-tabs__tab-label",onClick:()=>l(f),title:`${f.connectionName} / ${f.database}`,children:[f.database,e.jsx("span",{className:"database-tabs__tab-connection",children:f.connectionName})]}),e.jsx("button",{className:"database-tabs__tab-close",onClick:()=>c(f.id),title:y("terminal:database.closeTab"),"aria-label":`Close ${f.database} tab`,children:"×"})]},f.id))})},ee=a=>`db-panel-${a}`;function Ne(a){try{const x=localStorage.getItem(ee(a));return x?JSON.parse(x):{}}catch{return{}}}function ve(a,x){try{localStorage.setItem(ee(a),JSON.stringify(x))}catch{}}const ge=({building:a,onClose:x})=>{var B,W,Y,X;const{t:l}=J(["terminal","common"]),c=Z(a.id),y=me(a.id),f=be(a.id),Q=ue(a.id),S=r.useRef(Ne(a.id)),L=r.useRef(null),P=r.useRef(0),m=((B=a.database)==null?void 0:B.connections)??[],q=(s,i)=>`${s}:${i}`,I=s=>s?(S.current.queries??{})[s]??"":S.current.generalQuery??"",[R,k]=r.useState("results"),[n,d]=r.useState(0),[g,$]=r.useState(!1),[w,U]=r.useState(!1),[F,K]=r.useState(()=>(S.current.openTabs??[]).map(i=>{var u;return{id:`${i.connectionId}:${i.database}`,connectionId:i.connectionId,connectionName:((u=m.find(A=>A.id===i.connectionId))==null?void 0:u.name)??i.connectionId,database:i.database}})),[C,O]=r.useState(S.current.activeTabId??null),[N,G]=r.useState(()=>{const s=S.current.queries??{};return S.current.generalQuery,s}),[j,p]=r.useState(I(C)),D=r.useCallback(s=>{p(i=>{const u=typeof s=="function"?s(i):s;return G(A=>{const E={...A};return C&&(E[C]=u),E}),u})},[C]),b=c.activeConnectionId??S.current.connectionId??((W=a.database)==null?void 0:W.activeConnectionId)??((Y=m[0])==null?void 0:Y.id),_=c.activeDatabase??S.current.database??((X=a.database)==null?void 0:X.activeDatabase),z=m.find(s=>s.id===b),t=b&&_?`${b}:${_}`:"",o=t?c.tables.get(t)??[]:[],T=r.useMemo(()=>{const s=new Map;return!b||!_||o.forEach(i=>{const u=c.tableSchemas.get(`${b}:${_}:${i.name}`);u&&s.set(i.name,{columns:u.columns})}),s},[b,_,o,c.tableSchemas]),v=r.useCallback((s,i)=>{var E;const u=q(s,i),A=((E=m.find(M=>M.id===s))==null?void 0:E.name)??s;K(M=>{if(M.some(ie=>ie.id===u))return M;const ce={id:u,connectionId:s,connectionName:A,database:i};return[...M,ce]}),O(u),p(N[u]??""),h.setActiveConnection(a.id,s),h.setActiveDatabase(a.id,i)},[a.id,m,N]),ae=r.useCallback(s=>{K(i=>i.filter(u=>u.id!==s)),C===s&&K(i=>{if(i.length>0){const u=i[0];O(u.id),p(N[u.id]??""),h.setActiveConnection(a.id,u.connectionId),h.setActiveDatabase(a.id,u.database)}else O(null),p("");return i})},[C,a.id,N]),se=r.useCallback(s=>{O(s.id),p(N[s.id]??""),h.setActiveConnection(a.id,s.connectionId),h.setActiveDatabase(a.id,s.database)},[a.id,N]);r.useEffect(()=>{if(!w&&m.length>0){const s=S.current;s.connectionId&&m.some(i=>i.id===s.connectionId)&&(h.setActiveConnection(a.id,s.connectionId),h.listDatabases(a.id,s.connectionId),s.database&&(h.setActiveDatabase(a.id,s.database),h.listTables(a.id,s.connectionId,s.database))),U(!0)}},[a.id,m,w]),r.useEffect(()=>{h.requestQueryHistory(a.id)},[a.id]),r.useEffect(()=>{const s=i=>{i.key==="Escape"&&(i.preventDefault(),i.stopPropagation(),x())};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[x]),r.useEffect(()=>{w&&b&&ve(a.id,{connectionId:b,database:_,lastQuery:j,queries:N,generalQuery:"",openTabs:F.map(s=>({connectionId:s.connectionId,database:s.database})),activeTabId:C??void 0})},[a.id,b,_,j,w,F,C,N]);const te=r.useCallback(s=>{var i;if(!(!b||!_||!j.trim()||Q))if(s==="cursor"){const u=(i=L.current)==null?void 0:i.querySelector(".query-editor__textarea"),A=(u==null?void 0:u.selectionStart)??P.current,E=he(j,A);E&&h.executeQuery(a.id,b,_,E)}else{const u=_e(j);if(u.length<=1)h.executeQuery(a.id,b,_,j.trim());else{const A=b,E=_;(async()=>{for(const M of u)await h.executeQueryAndWait(a.id,A,E,M.sql)})()}}},[a.id,b,_,j,Q]),ne=r.useCallback(s=>{D(s),k("results")},[]),re=r.useCallback(s=>{h.setActiveConnection(a.id,s),h.listDatabases(a.id,s)},[a.id]),le=r.useCallback(s=>{b&&(v(b,s),h.listTables(a.id,b,s))},[a.id,b,v]),V=y[n];return m.length===0?e.jsxs("div",{className:"database-panel",ref:L,children:[e.jsxs("div",{className:"database-panel__header",children:[e.jsxs("div",{className:"database-panel__title",children:[e.jsx("span",{className:"database-panel__icon",children:e.jsx(H,{name:"database",size:16})}),e.jsx("span",{className:"database-panel__name",children:a.name})]}),e.jsx("button",{className:"database-panel__close",onClick:x,children:"×"})]}),e.jsx("div",{className:"database-panel__body",children:e.jsxs("div",{className:"database-panel__no-connections",children:[e.jsx("div",{className:"database-panel__no-connections-icon",children:e.jsx(H,{name:"plug",size:32})}),e.jsx("h3",{children:l("terminal:database.noConnections")}),e.jsx("p",{children:l("terminal:database.noConnectionsDesc")}),e.jsx("p",{children:l("terminal:database.toGetStarted")}),e.jsxs("ol",{children:[e.jsx("li",{children:l("terminal:database.step1Close")}),e.jsx("li",{children:l("terminal:database.step2Settings")}),e.jsx("li",{children:l("terminal:database.step3AddConnection")}),e.jsx("li",{children:l("terminal:database.step4Reopen")})]})]})})]}):e.jsxs("div",{className:"database-panel",ref:L,children:[e.jsxs("div",{className:"database-panel__header",children:[e.jsxs("div",{className:"database-panel__title",children:[e.jsx("span",{className:"database-panel__icon",children:(z==null?void 0:z.engine)==="mysql"?"🐬":"🐘"}),e.jsx("span",{className:"database-panel__name",children:a.name}),z&&e.jsxs("span",{className:"database-panel__connection-info",children:[z.name," / ",_||l("terminal:database.noDatabaseSelected")]})]}),e.jsx("button",{className:"database-panel__close",onClick:x,children:"×"})]}),e.jsxs("div",{className:"database-panel__body",children:[e.jsx(fe,{building:a,connections:m,activeConnectionId:b,activeDatabase:_,collapsed:g,onToggleCollapse:()=>$(!g),onConnectionChange:re,onDatabaseChange:le,onInsertTable:s=>D(i=>i+` ${s}`),onSelectTableQuery:s=>{const i=`SELECT * FROM ${s}`;D(i),b&&_&&h.executeQuery(a.id,b,_,i)}}),e.jsxs("div",{className:"database-panel__main",children:[F.length>0&&e.jsx(ye,{tabs:F,activeTabId:C,onTabClick:se,onTabClose:ae}),e.jsx(pe,{query:j,onChange:D,onExecute:te,isExecuting:Q,disabled:!b||!_,tables:o,tableSchemas:T,onRequestTableSchema:s=>{b&&_&&h.getTableSchema(a.id,b,_,s)}}),e.jsxs("div",{className:"database-panel__tabs",children:[e.jsxs("button",{className:`database-panel__tab ${R==="results"?"database-panel__tab--active":""}`,onClick:()=>k("results"),children:[l("terminal:database.results"),y.length>0&&e.jsx("span",{className:"database-panel__tab-badge",children:y.length})]}),e.jsxs("button",{className:`database-panel__tab ${R==="history"?"database-panel__tab--active":""}`,onClick:()=>k("history"),children:[l("terminal:database.history"),f.length>0&&e.jsx("span",{className:"database-panel__tab-badge",children:f.length})]}),R==="results"&&y.length>1&&e.jsxs("div",{className:"database-panel__result-nav",children:[e.jsxs("button",{disabled:n>=y.length-1,onClick:()=>d(s=>s+1),children:["← ",l("terminal:database.older")]}),e.jsxs("span",{children:[n+1," / ",y.length]}),e.jsxs("button",{disabled:n<=0,onClick:()=>d(s=>s-1),children:[l("terminal:database.newer")," →"]})]})]}),e.jsx("div",{className:"database-panel__tab-content",children:R==="results"?V?e.jsx(xe,{result:V,buildingId:a.id,building:a}):e.jsxs("div",{className:"database-panel__empty",children:[e.jsx("p",{children:l("terminal:database.noResultsYet")}),e.jsx("p",{children:l("terminal:database.selectDbAndRun")})]}):e.jsx(je,{buildingId:a.id,history:f,onLoadQuery:ne})})]})]})]})};export{ge as DatabasePanel,fe as DatabaseSidebar,ye as DatabaseTabs,pe as QueryEditor,je as QueryHistoryPanel,xe as ResultsTable};