tide-commander 1.98.0 → 1.99.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 (43) hide show
  1. package/dist/assets/{BossLogsModal-P6MiZVuY.js → BossLogsModal-CDel834o.js} +1 -1
  2. package/dist/assets/{BossSpawnModal-DZJ1Ngsz.js → BossSpawnModal-BB9wL5VV.js} +1 -1
  3. package/dist/assets/{ControlsModal-BjV0a1kc.js → ControlsModal-D5RE5MvT.js} +1 -1
  4. package/dist/assets/{DockerLogsModal-DtddubKa.js → DockerLogsModal-B27P1JpZ.js} +1 -1
  5. package/dist/assets/{EmbeddedEditor-ByRepTwR.js → EmbeddedEditor-DP1jqsT_.js} +1 -1
  6. package/dist/assets/{GmailOAuthSetup-DS6NmxUi.js → GmailOAuthSetup-DvuL5G8Q.js} +1 -1
  7. package/dist/assets/{GoogleOAuthSetup-kQyKInRW.js → GoogleOAuthSetup-CG6bSCjv.js} +1 -1
  8. package/dist/assets/{IframeModal-BuTPDTx1.js → IframeModal-ClnUGmJV.js} +1 -1
  9. package/dist/assets/{IntegrationsPanel-Bm19ZAd6.js → IntegrationsPanel-0vdfxZRq.js} +2 -2
  10. package/dist/assets/{LogViewerModal-DFlUtkDD.js → LogViewerModal-DLQlrZ4O.js} +1 -1
  11. package/dist/assets/{MonitoringModal-BEEPwGu5.js → MonitoringModal-DiC9TNCy.js} +1 -1
  12. package/dist/assets/{PM2LogsModal-Di5MjyxZ.js → PM2LogsModal-BgPrnaP5.js} +1 -1
  13. package/dist/assets/{RestoreArchivedAreaModal-CNjmR7BX.js → RestoreArchivedAreaModal-CIN1OrOW.js} +1 -1
  14. package/dist/assets/{Scene2DCanvas-CA29sh9R.js → Scene2DCanvas-Bap6brvv.js} +1 -1
  15. package/dist/assets/{SceneManager-duyCA_TD.js → SceneManager-CidCW0PR.js} +1 -1
  16. package/dist/assets/{SkillsPanel-CkV4ci4Q.js → SkillsPanel-DHQTPaP2.js} +1 -1
  17. package/dist/assets/{SlackMultiInstanceSetup-iHZNQX3B.js → SlackMultiInstanceSetup-CQK4D89W.js} +1 -1
  18. package/dist/assets/{SpawnModal-bzQlnSQy.js → SpawnModal-Cx_k3HHC.js} +1 -1
  19. package/dist/assets/{SubordinateAssignmentModal-D6Ak_XQ1.js → SubordinateAssignmentModal-C1DOv51H.js} +1 -1
  20. package/dist/assets/{TriggerManagerPanel-CT8aMQ5P.js → TriggerManagerPanel-jP5RBK2L.js} +1 -1
  21. package/dist/assets/{WorkflowEditorPanel-DcV9ErU4.js → WorkflowEditorPanel-Dh6mZ8M4.js} +1 -1
  22. package/dist/assets/{index-Cirz97EK.js → index-B-ttQFx4.js} +2 -2
  23. package/dist/assets/index-BXnThzaG.js +11 -0
  24. package/dist/assets/{index-C0fIrrTS.js → index-CYwFXTQZ.js} +1 -1
  25. package/dist/assets/{index-Cnj2pM08.js → index-Cwlm-Pqi.js} +3 -3
  26. package/dist/assets/{index-Ba8umpS_.js → index-D96LXKm4.js} +1 -1
  27. package/dist/assets/{index-BQQV5Xax.js → index-DP5sMNS9.js} +1 -1
  28. package/dist/assets/{index-Dww2MWLN.js → index-DfEbuBH8.js} +1 -1
  29. package/dist/assets/{index-D2L5oc5D.js → index-DsKaX6TJ.js} +1 -1
  30. package/dist/assets/{index-DR7uaDtK.js → index-enJvXAbe.js} +1 -1
  31. package/dist/assets/{main-XbhAPjbi.js → main-B7wf_xU_.js} +91 -91
  32. package/dist/assets/main-DLzFxLC1.css +1 -0
  33. package/dist/assets/{web-C4LpSGoH.js → web-BHmmnvF7.js} +1 -1
  34. package/dist/assets/{web-CaPUSaID.js → web-IGuhG0xr.js} +1 -1
  35. package/dist/assets/{web-C-JnApw7.js → web-SOehUGgT.js} +1 -1
  36. package/dist/index.html +2 -2
  37. package/dist/locales/en/config.json +16 -1
  38. package/dist/src/packages/server/routes/index.js +2 -0
  39. package/dist/src/packages/server/routes/system.js +156 -0
  40. package/dist/src/packages/server/services/self-update-service.js +191 -0
  41. package/package.json +1 -1
  42. package/dist/assets/index-CDHzSAgq.js +0 -1
  43. package/dist/assets/main-CD03IZnY.css +0 -1
@@ -1,10 +1,10 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/EmbeddedEditor-ByRepTwR.js","assets/main-XbhAPjbi.js","assets/vendor-react--Eh9ivFN.js","assets/vendor-three-Chj50gSY.js","assets/main-CD03IZnY.css","assets/EmbeddedEditor-Dx2pJa2-.css"])))=>i.map(i=>d[i]);
2
- import{r as t,aJ as q,l as K,aX as Vt,M as $s,S as Tt,N as Hs,s as mt,u as le,j as e,I as M,bA as Mt,f as zs,bB as Os,bC as Dn,bD as As,bE as Gs,bF as Rn,bG as Fn,bH as Kt,bI as Pn,bJ as In,bK as Xt,bL as Ln,bM as Us,bN as Et,bO as St,aa as it,bP as ft,bQ as pt,bR as Es,bS as $n,b3 as Hn,bT as Yt,bU as zn,bV as On,bW as Ss,C as An,n as Gn}from"./main-XbhAPjbi.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function Un(s){const[n,l]=t.useState(null),[c,r]=t.useState(!1),i=t.useCallback(async()=>{if(s){r(!0);try{const f=await q(K(`/api/files/git-status?path=${encodeURIComponent(s)}`)),o=await f.json();f.ok?l(o):l({isGitRepo:!1,files:[]})}catch(f){console.error("[FileExplorer] Failed to load git status:",f),l({isGitRepo:!1,files:[]})}finally{r(!1)}}},[s]);return{gitStatus:n,loading:c,loadGitStatus:i}}async function Bn(s){try{const n=await q(K(`/api/files/git-original?path=${encodeURIComponent(s)}`)),l=await n.json();return n.ok&&!l.isNew?{content:l.content,isNew:!1}:{content:null,isNew:!0}}catch(n){return console.error("[FileExplorer] Failed to load original file:",n),{content:null,isNew:!0}}}const _n=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",""]),Vn=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".svg"]),Kn=new Set([".pdf"]),Wn=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 qn(s){const n=s.toLowerCase();return Vn.has(n)?"image":Kn.has(n)?"pdf":Wn.has(n)?"binary":(_n.has(n),"text")}function Jn(){const[s,n]=t.useState(null),[l,c]=t.useState(!1),[r,i]=t.useState(null),f=t.useCallback(async u=>{var g,j;c(!0),i(null);try{const p=u.substring(u.lastIndexOf(".")).toLowerCase(),b=qn(p),C=u.substring(u.lastIndexOf("/")+1);if(b==="image"){const k=await q(K(`/api/files/binary?path=${encodeURIComponent(u)}`));if(!k.ok){const w=await k.json().catch(()=>({error:"Failed to load image"}));i(w.error||"Failed to load image"),n(null);return}const d=await k.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(b==="pdf"){const k=await q(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await k.json();if(!k.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(Vt())}`)});return}if(b==="binary"){const k=await q(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await k.json();if(!k.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(Vt())}`)});return}const P=await q(K(`/api/files/read?path=${encodeURIComponent(u)}`)),x=await P.json();if(!P.ok){if((g=x.error)!=null&&g.includes("too large")||(j=x.error)!=null&&j.includes("binary")){const k=await q(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await k.json();if(k.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(Vt())}`)});return}}i(x.error||"Failed to load file"),n(null);return}n({...x,fileType:"text"})}catch(p){const b=p instanceof Error?p.message:"Failed to load file";i(b),n(null)}finally{c(!1)}},[]),o=t.useCallback(()=>{n(u=>(u!=null&&u.dataUrl&&u.dataUrl.startsWith("blob:")&&URL.revokeObjectURL(u.dataUrl),null)),i(null)},[]);return{file:s,loading:l,error:r,loadFile:f,clearFile:o,setFile:n}}const Wt="file-explorer-state",Yn=10080*60*1e3;function Xn(s,n){return n?`${Wt}-folder-${n}`:s?`${Wt}-area-${s}`:`${Wt}-default`}async function Qn(s){try{const n=await q(K(`/api/files/exists?path=${encodeURIComponent(s)}`));return n.ok?(await n.json()).exists===!0:!1}catch{return!1}}function Zn({areaId:s,folderPath:n,isOpen:l}){const c=Xn(s,n),r=t.useRef(!1);t.useEffect(()=>{r.current=!1},[s,n]);const i=t.useCallback(async()=>{if(r.current)return null;r.current=!0;try{const o=localStorage.getItem(c);if(!o)return null;const u=JSON.parse(o);if(Date.now()-u.timestamp>Yn)return localStorage.removeItem(c),null;const j=(await Promise.all(u.tabs.map(async b=>({tab:b,exists:await Qn(b.path)})))).filter(({exists:b})=>b).map(({tab:b})=>b);let p=u.activeTabPath;return p&&!j.some(b=>b.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(o){return console.error("[FileExplorerStorage] Failed to load state:",o),null}},[c]),f=t.useCallback(o=>{if(l)try{const u={tabs:o.tabs,activeTabPath:o.activeTabPath,viewMode:o.viewMode,selectedFolderIndex:o.selectedFolderIndex,expandedPaths:Array.from(o.expandedPaths),timestamp:Date.now()};localStorage.setItem(c,JSON.stringify(u))}catch(u){console.error("[FileExplorerStorage] Failed to save state:",u)}},[c,l]);return{loadStoredState:i,saveState:f}}const Ts=280,Ms=150,Ds=1200;function ea(){const[s,n]=t.useState(()=>{const g=$s(Tt.TREE_PANEL_WIDTH,Ts);return g>=Ms&&g<=Ds?g:Ts}),l=t.useRef(!1),[c,r]=t.useState(!1),i=t.useRef(0),f=t.useRef(0),o=t.useRef(s);o.current=s;const u=t.useCallback(g=>{g.preventDefault(),l.current=!0,r(!0),i.current=g.clientX,f.current=s,document.body.style.cursor="ew-resize",document.body.style.userSelect="none"},[s]);return t.useEffect(()=>{const g=p=>{if(!l.current)return;const b=p.clientX-i.current,C=Math.min(Ds,Math.max(Ms,f.current+b));n(C)},j=()=>{l.current&&(l.current=!1,r(!1),document.body.style.cursor="",document.body.style.userSelect="",Hs(Tt.TREE_PANEL_WIDTH,o.current))};return document.addEventListener("mousemove",g),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",j)}},[]),{treePanelWidth:s,handleResizeStart:u,isResizing:c}}const ta=100,sa=.65,na=36;function aa(){const[s,n]=t.useState(()=>$s(Tt.MOBILE_TREE_PANEL_HEIGHT,0)),l=t.useRef(s);l.current=s;const c=t.useRef(0),r=t.useRef(0),i=()=>Math.floor((window.innerHeight-na)*sa),f=p=>Math.min(i(),Math.max(ta,p)),o=t.useCallback(p=>{n(p);const b=document.querySelector(".file-explorer-main");b&&b.style.setProperty("--fe-mobile-tree-height",`${p}px`)},[]),u=t.useCallback(()=>{document.body.style.cursor="",document.body.style.userSelect="",Hs(Tt.MOBILE_TREE_PANEL_HEIGHT,l.current),mt.setTerminalResizing(!1)},[]),g=t.useCallback(p=>{p.preventDefault();const b=document.querySelector(".file-explorer-tree-panel"),C=l.current>0?l.current:(b==null?void 0:b.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 P=k=>{const d=k.clientY-c.current;o(f(r.current+d))},x=()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",x),u()};document.addEventListener("mousemove",P),document.addEventListener("mouseup",x)},[o,u]),j=t.useCallback(p=>{if(p.touches.length!==1)return;const b=document.querySelector(".file-explorer-tree-panel"),C=l.current>0?l.current:(b==null?void 0:b.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 P=k=>{if(k.touches.length!==1)return;k.preventDefault();const d=k.touches[0].clientY-c.current;o(f(r.current+d))},x=()=>{document.removeEventListener("touchmove",P),document.removeEventListener("touchend",x),document.removeEventListener("touchcancel",x),u()};document.addEventListener("touchmove",P,{passive:!1}),document.addEventListener("touchend",x),document.addEventListener("touchcancel",x)},[o,u]);return{mobileTreeHeight:s,handleResizeMouseDown:g,handleResizeTouchStart:j}}function Qt(){const[s,n]=t.useState([]),[l,c]=t.useState(!1),[r,i]=t.useState(null),[f,o]=t.useState(null),u=t.useCallback(async k=>{c(!0),i(null);try{const d=await q(K(`/api/files/git-branches?path=${encodeURIComponent(k)}`)),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=t.useCallback(async(k,d)=>{o("checkout"),i(null);try{const v=await q(K("/api/files/git-checkout"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k,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{o(null)}},[]),j=t.useCallback(async(k,d,v)=>{o("create"),i(null);try{const w=await q(K("/api/files/git-branch-create"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k,name:d,startPoint:v})}),R=await w.json();return w.ok||i(R.error||"Failed to create branch"),R}catch(w){console.error("[GitBranches] Create branch failed:",w);const R={success:!1,error:"Failed to create branch"};return i(R.error),R}finally{o(null)}},[]),p=t.useCallback(async k=>{o("pull"),i(null);try{const d=await q(K("/api/files/git-pull"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),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{o(null)}},[]),b=t.useCallback(async k=>{o("push"),i(null);try{const d=await q(K("/api/files/git-push"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),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{o(null)}},[]),C=t.useCallback(async(k,d)=>{o("merge"),i(null);try{const v=await q(K("/api/files/git-merge"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k,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{o(null)}},[]),P=t.useCallback(async k=>{o("merge-abort"),i(null);try{const d=await q(K("/api/files/git-merge-abort"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),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{o(null)}},[]),x=t.useCallback(async k=>{o("merge-continue"),i(null);try{const d=await q(K("/api/files/git-merge-continue"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),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{o(null)}},[]);return{branches:s,loading:l,error:r,operationInProgress:f,loadBranches:u,checkoutBranch:g,createBranch:j,pullFromRemote:p,pushToRemote:b,mergeBranch:C,mergeAbort:P,mergeContinue:x}}const ra=50,ia=400,Rs={branch:"",author:"",since:"",until:"",searchPath:"",search:""};function la(){const[s,n]=t.useState([]),[l,c]=t.useState(!1),[r,i]=t.useState(!1),[f,o]=t.useState(null),[u,g]=t.useState(!1),[j,p]=t.useState(0),[b,C]=t.useState({...Rs}),[P,x]=t.useState(null),[k,d]=t.useState([]),[v,w]=t.useState(!1),[R,z]=t.useState([]),[O,G]=t.useState(!1),H=t.useRef(null),ae=t.useRef(""),ee=t.useCallback((A,Z,L)=>{const S=L||b,W=new URLSearchParams;return W.set("path",A),W.set("limit",String(ra)),W.set("offset",String(Z)),S.branch&&W.set("branch",S.branch),S.author&&W.set("author",S.author),S.since&&W.set("since",S.since),S.until&&W.set("until",S.until),S.searchPath&&W.set("searchPath",S.searchPath),S.search&&W.set("search",S.search),W.toString()},[b]),T=t.useCallback(async A=>{ae.current=A,c(!0),o(null),x(null),d([]);try{const Z=ee(A,0),L=await q(K(`/api/files/git-log?${Z}`)),S=await L.json();L.ok?(n(S.commits||[]),p(S.total||0),g(S.hasMore||!1)):(o(S.error||"Failed to load git history"),n([]))}catch(Z){console.error("[useGitHistory] loadHistory error:",Z),o("Failed to load git history"),n([])}finally{c(!1)}},[ee]),D=t.useCallback(async A=>{if(!(r||!u)){i(!0);try{const Z=ee(A,s.length),L=await q(K(`/api/files/git-log?${Z}`)),S=await L.json();L.ok&&(n(W=>[...W,...S.commits||[]]),p(S.total||0),g(S.hasMore||!1))}catch(Z){console.error("[useGitHistory] loadMore error:",Z)}finally{i(!1)}}},[ee,s.length,u,r]),F=t.useCallback(async A=>{if(x(A),!A){d([]);return}w(!0);try{const Z=ae.current,L=new URLSearchParams({path:Z,hash:A.hash}),S=await q(K(`/api/files/git-commit-files?${L}`)),W=await S.json();S.ok?d(W.files||[]):d([])}catch(Z){console.error("[useGitHistory] selectCommit files error:",Z),d([])}finally{w(!1)}},[]),re=t.useCallback((A,Z)=>{C(L=>({...L,[A]:Z}))},[]),_=t.useCallback(()=>{C({...Rs})},[]);t.useEffect(()=>{const A=ae.current;if(A)return H.current&&clearTimeout(H.current),H.current=setTimeout(()=>{T(A)},ia),()=>{H.current&&clearTimeout(H.current)}},[b]);const ge=t.useCallback(async A=>{G(!0);try{const Z=new URLSearchParams({path:A}),L=await q(K(`/api/files/git-authors?${Z}`)),S=await L.json();L.ok&&z(S.authors||[])}catch(Z){console.error("[useGitHistory] loadAuthors error:",Z)}finally{G(!1)}},[]);return{commits:s,loading:l,loadingMore:r,error:f,hasMore:u,total:j,filters:b,setFilter:re,resetFilters:_,selectedCommit:P,selectCommit:F,commitFiles:k,commitFilesLoading:v,loadHistory:T,loadMore:D,authors:R,authorsLoading:O,loadAuthors:ge}}function oa(s){if(!s.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 l of n){const c=s.current.querySelector(l);if(c&&Fs(c))return c}return Fs(s.current)?s.current:null}function Fs(s){const n=["auto","scroll"].includes(getComputedStyle(s).overflowY),l=s.scrollHeight>s.clientHeight||s.scrollWidth>s.clientWidth;return n&&l}function Bs(s){if(!s)return 19.5;const n=parseFloat(getComputedStyle(s).lineHeight);return isNaN(n)?19.5:n}function qt(s,n=!0){const l=n?s.scrollHeight:0;s.scrollTo({top:l,behavior:"smooth"})}function ca(s){const{scrollTop:n,scrollHeight:l,clientHeight:c}=s;return l<=c?100:Math.round(n/(l-c)*100)}function da(s,n){const l=Bs(s),c=s.scrollTop,r=Math.floor(c/l)+1,i=n.split(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/EmbeddedEditor-DP1jqsT_.js","assets/main-B7wf_xU_.js","assets/vendor-react--Eh9ivFN.js","assets/vendor-three-Chj50gSY.js","assets/main-DLzFxLC1.css","assets/EmbeddedEditor-Dx2pJa2-.css"])))=>i.map(i=>d[i]);
2
+ import{r as t,aJ as q,l as K,aX as Vt,M as $s,S as Tt,N as Hs,s as mt,u as le,j as e,I as M,bA as Mt,f as zs,bB as Os,bC as Dn,bD as As,bE as Gs,bF as Rn,bG as Fn,bH as Kt,bI as Pn,bJ as In,bK as Xt,bL as Ln,bM as Us,bN as Et,bO as St,aa as it,bP as ft,bQ as pt,bR as Es,bS as $n,b3 as Hn,bT as Yt,bU as zn,bV as On,bW as Ss,C as An,n as Gn}from"./main-B7wf_xU_.js";import"./vendor-react--Eh9ivFN.js";import"./vendor-three-Chj50gSY.js";function Un(s){const[n,l]=t.useState(null),[c,r]=t.useState(!1),i=t.useCallback(async()=>{if(s){r(!0);try{const f=await q(K(`/api/files/git-status?path=${encodeURIComponent(s)}`)),o=await f.json();f.ok?l(o):l({isGitRepo:!1,files:[]})}catch(f){console.error("[FileExplorer] Failed to load git status:",f),l({isGitRepo:!1,files:[]})}finally{r(!1)}}},[s]);return{gitStatus:n,loading:c,loadGitStatus:i}}async function Bn(s){try{const n=await q(K(`/api/files/git-original?path=${encodeURIComponent(s)}`)),l=await n.json();return n.ok&&!l.isNew?{content:l.content,isNew:!1}:{content:null,isNew:!0}}catch(n){return console.error("[FileExplorer] Failed to load original file:",n),{content:null,isNew:!0}}}const _n=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",""]),Vn=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".svg"]),Kn=new Set([".pdf"]),Wn=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 qn(s){const n=s.toLowerCase();return Vn.has(n)?"image":Kn.has(n)?"pdf":Wn.has(n)?"binary":(_n.has(n),"text")}function Jn(){const[s,n]=t.useState(null),[l,c]=t.useState(!1),[r,i]=t.useState(null),f=t.useCallback(async u=>{var g,j;c(!0),i(null);try{const p=u.substring(u.lastIndexOf(".")).toLowerCase(),b=qn(p),C=u.substring(u.lastIndexOf("/")+1);if(b==="image"){const k=await q(K(`/api/files/binary?path=${encodeURIComponent(u)}`));if(!k.ok){const w=await k.json().catch(()=>({error:"Failed to load image"}));i(w.error||"Failed to load image"),n(null);return}const d=await k.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(b==="pdf"){const k=await q(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await k.json();if(!k.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(Vt())}`)});return}if(b==="binary"){const k=await q(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await k.json();if(!k.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(Vt())}`)});return}const P=await q(K(`/api/files/read?path=${encodeURIComponent(u)}`)),x=await P.json();if(!P.ok){if((g=x.error)!=null&&g.includes("too large")||(j=x.error)!=null&&j.includes("binary")){const k=await q(K(`/api/files/info?path=${encodeURIComponent(u)}`)),d=await k.json();if(k.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(Vt())}`)});return}}i(x.error||"Failed to load file"),n(null);return}n({...x,fileType:"text"})}catch(p){const b=p instanceof Error?p.message:"Failed to load file";i(b),n(null)}finally{c(!1)}},[]),o=t.useCallback(()=>{n(u=>(u!=null&&u.dataUrl&&u.dataUrl.startsWith("blob:")&&URL.revokeObjectURL(u.dataUrl),null)),i(null)},[]);return{file:s,loading:l,error:r,loadFile:f,clearFile:o,setFile:n}}const Wt="file-explorer-state",Yn=10080*60*1e3;function Xn(s,n){return n?`${Wt}-folder-${n}`:s?`${Wt}-area-${s}`:`${Wt}-default`}async function Qn(s){try{const n=await q(K(`/api/files/exists?path=${encodeURIComponent(s)}`));return n.ok?(await n.json()).exists===!0:!1}catch{return!1}}function Zn({areaId:s,folderPath:n,isOpen:l}){const c=Xn(s,n),r=t.useRef(!1);t.useEffect(()=>{r.current=!1},[s,n]);const i=t.useCallback(async()=>{if(r.current)return null;r.current=!0;try{const o=localStorage.getItem(c);if(!o)return null;const u=JSON.parse(o);if(Date.now()-u.timestamp>Yn)return localStorage.removeItem(c),null;const j=(await Promise.all(u.tabs.map(async b=>({tab:b,exists:await Qn(b.path)})))).filter(({exists:b})=>b).map(({tab:b})=>b);let p=u.activeTabPath;return p&&!j.some(b=>b.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(o){return console.error("[FileExplorerStorage] Failed to load state:",o),null}},[c]),f=t.useCallback(o=>{if(l)try{const u={tabs:o.tabs,activeTabPath:o.activeTabPath,viewMode:o.viewMode,selectedFolderIndex:o.selectedFolderIndex,expandedPaths:Array.from(o.expandedPaths),timestamp:Date.now()};localStorage.setItem(c,JSON.stringify(u))}catch(u){console.error("[FileExplorerStorage] Failed to save state:",u)}},[c,l]);return{loadStoredState:i,saveState:f}}const Ts=280,Ms=150,Ds=1200;function ea(){const[s,n]=t.useState(()=>{const g=$s(Tt.TREE_PANEL_WIDTH,Ts);return g>=Ms&&g<=Ds?g:Ts}),l=t.useRef(!1),[c,r]=t.useState(!1),i=t.useRef(0),f=t.useRef(0),o=t.useRef(s);o.current=s;const u=t.useCallback(g=>{g.preventDefault(),l.current=!0,r(!0),i.current=g.clientX,f.current=s,document.body.style.cursor="ew-resize",document.body.style.userSelect="none"},[s]);return t.useEffect(()=>{const g=p=>{if(!l.current)return;const b=p.clientX-i.current,C=Math.min(Ds,Math.max(Ms,f.current+b));n(C)},j=()=>{l.current&&(l.current=!1,r(!1),document.body.style.cursor="",document.body.style.userSelect="",Hs(Tt.TREE_PANEL_WIDTH,o.current))};return document.addEventListener("mousemove",g),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",j)}},[]),{treePanelWidth:s,handleResizeStart:u,isResizing:c}}const ta=100,sa=.65,na=36;function aa(){const[s,n]=t.useState(()=>$s(Tt.MOBILE_TREE_PANEL_HEIGHT,0)),l=t.useRef(s);l.current=s;const c=t.useRef(0),r=t.useRef(0),i=()=>Math.floor((window.innerHeight-na)*sa),f=p=>Math.min(i(),Math.max(ta,p)),o=t.useCallback(p=>{n(p);const b=document.querySelector(".file-explorer-main");b&&b.style.setProperty("--fe-mobile-tree-height",`${p}px`)},[]),u=t.useCallback(()=>{document.body.style.cursor="",document.body.style.userSelect="",Hs(Tt.MOBILE_TREE_PANEL_HEIGHT,l.current),mt.setTerminalResizing(!1)},[]),g=t.useCallback(p=>{p.preventDefault();const b=document.querySelector(".file-explorer-tree-panel"),C=l.current>0?l.current:(b==null?void 0:b.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 P=k=>{const d=k.clientY-c.current;o(f(r.current+d))},x=()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",x),u()};document.addEventListener("mousemove",P),document.addEventListener("mouseup",x)},[o,u]),j=t.useCallback(p=>{if(p.touches.length!==1)return;const b=document.querySelector(".file-explorer-tree-panel"),C=l.current>0?l.current:(b==null?void 0:b.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 P=k=>{if(k.touches.length!==1)return;k.preventDefault();const d=k.touches[0].clientY-c.current;o(f(r.current+d))},x=()=>{document.removeEventListener("touchmove",P),document.removeEventListener("touchend",x),document.removeEventListener("touchcancel",x),u()};document.addEventListener("touchmove",P,{passive:!1}),document.addEventListener("touchend",x),document.addEventListener("touchcancel",x)},[o,u]);return{mobileTreeHeight:s,handleResizeMouseDown:g,handleResizeTouchStart:j}}function Qt(){const[s,n]=t.useState([]),[l,c]=t.useState(!1),[r,i]=t.useState(null),[f,o]=t.useState(null),u=t.useCallback(async k=>{c(!0),i(null);try{const d=await q(K(`/api/files/git-branches?path=${encodeURIComponent(k)}`)),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=t.useCallback(async(k,d)=>{o("checkout"),i(null);try{const v=await q(K("/api/files/git-checkout"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k,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{o(null)}},[]),j=t.useCallback(async(k,d,v)=>{o("create"),i(null);try{const w=await q(K("/api/files/git-branch-create"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k,name:d,startPoint:v})}),R=await w.json();return w.ok||i(R.error||"Failed to create branch"),R}catch(w){console.error("[GitBranches] Create branch failed:",w);const R={success:!1,error:"Failed to create branch"};return i(R.error),R}finally{o(null)}},[]),p=t.useCallback(async k=>{o("pull"),i(null);try{const d=await q(K("/api/files/git-pull"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),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{o(null)}},[]),b=t.useCallback(async k=>{o("push"),i(null);try{const d=await q(K("/api/files/git-push"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),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{o(null)}},[]),C=t.useCallback(async(k,d)=>{o("merge"),i(null);try{const v=await q(K("/api/files/git-merge"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k,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{o(null)}},[]),P=t.useCallback(async k=>{o("merge-abort"),i(null);try{const d=await q(K("/api/files/git-merge-abort"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),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{o(null)}},[]),x=t.useCallback(async k=>{o("merge-continue"),i(null);try{const d=await q(K("/api/files/git-merge-continue"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:k})}),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{o(null)}},[]);return{branches:s,loading:l,error:r,operationInProgress:f,loadBranches:u,checkoutBranch:g,createBranch:j,pullFromRemote:p,pushToRemote:b,mergeBranch:C,mergeAbort:P,mergeContinue:x}}const ra=50,ia=400,Rs={branch:"",author:"",since:"",until:"",searchPath:"",search:""};function la(){const[s,n]=t.useState([]),[l,c]=t.useState(!1),[r,i]=t.useState(!1),[f,o]=t.useState(null),[u,g]=t.useState(!1),[j,p]=t.useState(0),[b,C]=t.useState({...Rs}),[P,x]=t.useState(null),[k,d]=t.useState([]),[v,w]=t.useState(!1),[R,z]=t.useState([]),[O,G]=t.useState(!1),H=t.useRef(null),ae=t.useRef(""),ee=t.useCallback((A,Z,L)=>{const S=L||b,W=new URLSearchParams;return W.set("path",A),W.set("limit",String(ra)),W.set("offset",String(Z)),S.branch&&W.set("branch",S.branch),S.author&&W.set("author",S.author),S.since&&W.set("since",S.since),S.until&&W.set("until",S.until),S.searchPath&&W.set("searchPath",S.searchPath),S.search&&W.set("search",S.search),W.toString()},[b]),T=t.useCallback(async A=>{ae.current=A,c(!0),o(null),x(null),d([]);try{const Z=ee(A,0),L=await q(K(`/api/files/git-log?${Z}`)),S=await L.json();L.ok?(n(S.commits||[]),p(S.total||0),g(S.hasMore||!1)):(o(S.error||"Failed to load git history"),n([]))}catch(Z){console.error("[useGitHistory] loadHistory error:",Z),o("Failed to load git history"),n([])}finally{c(!1)}},[ee]),D=t.useCallback(async A=>{if(!(r||!u)){i(!0);try{const Z=ee(A,s.length),L=await q(K(`/api/files/git-log?${Z}`)),S=await L.json();L.ok&&(n(W=>[...W,...S.commits||[]]),p(S.total||0),g(S.hasMore||!1))}catch(Z){console.error("[useGitHistory] loadMore error:",Z)}finally{i(!1)}}},[ee,s.length,u,r]),F=t.useCallback(async A=>{if(x(A),!A){d([]);return}w(!0);try{const Z=ae.current,L=new URLSearchParams({path:Z,hash:A.hash}),S=await q(K(`/api/files/git-commit-files?${L}`)),W=await S.json();S.ok?d(W.files||[]):d([])}catch(Z){console.error("[useGitHistory] selectCommit files error:",Z),d([])}finally{w(!1)}},[]),re=t.useCallback((A,Z)=>{C(L=>({...L,[A]:Z}))},[]),_=t.useCallback(()=>{C({...Rs})},[]);t.useEffect(()=>{const A=ae.current;if(A)return H.current&&clearTimeout(H.current),H.current=setTimeout(()=>{T(A)},ia),()=>{H.current&&clearTimeout(H.current)}},[b]);const ge=t.useCallback(async A=>{G(!0);try{const Z=new URLSearchParams({path:A}),L=await q(K(`/api/files/git-authors?${Z}`)),S=await L.json();L.ok&&z(S.authors||[])}catch(Z){console.error("[useGitHistory] loadAuthors error:",Z)}finally{G(!1)}},[]);return{commits:s,loading:l,loadingMore:r,error:f,hasMore:u,total:j,filters:b,setFilter:re,resetFilters:_,selectedCommit:P,selectCommit:F,commitFiles:k,commitFilesLoading:v,loadHistory:T,loadMore:D,authors:R,authorsLoading:O,loadAuthors:ge}}function oa(s){if(!s.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 l of n){const c=s.current.querySelector(l);if(c&&Fs(c))return c}return Fs(s.current)?s.current:null}function Fs(s){const n=["auto","scroll"].includes(getComputedStyle(s).overflowY),l=s.scrollHeight>s.clientHeight||s.scrollWidth>s.clientWidth;return n&&l}function Bs(s){if(!s)return 19.5;const n=parseFloat(getComputedStyle(s).lineHeight);return isNaN(n)?19.5:n}function qt(s,n=!0){const l=n?s.scrollHeight:0;s.scrollTo({top:l,behavior:"smooth"})}function ca(s){const{scrollTop:n,scrollHeight:l,clientHeight:c}=s;return l<=c?100:Math.round(n/(l-c)*100)}function da(s,n){const l=Bs(s),c=s.scrollTop,r=Math.floor(c/l)+1,i=n.split(`
3
3
  `).length;return Math.min(r,i)}function ua(s,n,l=!1){if(!n)return[];l||s.toLowerCase();const c=l?n:n.toLowerCase(),r=[];let i=0;const f=s.split(`
4
4
  `);let o=0;for(let u=0;u<f.length;u++){const g=f[u],j=l?g:g.toLowerCase();let p=0,b=j.indexOf(c);for(;b!==-1;){const C=o+b;r.push({index:i++,line:u+1,column:b,length:c.length,charIndex:C}),p=b+c.length,b=j.indexOf(c,p)}o+=g.length+1}return r}function lt(s){return/[\w]/.test(s)}function Ae(s){return/\s/.test(s)}function ha(s,n,l){let c=n-1,r=l;const i=s.length,f=s[c]||"";if(r<f.length){const g=lt(f[r]);if(!Ae(f[r]))for(;r<f.length&&!Ae(f[r])&&lt(f[r])===g;)r++}for(;c<i;){const g=s[c]||"";for(;r<g.length&&Ae(g[r]);)r++;if(r<g.length)return{line:c+1,col:r};c++,r=0}const o=i,u=Math.max(0,(s[i-1]||"").length-1);return{line:o,col:u}}function ma(s,n,l){let c=n-1,r=l+1;const i=s.length;for(;c<i;){const u=s[c]||"";for(;r<u.length&&Ae(u[r]);)r++;if(r<u.length)break;c++,r=0}if(c>=i)return{line:i,col:Math.max(0,(s[i-1]||"").length-1)};const f=s[c]||"",o=lt(f[r]);for(;r+1<f.length&&!Ae(f[r+1])&&lt(f[r+1])===o;)r++;return{line:c+1,col:r}}function fa(s,n,l){let c=n-1,r=l-1;for(;c>=0;){const o=s[c]||"";for(;r>=0&&Ae(o[r]);)r--;if(r>=0)break;c--,c>=0&&(r=(s[c]||"").length-1)}if(c<0)return{line:1,col:0};const i=s[c]||"",f=lt(i[r]);for(;r>0&&!Ae(i[r-1])&&lt(i[r-1])===f;)r--;return{line:c+1,col:r}}function pa(s,n,l,c){if(c==="none")return"";const{anchorLine:r,anchorCol:i,headLine:f,headCol:o}=l;if(c==="line"){const C=Math.min(r,f),P=Math.max(r,f);return n.slice(C-1,P).join(`
5
5
  `)}let u,g,j,p;if(r<f||r===f&&i<=o?(u=r,g=i,j=f,p=o):(u=f,g=o,j=r,p=i),u===j)return(n[u-1]||"").substring(g,p+1);const b=[];b.push((n[u-1]||"").substring(g));for(let C=u;C<j-1;C++)b.push(n[C]||"");return b.push((n[j-1]||"").substring(0,p+1)),b.join(`
6
6
  `)}function _s(s){const{containerRef:n,isEnabled:l=!0,content:c="",onClose:r,onSearchOpen:i}=s,f=t.useRef({percentage:0,line:1,column:1}),o=t.useRef(null),u=t.useRef(19.5),g=t.useMemo(()=>c.split(`
7
- `),[c]),j=g.length,[p,b]=t.useState(1),[C,P]=t.useState(0),[x,k]=t.useState(!1),[d,v]=t.useState("none"),[w,R]=t.useState(null),[z,O]=t.useState(!1),[G,H]=t.useState(""),[ae,ee]=t.useState(0),[T,D]=t.useState(!1),F=t.useMemo(()=>ua(c,G,!1),[c,G]),re=t.useCallback(()=>{const m=o.current;if(!m)return;const J=ca(m),ie=da(m,c),V=Math.max(1,Math.round(m.scrollLeft/7.8)+1);f.current={percentage:J,line:ie,column:V}},[c]),_=t.useCallback(()=>{O(!0),H(""),ee(0),i==null||i()},[i]),ge=t.useCallback(()=>{O(!1),H(""),ee(0)},[]),A=t.useCallback(()=>{D(m=>!m)},[]),Z=t.useCallback(m=>{const J=o.current;if(!J)return;const ie=J.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;J.scrollTo({top:Math.max(0,Q-te),behavior:"smooth"})},[]);t.useEffect(()=>{!z||F.length===0||ee(0)},[F,z]),t.useEffect(()=>{if(!z||F.length===0)return;const m=F[ae];m&&(b(m.line),P(m.column),Z(m.line))},[z,F,ae,Z]);const L=t.useCallback(()=>{F.length!==0&&ee(m=>(m+1)%F.length)},[F]),S=t.useCallback(()=>{F.length!==0&&ee(m=>(m-1+F.length)%F.length)},[F]),W=t.useCallback(m=>{const J=o.current;if(!J)return;const ie=J.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=J.scrollTop,U=xe+J.clientHeight;te<xe?J.scrollTo({top:Math.max(0,te),behavior:"auto"}):Ne>U&&J.scrollTo({top:Ne-J.clientHeight,behavior:"auto"})},[]),se=t.useCallback((m,J)=>{b(m),P(J),W(m),d!=="none"&&R(ie=>ie?{...ie,headLine:m,headCol:J}:null)},[d,W]),be=t.useCallback(()=>{if(d==="none"||!w)return;const m=pa(c,g,w,d);m&&navigator.clipboard.writeText(m).catch(()=>{const J=document.createElement("textarea");J.value=m,J.style.position="fixed",J.style.left="-9999px",document.body.appendChild(J),J.select(),document.execCommand("copy"),document.body.removeChild(J)}),v("none"),R(null)},[d,w,c,g]),de=t.useCallback(m=>{const J=m.target;if((J.tagName==="INPUT"||J.tagName==="TEXTAREA")&&m.key!=="Escape")return;const ue=o.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,ne)=>{const pe=Math.max(0,(g[U-1]||"").length-1);return Math.min(ne,Math.max(0,pe))},xe=(U,ne)=>{const pe=Ne(U,ne);se(U,pe)};if(m.key==="v"&&!m.shiftKey&&!m.ctrlKey&&!z)m.preventDefault(),m.stopPropagation(),d==="char"?(v("none"),R(null)):(v("char"),R({anchorLine:p,anchorCol:C,headLine:p,headCol:C})),V=!0;else if(m.key==="V"&&m.shiftKey&&!m.ctrlKey&&!z)m.preventDefault(),m.stopPropagation(),d==="line"?(v("none"),R(null)):(v("line"),R({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"&&!z){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"&&!z){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"&&!z){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"&&!z||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"&&!z)m.preventDefault(),m.stopPropagation(),se(1,0),qt(ue,!1),V=!0;else if(m.key==="Home")m.preventDefault(),m.stopPropagation(),se(1,0),qt(ue,!1),V=!0;else if(m.key==="G"&&m.shiftKey||m.key==="End")m.preventDefault(),m.stopPropagation(),se(j,0),qt(ue,!0),V=!0;else if(m.key==="h"||m.key==="ArrowLeft")m.preventDefault(),m.stopPropagation(),se(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;se(p,Math.min(C+1,Math.max(0,U-1))),V=!0}else if(m.key==="w"&&!m.ctrlKey&&!z){m.preventDefault(),m.stopPropagation();const U=ha(g,p,C);se(U.line,U.col),V=!0}else if(m.key==="e"&&!m.ctrlKey&&!z){m.preventDefault(),m.stopPropagation();const U=ma(g,p,C);se(U.line,U.col),V=!0}else if(m.key==="b"&&!z){m.preventDefault(),m.stopPropagation();const U=fa(g,p,C);se(U.line,U.col),V=!0}else if(m.key==="0")m.preventDefault(),m.stopPropagation(),se(p,0),V=!0;else if(m.key==="$")m.preventDefault(),m.stopPropagation(),se(p,Math.max(0,(g[p-1]||"").length-1)),V=!0;else if(m.key==="^"){m.preventDefault(),m.stopPropagation();const ne=(g[p-1]||"").search(/\S/);se(p,ne>=0?ne:0),V=!0}else m.key==="/"?(m.preventDefault(),m.stopPropagation(),_(),V=!0):m.key==="n"&&!z?(m.preventDefault(),m.stopPropagation(),L(),V=!0):m.key==="N"&&m.shiftKey&&!z?(m.preventDefault(),m.stopPropagation(),S(),V=!0):m.key==="?"&&d==="none"?(m.preventDefault(),m.stopPropagation(),A(),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"),R(null),V=!0):z?(m.preventDefault(),m.stopPropagation(),ge(),V=!0):x&&(m.preventDefault(),m.stopPropagation(),k(!1),V=!0));V&&(m.key!=="Escape"&&!x&&k(!0),requestAnimationFrame(re))},[r,re,j,g,p,C,W,z,ge,d,x,se,be,_,L,S,A]);return t.useEffect(()=>{if(!l)return;const m=oa(n);if(o.current=m,!m){console.warn("[useLessNavigation] Could not find scrollable container");return}u.current=Bs(m);const J=()=>{re()};return window.addEventListener("keydown",de,{capture:!0}),m.addEventListener("scroll",J,{passive:!0}),re(),()=>{window.removeEventListener("keydown",de,{capture:!0}),m.removeEventListener("scroll",J)}},[l,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:z,searchQuery:G,searchMatches:F,currentMatchIndex:ae,startSearch:_,setSearchQuery:H,nextMatch:L,prevMatch:S,clearSearch:ge,helpActive:T,toggleHelp:A}}const Zt=({query:s,onQueryChange:n,matchCount:l,currentIndex:c,onNext:r,onPrev:i,onClose:f})=>{const{t:o}=le(["terminal"]),u=t.useRef(null);t.useEffect(()=>{var p;(p=u.current)==null||p.focus()},[]);const g=t.useCallback(p=>{p.stopPropagation(),p.key==="Enter"||p.key==="ArrowDown"?(p.preventDefault(),r()):p.key==="ArrowUp"&&(p.preventDefault(),i())},[r,i]),j=l===0&&s?o("terminal:fileExplorer.noMatches"):l>0?`${c+1}/${l}`:"";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:o("terminal:fileExplorer.searchInFile"),value:s,onChange:p=>n(p.target.value),onKeyDown:g,autoComplete:"off",spellCheck:"false"})]}),s&&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:l===0,title:o("terminal:fileExplorer.previousMatch"),"aria-label":o("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:l===0,title:o("terminal:fileExplorer.nextMatch"),"aria-label":o("terminal:fileExplorer.nextMatch"),children:e.jsx(M,{name:"caret-down",size:10})})]})]}),e.jsx("button",{className:"file-viewer-search-close",onClick:f,title:o("terminal:fileExplorer.closeSearch"),"aria-label":o("terminal:fileExplorer.closeSearch"),children:e.jsx(M,{name:"close",size:12})})]})};Zt.displayName="SearchBar";const ga=[{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:s})=>{const{t:n}=le(["terminal"]),l=t.useCallback(i=>{i.target===i.currentTarget&&s()},[s]),c=t.useCallback(i=>{(i.key==="Escape"||i.key==="?")&&(i.preventDefault(),i.stopPropagation(),s())},[s]),r=ga.reduce((i,f)=>(i[f.category]||(i[f.category]=[]),i[f.category].push(f),i),{});return e.jsx("div",{className:"keybindings-help-overlay",onClick:l,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:s,"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((o,u)=>e.jsxs("div",{className:"keybindings-help-item",children:[e.jsx("div",{className:"keybindings-help-keys",children:o.keys.map((g,j)=>e.jsx("kbd",{className:"keybindings-help-key",children:g},j))}),e.jsx("div",{className:"keybindings-help-description",children:o.description})]},u))})]},i))}),e.jsx("p",{className:"keybindings-help-footer",children:n("terminal:fileExplorer.keybindingsFooter")})]})})};es.displayName="KeybindingsHelp";const Ps=t.lazy(()=>Dn(()=>import("./EmbeddedEditor-ByRepTwR.js"),__vite__mapDeps([0,1,2,3,4,5])).then(s=>({default:s.EmbeddedEditor}))),xa=[".md",".mdx",".markdown"],Is="file-viewer-markdown-render",ya=[".puml",".plantuml",".iuml",".pu"],Ls="file-viewer-plantuml-render",ba="https://kroki.io/plantuml/svg";function ja(s){return xa.includes(s.toLowerCase())}function va(s){return ya.includes(s.toLowerCase())}function wa(){const[s,n]=t.useState(()=>{try{const c=localStorage.getItem(Is);return c===null?!0:c==="true"}catch{return!0}}),l=t.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Is,String(r))}catch{}return r})},[]);return[s,l]}function Ca(){const[s,n]=t.useState(()=>{try{const c=localStorage.getItem(Ls);return c===null?!0:c==="true"}catch{return!0}}),l=t.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ls,String(r))}catch{}return r})},[]);return[s,l]}function Na(s){const n=new TextEncoder().encode(s);let l="";for(const c of n)l+=String.fromCharCode(c);return`data:image/svg+xml;base64,${window.btoa(l)}`}function Ge({file:s,rightContent:n,onRevealInTree:l,editMode:c,onToggleEdit:r}){const{t:i}=le(["terminal","common"]),[f,o]=t.useState("idle"),u=s.fileType==="text"?Mt(s.extension):s.extension.slice(1).toUpperCase(),{settings:g}=zs(),j=async()=>{o("loading");try{const p=await q(K("/api/files/open-in-editor"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s.path,...g.externalEditorCommand&&{editorCommand:g.externalEditorCommand}})});if(!p.ok){const b=await p.json().catch(()=>({error:"Unknown error"}));console.error("Failed to open in editor:",b),o("error"),setTimeout(()=>o("idle"),2e3);return}o("success"),setTimeout(()=>o("idle"),2e3)}catch(p){console.error("Error opening file in editor:",p),o("error"),setTimeout(()=>o("idle"),2e3)}};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:s.filename}),e.jsxs("span",{className:"file-viewer-meta",children:[Os(s.size)," • ",u,s.content&&` • ${s.content.split(`
7
+ `),[c]),j=g.length,[p,b]=t.useState(1),[C,P]=t.useState(0),[x,k]=t.useState(!1),[d,v]=t.useState("none"),[w,R]=t.useState(null),[z,O]=t.useState(!1),[G,H]=t.useState(""),[ae,ee]=t.useState(0),[T,D]=t.useState(!1),F=t.useMemo(()=>ua(c,G,!1),[c,G]),re=t.useCallback(()=>{const m=o.current;if(!m)return;const J=ca(m),ie=da(m,c),V=Math.max(1,Math.round(m.scrollLeft/7.8)+1);f.current={percentage:J,line:ie,column:V}},[c]),_=t.useCallback(()=>{O(!0),H(""),ee(0),i==null||i()},[i]),ge=t.useCallback(()=>{O(!1),H(""),ee(0)},[]),A=t.useCallback(()=>{D(m=>!m)},[]),Z=t.useCallback(m=>{const J=o.current;if(!J)return;const ie=J.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;J.scrollTo({top:Math.max(0,Q-te),behavior:"smooth"})},[]);t.useEffect(()=>{!z||F.length===0||ee(0)},[F,z]),t.useEffect(()=>{if(!z||F.length===0)return;const m=F[ae];m&&(b(m.line),P(m.column),Z(m.line))},[z,F,ae,Z]);const L=t.useCallback(()=>{F.length!==0&&ee(m=>(m+1)%F.length)},[F]),S=t.useCallback(()=>{F.length!==0&&ee(m=>(m-1+F.length)%F.length)},[F]),W=t.useCallback(m=>{const J=o.current;if(!J)return;const ie=J.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=J.scrollTop,U=xe+J.clientHeight;te<xe?J.scrollTo({top:Math.max(0,te),behavior:"auto"}):Ne>U&&J.scrollTo({top:Ne-J.clientHeight,behavior:"auto"})},[]),se=t.useCallback((m,J)=>{b(m),P(J),W(m),d!=="none"&&R(ie=>ie?{...ie,headLine:m,headCol:J}:null)},[d,W]),be=t.useCallback(()=>{if(d==="none"||!w)return;const m=pa(c,g,w,d);m&&navigator.clipboard.writeText(m).catch(()=>{const J=document.createElement("textarea");J.value=m,J.style.position="fixed",J.style.left="-9999px",document.body.appendChild(J),J.select(),document.execCommand("copy"),document.body.removeChild(J)}),v("none"),R(null)},[d,w,c,g]),de=t.useCallback(m=>{const J=m.target;if((J.tagName==="INPUT"||J.tagName==="TEXTAREA")&&m.key!=="Escape")return;const ue=o.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,ne)=>{const pe=Math.max(0,(g[U-1]||"").length-1);return Math.min(ne,Math.max(0,pe))},xe=(U,ne)=>{const pe=Ne(U,ne);se(U,pe)};if(m.key==="v"&&!m.shiftKey&&!m.ctrlKey&&!z)m.preventDefault(),m.stopPropagation(),d==="char"?(v("none"),R(null)):(v("char"),R({anchorLine:p,anchorCol:C,headLine:p,headCol:C})),V=!0;else if(m.key==="V"&&m.shiftKey&&!m.ctrlKey&&!z)m.preventDefault(),m.stopPropagation(),d==="line"?(v("none"),R(null)):(v("line"),R({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"&&!z){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"&&!z){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"&&!z){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"&&!z||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"&&!z)m.preventDefault(),m.stopPropagation(),se(1,0),qt(ue,!1),V=!0;else if(m.key==="Home")m.preventDefault(),m.stopPropagation(),se(1,0),qt(ue,!1),V=!0;else if(m.key==="G"&&m.shiftKey||m.key==="End")m.preventDefault(),m.stopPropagation(),se(j,0),qt(ue,!0),V=!0;else if(m.key==="h"||m.key==="ArrowLeft")m.preventDefault(),m.stopPropagation(),se(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;se(p,Math.min(C+1,Math.max(0,U-1))),V=!0}else if(m.key==="w"&&!m.ctrlKey&&!z){m.preventDefault(),m.stopPropagation();const U=ha(g,p,C);se(U.line,U.col),V=!0}else if(m.key==="e"&&!m.ctrlKey&&!z){m.preventDefault(),m.stopPropagation();const U=ma(g,p,C);se(U.line,U.col),V=!0}else if(m.key==="b"&&!z){m.preventDefault(),m.stopPropagation();const U=fa(g,p,C);se(U.line,U.col),V=!0}else if(m.key==="0")m.preventDefault(),m.stopPropagation(),se(p,0),V=!0;else if(m.key==="$")m.preventDefault(),m.stopPropagation(),se(p,Math.max(0,(g[p-1]||"").length-1)),V=!0;else if(m.key==="^"){m.preventDefault(),m.stopPropagation();const ne=(g[p-1]||"").search(/\S/);se(p,ne>=0?ne:0),V=!0}else m.key==="/"?(m.preventDefault(),m.stopPropagation(),_(),V=!0):m.key==="n"&&!z?(m.preventDefault(),m.stopPropagation(),L(),V=!0):m.key==="N"&&m.shiftKey&&!z?(m.preventDefault(),m.stopPropagation(),S(),V=!0):m.key==="?"&&d==="none"?(m.preventDefault(),m.stopPropagation(),A(),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"),R(null),V=!0):z?(m.preventDefault(),m.stopPropagation(),ge(),V=!0):x&&(m.preventDefault(),m.stopPropagation(),k(!1),V=!0));V&&(m.key!=="Escape"&&!x&&k(!0),requestAnimationFrame(re))},[r,re,j,g,p,C,W,z,ge,d,x,se,be,_,L,S,A]);return t.useEffect(()=>{if(!l)return;const m=oa(n);if(o.current=m,!m){console.warn("[useLessNavigation] Could not find scrollable container");return}u.current=Bs(m);const J=()=>{re()};return window.addEventListener("keydown",de,{capture:!0}),m.addEventListener("scroll",J,{passive:!0}),re(),()=>{window.removeEventListener("keydown",de,{capture:!0}),m.removeEventListener("scroll",J)}},[l,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:z,searchQuery:G,searchMatches:F,currentMatchIndex:ae,startSearch:_,setSearchQuery:H,nextMatch:L,prevMatch:S,clearSearch:ge,helpActive:T,toggleHelp:A}}const Zt=({query:s,onQueryChange:n,matchCount:l,currentIndex:c,onNext:r,onPrev:i,onClose:f})=>{const{t:o}=le(["terminal"]),u=t.useRef(null);t.useEffect(()=>{var p;(p=u.current)==null||p.focus()},[]);const g=t.useCallback(p=>{p.stopPropagation(),p.key==="Enter"||p.key==="ArrowDown"?(p.preventDefault(),r()):p.key==="ArrowUp"&&(p.preventDefault(),i())},[r,i]),j=l===0&&s?o("terminal:fileExplorer.noMatches"):l>0?`${c+1}/${l}`:"";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:o("terminal:fileExplorer.searchInFile"),value:s,onChange:p=>n(p.target.value),onKeyDown:g,autoComplete:"off",spellCheck:"false"})]}),s&&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:l===0,title:o("terminal:fileExplorer.previousMatch"),"aria-label":o("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:l===0,title:o("terminal:fileExplorer.nextMatch"),"aria-label":o("terminal:fileExplorer.nextMatch"),children:e.jsx(M,{name:"caret-down",size:10})})]})]}),e.jsx("button",{className:"file-viewer-search-close",onClick:f,title:o("terminal:fileExplorer.closeSearch"),"aria-label":o("terminal:fileExplorer.closeSearch"),children:e.jsx(M,{name:"close",size:12})})]})};Zt.displayName="SearchBar";const ga=[{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:s})=>{const{t:n}=le(["terminal"]),l=t.useCallback(i=>{i.target===i.currentTarget&&s()},[s]),c=t.useCallback(i=>{(i.key==="Escape"||i.key==="?")&&(i.preventDefault(),i.stopPropagation(),s())},[s]),r=ga.reduce((i,f)=>(i[f.category]||(i[f.category]=[]),i[f.category].push(f),i),{});return e.jsx("div",{className:"keybindings-help-overlay",onClick:l,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:s,"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((o,u)=>e.jsxs("div",{className:"keybindings-help-item",children:[e.jsx("div",{className:"keybindings-help-keys",children:o.keys.map((g,j)=>e.jsx("kbd",{className:"keybindings-help-key",children:g},j))}),e.jsx("div",{className:"keybindings-help-description",children:o.description})]},u))})]},i))}),e.jsx("p",{className:"keybindings-help-footer",children:n("terminal:fileExplorer.keybindingsFooter")})]})})};es.displayName="KeybindingsHelp";const Ps=t.lazy(()=>Dn(()=>import("./EmbeddedEditor-DP1jqsT_.js"),__vite__mapDeps([0,1,2,3,4,5])).then(s=>({default:s.EmbeddedEditor}))),xa=[".md",".mdx",".markdown"],Is="file-viewer-markdown-render",ya=[".puml",".plantuml",".iuml",".pu"],Ls="file-viewer-plantuml-render",ba="https://kroki.io/plantuml/svg";function ja(s){return xa.includes(s.toLowerCase())}function va(s){return ya.includes(s.toLowerCase())}function wa(){const[s,n]=t.useState(()=>{try{const c=localStorage.getItem(Is);return c===null?!0:c==="true"}catch{return!0}}),l=t.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Is,String(r))}catch{}return r})},[]);return[s,l]}function Ca(){const[s,n]=t.useState(()=>{try{const c=localStorage.getItem(Ls);return c===null?!0:c==="true"}catch{return!0}}),l=t.useCallback(()=>{n(c=>{const r=!c;try{localStorage.setItem(Ls,String(r))}catch{}return r})},[]);return[s,l]}function Na(s){const n=new TextEncoder().encode(s);let l="";for(const c of n)l+=String.fromCharCode(c);return`data:image/svg+xml;base64,${window.btoa(l)}`}function Ge({file:s,rightContent:n,onRevealInTree:l,editMode:c,onToggleEdit:r}){const{t:i}=le(["terminal","common"]),[f,o]=t.useState("idle"),u=s.fileType==="text"?Mt(s.extension):s.extension.slice(1).toUpperCase(),{settings:g}=zs(),j=async()=>{o("loading");try{const p=await q(K("/api/files/open-in-editor"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s.path,...g.externalEditorCommand&&{editorCommand:g.externalEditorCommand}})});if(!p.ok){const b=await p.json().catch(()=>({error:"Unknown error"}));console.error("Failed to open in editor:",b),o("error"),setTimeout(()=>o("idle"),2e3);return}o("success"),setTimeout(()=>o("idle"),2e3)}catch(p){console.error("Error opening file in editor:",p),o("error"),setTimeout(()=>o("idle"),2e3)}};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:s.filename}),e.jsxs("span",{className:"file-viewer-meta",children:[Os(s.size)," • ",u,s.content&&` • ${s.content.split(`
8
8
  `).length} lines`]})]}),e.jsxs("div",{className:"file-viewer-header-right",children:[r&&s.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"})})}),e.jsx("button",{className:`file-viewer-open-editor-btn ${f}`,onClick:j,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"})})}),l&&e.jsx("button",{className:"file-viewer-locate-btn",onClick:()=>l(s.path),title:i("terminal:fileExplorer.locateInTree"),children:e.jsx(M,{name:"target",size:14})}),n]})]})}function ka({file:s,onRevealInTree:n,renderMarkdown:l,onToggleRender:c,editMode:r,onToggleEdit:i}){const f=t.useRef(null),o=t.useRef(null),u=t.useRef(null),{t:g}=le(["terminal","common"]),[j,p]=t.useState("idle"),[b,C]=t.useState("idle"),[P,x]=t.useState("idle"),[k,d]=t.useState("idle"),v=_s({containerRef:u,isEnabled:!0,content:s.content});t.useEffect(()=>{if(!l&&f.current){const H=Mt(s.extension);As(H).then(()=>{f.current&&Gs(f.current)})}},[s,l]);const w=t.useCallback(async()=>{if(!o.current){p("error"),setTimeout(()=>p("idle"),2e3);return}try{const H=o.current.innerHTML,ae=Rn(H),ee=o.current.innerText;await Fn(ae,ee),p("copied"),setTimeout(()=>p("idle"),2e3)}catch{p("error"),setTimeout(()=>p("idle"),2e3)}},[]),R=t.useCallback(async()=>{if(!o.current){C("error"),setTimeout(()=>C("idle"),2e3);return}try{const H=o.current.innerHTML;await Kt(H),C("copied"),setTimeout(()=>C("idle"),2e3)}catch{C("error"),setTimeout(()=>C("idle"),2e3)}},[]),z=t.useCallback(async()=>{try{await Kt(s.content),x("copied"),setTimeout(()=>x("idle"),2e3)}catch{x("error"),setTimeout(()=>x("idle"),2e3)}},[s.content]),O=t.useCallback(async()=>{try{await Kt(s.content),d("copied"),setTimeout(()=>d("idle"),2e3)}catch{d("error"),setTimeout(()=>d("idle"),2e3)}},[s.content]),G=e.jsxs("div",{className:"file-viewer-header-buttons",children:[l&&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 ${b}`,onClick:R,title:g("terminal:fileExplorer.copyHtmlTitle"),children:g(b==="copied"?"terminal:fileExplorer.copied":b==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyHtml")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${P}`,onClick:z,title:g("terminal:fileExplorer.copyMarkdownTitle"),children:g(P==="copied"?"terminal:fileExplorer.copied":P==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyMarkdown")}),e.jsx("button",{className:`file-viewer-copy-html-btn ${k}`,onClick:O,title:g("terminal:fileExplorer.copyOriginalTitle"),children:g(k==="copied"?"terminal:fileExplorer.copied":k==="error"?"terminal:fileExplorer.copyError":"terminal:fileExplorer.copyOriginal")})]}),e.jsx("button",{className:`file-viewer-render-toggle ${l?"active":""}`,onClick:c,title:g(l?"terminal:fileExplorer.showSource":"terminal:fileExplorer.renderMarkdown"),children:l?"</>":"Aa"})]});return e.jsxs(e.Fragment,{children:[e.jsx(Ge,{file:s,onRevealInTree:n,rightContent:G,editMode:r,onToggleEdit:i}),e.jsxs("div",{className:"file-viewer-content-wrapper",ref:u,children:[l?e.jsx("div",{className:"file-viewer-markdown-wrapper",children:e.jsx("div",{className:"markdown-content",ref:o,children:e.jsx(Pn,{remarkPlugins:[In],children:s.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:s.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 Ea({file:s,onRevealInTree:n,renderPlantUml:l,onToggleRender:c,editMode:r,onToggleEdit:i}){const{t:f}=le(["terminal"]),o=t.useRef(null),u=t.useRef(null),[g,j]=t.useState(null),[p,b]=t.useState(!1),[C,P]=t.useState(null),x=_s({containerRef:u,isEnabled:!0,content:s.content});t.useEffect(()=>{if(!l&&o.current){const d=Mt(s.extension);As(d).then(()=>{o.current&&Gs(o.current)})}},[s,l]),t.useEffect(()=>{if(!l)return;if(!s.content.trim()){j(null),P("Diagram is empty");return}const d=new AbortController;return b(!0),P(null),(async()=>{try{const w=await fetch(ba,{method:"POST",headers:{"Content-Type":"text/plain; charset=utf-8",Accept:"image/svg+xml"},body:s.content,signal:d.signal});if(!w.ok)throw new Error(`Render failed (${w.status})`);const R=await w.text();if(!R.includes("<svg"))throw new Error("Invalid SVG output");j(Na(R))}catch(w){if(d.signal.aborted)return;const R=w instanceof Error?w.message:"Failed to render diagram";P(R),j(null)}finally{d.signal.aborted||b(!1)}})(),()=>d.abort()},[s.path,s.content,l]);const k=e.jsx("div",{className:"file-viewer-header-buttons",children:e.jsx("button",{className:`file-viewer-render-toggle ${l?"active":""}`,onClick:c,title:f(l?"terminal:fileExplorer.showSource":"terminal:fileExplorer.renderDiagram"),children:l?"</>":f("terminal:fileExplorer.diagram")})});return e.jsxs(e.Fragment,{children:[e.jsx(Ge,{file:s,onRevealInTree:n,rightContent:k,editMode:r,onToggleEdit:i}),e.jsxs("div",{className:"file-viewer-content-wrapper",ref:u,children:[l?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:s.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:o,className:"language-plaintext",children:s.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 Sa({file:s,onRevealInTree:n}){const{t:l}=le(["common","terminal"]),c=()=>{if(s.dataUrl){const r=document.createElement("a");r.href=s.dataUrl,r.download=s.filename,r.click()}};return e.jsxs(e.Fragment,{children:[e.jsx(Ge,{file:s,onRevealInTree:n,rightContent:e.jsx("button",{className:"file-viewer-download-btn",onClick:c,title:l("common:buttons.download"),children:l("common:buttons.download")})}),e.jsx("div",{className:"file-viewer-image-wrapper",children:s.dataUrl?e.jsx("img",{src:s.dataUrl,alt:s.filename,className:"file-viewer-image"}):e.jsx("div",{className:"file-viewer-placeholder",children:l("terminal:fileExplorer.failedToLoadImage")})})]})}function Ta({file:s,onRevealInTree:n}){const{t:l}=le(["common","terminal"]),c=()=>{if(s.dataUrl){const r=document.createElement("a");r.href=s.dataUrl,r.download=s.filename,r.click()}};return e.jsxs(e.Fragment,{children:[e.jsx(Ge,{file:s,onRevealInTree:n,rightContent:e.jsx("button",{className:"file-viewer-download-btn",onClick:c,title:l("common:buttons.download"),children:l("common:buttons.download")})}),e.jsx("div",{className:"file-viewer-pdf-wrapper",children:s.dataUrl?e.jsx("iframe",{src:s.dataUrl,title:s.filename,className:"file-viewer-pdf"}):e.jsx("div",{className:"file-viewer-placeholder",children:l("terminal:fileExplorer.failedToLoadPdf")})})]})}function Ma({file:s,onRevealInTree:n}){const{t:l}=le(["terminal","common"]),c=()=>{if(s.dataUrl){const i=document.createElement("a");i.href=s.dataUrl,i.download=s.filename,i.click()}},r=()=>{const i=s.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(Ge,{file:s,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:s.filename}),e.jsx("div",{className:"file-viewer-binary-size",children:Os(s.size)}),e.jsx("div",{className:"file-viewer-binary-message",children:l("terminal:fileExplorer.cannotPreview")}),e.jsx("button",{className:"file-viewer-download-btn large",onClick:c,children:l("terminal:fileExplorer.downloadFile")})]})]})}function Da({file:s,loading:n,error:l,onRevealInTree:c,onFileEdited:r}){const{t:i}=le(["terminal","common"]),[f,o]=wa(),[u,g]=Ca(),[j,p]=t.useState(!1);t.useEffect(()=>{p(!1)},[s==null?void 0:s.path]);const b=t.useCallback(async w=>{if(!s)return;const R=await q(K("/api/files/write"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s.path,content:w})});if(!R.ok){const z=await R.json().catch(()=>({error:"Save failed"}));throw new Error(z.error||"Save failed")}},[s]),C=t.useCallback(()=>{p(w=>(w&&s&&(r==null||r(s.path)),!w))},[s,r]),P=t.useCallback(()=>{s&&(r==null||r(s.path))},[s,r]);if(n)return e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")});if(l)return e.jsx("div",{className:"file-viewer-placeholder error",children:l});if(!s)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=s.fileType||"text",k=x==="text"&&ja(s.extension),d=x==="text"&&va(s.extension),v=k||d;return v&&j&&s.content!=null?e.jsxs("div",{className:"file-viewer-content",children:[e.jsx(Ge,{file:s,onRevealInTree:c,editMode:!0,onToggleEdit:C}),e.jsx(t.Suspense,{fallback:e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")}),children:e.jsx(Ps,{content:s.content,extension:s.extension,onSave:b,onCancel:C},s.path)})]}):x==="text"&&!v&&s.content!=null?e.jsxs("div",{className:"file-viewer-content",children:[e.jsx(Ge,{file:s,onRevealInTree:c}),e.jsx(t.Suspense,{fallback:e.jsx("div",{className:"file-viewer-placeholder",children:i("common:status.loading")}),children:e.jsx(Ps,{content:s.content,extension:s.extension,onSave:b,onCancel:P},s.path)})]}):e.jsxs("div",{className:"file-viewer-content",children:[k&&e.jsx(ka,{file:s,onRevealInTree:c,renderMarkdown:f,onToggleRender:o,editMode:j,onToggleEdit:C}),d&&!k&&e.jsx(Ea,{file:s,onRevealInTree:c,renderPlantUml:u,onToggleRender:g,editMode:j,onToggleEdit:C}),x==="image"&&e.jsx(Sa,{file:s,onRevealInTree:c}),x==="pdf"&&e.jsx(Ta,{file:s,onRevealInTree:c}),x==="binary"&&e.jsx(Ma,{file:s,onRevealInTree:c})]})}const Vs=t.memo(Da,(s,n)=>s.loading!==n.loading||s.error!==n.error?!1:s.file===null&&n.file===null?!0:s.file===null||n.file===null?!1:s.file.path===n.file.path&&s.file.content===n.file.content&&s.file.modified===n.file.modified);Vs.displayName="FileViewer";function Ks({text:s,query:n}){if(!n)return e.jsx(e.Fragment,{children:s});const l=Ln(s,n);if(l)return e.jsxs(e.Fragment,{children:[s.slice(0,l.start),e.jsx("mark",{className:"search-highlight",children:s.slice(l.start,l.end)}),s.slice(l.end)]});const c=n.toLowerCase(),i=s.toLowerCase().indexOf(c);return i===-1?e.jsx(e.Fragment,{children:s}):e.jsxs(e.Fragment,{children:[s.slice(0,i),e.jsx("mark",{className:"search-highlight",children:s.slice(i,i+n.length)}),s.slice(i+n.length)]})}const Ra=t.memo(function({node:n,query:l,isSelected:c,onSelect:r,lineNumber:i}){const f=n.isDirectory?null:Xt(n),o=n.path.split("/");o[o.length-1];const u=o.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:l}),i&&e.jsxs("span",{className:"search-result-line-badge",children:[":",i]})]}),e.jsx("span",{className:"search-result-path",children:u})]})]})}),Fa=t.memo(function({match:n,query:l,isSelected:c,onSelect:r}){const{t:i}=le(["terminal"]),f={name:n.name,path:n.path,isDirectory:!1,extension:n.extension},o=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:[o?e.jsx("span",{className:"content-search-icon",style:{backgroundImage:`url('${o}')`},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,b)=>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:l})})]},`${n.path}-${p.line}-${b}`)),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 Pa({filenameResults:s,contentResults:n,onSelectFile:l,onSelectContent:c,selectedPath:r,query:i,lineNumber:f}){const{t:o}=le(["terminal"]),u=s.length>0,g=n.length>0;return!u&&!g?e.jsx("div",{className:"search-no-results",children:o("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:o("terminal:fileExplorer.files")}),e.jsx("span",{className:"unified-search-section-count",children:s.length})]}),e.jsx("div",{className:"unified-search-section-content",children:s.map(j=>e.jsx(Ra,{node:j,query:i,isSelected:r===j.path,onSelect:l,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:o("terminal:fileExplorer.content")}),e.jsx("span",{className:"unified-search-section-count",children:o("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(Fa,{match:j,query:i,isSelected:r===j.path,onSelect:c},j.path))})]})]})}const Ws=t.memo(Pa,(s,n)=>!(s.query!==n.query||s.selectedPath!==n.selectedPath||s.filenameResults.length!==n.filenameResults.length||s.contentResults.length!==n.contentResults.length));Ws.displayName="UnifiedSearchResults";const Ia=t.memo(function({file:n,isSelected:l,onSelect:c,onStage:r,isStaging:i,showDirPath:f,isChecked:o,onToggleCheck:u,onContextMenu:g,onDiscard:j}){const{t:p}=le(["terminal"]),b=n.status,C=pt[b],P=b==="deleted",x=b==="untracked"&&r,k=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 ${l?"selected":""}`,onClick:()=>!P&&c(n.path,b),onContextMenu:v=>{v.preventDefault(),g==null||g(v,n,b)},style:{cursor:P?"not-allowed":"pointer"},title:n.path,children:[u&&e.jsx("input",{type:"checkbox",className:"git-file-checkbox",checked:o||!1,onChange:v=>{v.stopPropagation(),u(n.path)},onClick:v=>v.stopPropagation()}),e.jsx("img",{className:"tree-icon",src:ft(k),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,b)},title:b==="untracked"||b==="added"?"Delete file":"Discard changes",children:e.jsx(M,{name:"revert",size:12})})]})}),La=16,$a=22,Ha=t.memo(function s({node:n,depth:l,expandedDirs:c,onToggleDir:r,selectedPath:i,onSelect:f,onStage:o,stagingPaths:u,checkedFiles:g,onToggleCheck:j,onContextMenu:p,onDirContextMenu:b,onDiscard:C}){const{t:P}=le(["terminal"]),x=l*La;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+$a}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"&&o&&e.jsx("button",{className:`git-stage-btn ${u!=null&&u.has(n.path)?"staging":""}`,onClick:w=>{w.stopPropagation(),u!=null&&u.has(n.path)||o(n.file.path)},title:P("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 k=c.has(n.path);return e.jsxs("div",{className:"tree-node-wrapper",children:[e.jsxs("div",{className:`tree-node directory ${k?"expanded":""}`,style:{paddingLeft:`${x}px`},onClick:()=>r(n.path),onContextMenu:d=>{d.preventDefault(),d.stopPropagation(),b==null||b(d,n)},children:[e.jsx("span",{className:`tree-arrow ${k?"expanded":""}`,children:e.jsx(M,{name:"caret-right",size:10})}),e.jsx("img",{className:"tree-folder-icon",src:k?"/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:P("terminal:fileExplorer.fileCount",{count:n.fileCount})})]}),k&&e.jsx("div",{className:"tree-children",children:n.children.map(d=>e.jsx(s,{node:d,depth:l+1,expandedDirs:c,onToggleDir:r,selectedPath:i,onSelect:f,onStage:o,stagingPaths:u,checkedFiles:g,onToggleCheck:j,onContextMenu:p,onDirContextMenu:b,onDiscard:C},d.path))})]})}),Jt=t.memo(function({groupLabel:n,groupIcon:l,groupColor:c,files:r,treeNodes:i,viewMode:f,selectedPath:o,expandedDirs:u,onToggleDir:g,onFileSelect:j,onStageFile:p,onStageAll:b,stagingPaths:C,checkedFiles:P,onToggleCheck:x,onContextMenu:k,onDirContextMenu:d,onDiscardFile:v,onDiscardAll:w}){const{t:R}=le(["terminal"]);if(r.length===0)return null;const z=r.some(H=>H.status==="untracked"),O=z&&b&&r.length>0,G=C?r.every(H=>C.has(H.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:l}),n," (",r.length,")",O&&e.jsx("button",{className:`git-stage-all-btn ${G?"staging":""}`,onClick:H=>{H.stopPropagation(),G||b()},title:R("terminal:fileExplorer.stageAllUntracked"),disabled:G,children:G?"...":R("terminal:fileExplorer.stageAll")}),w&&e.jsxs("button",{className:"git-discard-all-btn",onClick:H=>{H.stopPropagation(),w()},title:z?`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(H=>e.jsx(Ha,{node:H,depth:0,expandedDirs:u,onToggleDir:g,selectedPath:o,onSelect:j,onStage:p,stagingPaths:C,checkedFiles:P,onToggleCheck:x,onContextMenu:k,onDirContextMenu:d,onDiscard:v},H.path))}):e.jsx("div",{className:"git-flat-content",children:r.map(H=>e.jsx(Ia,{file:H,isSelected:o===H.path,onSelect:j,onStage:H.status==="untracked"?p:void 0,isStaging:C==null?void 0:C.has(H.path),showDirPath:!0,isChecked:P==null?void 0:P.has(H.path),onToggleCheck:x,onContextMenu:k,onDiscard:v},H.path))})]})});function za({gitStatus:s,loading:n,onFileSelect:l,selectedPath:c,onRefresh:r,onStageFiles:i,stagingPaths:f,currentFolder:o,onCommitComplete:u,mergeInProgress:g,mergingBranch:j,onMergeContinue:p,onMergeAbort:b,onConflictOpen:C,onRevealInTree:P}){const{t:x}=le(["terminal","common"]),[k,d]=t.useState("tree"),[v,w]=t.useState(new Set),[R,z]=t.useState(""),[O,G]=t.useState(""),[H,ae]=t.useState(!1),[ee,T]=t.useState(new Set),[D,F]=t.useState(!1),[re,_]=t.useState(null),ge=t.useRef(null),{showToast:A}=Us(),[Z,L]=t.useState(null),[S,W]=t.useState(null),[se,be]=t.useState(null),de=t.useCallback((N,I)=>{be({files:[N],label:N.name})},[]),m=t.useCallback(async()=>{if(!(!se||!o))try{const N=await q(K("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:se.files.map(B=>({path:B.path,status:B.status})),directory:o})}),I=await N.json();N.ok&&I.success?(A("success","Discarded",`Reverted ${se.files.length} file(s)`),r()):A("error","Discard Failed",I.error||"Could not discard changes")}catch{A("error","Discard Failed","Network error")}finally{be(null)}},[se,o,r,A]),J=t.useCallback((N,I,B)=>{N.preventDefault(),N.stopPropagation(),L({isOpen:!0,position:{x:N.clientX,y:N.clientY},file:I,status:B})},[]),ie=t.useCallback(async(N,I)=>{if(o)try{const B=await q(K("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:[{path:N.path,status:I}],directory:o})}),ke=await B.json();B.ok&&ke.success?(A("success","Discarded",`Restored ${N.name}`),r()):A("error","Discard Failed",ke.error||"Could not discard changes")}catch{A("error","Discard Failed","Network error")}},[o,r,A]),ue=t.useCallback(async N=>{try{await navigator.clipboard.writeText(N),A("success","Copied","Full path copied")}catch{A("error","Copy Failed","Could not copy path")}},[A]),V=t.useCallback(async N=>{const I=o&&N.startsWith(o+"/")?N.slice(o.length+1):N;try{await navigator.clipboard.writeText(I),A("success","Copied","Relative path copied")}catch{A("error","Copy Failed","Could not copy path")}},[o,A]),E=t.useMemo(()=>{if(!Z)return[];const{file:N,status:I}=Z,B=[];return I==="conflict"&&C?B.push({id:"open-conflict",label:x("terminal:fileExplorer.gitContextMenu.openConflictResolver"),icon:e.jsx(M,{name:"warn",size:14}),onClick:()=>C(N.path)}):I!=="deleted"&&B.push({id:"open-file",label:x("terminal:fileExplorer.gitContextMenu.openFile"),icon:e.jsx(M,{name:"file-text",size:14}),onClick:()=>l(N.path,I)}),I!=="conflict"&&B.push({id:"stage-file",label:x("terminal:fileExplorer.gitContextMenu.stageFile"),icon:e.jsx(M,{name:"plus",size:14}),onClick:()=>{i([N.path])}}),B.push({id:"divider-1",label:"",divider:!0,onClick:()=>{}}),(I==="modified"||I==="deleted"||I==="renamed"||I==="conflict")&&B.push({id:"discard-changes",label:x("terminal:fileExplorer.gitContextMenu.discardChanges"),icon:e.jsx(M,{name:"revert",size:14}),danger:!0,onClick:()=>{ie(N,I)}}),(I==="untracked"||I==="added")&&B.push({id:"delete-file",label:x("terminal:fileExplorer.gitContextMenu.deleteFile"),icon:e.jsx(M,{name:"trash",size:14}),danger:!0,onClick:()=>{ie(N,I)}}),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(N.path)}}),B.push({id:"copy-relative-path",label:x("terminal:fileExplorer.gitContextMenu.copyRelativePath"),icon:e.jsx(M,{name:"clipboard",size:14}),onClick:()=>{V(N.path)}}),P&&I!=="deleted"&&B.push({id:"reveal-in-tree",label:x("terminal:fileExplorer.gitContextMenu.revealInTree"),icon:e.jsx(M,{name:"target",size:14}),onClick:()=>P(N.path)}),B},[Z,l,i,C,P,ie,ue,V,x]),Q=t.useCallback((N,I)=>{N.preventDefault(),N.stopPropagation(),W({isOpen:!0,position:{x:N.clientX,y:N.clientY},node:I})},[]),te=t.useCallback(N=>!N.isDirectory&&N.file?[N.file]:N.children.flatMap(I=>te(I)),[]),Ne=t.useCallback(async N=>{if(!o)return;const I=te(N);if(I.length!==0)try{const B=await q(K("/api/files/git-discard"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:I.map(Te=>({path:Te.path,status:Te.status})),directory:o})}),ke=await B.json();B.ok&&ke.success?(A("success","Discarded",`Reverted ${I.length} file(s) in ${N.name}`),r()):A("error","Discard Failed",ke.error||"Could not discard changes")}catch{A("error","Discard Failed","Network error")}},[o,te,r,A]),xe=t.useMemo(()=>{if(!S)return[];const{node:N}=S,I=te(N);return[{id:"discard-dir",label:`Discard Changes (${I.length} files)`,icon:e.jsx(M,{name:"revert",size:14}),danger:!0,onClick:()=>{Ne(N)}},{id:"stage-dir",label:`Stage All (${I.length} files)`,icon:e.jsx(M,{name:"plus",size:14}),onClick:()=>{i(I.map(B=>B.path))}}]},[S,te,Ne,i]),U=t.useCallback(N=>{w(I=>{const B=new Set(I);return B.has(N)?B.delete(N):B.add(N),B})},[]),{conflictFiles:ne,conflictTree:pe,changesFiles:me,changesTree:Ue,untrackedFiles:Se,untrackedTree:Dt,allDirPaths:$e}=t.useMemo(()=>{if(!s||!s.isGitRepo||s.files.length===0)return{conflictFiles:[],conflictTree:[],changesFiles:[],changesTree:[],untrackedFiles:[],untrackedTree:[],allDirPaths:new Set};const N=new Set,I=s.files.filter(Re=>Re.status==="conflict"),B=Et(I);St(B,N);const ke=s.files.filter(Re=>Re.status==="modified"||Re.status==="added"||Re.status==="deleted"||Re.status==="renamed"),Te=Et(ke);St(Te,N);const ot=s.files.filter(Re=>Re.status==="untracked"),Ke=Et(ot);return St(Ke,N),{conflictFiles:I,conflictTree:B,changesFiles:ke,changesTree:Te,untrackedFiles:ot,untrackedTree:Ke,allDirPaths:N}},[s]);t.useEffect(()=>{w($e)},[$e]),t.useEffect(()=>{s!=null&&s.files&&T(new Set(s.files.map(N=>N.path)))},[s==null?void 0:s.files]);const Rt=t.useCallback(()=>{me.length!==0&&be({files:me,label:`${me.length} changed files`})},[me]),Be=t.useCallback(()=>{Se.length!==0&&be({files:Se,label:`${Se.length} unversioned files`})},[Se]),Ft=t.useCallback(()=>{ne.length!==0&&be({files:ne,label:`${ne.length} conflicted files`})},[ne]),_e=ne.length>0;t.useEffect(()=>{if(re){const N=re.type==="error"?8e3:4e3,I=setTimeout(()=>_(null),N);return()=>clearTimeout(I)}},[re]);const gt=t.useCallback(async()=>{const N=!H;if(ae(N),N&&o){G(R);try{const B=await(await q(K(`/api/files/git-log-message?path=${encodeURIComponent(o)}`))).json();B.message&&z(B.message)}catch{}}else z(O)},[H,o,R,O]),je=t.useCallback(N=>{T(I=>{const B=new Set(I);return B.has(N)?B.delete(N):B.add(N),B})},[]),Pt=t.useCallback(()=>{if(!(s!=null&&s.files))return;const N=s.files.map(B=>B.path),I=N.every(B=>ee.has(B));T(I?new Set:new Set(N))},[s==null?void 0:s.files,ee]),ve=t.useCallback(async N=>{if(!(!o||!R.trim()||ee.size===0||D)){F(!0),_(null);try{const I=await q(K("/api/files/git-commit"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:o,message:R.trim(),amend:H,paths:Array.from(ee)})}),B=await I.json();if(!I.ok||!B.success){_({type:"error",text:B.error||"Commit failed"}),F(!1);return}if(N)try{const ke=await q(K("/api/files/git-push"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:o})}),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")});z(""),G(""),ae(!1),r(),u==null||u()}catch(I){_({type:"error",text:I.message||"Commit failed"})}finally{F(!1)}}},[o,R,H,ee,D,r,u]);if(n)return e.jsx("div",{className:"git-changes-loading",children:x("terminal:fileExplorer.loadingGitStatus")});if(!s||!s.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(s.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:s.branch})})]});const xt=N=>{i([N])},Ve=()=>{const N=Se.map(I=>I.path);N.length>0&&i(N)},De=(N,I)=>{I==="conflict"&&C?C(N):l(N,I)};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})}),s.branch]}),s.counts&&e.jsxs("div",{className:"git-changes-summary",children:[(s.counts.conflict??0)>0&&e.jsxs("span",{className:"git-count conflict",children:[s.counts.conflict,"C"]}),s.counts.modified>0&&e.jsxs("span",{className:"git-count modified",children:[s.counts.modified,"M"]}),s.counts.added>0&&e.jsxs("span",{className:"git-count added",children:[s.counts.added,"A"]}),s.counts.deleted>0&&e.jsxs("span",{className:"git-count deleted",children:[s.counts.deleted,"D"]}),s.counts.untracked>0&&e.jsxs("span",{className:"git-count untracked",children:[s.counts.untracked,"?"]})]}),e.jsxs("div",{className:"git-view-toggle",children:[e.jsx("button",{className:`git-view-toggle-btn ${k==="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 ${k==="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:_e,title:x(_e?"terminal:fileExplorer.resolveAllConflictsFirst":"terminal:fileExplorer.continueMerge"),children:x("terminal:fileExplorer.continue")}),e.jsx("button",{className:"git-merge-abort-btn",onClick:b,title:x("terminal:fileExplorer.abortMerge"),children:x("terminal:fileExplorer.abort")})]})]}),e.jsxs("div",{className:"git-changes-list",children:[e.jsx(Jt,{groupLabel:x("terminal:fileExplorer.gitGroups.conflicts"),groupIcon:"C",groupColor:"#ff5555",files:ne,treeNodes:pe,viewMode:k,selectedPath:c,expandedDirs:v,onToggleDir:U,onFileSelect:De,checkedFiles:ee,onToggleCheck:je,onContextMenu:J,onDirContextMenu:Q,onDiscardFile:de,onDiscardAll:Ft}),e.jsx(Jt,{groupLabel:x("terminal:fileExplorer.gitGroups.changes"),groupIcon:"~",groupColor:"#c89a5a",files:me,treeNodes:Ue,viewMode:k,selectedPath:c,expandedDirs:v,onToggleDir:U,onFileSelect:De,checkedFiles:ee,onToggleCheck:je,onContextMenu:J,onDirContextMenu:Q,onDiscardFile:de,onDiscardAll:Rt}),e.jsx(Jt,{groupLabel:x("terminal:fileExplorer.gitGroups.unversioned"),groupIcon:"?",groupColor:"#6ab8c8",files:Se,treeNodes:Dt,viewMode:k,selectedPath:c,expandedDirs:v,onToggleDir:U,onFileSelect:De,onStageFile:xt,onStageAll:Ve,stagingPaths:f,checkedFiles:ee,onToggleCheck:je,onContextMenu:J,onDirContextMenu:Q,onDiscardFile:de,onDiscardAll:Be})]}),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:H,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:Pt,title:ee.size===s.files.length?x("terminal:fileExplorer.deselectAll"):x("terminal:fileExplorer.selectAll"),children:ee.size===s.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:R,onChange:N=>z(N.target.value),onKeyDown:N=>{(N.metaKey||N.ctrlKey)&&N.key==="Enter"&&(N.preventDefault(),ve(!1)),(N.metaKey||N.ctrlKey)&&N.shiftKey&&N.key==="Enter"&&(N.preventDefault(),ve(!0)),N.stopPropagation()},rows:3,disabled:D}),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:!R.trim()||ee.size===0||D,title:x("terminal:fileExplorer.commitCtrlEnter"),children:x(D?"terminal:fileExplorer.committing":"terminal:fileExplorer.commitAction")}),e.jsx("button",{className:"git-commit-push-btn",onClick:()=>ve(!0),disabled:!R.trim()||ee.size===0||D,title:x("terminal:fileExplorer.commitAndPushCtrlShiftEnter"),children:D?"...":x("terminal:fileExplorer.commitAndPush")})]})]}),Z&&e.jsx(it,{isOpen:Z.isOpen,position:Z.position,worldPosition:{x:0,z:0},actions:E,onClose:()=>L(null)}),S&&e.jsx(it,{isOpen:S.isOpen,position:S.position,worldPosition:{x:0,z:0},actions:xe,onClose:()=>W(null)}),se&&e.jsx("div",{className:"git-discard-confirm-overlay",onClick:()=>be(null),children:e.jsxs("div",{className:"git-discard-confirm",onClick:N=>N.stopPropagation(),children:[e.jsx("p",{children:se.files.some(N=>N.status==="untracked"||N.status==="added")?e.jsxs(e.Fragment,{children:["Delete ",e.jsx("strong",{children:se.label}),"?"]}):e.jsxs(e.Fragment,{children:["Discard changes to ",e.jsx("strong",{children:se.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:se.files.some(N=>N.status==="untracked"||N.status==="added")?"Delete":"Discard"})]})]})})]})}const qs=t.memo(za,(s,n)=>s.loading!==n.loading||s.selectedPath!==n.selectedPath||s.stagingPaths!==n.stagingPaths||s.currentFolder!==n.currentFolder||s.mergeInProgress!==n.mergeInProgress||s.mergingBranch!==n.mergingBranch?!1:s.gitStatus===null&&n.gitStatus===null?!0:!(s.gitStatus===null||n.gitStatus===null||s.gitStatus.isGitRepo!==n.gitStatus.isGitRepo||s.gitStatus.branch!==n.gitStatus.branch||s.gitStatus.files.length!==n.gitStatus.files.length||s.gitStatus.mergeInProgress!==n.gitStatus.mergeInProgress));qs.displayName="GitChanges";const Oa=t.memo(function({tab:n,isActive:l,onSelect:c,onClose:r,onContextMenu:i}){const{t:f}=le(["terminal"]),o={name:n.filename,path:n.path,isDirectory:!1,extension:n.extension},u=t.useCallback(()=>{c(n.path)},[c,n.path]),g=t.useCallback(b=>{b.button===1&&(b.preventDefault(),b.stopPropagation(),r(n.path))},[r,n.path]),j=t.useCallback(b=>{b.preventDefault(),b.stopPropagation(),r(n.path)},[r,n.path]),p=t.useCallback(b=>{b.preventDefault(),b.stopPropagation(),i(b,n)},[i,n]);return e.jsxs("div",{className:`file-tab ${l?"active":""}`,onClick:u,onMouseDown:g,onContextMenu:p,title:n.path,children:[e.jsx("img",{className:"file-tab-icon",src:Xt(o),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 Aa(s){return typeof s.path=="string"&&s.path.startsWith("/")}function Ga({tabs:s,activeTabPath:n,onSelectTab:l,onCloseTab:c,onShowGitHistory:r}){const{t:i}=le(["terminal"]),[f,o]=t.useState(null),u=t.useCallback((p,b)=>{o({isOpen:!0,position:{x:p.clientX,y:p.clientY},tab:b})},[]),g=t.useCallback(()=>o(null),[]),j=t.useMemo(()=>{if(!f)return[];const p=f.tab,b=!!r&&Aa(p);return[{id:"git-history",label:i("terminal:fileExplorer.showGitHistory")??"Show Git History",icon:e.jsx(M,{name:"git-commit",size:14}),disabled:!b,onClick:()=>{b&&r(p.path)}}]},[f,r,i]);return s.length===0?null:e.jsxs("div",{className:"file-tabs-bar",children:[e.jsx("div",{className:"file-tabs-container",children:s.map(p=>e.jsx(Oa,{tab:p,isActive:n===p.path,onSelect:l,onClose:c,onContextMenu:u},p.path))}),f&&e.jsx(it,{isOpen:f.isOpen,position:f.position,worldPosition:{x:0,z:0},actions:j,onClose:g})]})}const Js=t.memo(Ga,(s,n)=>{if(s.activeTabPath!==n.activeTabPath||s.tabs.length!==n.tabs.length||s.onShowGitHistory!==n.onShowGitHistory)return!1;for(let l=0;l<s.tabs.length;l++)if(s.tabs[l].path!==n.tabs[l].path)return!1;return!0});Js.displayName="FileTabs";const Ua=t.memo(function({currentFolder:n,gitStatus:l,onBranchChanged:c,onMerge:r,onCompare:i,onPullConflicts:f}){const{t:o}=le(["terminal","common"]),[u,g]=t.useState(!1),[j,p]=t.useState(""),[b,C]=t.useState(!1),[P,x]=t.useState(""),[k,d]=t.useState(!1),[v,w]=t.useState(null),[R,z]=t.useState(null),O=t.useRef(null),G=t.useRef(null),H=t.useRef(null),{branches:ae,loading:ee,operationInProgress:T,loadBranches:D,checkoutBranch:F,createBranch:re,pullFromRemote:_,pushToRemote:ge}=Qt();t.useEffect(()=>{u&&n&&(D(n),setTimeout(()=>{var E;return(E=G.current)==null?void 0:E.focus()},50)),u||(p(""),C(!1),x(""),w(null))},[u,n,D]),t.useEffect(()=>{if(v){const E=v.type==="error"?8e3:3e3,Q=setTimeout(()=>w(null),E);return()=>clearTimeout(Q)}},[v]),t.useEffect(()=>{b&&setTimeout(()=>{var E;return(E=H.current)==null?void 0:E.focus()},50)},[b]),t.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 A=t.useCallback(async E=>{if(!n||T||E.isCurrent)return;const Q=await F(n,E.name);Q.success?(w({type:"success",text:o("terminal:fileExplorer.switchedToBranch",{branch:Q.branch||E.name})}),c(),D(n)):w({type:"error",text:Q.error||o("terminal:fileExplorer.checkoutFailed")})},[n,T,F,c,D]),Z=t.useCallback(async()=>{if(!n||!P.trim()||T)return;const E=await re(n,P.trim());E.success?(w({type:"success",text:o("terminal:fileExplorer.createdBranch",{branch:E.branch})}),C(!1),x(""),c(),D(n)):w({type:"error",text:E.error||o("terminal:fileExplorer.createBranchFailed")})},[n,P,T,re,c,D]),L=t.useCallback(async()=>{if(!n||T)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:o("terminal:fileExplorer.pullComplete")}),c(),D(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||o("terminal:fileExplorer.pullFailed")})},[n,T,_,c,D,f]),S=t.useCallback(async()=>{if(!n||T)return;const E=await ge(n);E.success?w({type:"success",text:o("terminal:fileExplorer.pushComplete")}):w({type:"error",text:E.error||o("terminal:fileExplorer.pushFailed")})},[n,T,ge]),[W,se]=t.useState(!1),be=t.useCallback(async()=>{if(!(!n||T||W)){se(!0);try{const E=await q(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(),D(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{se(!1)}}},[n,T,W,c,D]),de=(l==null?void 0:l.branch)||"unknown",m=!!T,J=t.useCallback((E,Q)=>{Q.isCurrent||(E.preventDefault(),E.stopPropagation(),z({isOpen:!0,position:{x:E.clientX,y:E.clientY},branch:Q.name}))},[]),ie=t.useMemo(()=>{if(!R)return[];const E=!!T||(l==null?void 0:l.mergeInProgress);return[{id:"compare",label:o("terminal:fileExplorer.showDiffWith",{branch:R.branch}),icon:e.jsx(M,{name:"arrows-horizontal",size:14}),disabled:!!T,onClick:()=>{i==null||i(R.branch),g(!1)}},{id:"merge",label:o("terminal:fileExplorer.mergeInto",{source:R.branch,target:de}),icon:"⤵",disabled:!!E,onClick:()=>{r&&r(R.branch),g(!1)}},{id:"divider-1",label:"",divider:!0,onClick:()=>{}},{id:"checkout",label:o("terminal:fileExplorer.checkoutBranch",{branch:R.branch}),icon:e.jsx(M,{name:"git-branch",size:14}),disabled:!!T,onClick:()=>{const Q=ae.find(te=>te.name===R.branch);Q&&A(Q)}}]},[R,T,l==null?void 0:l.mergeInProgress,de,r,i,ae,A]),ue=t.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=t.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:O,children:[e.jsx("div",{className:"branch-widget-search",children:e.jsx("input",{ref:G,type:"text",className:"branch-widget-search-input",placeholder:o("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:o("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:o(T==="pull"?"terminal:fileExplorer.pulling":"terminal:fileExplorer.pull")})]}),e.jsxs("div",{className:`branch-widget-action-item ${m?"disabled":""}`,onClick:S,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:o(T==="push"?"terminal:fileExplorer.pushing":"terminal:fileExplorer.push")})]}),e.jsxs("div",{className:`branch-widget-action-item ${m?"disabled":""}`,onClick:()=>{m||C(!b)},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:o("terminal:fileExplorer.newBranch")})]})]}),b&&e.jsxs("div",{className:"branch-widget-new-branch",children:[e.jsx("input",{ref:H,type:"text",className:"branch-widget-new-branch-input",placeholder:o("terminal:fileExplorer.branchNamePlaceholder"),value:P,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:!P.trim()||m,children:T==="create"?"...":o("common:buttons.create")})]}),e.jsxs("div",{className:"branch-widget-section-header",children:[o("terminal:fileExplorer.localBranches"),ee&&e.jsxs("span",{className:"branch-widget-loading-hint",children:[" ",o("terminal:fileExplorer.loading")]})]}),e.jsxs("div",{className:"branch-widget-branch-list",children:[ue.length===0&&!ee&&e.jsx("div",{className:"branch-widget-empty",children:o("terminal:fileExplorer.noBranchesFound")}),ue.map(E=>e.jsxs("div",{className:`branch-widget-branch-item ${E.isCurrent?"current":""} ${m?"disabled":""}`,onClick:()=>A(E),onContextMenu:Q=>J(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(!k),children:[e.jsx("span",{className:"branch-widget-section-toggle",children:k?"▾":"▸"}),o("terminal:fileExplorer.remoteBranches",{count:V.length})]}),k&&e.jsx("div",{className:"branch-widget-branch-list",children:V.map(E=>e.jsxs("div",{className:`branch-widget-branch-item remote ${m?"disabled":""}`,onClick:()=>A(E),onContextMenu:Q=>J(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))})]})]}),R&&e.jsx(it,{isOpen:R.isOpen,position:R.position,worldPosition:{x:0,z:0},actions:ie,onClose:()=>z(null)})]})});function Ba(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function kt(s,n){if(!s)return"";const l=Es.languages[n];return l?Es.highlight(s,l,n):Ba(s)}function _a(s){const n=[],l=s.split(`
9
9
  `);let c=[],r=!1,i=[],f=[],o=!1;for(const u of l)u.startsWith("<<<<<<<")?(c.length>0&&(n.push({type:"unchanged",content:c.join(`
10
10
  `)}),c=[]),r=!0,o=!1,i=[],f=[]):u.startsWith("=======")&&r?o=!0:u.startsWith(">>>>>>>")&&r?(n.push({type:"conflict",ours:i.join(`
@@ -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-XbhAPjbi.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:A,onSelectTableQuery:M})=>{const{t:m}=J(["terminal"]),w=Z(a.id),[P,R]=r.useState(new Set),[k,n]=r.useState(""),[d,g]=r.useState(""),[$,q]=r.useState(!1),[U,F]=r.useState(null),K=r.useRef(null),C=r.useRef(null),O=r.useRef(null),N=l?w.databases.get(l)??[]:[],I=l&&c?`${l}:${c}`:"",j=I?w.tables.get(I)??[]:[],p=l?w.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)&&q(!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}`;w.tableSchemas.has(v)||h.getTableSchema(a.id,l,c,t)}return T})},[a.id,l,c,w.tableSchemas]),z=t=>{if(!l||!c)return null;const o=`${l}:${c}:${t}`;return w.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),$||q(!0)},onFocus:()=>{q(!0),n("")},onKeyDown:t=>{var o,T;t.key==="Escape"?(q(!1),n(""),(o=K.current)==null||o.blur()):t.key==="Enter"&&D.length===1&&(S(D[0]),q(!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),q(!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=P.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),M(t.name)},children:t.name}),e.jsx("button",{className:"database-sidebar__table-insert",onClick:v=>{v.stopPropagation(),A(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:()=>A(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),[A,M]=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]),w=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"})},P=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(()=>{M(!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:w(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=>P(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:A,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:()=>M(!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,Y,W,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)),A=r.useRef(null),M=r.useRef(0),m=((B=a.database)==null?void 0:B.connections)??[],w=(s,i)=>`${s}:${i}`,P=s=>s?(S.current.queries??{})[s]??"":S.current.generalQuery??"",[R,k]=r.useState("results"),[n,d]=r.useState(0),[g,$]=r.useState(!1),[q,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(L=>L.id===i.connectionId))==null?void 0:u.name)??i.connectionId,database:i.database}})),[C,O]=r.useState(S.current.activeTabId??null),[N,I]=r.useState(()=>{const s=S.current.queries??{};return S.current.generalQuery,s}),[j,p]=r.useState(P(C)),D=r.useCallback(s=>{p(i=>{const u=typeof s=="function"?s(i):s;return I(L=>{const E={...L};return C&&(E[C]=u),E}),u})},[C]),b=c.activeConnectionId??S.current.connectionId??((Y=a.database)==null?void 0:Y.activeConnectionId)??((W=m[0])==null?void 0:W.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=w(s,i),L=((E=m.find(G=>G.id===s))==null?void 0:E.name)??s;K(G=>{if(G.some(ie=>ie.id===u))return G;const ce={id:u,connectionId:s,connectionName:L,database:i};return[...G,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(!q&&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,q]),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(()=>{q&&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,q,F,C,N]);const te=r.useCallback(s=>{var i;if(!(!b||!_||!j.trim()||Q))if(s==="cursor"){const u=(i=A.current)==null?void 0:i.querySelector(".query-editor__textarea"),L=(u==null?void 0:u.selectionStart)??M.current,E=he(j,L);E&&h.executeQuery(a.id,b,_,E)}else{const u=_e(j);u.length<=1?h.executeQuery(a.id,b,_,j.trim()):u.forEach((L,E)=>{setTimeout(()=>{h.executeQuery(a.id,b,_,L.sql)},E*150)})}},[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:A,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:A,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-B7wf_xU_.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:A,onSelectTableQuery:M})=>{const{t:m}=J(["terminal"]),w=Z(a.id),[P,R]=r.useState(new Set),[k,n]=r.useState(""),[d,g]=r.useState(""),[$,q]=r.useState(!1),[U,F]=r.useState(null),K=r.useRef(null),C=r.useRef(null),O=r.useRef(null),N=l?w.databases.get(l)??[]:[],I=l&&c?`${l}:${c}`:"",j=I?w.tables.get(I)??[]:[],p=l?w.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)&&q(!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}`;w.tableSchemas.has(v)||h.getTableSchema(a.id,l,c,t)}return T})},[a.id,l,c,w.tableSchemas]),z=t=>{if(!l||!c)return null;const o=`${l}:${c}:${t}`;return w.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),$||q(!0)},onFocus:()=>{q(!0),n("")},onKeyDown:t=>{var o,T;t.key==="Escape"?(q(!1),n(""),(o=K.current)==null||o.blur()):t.key==="Enter"&&D.length===1&&(S(D[0]),q(!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),q(!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=P.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),M(t.name)},children:t.name}),e.jsx("button",{className:"database-sidebar__table-insert",onClick:v=>{v.stopPropagation(),A(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:()=>A(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),[A,M]=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]),w=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"})},P=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(()=>{M(!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:w(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=>P(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:A,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:()=>M(!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,Y,W,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)),A=r.useRef(null),M=r.useRef(0),m=((B=a.database)==null?void 0:B.connections)??[],w=(s,i)=>`${s}:${i}`,P=s=>s?(S.current.queries??{})[s]??"":S.current.generalQuery??"",[R,k]=r.useState("results"),[n,d]=r.useState(0),[g,$]=r.useState(!1),[q,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(L=>L.id===i.connectionId))==null?void 0:u.name)??i.connectionId,database:i.database}})),[C,O]=r.useState(S.current.activeTabId??null),[N,I]=r.useState(()=>{const s=S.current.queries??{};return S.current.generalQuery,s}),[j,p]=r.useState(P(C)),D=r.useCallback(s=>{p(i=>{const u=typeof s=="function"?s(i):s;return I(L=>{const E={...L};return C&&(E[C]=u),E}),u})},[C]),b=c.activeConnectionId??S.current.connectionId??((Y=a.database)==null?void 0:Y.activeConnectionId)??((W=m[0])==null?void 0:W.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=w(s,i),L=((E=m.find(G=>G.id===s))==null?void 0:E.name)??s;K(G=>{if(G.some(ie=>ie.id===u))return G;const ce={id:u,connectionId:s,connectionName:L,database:i};return[...G,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(!q&&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,q]),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(()=>{q&&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,q,F,C,N]);const te=r.useCallback(s=>{var i;if(!(!b||!_||!j.trim()||Q))if(s==="cursor"){const u=(i=A.current)==null?void 0:i.querySelector(".query-editor__textarea"),L=(u==null?void 0:u.selectionStart)??M.current,E=he(j,L);E&&h.executeQuery(a.id,b,_,E)}else{const u=_e(j);u.length<=1?h.executeQuery(a.id,b,_,j.trim()):u.forEach((L,E)=>{setTimeout(()=>{h.executeQuery(a.id,b,_,L.sql)},E*150)})}},[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:A,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:A,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};