@pi-chamber/web 0.2.2 → 0.3.1

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 (71) hide show
  1. package/bin/cli.test.js +6 -8
  2. package/bin/lib/cli-tunnel-capabilities.js +0 -2
  3. package/dist/assets/{CommitSection-DPjTv8fA.js → CommitSection-C336377Z.js} +1 -1
  4. package/dist/assets/{DiagramEditor-ChOor9l9.js → DiagramEditor-gHLCXHtr.js} +1 -1
  5. package/dist/assets/{DiagramView-3hAT86v_.js → DiagramView-DlHzRRBc.js} +1 -1
  6. package/dist/assets/{DiffView-D1dyOiw2.js → DiffView-5wHwK-lg.js} +1 -1
  7. package/dist/assets/{FilesView-BCzghrc7.js → FilesView-5bswI3JZ.js} +6 -6
  8. package/dist/assets/{GitView-CYF1E1p4.js → GitView-BfykGpGh.js} +4 -4
  9. package/dist/assets/{JsonTreeView-CrJO6LNu.js → JsonTreeView-HVwQS7qG.js} +1 -1
  10. package/dist/assets/{MarkdownRendererImpl-BmKjrkGD.js → MarkdownRendererImpl-kjd4e0N8.js} +1 -1
  11. package/dist/assets/{PatchDiff-DgvPLx6x.js → PatchDiff-Dlm4RU8n.js} +1 -1
  12. package/dist/assets/{PierreDiffViewer-InnT0JVA.js → PierreDiffViewer-St32rXlD.js} +1 -1
  13. package/dist/assets/{SessionSwitcherDropdown-C0OdvirK.js → SessionSwitcherDropdown-D5bWfZNA.js} +100 -101
  14. package/dist/assets/SettingsView-FGe5TEQq.js +4 -0
  15. package/dist/assets/SettingsWindow-Ck_uhTnx.js +1 -0
  16. package/dist/assets/{ToolOutputDialog-gzwcb8nI.js → ToolOutputDialog-BCONUv3r.js} +5 -5
  17. package/dist/assets/{ToolPartDiffPreview-C45V5bhy.js → ToolPartDiffPreview-BdVuk2kc.js} +1 -1
  18. package/dist/assets/{VirtualizedFileDiff-uKfnkQWb.js → VirtualizedFileDiff-BsAZM0jo.js} +1 -1
  19. package/dist/assets/{collapsible-Bq8sDiKS.js → collapsible-Wnmq-13H.js} +1 -1
  20. package/dist/assets/{computeVirtualFileMetrics-BPgZ_RSe.js → computeVirtualFileMetrics-skbyL2Az.js} +2 -2
  21. package/dist/assets/{contextFileOpenGuard-CydO7PkI.js → contextFileOpenGuard-BsxQITMZ.js} +1 -1
  22. package/dist/assets/index-8TL2HlaR.js +8 -0
  23. package/dist/assets/{index-BSuNNtBh.js → index-Bfp6eYap.js} +1 -1
  24. package/dist/assets/index-riABQmQ_.css +1 -0
  25. package/dist/assets/{isDiffPlainText-f9b4cKNo.js → isDiffPlainText-dZkfk3yG.js} +1 -1
  26. package/dist/assets/{isFilePlainText-BjESb-gU.js → isFilePlainText-UL_tMQZx.js} +1 -1
  27. package/dist/assets/{main-B508FBXr.js → main-CHQfoyRP.js} +2 -2
  28. package/dist/assets/main-DbnYXZeK.js +133 -0
  29. package/dist/assets/{markdownCore-BFmf8a-O.js → markdownCore-qX3mJFkL.js} +2 -2
  30. package/dist/assets/{miniChat-BTlz8IPL.js → miniChat-3QtCNwHl.js} +2 -2
  31. package/dist/assets/{mobile-DBkrRt80.js → mobile-B_CyfRAX.js} +2 -2
  32. package/dist/assets/renderElectronMiniChatApp-OToslrv-.js +1 -0
  33. package/dist/assets/renderMobileApp-BD_wep_I.js +14 -0
  34. package/dist/assets/{runtimeSurface-Bec4O8FD.js → runtimeSurface-CkdOpqo7.js} +1 -1
  35. package/dist/assets/{useInlineCommentController-CHmIm0Rr.js → useInlineCommentController-DVif5Fr8.js} +2 -2
  36. package/dist/assets/usePanelSlide-C_PJmPXW.js +56 -0
  37. package/dist/assets/{useWindowTitle-CE5N_NeU.js → useWindowTitle-BZVlLMCy.js} +3 -3
  38. package/dist/assets/{vendor-base-ui-DwfTg5wD.js → vendor-base-ui-DL8r2fgQ.js} +1 -1
  39. package/dist/assets/{vendor-codemirror-language-data-q1yHU1R9.js → vendor-codemirror-language-data-C-924Z4o.js} +2 -2
  40. package/dist/assets/{vendor-sonner-dWA7qvjr.js → vendor-sonner-CW8w438f.js} +1 -1
  41. package/dist/assets/{web-components-CLirSfwt.js → web-components-BG-6PEN4.js} +1 -1
  42. package/dist/index.html +4 -4
  43. package/dist/mini-chat.html +3 -3
  44. package/dist/mobile.html +3 -3
  45. package/package.json +1 -1
  46. package/server/lib/package-manager.js +0 -34
  47. package/server/lib/pi/routes.js +52 -4
  48. package/server/lib/pi/routes.test.js +14 -6
  49. package/server/lib/pi/session-daemon/DOCUMENTATION.md +4 -3
  50. package/server/lib/pi/session-daemon/message-entry-aliases.js +100 -0
  51. package/server/lib/pi/session-daemon/runtime-registry.js +3 -0
  52. package/server/lib/pi/session-daemon/session-daemon.js +184 -16
  53. package/server/lib/pi/session-daemon/session-daemon.test.js +310 -5
  54. package/server/lib/pi/session-daemon/supervisor.js +20 -1
  55. package/server/lib/pi/session-daemon/supervisor.test.js +43 -0
  56. package/server/lib/tunnels/DOCUMENTATION.md +6 -7
  57. package/server/lib/tunnels/executable-search.test.js +4 -4
  58. package/server/lib/tunnels/install-help.js +0 -10
  59. package/server/lib/tunnels/install-help.test.js +0 -9
  60. package/server/lib/tunnels/types.js +0 -1
  61. package/dist/assets/SettingsView-JAfC_cBL.js +0 -3
  62. package/dist/assets/SettingsWindow-BBEsjcJE.js +0 -1
  63. package/dist/assets/index-CH7o4-_q.js +0 -8
  64. package/dist/assets/index-o4Eea60G.css +0 -1
  65. package/dist/assets/main-nG4uFyAy.js +0 -133
  66. package/dist/assets/renderElectronMiniChatApp-DW3fSR5w.js +0 -1
  67. package/dist/assets/renderMobileApp-9qkroKty.js +0 -14
  68. package/dist/assets/usePanelSlide-DCX8qQ4K.js +0 -56
  69. package/server/lib/ngrok-tunnel.js +0 -343
  70. package/server/lib/ngrok-tunnel.test.js +0 -50
  71. package/server/lib/tunnels/providers/ngrok.js +0 -32
@@ -1,14 +1,14 @@
1
- import{j as t,R as n,b as bo}from"./vendor-react-DYyjh7Q0.js";import{x as wo,y as yo,z as jo,A as No,M as Es,n as Ee,u as ue,bG as ko,a8 as Rs,B as Co,r as zs,H as rn,e as So,bH as Fo,G as Eo,bI as Ro}from"./index-CH7o4-_q.js";import{f as $,Y as vr,B as S,T as Ye,q as Xe,I as v,s as Ze,dB as zo,C as Do,aJ as Po,aV as Mo,E as To,G as Lo,ax as Oo,dC as Ds,t as A,a5 as Ao,V as nn,dy as fr,b1 as Io,dD as sn,W as Ps,dE as Ms,dz as Ts,dA as Bo,dF as $o,dG as Vo,b5 as Wo,dH as Ls,D as da,w as fa,x as ma,y as pa,z as ha,A as ga,as as pn,at as hn,F as hr,au as gn,az as gr,ay as an,X as on,bj as Os,cU as _o,cV as qo,dI as _t,av as br,aw as Ho,aA as Go}from"./SessionSwitcherDropdown-C0OdvirK.js";import{E as mr,p as Ko,q as Uo,t as Jo,v as Yo,w as Xo}from"./usePanelSlide-DCX8qQ4K.js";import{E as Zo,o as ut,k as xn,i as xa,a as Qo,S as ei}from"./vendor-codemirror-state-CNWM3Q8V.js";import{s as ti,d as ri,E as se,e as ni,f as As,k as cn,V as va,D as yr,W as si}from"./vendor-codemirror-view-DSzLbZiS.js";import{h as ai,k as oi,l as ii,j as ci}from"./vendor-codemirror-commands-RrgJ8H_6.js";import{i as li,y as ui,H as Is,x as pr,z as di}from"./vendor-codemirror-language-E2vgV9K3.js";import{a as Bs,g as wr,b as $s,c as Vs,o as fi,d as mi}from"./vendor-codemirror-search-8kyQdB3f.js";import{v as pi,g as hi}from"./vendor-replit-codemirror-vim-BJY5fGLS.js";import{F as gi,J as xi}from"./JsonTreeView-CrJO6LNu.js";import{a as d,c as vi}from"./vendor-lezer-highlight-CDMHUZ74.js";import{ensurePierreThemeRegistered as Ws,getResolvedShikiTheme as bi}from"./appThemeRegistry-BK0dHKa6.js";import{D as wi}from"./DiagramEditor-ChOor9l9.js";import{I as _s,a as yi,u as ji,n as Ni}from"./useInlineCommentController-CHmIm0Rr.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-CnsBKjP5.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./runtimeSurface-Bec4O8FD.js";import"./vendor-dnd-kit-core-GipZW2tY.js";import"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import"./vendor-dnd-kit-accessibility-Cv52zwWT.js";import"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import"./vendor-base-ui-DwfTg5wD.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-sVFnuruh.js";import"./vendor-floating-ui-dom-Bkw82kL9.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-B7OScDIw.js";import"./vendor-cmdk-BCEUzcHE.js";import"./vendor-radix-ui-react-dialog-jX3Dld8c.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-D1GnwnP9.js";import"./vendor-radix-ui-react-context-CM4yFQ2I.js";import"./vendor-radix-ui-react-id-BcxRjnbX.js";import"./vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js";import"./vendor-radix-ui-react-use-controllable-state-C_ecoh35.js";import"./vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js";import"./vendor-radix-ui-react-primitive-CfpW6_IT.js";import"./vendor-radix-ui-react-slot-BxUc3Pvz.js";import"./vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js";import"./vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js";import"./vendor-radix-ui-react-focus-scope-C2K7lNPv.js";import"./vendor-radix-ui-react-portal-xlJWBfDg.js";import"./vendor-radix-ui-react-presence-Btn-Dp7L.js";import"./vendor-radix-ui-react-focus-guards-D5MZ0nQs.js";import"./vendor-react-remove-scroll-CfeMe0DL.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-C9YRs2nU.js";import"./vendor-react-style-singleton-B1H4bWSG.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-C-AuTczP.js";import"./vendor-use-callback-ref-CJB0R85I.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-lang-javascript-BUlYhQ3o.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-codemirror-autocomplete-BS2SpSAZ.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-codemirror-lang-json-CqayksDf.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-Ba8JZ6fp.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-DK27qQri.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-CvO36Y1p.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-q1yHU1R9.js";import"./vendor-codemirror-lang-python-_2bIYTiJ.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-DJASDzNt.js";import"./vendor-motion-dom-DJLgZh4Q.js";import"./vendor-motion-utils-BGh8QBgx.js";import"./vendor-sonner-dWA7qvjr.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./permissionStore-BRcQ9Jgt.js";import"./web-components-CLirSfwt.js";import"./computeVirtualFileMetrics-BPgZ_RSe.js";import"./vendor-shiki-Bbf2GEcE.js";import"./vendor-shikijs-core-CGM_jqPK.js";import"./vendor-shikijs-types-CPSbSeK6.js";import"./vendor-shikijs-vscode-textmate-BgLrS_2D.js";import"./vendor-hast-util-to-html-BKBhbTDb.js";import"./vendor-html-void-elements-CkdplsNl.js";import"./vendor-property-information-rJCbAzvX.js";import"./vendor-zwitch-C2o2j-tx.js";import"./vendor-stringify-entities-CsH1VEn9.js";import"./vendor-character-entities-legacy-BpoLgcEt.js";import"./vendor-character-entities-html4-D7taRCQ7.js";import"./vendor-ccount-c2V3InAJ.js";import"./vendor-comma-separated-tokens-D8TqSuIK.js";import"./vendor-space-separated-tokens-DD3iYX1K.js";import"./vendor-hast-util-whitespace-D4Wp6AEg.js";import"./vendor-shikijs-engine-oniguruma-DPWuIF1G.js";import"./themeResolver-BmJyTmjJ.js";import"./vendor-pierre-theming-C6Z4M5_u.js";import"./vendor-shikijs-engine-javascript-Cme4830A.js";import"./vendor-oniguruma-to-es-DLBnFDCE.js";import"./vendor-oniguruma-parser-C0D4_9rT.js";import"./vendor-regex-BBWcyTkg.js";import"./vendor-regex-utilities-2BQyy0xI.js";import"./vendor-regex-recursion-JU4mF-dD.js";import"./vendor-shikijs-transformers-CZWsLLKm.js";import"./Virtualizer-BxW2CJGB.js";import"./isFilePlainText-BjESb-gU.js";import"./registerCustomTheme-BBXUCRnG.js";import"./vendor-react-drawio-Boqanm0j.js";import"./collapsible-Bq8sDiKS.js";function ki(r){const{drafts:a,editingDraftId:u,commentText:f,onTextChange:x,selection:p,isDragging:b,fileLabel:g,newWidgetId:y,mapDraftToRange:E,onSave:k,onCancel:L,onEdit:M,onDelete:R}=r,P=[];for(const o of a){const G=E(o);if(o.id===u){P.push({afterLine:G.end,id:`edit-${o.id}`,content:t.jsx(_s,{initialText:f,onTextChange:x,fileLabel:g,lineRange:G,isEditing:!0,onSave:k,onCancel:L},`edit-${o.id}`)});continue}P.push({afterLine:G.end,id:`card-${o.id}`,content:t.jsx(yi,{draft:o,onEdit:()=>M(o),onDelete:()=>R(o)},`card-${o.id}`)})}if(p&&!u&&!b){const o={...p,start:Math.min(p.start,p.end),end:Math.max(p.start,p.end)};P.push({afterLine:o.end,id:y,content:t.jsx(_s,{initialText:f,onTextChange:x,fileLabel:g,lineRange:o,isEditing:!1,onSave:k,onCancel:L},y)})}return P}const Ci=r=>r!==null&&typeof r=="object"&&"updateStatus"in r&&typeof r.updateStatus=="function",Si=r=>{const a=document.createElement("div");a.className="cm-vim-panel";const u=hi(r);if(!u)return{top:!1,dom:a};u.state.statusbar=a;const f=u.state.vimPlugin;return Ci(f)&&f.updateStatus(),{top:!1,dom:a,destroy(){u.state.statusbar===a&&(u.state.statusbar=null)}}};function qs(r){return r?[pi(),ti.of(Si),ri()]:[]}const Fi={next:"Next match",prev:"Previous match",select:"Select all matches",replace:"Replace",replaceAll:"Replace all",close:"Close"},Ei={case:"Match case",re:"Regular expression",word:"Match whole word"};function Ri(r){const a=r.querySelector(".cm-search");if(a){for(const[u,f]of Object.entries(Fi)){const x=a.querySelector(`button[name="${u}"]`);x&&!x.title&&(x.title=f)}for(const[u,f]of Object.entries(Ei)){const p=a.querySelector(`input[name="${u}"]`)?.parentElement;p&&!p.title&&(p.title=f)}}}const ln=new WeakMap;function zi(r,a){const u=wr(r.state);if(!u.valid)return ln.delete(r),0;const f=ln.get(r);if(!a&&f?.doc===r.state.doc&&f.query.eq(u))return f.total;const x=u.getCursor(r.state);let p=0;for(let b=x.next();!b.done;b=x.next())p+=1;return ln.set(r,{query:u,doc:r.state.doc,total:p}),p}function Di(r){const a=wr(r.state);if(!a.valid)return 0;const u=r.state.selection.main,f=a.getCursor(r.state);let x=0,p=0;for(let b=f.next();!b.done;b=f.next()){const g=b.value;if(x+=1,p===0&&(p=x),u.from===g.from&&u.to===g.to||u.from<g.to&&u.to>g.from||g.from>=u.head)return x}return p}function Hs(r,a,u=!1){const f=r.querySelector(".cm-search");if(!f)return;let x=f.querySelector(".cm-search-message");if(!x){x=document.createElement("span"),x.className="cm-search-message",x.setAttribute("aria-live","polite");const g=f.querySelector('button[name="next"]'),y=g?.parentNode===f?g:f.firstChild;f.insertBefore(x,y)}const p=zi(a,u),b=p===0?0:Di(a);x.textContent=p===0?"":`${b}/${p}`}const Gs=new ut,Ks=new ut,Us=new ut,Js=new ut,Ys=new ut,Xs=new ut,Zs=new ut,Qs=r=>r,un=ui,Pi=fi,Mi=mi;class Ti extends si{constructor(a,u){super(),this.id=a,this.containerMap=u}toDOM(){let a=this.containerMap.get(this.id);return a||(a=document.createElement("div"),a.className="oc-block-widget",a.dataset.widgetId=this.id,this.containerMap.set(this.id,a)),a}eq(a){return a.id===this.id}destroy(){}}const ea=(r,a)=>!r||r.length===0?[]:xa.define({create(u){const f=new xn,x=[...r].sort((p,b)=>p.afterLine-b.afterLine);for(const p of x){const b=u.doc.lines;if(p.afterLine>b)continue;const g=u.doc.line(p.afterLine);f.add(g.to,g.to,yr.widget({widget:new Ti(p.id,a),block:!0,side:1}))}return f.finish()},update(u,f){return u.map(f.changes)},provide:u=>se.decorations.from(u)}),ta=r=>{if(!r)return[];const a=Math.max(1,r.start),u=Math.max(a,r.end);return va.fromClass(class{decorations;constructor(f){this.decorations=this.build(f)}update(f){(f.docChanged||f.viewportChanged)&&(this.decorations=this.build(f.view))}build(f){const x=new xn;for(let p=a;p<=u&&p<=f.state.doc.lines;p+=1){const b=f.state.doc.line(p);x.add(b.from,b.from,yr.line({class:"oc-cm-selected-line"}))}return x.finish()}},{decorations:f=>f.decorations})};function ra({value:r,onChange:a,extensions:u,className:f,readOnly:x,lineNumbersConfig:p,highlightLines:b,onViewReady:g,onViewDestroy:y,blockWidgets:E,enableSearch:k,searchOpen:L,onSearchOpenChange:M,vimMode:R}){const P=n.useRef(null),o=n.useRef(null),G=n.useRef(r),xe=n.useRef(a),de=n.useRef(g),B=n.useRef(y),Ne=n.useRef(M),ae=n.useRef(E),Re=n.useRef(R),Oe=n.useRef(new Map),[dt,K]=n.useState([]),V=n.useCallback(w=>{const U=(w??[]).map(N=>{const T=Oe.current.get(N.id);return T?{id:N.id,content:N.content,container:T}:null}).filter(N=>N!==null);K(N=>N.length===U.length&&N.every((T,C)=>{const oe=U[C];return T.id===oe.id&&T.content===oe.content&&T.container===oe.container})?N:U)},[]),fe=n.useCallback(w=>{const U=P.current,N=w??o.current;if(!U||!N)return;const T=N.dom.querySelector(".cm-gutters"),C=T instanceof HTMLElement?T.getBoundingClientRect().width:0;U.style.setProperty("--oc-editor-gutter-width",`${C}px`)},[]);return n.useEffect(()=>{G.current=r},[r]),n.useEffect(()=>{xe.current=a},[a]),n.useEffect(()=>{de.current=g,B.current=y},[g,y]),n.useEffect(()=>{Ne.current=M},[M]),n.useEffect(()=>{ae.current=E,V(E)},[E,V]),n.useEffect(()=>{if(!P.current)return;const w=(()=>{if(typeof document>"u")return null;const N=document.querySelector('meta[name="csp-nonce"]')?.getAttribute("content");if(N)return N;const T=window.__PICHAMBER_CSP_NONCE__;return typeof T=="string"&&T.length>0?T:null})(),U=Zo.create({doc:G.current,extensions:[...w?[se.cspNonce.of(w)]:[],ni({fixed:!0}),Gs.of(As(p)),ai(),li.of(" "),Zs.of(qs(R)),cn.of([oi,...ii,...ci]),se.updateListener.of(N=>{fe(N.view),(N.viewportChanged||N.geometryChanged)&&V(ae.current);const T=Bs(N.startState),C=Bs(N.state);T!==C&&Ne.current?.(C);const oe=!wr(N.startState).eq(wr(N.state));if(C&&(T!==C||oe||N.docChanged||N.selectionSet)&&Hs(N.view.dom,N.view,T!==C||oe||N.docChanged),!N.docChanged)return;const O=N.state.doc.toString();G.current=O,xe.current(O),V(ae.current)}),Ks.of(se.editable.of(!x)),Us.of(u??[]),Js.of(ta(b)),Ys.of(ea(E,Oe.current)),Xs.of(k?[$s({top:!0}),cn.of(Qs(Vs))]:[])]});return o.current=new se({state:U,parent:P.current}),un(o.current,o.current.state.doc.length,200),o.current.requestMeasure(),requestAnimationFrame(()=>{fe(o.current),V(ae.current)}),o.current&&de.current?.(o.current),()=>{B.current?.(),o.current?.destroy(),o.current=null,K([])}},[ae,fe,V]),n.useEffect(()=>{const w=o.current;w&&(w.dispatch({effects:[Gs.reconfigure(As(p)),Ks.reconfigure(se.editable.of(!x)),Us.reconfigure(u??[]),Js.reconfigure(ta(b)),Ys.reconfigure(ea(E,Oe.current)),Xs.reconfigure(k?[$s({top:!0}),cn.of(Qs(Vs))]:[])]}),un(w,w.state.doc.length,200),w.requestMeasure(),requestAnimationFrame(()=>{fe(w),V(ae.current)}))},[u,b,p,x,E,k,fe,V]),n.useEffect(()=>{const w=o.current;if(!w){Re.current=R;return}Re.current!==R&&(Re.current=R,w.dispatch({effects:Zs.reconfigure(qs(R))}))},[R]),n.useEffect(()=>{const w=o.current;!w||k===!1||(L?(Pi(w),requestAnimationFrame(()=>{Ri(w.dom),Hs(w.dom,w,!0)})):Mi(w))},[L,k]),n.useEffect(()=>{const w=o.current;if(!w)return;const U=w.state.doc.toString();U!==r&&(w.dispatch({changes:{from:0,to:U.length,insert:r}}),un(w,w.state.doc.length,300),w.requestMeasure(),requestAnimationFrame(()=>fe(w)))},[r,fe]),t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:P,className:$("h-full w-full","[&_.cm-editor]:h-full [&_.cm-editor]:w-full","[&_.cm-scroller]:font-mono [&_.cm-scroller]:text-[var(--text-code)] [&_.cm-scroller]:leading-6","[&_.cm-lineNumbers]:text-[var(--tools-edit-line-number)]",f)}),dt.map(w=>bo.createPortal(w.content,w.container,w.id))]})}const Li=(r,a)=>{if(!a)return null;const u=Number.parseInt(r.trim(),10);return!Number.isFinite(u)||u<1?null:Math.min(u,a.state.doc.lines)},na=(r,a)=>{const u=r.state.doc.lineAt(a.main.head);return{lineNumber:u.number,character:a.main.head-u.from+1,selection:a}},sa=(r,a,u)=>{const f=r.state.doc.line(a),x=Math.max(1,Math.min(u,f.length+1)),p=f.from+x-1;r.dispatch({selection:Qo.cursor(p),effects:se.scrollIntoView(p,{y:"center"})})};function Oi({open:r,onOpenChange:a,view:u,variant:f="overlay"}){const[x,p]=n.useState(""),b=n.useRef(null),g=n.useRef(!1),y=n.useRef(null),E=n.useRef(null),k=n.useMemo(()=>Li(x,u),[x,u]);n.useEffect(()=>{!r||!u||(g.current=!1,b.current=na(u,u.state.selection),p(""))},[r,u]),n.useEffect(()=>{r&&window.requestAnimationFrame(()=>{E.current?.focus(),E.current?.select()})},[r]),n.useEffect(()=>{if(!(!r||!u||!b.current)){if(k===null){const{selection:o}=b.current;u.dispatch({selection:o,effects:se.scrollIntoView(o.main.from,{y:"center"})});return}sa(u,k,b.current.character)}},[k,r,u]);const L=n.useCallback(()=>{if(!u||g.current||!b.current)return;const{selection:o}=b.current;u.dispatch({selection:o,effects:se.scrollIntoView(o.main.from,{y:"center"})})},[u]),M=n.useCallback(o=>{o||L(),a(o)},[a,L]),R=n.useCallback(()=>{!u||k===null||!b.current||(g.current=!0,sa(u,k,b.current.character),a(!1),u.focus())},[k,a,u]);n.useEffect(()=>{if(!r)return;const o=xe=>{const de=y.current,B=xe.target;!de||!(B instanceof Node)||de.contains(B)||M(!1)},G=xe=>{xe.key==="Escape"&&(xe.preventDefault(),M(!1))};return document.addEventListener("pointerdown",o,!0),document.addEventListener("keydown",G,!0),()=>{document.removeEventListener("pointerdown",o,!0),document.removeEventListener("keydown",G,!0)}},[M,r,f]);const P=n.useMemo(()=>u?k===null?`Current Line: ${(b.current??na(u,u.state.selection)).lineNumber}. Type a line number between 1 and ${u.state.doc.lines} to navigate to.`:`Go to line ${k}`:"Editor unavailable.",[k,u]);return f==="inline"?r?t.jsxs("div",{ref:y,className:"ml-1 flex h-6 items-center gap-1",children:[t.jsx(vr,{ref:E,type:"number",min:1,step:1,inputMode:"numeric",value:x,onChange:o=>p(o.target.value),onKeyDown:o=>{o.key==="Enter"&&(o.preventDefault(),R())},placeholder:"Line",className:"h-6 w-20 rounded-md border-border/70 bg-transparent px-2 typography-meta"}),t.jsx(S,{variant:"outline",size:"xs",onClick:R,disabled:!u||k===null,className:"h-6 px-2",children:"Go"})]}):null:t.jsx("div",{ref:y,className:$("absolute left-3 top-3 z-40 w-[min(32rem,calc(100%-1.5rem))] rounded-xl border border-[var(--interactive-border)] bg-[color:color-mix(in_srgb,var(--surface-elevated)_94%,transparent)] p-2.5 shadow-lg backdrop-blur-sm transition-all",r?"pointer-events-auto translate-y-0 opacity-100":"pointer-events-none -translate-y-1 opacity-0"),children:t.jsxs("div",{className:"min-w-0",children:[t.jsx(vr,{ref:E,type:"number",min:1,step:1,inputMode:"numeric",value:x,onChange:o=>p(o.target.value),onKeyDown:o=>{o.key==="Enter"&&(o.preventDefault(),R())},placeholder:"Line number",className:"h-8 w-full rounded-md border-border/70 bg-background/60 typography-ui-label"}),t.jsx("div",{className:"mt-2 rounded-md bg-primary/15 px-3 py-1.5 typography-ui-label text-foreground/95",children:P})]})})}const dn=({currentMode:r,onToggle:a})=>{const u=r==="preview",f=u?"Switch to edit mode":"Switch to preview mode",x=u?"Edit":"Preview";return t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx(S,{variant:"ghost",size:"sm",onClick:a,"aria-label":f,className:"h-5 w-5 p-0",children:u?t.jsx(v,{name:"eye",className:"size-4","aria-hidden":"true"}):t.jsx(v,{name:"eye-off",className:"size-4","aria-hidden":"true"})})}),t.jsx(Ze,{sideOffset:8,children:x})]})};function aa(r,a){const u=r.metadata.variant==="dark",f=r.config?.fonts?.mono||"monospace",x=r.colors.syntax.highlights||{},p=r.colors.syntax.tokens||{},b=a?.fontSize?`${a.fontSize}px`:"var(--text-code)",g=se.theme({"&":{backgroundColor:"var(--background)",color:r.colors.syntax.base.foreground,fontSize:b,lineHeight:"1.5",position:"relative"},".cm-scroller":{fontFamily:f,backgroundColor:"var(--background)"},".cm-comment":{color:r.colors.syntax.base.comment},".cm-keyword":{color:r.colors.syntax.base.keyword},".cm-string":{color:r.colors.syntax.base.string},".cm-string-2":{color:p.stringEscape||r.colors.syntax.base.string},".cm-number":{color:r.colors.syntax.base.number},".cm-operator":{color:r.colors.syntax.base.operator},".cm-punctuation":{color:p.punctuation||r.colors.syntax.base.comment},".cm-atom":{color:p.boolean||r.colors.syntax.base.number},".cm-builtin":{color:p.functionCall||r.colors.syntax.base.function},".cm-def":{color:p.variableGlobal||r.colors.syntax.base.variable},".cm-attribute":{color:p.variableOther||p.variableProperty||r.colors.syntax.base.operator},".cm-meta":{color:r.colors.syntax.base.comment},".cm-property":{color:p.variableProperty||r.colors.syntax.base.keyword},".cm-variable":{color:r.colors.syntax.base.variable},".cm-variable-2":{color:p.variableOther||r.colors.syntax.base.function},".cm-variable-3":{color:p.variableGlobal||r.colors.syntax.base.type},".cm-tag":{color:p.tag||r.colors.syntax.base.keyword},".cm-link":{color:p.url||r.colors.syntax.base.keyword,textDecoration:"underline"},".cm-content":{caretColor:r.colors.interactive.cursor},".cm-cursor, .cm-dropCursor":{borderLeftColor:r.colors.interactive.cursor},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:r.colors.interactive.selection},".cm-gutters":{backgroundColor:"var(--background)",color:x.lineNumber||r.colors.syntax.base.comment,borderRight:`1px solid ${r.colors.interactive.border}`,position:"sticky",paddingRight:"8px",left:0,zIndex:2,boxShadow:"0 0 0 var(--background)"},".cm-gutter":{backgroundColor:"var(--background)"},".cm-gutterElement":{backgroundColor:"var(--background)"},".cm-lineNumbers":{backgroundColor:"var(--background)"},".cm-lineNumbers .cm-gutterElement":{paddingLeft:"8px",paddingRight:"8px",minWidth:"42px"},".cm-activeLineGutter":{color:x.lineNumberActive||r.colors.syntax.base.foreground},".cm-activeLine":{backgroundColor:r.colors.surface.overlay},".cm-panels":{backgroundColor:"transparent",color:r.colors.surface.foreground,position:"absolute",top:"0",right:"0",left:"auto",width:"auto",zIndex:10,pointerEvents:"none"},".cm-panels-top":{borderBottom:"none",position:"absolute",top:"6px",right:"14px",left:"auto",width:"auto"},".cm-panels-bottom":{position:"static",width:"100%",pointerEvents:"auto"},".cm-panels-bottom .cm-vim-panel":{borderTop:`1px solid ${r.colors.interactive.border}`,backgroundColor:r.colors.surface.elevated,color:r.colors.surface.mutedForeground,fontFamily:"var(--font-mono)",fontSize:"12px",minHeight:"22px",padding:"2px 8px"},".cm-panel.cm-search":{pointerEvents:"auto",padding:"4px",backgroundColor:`color-mix(in srgb, ${r.colors.surface.elevated} 85%, transparent)`,border:`1px solid ${r.colors.interactive.border}`,borderRadius:"10px",boxShadow:`0 2px 8px color-mix(in srgb, ${r.colors.surface.background} 60%, transparent)`,width:"auto",minWidth:"360px",maxWidth:"480px"},".cm-search":{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"0",width:"100%",color:r.colors.surface.foreground,fontFamily:"inherit",fontSize:"13px",lineHeight:"1"},".cm-search br":{display:"none"},".cm-search .cm-textfield":{appearance:"none",height:"26px",margin:0,padding:"0 8px",borderRadius:"6px !important",border:`1px solid ${r.colors.interactive.border}`,backgroundColor:r.colors.surface.background,color:r.colors.surface.foreground,fontFamily:"inherit",fontSize:"12px",lineHeight:"1",outline:"none",transition:"border-color 150ms ease"},".cm-search .cm-textfield::placeholder":{color:r.colors.surface.mutedForeground,opacity:1},".cm-search .cm-textfield:focus":{borderColor:r.colors.primary.base},'.cm-search .cm-textfield[name="search"]':{order:1,flex:"1 1 120px",maxWidth:"calc(100% - 142px)",minWidth:"100px"},".cm-search label":{order:2,display:"inline-flex",alignItems:"center",justifyContent:"center",width:"26px",height:"26px",minWidth:"26px",flexShrink:"0",margin:0,marginLeft:"1px",padding:0,borderRadius:"4px",border:"1px solid transparent",backgroundColor:"transparent",color:"transparent",cursor:"pointer",userSelect:"none",fontSize:"1px",lineHeight:"0",overflow:"hidden",position:"relative",transition:"background-color 120ms ease, border-color 120ms ease"},".cm-search label:hover":{backgroundColor:r.colors.interactive.hover},'.cm-search label:has(input[type="checkbox"]:checked)':{backgroundColor:r.colors.interactive.hover,borderColor:r.colors.interactive.border},'.cm-search [type="checkbox"]':{appearance:"none",WebkitAppearance:"none",width:"0",height:"0",margin:"0",padding:"0",border:"none",position:"absolute",opacity:"0",pointerEvents:"none"},".cm-search label::after":{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",fontSize:"13px",fontWeight:"600",lineHeight:"1",fontFamily:"inherit",color:r.colors.surface.mutedForeground,pointerEvents:"none"},".cm-search label:hover::after":{color:r.colors.surface.foreground},'.cm-search label:has(input[type="checkbox"]:checked)::after':{color:r.colors.surface.foreground},'.cm-search label:has(input[name="case"])::after':{content:'"Aa"',fontSize:"12px",letterSpacing:"-0.5px"},'.cm-search label:has(input[name="re"])::after':{content:'".*"',fontSize:"13px",fontFamily:"monospace"},'.cm-search label:has(input[name="word"])::after':{content:'"ab"',fontSize:"12px",textDecoration:"underline",textUnderlineOffset:"2px"},".cm-search .cm-search-message":{order:3,color:r.colors.surface.mutedForeground,backgroundColor:"transparent",border:"none",borderRadius:"0",padding:"0 6px",fontSize:"11px",whiteSpace:"nowrap",lineHeight:"26px"},".cm-search .cm-button":{appearance:"none",WebkitAppearance:"none",display:"inline-flex",alignItems:"center",justifyContent:"center",width:"26px",height:"26px",minWidth:"26px",flexShrink:"0",margin:0,marginLeft:"1px",padding:0,borderRadius:"4px",border:"none",backgroundColor:"transparent",backgroundImage:"none",color:"transparent",cursor:"pointer",fontSize:"1px",fontWeight:"400",lineHeight:"0",overflow:"hidden",position:"relative",boxShadow:"none",transition:"background-color 120ms ease"},".cm-search .cm-button::after":{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",fontSize:"15px",lineHeight:"1",color:r.colors.surface.mutedForeground,pointerEvents:"none"},".cm-search .cm-button:hover":{backgroundColor:r.colors.interactive.hover},".cm-search .cm-button:hover::after":{color:r.colors.surface.foreground},".cm-search .cm-button:active":{backgroundColor:r.colors.interactive.active},".cm-search .cm-button:focus-visible":{outline:"none",boxShadow:`0 0 0 1px ${r.colors.interactive.focusRing}`},".cm-search .cm-button:disabled":{opacity:.4,cursor:"default",pointerEvents:"none"},'.cm-search .cm-button[name="prev"]':{order:21,marginTop:"2px"},'.cm-search .cm-button[name="prev"]::after':{content:'"↑"'},'.cm-search .cm-button[name="next"]':{order:22,marginTop:"2px"},'.cm-search .cm-button[name="next"]::after':{content:'"↓"'},'.cm-search .cm-button[name="select"]':{order:23,marginTop:"2px"},'.cm-search .cm-button[name="select"]::after':{content:'"≡"',fontSize:"17px"},'.cm-panel.cm-search button[name="close"]':{order:5,appearance:"none",WebkitAppearance:"none",display:"inline-flex",alignItems:"center",justifyContent:"center",width:"26px",height:"26px",minWidth:"26px",flexShrink:"0",margin:"0 0 0 auto",padding:"0",borderRadius:"4px",border:"none",backgroundColor:"transparent",backgroundImage:"none",color:r.colors.surface.mutedForeground,cursor:"pointer",fontSize:"16px",lineHeight:"1",boxShadow:"none",position:"relative",overflow:"visible",transition:"background-color 120ms ease, color 120ms ease"},'.cm-panel.cm-search button[name="close"]:hover':{backgroundColor:r.colors.interactive.hover,color:r.colors.surface.foreground},'.cm-search .cm-button[name="replace"]':{order:24,marginTop:"2px"},'.cm-search .cm-button[name="replace"]::after':{content:'"⇄"'},'.cm-search .cm-button[name="replaceAll"], .cm-search .cm-button[name="replace-all"]':{order:25,marginTop:"2px"},'.cm-search .cm-button[name="replaceAll"]::after, .cm-search .cm-button[name="replace-all"]::after':{content:'"⇉"'},'.cm-search .cm-textfield[name="replace"]':{order:20,flex:"1 1 100%",maxWidth:"calc(100% - 142px)",minWidth:"80px",marginTop:"2px"},".cm-searchMatch":{backgroundColor:r.colors.status.infoBackground,boxShadow:`inset 0 0 0 1px ${r.colors.status.infoBorder}`,borderRadius:"2px"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:r.colors.interactive.selection,color:r.colors.interactive.selectionForeground,boxShadow:`inset 0 0 0 1px ${r.colors.interactive.borderFocus}`},"&.cm-focused":{outline:"none"}},{dark:u}),y=Is.define([{tag:[d.comment,d.docComment,d.meta,d.documentMeta],class:"cm-comment"},{tag:[d.keyword,d.controlKeyword,d.moduleKeyword,d.definitionKeyword,d.modifier],class:"cm-keyword"},{tag:[d.operatorKeyword,d.operator,d.derefOperator,d.updateOperator,d.definitionOperator,d.typeOperator,d.controlOperator,d.logicOperator,d.bitwiseOperator,d.arithmeticOperator,d.compareOperator],class:"cm-operator"},{tag:[d.punctuation,d.separator,d.bracket,d.paren,d.brace,d.squareBracket,d.angleBracket],class:"cm-punctuation"},{tag:[d.string,d.regexp,d.attributeValue,d.special(d.string),d.monospace],class:"cm-string"},{tag:d.escape,class:"cm-string-2"},{tag:[d.number,d.bool,d.atom,d.null,d.self],class:"cm-number"},{tag:[d.function(d.variableName),d.function(d.definition(d.variableName)),d.function(d.propertyName),d.standard(d.variableName),d.special(d.variableName)],class:"cm-builtin"},{tag:d.definition(d.variableName),class:"cm-def"},{tag:[d.variableName,d.local(d.variableName),d.constant(d.variableName),d.literal],class:"cm-variable"},{tag:d.propertyName,class:"cm-property"},{tag:d.attributeName,class:"cm-attribute"},{tag:[d.className,d.typeName,d.namespace],class:"cm-variable-3"},{tag:[d.tagName,d.labelName,d.annotation,d.macroName],class:"cm-tag"},{tag:d.link,class:"cm-link"},{tag:[d.heading,d.heading1,d.heading2,d.heading3,d.heading4,d.heading5,d.heading6],class:"cm-keyword"}]),E=Is.define([{tag:[d.comment,d.docComment,d.meta,d.documentMeta],color:r.colors.syntax.base.comment},{tag:[d.keyword,d.controlKeyword,d.moduleKeyword,d.definitionKeyword,d.modifier],color:r.colors.syntax.base.keyword},{tag:[d.operatorKeyword,d.operator,d.derefOperator,d.updateOperator,d.definitionOperator,d.typeOperator,d.controlOperator,d.logicOperator,d.bitwiseOperator,d.arithmeticOperator,d.compareOperator],color:r.colors.syntax.base.operator},{tag:[d.string,d.regexp,d.attributeValue,d.special(d.string),d.monospace],color:r.colors.syntax.base.string},{tag:d.escape,color:p.stringEscape||r.colors.syntax.base.string},{tag:[d.number,d.bool,d.atom,d.null,d.self],color:r.colors.syntax.base.number},{tag:[d.function(d.variableName),d.function(d.definition(d.variableName)),d.function(d.propertyName),d.standard(d.variableName),d.special(d.variableName)],color:r.colors.syntax.base.function},{tag:d.definition(d.variableName),color:p.variableGlobal||r.colors.syntax.base.variable},{tag:[d.variableName,d.local(d.variableName),d.constant(d.variableName),d.literal],color:r.colors.syntax.base.variable},{tag:d.propertyName,color:p.variableProperty||r.colors.syntax.base.variable},{tag:d.attributeName,color:p.variableOther||r.colors.syntax.base.variable},{tag:[d.className,d.typeName,d.namespace],color:r.colors.syntax.base.type},{tag:[d.tagName,d.labelName,d.annotation,d.macroName],color:p.tag||r.colors.syntax.base.keyword},{tag:d.link,color:p.url||r.colors.syntax.base.function,textDecoration:"underline"},{tag:[d.punctuation,d.separator,d.bracket,d.paren,d.brace,d.squareBracket,d.angleBracket],color:p.punctuation||r.colors.syntax.base.comment}]);return a?.syntaxColors===!1?[g]:[g,pr(di,{fallback:!0}),pr(vi),pr(y),pr(E)]}const Ai=180,ba=ei.define(),Ii=1,Bi=2,$i=4,oa=new Map,Vi=(r,a)=>{const u=`${r}|${a}`,f=oa.get(u);if(f)return f;let x="";r&&(x+=`color:${r};`),a&Ii&&(x+="font-style:italic;"),a&Bi&&(x+="font-weight:bold;"),a&$i&&(x+="text-decoration:underline;");const p=yr.mark({attributes:{style:x}});return oa.set(u,p),p},Wi=(r,a)=>{const u=new xn,f=r.state.doc,x=Math.min(a.length,f.lines);for(let p=0;p<x;p+=1){const b=a[p];if(!b||b.length===0)continue;const g=f.line(p+1);let y=g.from;for(const[E,k,L]of b){if(E<=0)continue;const M=y,R=Math.min(y+E,g.to);y+=E,!(R<=M)&&(!k&&!L||u.add(M,R,Vi(k,L)))}}return u.finish()},_i=xa.define({create(){return yr.none},update(r,a){let u=r.map(a.changes);for(const f of a.effects)f.is(ba)&&(u=f.value);return u},provide:r=>se.decorations.from(r)}),qi=r=>va.fromClass(class{timer;generation=0;constructor(a){this.tokenize(a)}update(a){a.docChanged&&this.schedule(a.view)}schedule(a){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.tokenize(a)},Ai)}async tokenize(a){const u=++this.generation,f=a.state.doc.toString(),x=await zo(f,r.language,r.themeName,r.theme);x&&u===this.generation&&a.state.doc.length===f.length&&a.dispatch({effects:ba.of(Wi(a,x))})}destroy(){this.timer&&clearTimeout(this.timer)}}),Hi=r=>[_i,qi(r)];function Gi(r){return!(!r.autoSaveEnabled||!r.isDirty||!r.canWrite||r.isSaving||r.fileLoading||r.isNonEditableBinary||!r.selectedFilePath||r.loadedFilePath!==r.selectedFilePath)}function Ki(r){return r.selectedFilePath?r.isDirty?!(r.fileLoading||r.loadedFilePath!==r.selectedFilePath||r.isNonEditableBinary||r.draftContent===""&&r.fileContent!==""&&r.loadedFilePath!==r.selectedFilePath):!0:!1}const Ui=r=>{const a=I(r);if(!a)return"";if(a==="/"||/^[A-Za-z]:\/$/.test(a))return a;const u=a.lastIndexOf("/");if(u<0)return a;if(u===0)return"/";const f=a.slice(0,u);return/^[A-Za-z]:$/.test(f)?`${f}/`:f},Ji=({label:r,iconDataUrl:a})=>{const[u,f]=n.useState(!1),x=r.trim().slice(0,1).toUpperCase()||"?";return a&&!u?t.jsx("img",{src:a,alt:"",className:"size-4 rounded-sm",onError:()=>f(!0)}):t.jsx("span",{className:$("size-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:x})},Yi=r=>r.slice().sort((a,u)=>a.type!==u.type?a.type==="directory"?-1:1:a.name.localeCompare(u.name)),I=r=>{if(!r)return"";const a=r.replace(/\\/g,"/"),u=a.startsWith("//");let f=a.replace(/\/+/g,"/");u&&!f.startsWith("//")&&(f=`/${f}`);const x=f==="/",p=/^[A-Za-z]:\/$/.test(f);return!x&&!p&&(f=f.replace(/\/+$/,"")),f},Xi=r=>r.startsWith("/")||r.startsWith("//")||/^[A-Za-z]:\//.test(r),Et=r=>/^[A-Za-z]:\//.test(r)?r.toLowerCase():r,Ht=(r,a)=>{const u=I(a),f=I(r);if(!u||!f)return!1;const x=Et(u),p=Et(f);return p===x||p.startsWith(`${x}/`)},ia=(r,a)=>{const u=I(a),f=I(r);if(!Ht(f,u))return[];const p=f.slice(u.length).replace(/^\//,"").split("/"),b=[];let g=u;for(let y=0;y<p.length-1;y++)g=g?`${g}/${p[y]}`:p[y],b.push(g);return b},xr=(r,a)=>{if(!a)return"";const u=I(a);if(!r||!Ht(u,r))return u;const f=u.slice(r.length);return f.startsWith("/")?f.slice(1):f},Zi=new Set(["node_modules"]),Qi=({status:r})=>{const a={open:"var(--status-info)",modified:"var(--status-warning)","git-modified":"var(--status-warning)","git-added":"var(--status-success)","git-deleted":"var(--status-error)"}[r];return t.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:a}})},ca=({name:r})=>{const a=n.useRef(null),u=n.useRef(null),[f,x]=n.useState(!1);return n.useLayoutEffect(()=>{const p=a.current,b=u.current;if(!p||!b)return;const g=()=>{x(b.scrollWidth>p.clientWidth+1)};g();const y=new ResizeObserver(g);return y.observe(p),y.observe(b),()=>{y.disconnect()}},[r]),t.jsxs("span",{ref:a,className:"relative block min-w-0 flex-1 overflow-hidden whitespace-nowrap",children:[t.jsx("span",{ref:u,"aria-hidden":"true",className:"invisible absolute whitespace-nowrap",children:r}),f?t.jsxs("span",{className:"open-file-name-marquee-track",children:[t.jsx("span",{className:"open-file-name-marquee-item",children:r}),t.jsx("span",{className:"open-file-name-marquee-item","aria-hidden":"true",children:r})]}):t.jsx("span",{className:"block min-w-0 truncate",children:r})]})},ec=r=>Zi.has(r),tc=r=>{const a=I(r);return a==="node_modules"||a.endsWith("/node_modules")||a.includes("/node_modules/")},rc=r=>{const u=(r instanceof Error?r.message:String(r??"")).toLowerCase();return u.includes("is a directory")||u.includes("eisdir")},la=r=>{const u=(r instanceof Error?r.message:String(r??"")).toLowerCase();return u.includes("file not found")||u.includes("enoent")||u.includes("no such file")||u.includes("does not exist")},qt=2e5,nc=r=>{let a=0,u=0;for(let f=0;f<r.length;f+=1)r.charCodeAt(f)===10&&(f>0&&r.charCodeAt(f-1)===13?a+=1:u+=1);return a>u?`\r
1
+ import{j as t,R as n,b as bo}from"./vendor-react-DYyjh7Q0.js";import{z as wo,A as yo,B as jo,C as No,O as Es,o as Ee,u as ue,bI as ko,aa as Rs,D as Co,r as Ds,J as rn,e as So,bJ as Fo,I as Eo,bK as Ro}from"./index-8TL2HlaR.js";import{f as $,Y as vr,B as S,T as Ye,q as Xe,I as v,s as Ze,dD as Do,C as zo,aJ as Po,aV as Mo,E as To,G as Lo,ax as Oo,dE as zs,t as A,a5 as Ao,V as nn,dA as fr,b3 as Io,dF as sn,W as Ps,dG as Ms,dB as Ts,dC as Bo,dH as $o,dI as Vo,b7 as Wo,dJ as Ls,D as da,w as fa,x as ma,y as pa,z as ha,A as ga,as as pn,at as hn,F as hr,au as gn,az as gr,ay as an,X as on,bl as Os,cV as _o,cW as qo,dK as _t,av as br,aw as Ho,aA as Ko}from"./SessionSwitcherDropdown-D5bWfZNA.js";import{E as mr,p as Go,q as Uo,t as Jo,v as Yo,w as Xo}from"./usePanelSlide-C_PJmPXW.js";import{E as Zo,o as ut,k as xn,i as xa,a as Qo,S as ei}from"./vendor-codemirror-state-CNWM3Q8V.js";import{s as ti,d as ri,E as se,e as ni,f as As,k as cn,V as va,D as yr,W as si}from"./vendor-codemirror-view-DSzLbZiS.js";import{h as ai,k as oi,l as ii,j as ci}from"./vendor-codemirror-commands-RrgJ8H_6.js";import{i as li,y as ui,H as Is,x as pr,z as di}from"./vendor-codemirror-language-E2vgV9K3.js";import{a as Bs,g as wr,b as $s,c as Vs,o as fi,d as mi}from"./vendor-codemirror-search-8kyQdB3f.js";import{v as pi,g as hi}from"./vendor-replit-codemirror-vim-BJY5fGLS.js";import{F as gi,J as xi}from"./JsonTreeView-HVwQS7qG.js";import{a as d,c as vi}from"./vendor-lezer-highlight-CDMHUZ74.js";import{ensurePierreThemeRegistered as Ws,getResolvedShikiTheme as bi}from"./appThemeRegistry-BK0dHKa6.js";import{D as wi}from"./DiagramEditor-gHLCXHtr.js";import{I as _s,a as yi,u as ji,n as Ni}from"./useInlineCommentController-DVif5Fr8.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-CnsBKjP5.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-base-ui-DL8r2fgQ.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-sVFnuruh.js";import"./vendor-floating-ui-dom-Bkw82kL9.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-B7OScDIw.js";import"./runtimeSurface-CkdOpqo7.js";import"./vendor-dnd-kit-core-GipZW2tY.js";import"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import"./vendor-dnd-kit-accessibility-Cv52zwWT.js";import"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import"./vendor-cmdk-BCEUzcHE.js";import"./vendor-radix-ui-react-dialog-jX3Dld8c.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-D1GnwnP9.js";import"./vendor-radix-ui-react-context-CM4yFQ2I.js";import"./vendor-radix-ui-react-id-BcxRjnbX.js";import"./vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js";import"./vendor-radix-ui-react-use-controllable-state-C_ecoh35.js";import"./vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js";import"./vendor-radix-ui-react-primitive-CfpW6_IT.js";import"./vendor-radix-ui-react-slot-BxUc3Pvz.js";import"./vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js";import"./vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js";import"./vendor-radix-ui-react-focus-scope-C2K7lNPv.js";import"./vendor-radix-ui-react-portal-xlJWBfDg.js";import"./vendor-radix-ui-react-presence-Btn-Dp7L.js";import"./vendor-radix-ui-react-focus-guards-D5MZ0nQs.js";import"./vendor-react-remove-scroll-CfeMe0DL.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-C9YRs2nU.js";import"./vendor-react-style-singleton-B1H4bWSG.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-C-AuTczP.js";import"./vendor-use-callback-ref-CJB0R85I.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-lang-javascript-BUlYhQ3o.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-codemirror-autocomplete-BS2SpSAZ.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-codemirror-lang-json-CqayksDf.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-Ba8JZ6fp.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-DK27qQri.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-CvO36Y1p.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-C-924Z4o.js";import"./vendor-codemirror-lang-python-_2bIYTiJ.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-DJASDzNt.js";import"./vendor-motion-dom-DJLgZh4Q.js";import"./vendor-motion-utils-BGh8QBgx.js";import"./vendor-sonner-CW8w438f.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./permissionStore-BRcQ9Jgt.js";import"./web-components-BG-6PEN4.js";import"./computeVirtualFileMetrics-skbyL2Az.js";import"./vendor-shiki-Bbf2GEcE.js";import"./vendor-shikijs-core-CGM_jqPK.js";import"./vendor-shikijs-types-CPSbSeK6.js";import"./vendor-shikijs-vscode-textmate-BgLrS_2D.js";import"./vendor-hast-util-to-html-BKBhbTDb.js";import"./vendor-html-void-elements-CkdplsNl.js";import"./vendor-property-information-rJCbAzvX.js";import"./vendor-zwitch-C2o2j-tx.js";import"./vendor-stringify-entities-CsH1VEn9.js";import"./vendor-character-entities-legacy-BpoLgcEt.js";import"./vendor-character-entities-html4-D7taRCQ7.js";import"./vendor-ccount-c2V3InAJ.js";import"./vendor-comma-separated-tokens-D8TqSuIK.js";import"./vendor-space-separated-tokens-DD3iYX1K.js";import"./vendor-hast-util-whitespace-D4Wp6AEg.js";import"./vendor-shikijs-engine-oniguruma-DPWuIF1G.js";import"./themeResolver-BmJyTmjJ.js";import"./vendor-pierre-theming-C6Z4M5_u.js";import"./vendor-shikijs-engine-javascript-Cme4830A.js";import"./vendor-oniguruma-to-es-DLBnFDCE.js";import"./vendor-oniguruma-parser-C0D4_9rT.js";import"./vendor-regex-BBWcyTkg.js";import"./vendor-regex-utilities-2BQyy0xI.js";import"./vendor-regex-recursion-JU4mF-dD.js";import"./vendor-shikijs-transformers-CZWsLLKm.js";import"./Virtualizer-BxW2CJGB.js";import"./isFilePlainText-UL_tMQZx.js";import"./registerCustomTheme-BBXUCRnG.js";import"./vendor-react-drawio-Boqanm0j.js";import"./collapsible-Wnmq-13H.js";function ki(r){const{drafts:a,editingDraftId:u,commentText:f,onTextChange:x,selection:p,isDragging:b,fileLabel:g,newWidgetId:y,mapDraftToRange:E,onSave:k,onCancel:L,onEdit:M,onDelete:R}=r,P=[];for(const o of a){const K=E(o);if(o.id===u){P.push({afterLine:K.end,id:`edit-${o.id}`,content:t.jsx(_s,{initialText:f,onTextChange:x,fileLabel:g,lineRange:K,isEditing:!0,onSave:k,onCancel:L},`edit-${o.id}`)});continue}P.push({afterLine:K.end,id:`card-${o.id}`,content:t.jsx(yi,{draft:o,onEdit:()=>M(o),onDelete:()=>R(o)},`card-${o.id}`)})}if(p&&!u&&!b){const o={...p,start:Math.min(p.start,p.end),end:Math.max(p.start,p.end)};P.push({afterLine:o.end,id:y,content:t.jsx(_s,{initialText:f,onTextChange:x,fileLabel:g,lineRange:o,isEditing:!1,onSave:k,onCancel:L},y)})}return P}const Ci=r=>r!==null&&typeof r=="object"&&"updateStatus"in r&&typeof r.updateStatus=="function",Si=r=>{const a=document.createElement("div");a.className="cm-vim-panel";const u=hi(r);if(!u)return{top:!1,dom:a};u.state.statusbar=a;const f=u.state.vimPlugin;return Ci(f)&&f.updateStatus(),{top:!1,dom:a,destroy(){u.state.statusbar===a&&(u.state.statusbar=null)}}};function qs(r){return r?[pi(),ti.of(Si),ri()]:[]}const Fi={next:"Next match",prev:"Previous match",select:"Select all matches",replace:"Replace",replaceAll:"Replace all",close:"Close"},Ei={case:"Match case",re:"Regular expression",word:"Match whole word"};function Ri(r){const a=r.querySelector(".cm-search");if(a){for(const[u,f]of Object.entries(Fi)){const x=a.querySelector(`button[name="${u}"]`);x&&!x.title&&(x.title=f)}for(const[u,f]of Object.entries(Ei)){const p=a.querySelector(`input[name="${u}"]`)?.parentElement;p&&!p.title&&(p.title=f)}}}const ln=new WeakMap;function Di(r,a){const u=wr(r.state);if(!u.valid)return ln.delete(r),0;const f=ln.get(r);if(!a&&f?.doc===r.state.doc&&f.query.eq(u))return f.total;const x=u.getCursor(r.state);let p=0;for(let b=x.next();!b.done;b=x.next())p+=1;return ln.set(r,{query:u,doc:r.state.doc,total:p}),p}function zi(r){const a=wr(r.state);if(!a.valid)return 0;const u=r.state.selection.main,f=a.getCursor(r.state);let x=0,p=0;for(let b=f.next();!b.done;b=f.next()){const g=b.value;if(x+=1,p===0&&(p=x),u.from===g.from&&u.to===g.to||u.from<g.to&&u.to>g.from||g.from>=u.head)return x}return p}function Hs(r,a,u=!1){const f=r.querySelector(".cm-search");if(!f)return;let x=f.querySelector(".cm-search-message");if(!x){x=document.createElement("span"),x.className="cm-search-message",x.setAttribute("aria-live","polite");const g=f.querySelector('button[name="next"]'),y=g?.parentNode===f?g:f.firstChild;f.insertBefore(x,y)}const p=Di(a,u),b=p===0?0:zi(a);x.textContent=p===0?"":`${b}/${p}`}const Ks=new ut,Gs=new ut,Us=new ut,Js=new ut,Ys=new ut,Xs=new ut,Zs=new ut,Qs=r=>r,un=ui,Pi=fi,Mi=mi;class Ti extends si{constructor(a,u){super(),this.id=a,this.containerMap=u}toDOM(){let a=this.containerMap.get(this.id);return a||(a=document.createElement("div"),a.className="oc-block-widget",a.dataset.widgetId=this.id,this.containerMap.set(this.id,a)),a}eq(a){return a.id===this.id}destroy(){}}const ea=(r,a)=>!r||r.length===0?[]:xa.define({create(u){const f=new xn,x=[...r].sort((p,b)=>p.afterLine-b.afterLine);for(const p of x){const b=u.doc.lines;if(p.afterLine>b)continue;const g=u.doc.line(p.afterLine);f.add(g.to,g.to,yr.widget({widget:new Ti(p.id,a),block:!0,side:1}))}return f.finish()},update(u,f){return u.map(f.changes)},provide:u=>se.decorations.from(u)}),ta=r=>{if(!r)return[];const a=Math.max(1,r.start),u=Math.max(a,r.end);return va.fromClass(class{decorations;constructor(f){this.decorations=this.build(f)}update(f){(f.docChanged||f.viewportChanged)&&(this.decorations=this.build(f.view))}build(f){const x=new xn;for(let p=a;p<=u&&p<=f.state.doc.lines;p+=1){const b=f.state.doc.line(p);x.add(b.from,b.from,yr.line({class:"oc-cm-selected-line"}))}return x.finish()}},{decorations:f=>f.decorations})};function ra({value:r,onChange:a,extensions:u,className:f,readOnly:x,lineNumbersConfig:p,highlightLines:b,onViewReady:g,onViewDestroy:y,blockWidgets:E,enableSearch:k,searchOpen:L,onSearchOpenChange:M,vimMode:R}){const P=n.useRef(null),o=n.useRef(null),K=n.useRef(r),xe=n.useRef(a),de=n.useRef(g),B=n.useRef(y),Ne=n.useRef(M),ae=n.useRef(E),Re=n.useRef(R),Oe=n.useRef(new Map),[dt,G]=n.useState([]),V=n.useCallback(w=>{const U=(w??[]).map(N=>{const T=Oe.current.get(N.id);return T?{id:N.id,content:N.content,container:T}:null}).filter(N=>N!==null);G(N=>N.length===U.length&&N.every((T,C)=>{const oe=U[C];return T.id===oe.id&&T.content===oe.content&&T.container===oe.container})?N:U)},[]),fe=n.useCallback(w=>{const U=P.current,N=w??o.current;if(!U||!N)return;const T=N.dom.querySelector(".cm-gutters"),C=T instanceof HTMLElement?T.getBoundingClientRect().width:0;U.style.setProperty("--oc-editor-gutter-width",`${C}px`)},[]);return n.useEffect(()=>{K.current=r},[r]),n.useEffect(()=>{xe.current=a},[a]),n.useEffect(()=>{de.current=g,B.current=y},[g,y]),n.useEffect(()=>{Ne.current=M},[M]),n.useEffect(()=>{ae.current=E,V(E)},[E,V]),n.useEffect(()=>{if(!P.current)return;const w=(()=>{if(typeof document>"u")return null;const N=document.querySelector('meta[name="csp-nonce"]')?.getAttribute("content");if(N)return N;const T=window.__PICHAMBER_CSP_NONCE__;return typeof T=="string"&&T.length>0?T:null})(),U=Zo.create({doc:K.current,extensions:[...w?[se.cspNonce.of(w)]:[],ni({fixed:!0}),Ks.of(As(p)),ai(),li.of(" "),Zs.of(qs(R)),cn.of([oi,...ii,...ci]),se.updateListener.of(N=>{fe(N.view),(N.viewportChanged||N.geometryChanged)&&V(ae.current);const T=Bs(N.startState),C=Bs(N.state);T!==C&&Ne.current?.(C);const oe=!wr(N.startState).eq(wr(N.state));if(C&&(T!==C||oe||N.docChanged||N.selectionSet)&&Hs(N.view.dom,N.view,T!==C||oe||N.docChanged),!N.docChanged)return;const O=N.state.doc.toString();K.current=O,xe.current(O),V(ae.current)}),Gs.of(se.editable.of(!x)),Us.of(u??[]),Js.of(ta(b)),Ys.of(ea(E,Oe.current)),Xs.of(k?[$s({top:!0}),cn.of(Qs(Vs))]:[])]});return o.current=new se({state:U,parent:P.current}),un(o.current,o.current.state.doc.length,200),o.current.requestMeasure(),requestAnimationFrame(()=>{fe(o.current),V(ae.current)}),o.current&&de.current?.(o.current),()=>{B.current?.(),o.current?.destroy(),o.current=null,G([])}},[ae,fe,V]),n.useEffect(()=>{const w=o.current;w&&(w.dispatch({effects:[Ks.reconfigure(As(p)),Gs.reconfigure(se.editable.of(!x)),Us.reconfigure(u??[]),Js.reconfigure(ta(b)),Ys.reconfigure(ea(E,Oe.current)),Xs.reconfigure(k?[$s({top:!0}),cn.of(Qs(Vs))]:[])]}),un(w,w.state.doc.length,200),w.requestMeasure(),requestAnimationFrame(()=>{fe(w),V(ae.current)}))},[u,b,p,x,E,k,fe,V]),n.useEffect(()=>{const w=o.current;if(!w){Re.current=R;return}Re.current!==R&&(Re.current=R,w.dispatch({effects:Zs.reconfigure(qs(R))}))},[R]),n.useEffect(()=>{const w=o.current;!w||k===!1||(L?(Pi(w),requestAnimationFrame(()=>{Ri(w.dom),Hs(w.dom,w,!0)})):Mi(w))},[L,k]),n.useEffect(()=>{const w=o.current;if(!w)return;const U=w.state.doc.toString();U!==r&&(w.dispatch({changes:{from:0,to:U.length,insert:r}}),un(w,w.state.doc.length,300),w.requestMeasure(),requestAnimationFrame(()=>fe(w)))},[r,fe]),t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:P,className:$("h-full w-full","[&_.cm-editor]:h-full [&_.cm-editor]:w-full","[&_.cm-scroller]:font-mono [&_.cm-scroller]:text-[var(--text-code)] [&_.cm-scroller]:leading-6","[&_.cm-lineNumbers]:text-[var(--tools-edit-line-number)]",f)}),dt.map(w=>bo.createPortal(w.content,w.container,w.id))]})}const Li=(r,a)=>{if(!a)return null;const u=Number.parseInt(r.trim(),10);return!Number.isFinite(u)||u<1?null:Math.min(u,a.state.doc.lines)},na=(r,a)=>{const u=r.state.doc.lineAt(a.main.head);return{lineNumber:u.number,character:a.main.head-u.from+1,selection:a}},sa=(r,a,u)=>{const f=r.state.doc.line(a),x=Math.max(1,Math.min(u,f.length+1)),p=f.from+x-1;r.dispatch({selection:Qo.cursor(p),effects:se.scrollIntoView(p,{y:"center"})})};function Oi({open:r,onOpenChange:a,view:u,variant:f="overlay"}){const[x,p]=n.useState(""),b=n.useRef(null),g=n.useRef(!1),y=n.useRef(null),E=n.useRef(null),k=n.useMemo(()=>Li(x,u),[x,u]);n.useEffect(()=>{!r||!u||(g.current=!1,b.current=na(u,u.state.selection),p(""))},[r,u]),n.useEffect(()=>{r&&window.requestAnimationFrame(()=>{E.current?.focus(),E.current?.select()})},[r]),n.useEffect(()=>{if(!(!r||!u||!b.current)){if(k===null){const{selection:o}=b.current;u.dispatch({selection:o,effects:se.scrollIntoView(o.main.from,{y:"center"})});return}sa(u,k,b.current.character)}},[k,r,u]);const L=n.useCallback(()=>{if(!u||g.current||!b.current)return;const{selection:o}=b.current;u.dispatch({selection:o,effects:se.scrollIntoView(o.main.from,{y:"center"})})},[u]),M=n.useCallback(o=>{o||L(),a(o)},[a,L]),R=n.useCallback(()=>{!u||k===null||!b.current||(g.current=!0,sa(u,k,b.current.character),a(!1),u.focus())},[k,a,u]);n.useEffect(()=>{if(!r)return;const o=xe=>{const de=y.current,B=xe.target;!de||!(B instanceof Node)||de.contains(B)||M(!1)},K=xe=>{xe.key==="Escape"&&(xe.preventDefault(),M(!1))};return document.addEventListener("pointerdown",o,!0),document.addEventListener("keydown",K,!0),()=>{document.removeEventListener("pointerdown",o,!0),document.removeEventListener("keydown",K,!0)}},[M,r,f]);const P=n.useMemo(()=>u?k===null?`Current Line: ${(b.current??na(u,u.state.selection)).lineNumber}. Type a line number between 1 and ${u.state.doc.lines} to navigate to.`:`Go to line ${k}`:"Editor unavailable.",[k,u]);return f==="inline"?r?t.jsxs("div",{ref:y,className:"ml-1 flex h-6 items-center gap-1",children:[t.jsx(vr,{ref:E,type:"number",min:1,step:1,inputMode:"numeric",value:x,onChange:o=>p(o.target.value),onKeyDown:o=>{o.key==="Enter"&&(o.preventDefault(),R())},placeholder:"Line",className:"h-6 w-20 rounded-md border-border/70 bg-transparent px-2 typography-meta"}),t.jsx(S,{variant:"outline",size:"xs",onClick:R,disabled:!u||k===null,className:"h-6 px-2",children:"Go"})]}):null:t.jsx("div",{ref:y,className:$("absolute left-3 top-3 z-40 w-[min(32rem,calc(100%-1.5rem))] rounded-xl border border-[var(--interactive-border)] bg-[color:color-mix(in_srgb,var(--surface-elevated)_94%,transparent)] p-2.5 shadow-lg backdrop-blur-sm transition-all",r?"pointer-events-auto translate-y-0 opacity-100":"pointer-events-none -translate-y-1 opacity-0"),children:t.jsxs("div",{className:"min-w-0",children:[t.jsx(vr,{ref:E,type:"number",min:1,step:1,inputMode:"numeric",value:x,onChange:o=>p(o.target.value),onKeyDown:o=>{o.key==="Enter"&&(o.preventDefault(),R())},placeholder:"Line number",className:"h-8 w-full rounded-md border-border/70 bg-background/60 typography-ui-label"}),t.jsx("div",{className:"mt-2 rounded-md bg-primary/15 px-3 py-1.5 typography-ui-label text-foreground/95",children:P})]})})}const dn=({currentMode:r,onToggle:a})=>{const u=r==="preview",f=u?"Switch to edit mode":"Switch to preview mode",x=u?"Edit":"Preview";return t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx(S,{variant:"ghost",size:"sm",onClick:a,"aria-label":f,className:"h-5 w-5 p-0",children:u?t.jsx(v,{name:"eye",className:"size-4","aria-hidden":"true"}):t.jsx(v,{name:"eye-off",className:"size-4","aria-hidden":"true"})})}),t.jsx(Ze,{sideOffset:8,children:x})]})};function aa(r,a){const u=r.metadata.variant==="dark",f=r.config?.fonts?.mono||"monospace",x=r.colors.syntax.highlights||{},p=r.colors.syntax.tokens||{},b=a?.fontSize?`${a.fontSize}px`:"var(--text-code)",g=se.theme({"&":{backgroundColor:"var(--background)",color:r.colors.syntax.base.foreground,fontSize:b,lineHeight:"1.5",position:"relative"},".cm-scroller":{fontFamily:f,backgroundColor:"var(--background)"},".cm-comment":{color:r.colors.syntax.base.comment},".cm-keyword":{color:r.colors.syntax.base.keyword},".cm-string":{color:r.colors.syntax.base.string},".cm-string-2":{color:p.stringEscape||r.colors.syntax.base.string},".cm-number":{color:r.colors.syntax.base.number},".cm-operator":{color:r.colors.syntax.base.operator},".cm-punctuation":{color:p.punctuation||r.colors.syntax.base.comment},".cm-atom":{color:p.boolean||r.colors.syntax.base.number},".cm-builtin":{color:p.functionCall||r.colors.syntax.base.function},".cm-def":{color:p.variableGlobal||r.colors.syntax.base.variable},".cm-attribute":{color:p.variableOther||p.variableProperty||r.colors.syntax.base.operator},".cm-meta":{color:r.colors.syntax.base.comment},".cm-property":{color:p.variableProperty||r.colors.syntax.base.keyword},".cm-variable":{color:r.colors.syntax.base.variable},".cm-variable-2":{color:p.variableOther||r.colors.syntax.base.function},".cm-variable-3":{color:p.variableGlobal||r.colors.syntax.base.type},".cm-tag":{color:p.tag||r.colors.syntax.base.keyword},".cm-link":{color:p.url||r.colors.syntax.base.keyword,textDecoration:"underline"},".cm-content":{caretColor:r.colors.interactive.cursor},".cm-cursor, .cm-dropCursor":{borderLeftColor:r.colors.interactive.cursor},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:r.colors.interactive.selection},".cm-gutters":{backgroundColor:"var(--background)",color:x.lineNumber||r.colors.syntax.base.comment,borderRight:`1px solid ${r.colors.interactive.border}`,position:"sticky",paddingRight:"8px",left:0,zIndex:2,boxShadow:"0 0 0 var(--background)"},".cm-gutter":{backgroundColor:"var(--background)"},".cm-gutterElement":{backgroundColor:"var(--background)"},".cm-lineNumbers":{backgroundColor:"var(--background)"},".cm-lineNumbers .cm-gutterElement":{paddingLeft:"8px",paddingRight:"8px",minWidth:"42px"},".cm-activeLineGutter":{color:x.lineNumberActive||r.colors.syntax.base.foreground},".cm-activeLine":{backgroundColor:r.colors.surface.overlay},".cm-panels":{backgroundColor:"transparent",color:r.colors.surface.foreground,position:"absolute",top:"0",right:"0",left:"auto",width:"auto",zIndex:10,pointerEvents:"none"},".cm-panels-top":{borderBottom:"none",position:"absolute",top:"6px",right:"14px",left:"auto",width:"auto"},".cm-panels-bottom":{position:"static",width:"100%",pointerEvents:"auto"},".cm-panels-bottom .cm-vim-panel":{borderTop:`1px solid ${r.colors.interactive.border}`,backgroundColor:r.colors.surface.elevated,color:r.colors.surface.mutedForeground,fontFamily:"var(--font-mono)",fontSize:"12px",minHeight:"22px",padding:"2px 8px"},".cm-panel.cm-search":{pointerEvents:"auto",padding:"4px",backgroundColor:`color-mix(in srgb, ${r.colors.surface.elevated} 85%, transparent)`,border:`1px solid ${r.colors.interactive.border}`,borderRadius:"10px",boxShadow:`0 2px 8px color-mix(in srgb, ${r.colors.surface.background} 60%, transparent)`,width:"auto",minWidth:"360px",maxWidth:"480px"},".cm-search":{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"0",width:"100%",color:r.colors.surface.foreground,fontFamily:"inherit",fontSize:"13px",lineHeight:"1"},".cm-search br":{display:"none"},".cm-search .cm-textfield":{appearance:"none",height:"26px",margin:0,padding:"0 8px",borderRadius:"6px !important",border:`1px solid ${r.colors.interactive.border}`,backgroundColor:r.colors.surface.background,color:r.colors.surface.foreground,fontFamily:"inherit",fontSize:"12px",lineHeight:"1",outline:"none",transition:"border-color 150ms ease"},".cm-search .cm-textfield::placeholder":{color:r.colors.surface.mutedForeground,opacity:1},".cm-search .cm-textfield:focus":{borderColor:r.colors.primary.base},'.cm-search .cm-textfield[name="search"]':{order:1,flex:"1 1 120px",maxWidth:"calc(100% - 142px)",minWidth:"100px"},".cm-search label":{order:2,display:"inline-flex",alignItems:"center",justifyContent:"center",width:"26px",height:"26px",minWidth:"26px",flexShrink:"0",margin:0,marginLeft:"1px",padding:0,borderRadius:"4px",border:"1px solid transparent",backgroundColor:"transparent",color:"transparent",cursor:"pointer",userSelect:"none",fontSize:"1px",lineHeight:"0",overflow:"hidden",position:"relative",transition:"background-color 120ms ease, border-color 120ms ease"},".cm-search label:hover":{backgroundColor:r.colors.interactive.hover},'.cm-search label:has(input[type="checkbox"]:checked)':{backgroundColor:r.colors.interactive.hover,borderColor:r.colors.interactive.border},'.cm-search [type="checkbox"]':{appearance:"none",WebkitAppearance:"none",width:"0",height:"0",margin:"0",padding:"0",border:"none",position:"absolute",opacity:"0",pointerEvents:"none"},".cm-search label::after":{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",fontSize:"13px",fontWeight:"600",lineHeight:"1",fontFamily:"inherit",color:r.colors.surface.mutedForeground,pointerEvents:"none"},".cm-search label:hover::after":{color:r.colors.surface.foreground},'.cm-search label:has(input[type="checkbox"]:checked)::after':{color:r.colors.surface.foreground},'.cm-search label:has(input[name="case"])::after':{content:'"Aa"',fontSize:"12px",letterSpacing:"-0.5px"},'.cm-search label:has(input[name="re"])::after':{content:'".*"',fontSize:"13px",fontFamily:"monospace"},'.cm-search label:has(input[name="word"])::after':{content:'"ab"',fontSize:"12px",textDecoration:"underline",textUnderlineOffset:"2px"},".cm-search .cm-search-message":{order:3,color:r.colors.surface.mutedForeground,backgroundColor:"transparent",border:"none",borderRadius:"0",padding:"0 6px",fontSize:"11px",whiteSpace:"nowrap",lineHeight:"26px"},".cm-search .cm-button":{appearance:"none",WebkitAppearance:"none",display:"inline-flex",alignItems:"center",justifyContent:"center",width:"26px",height:"26px",minWidth:"26px",flexShrink:"0",margin:0,marginLeft:"1px",padding:0,borderRadius:"4px",border:"none",backgroundColor:"transparent",backgroundImage:"none",color:"transparent",cursor:"pointer",fontSize:"1px",fontWeight:"400",lineHeight:"0",overflow:"hidden",position:"relative",boxShadow:"none",transition:"background-color 120ms ease"},".cm-search .cm-button::after":{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",fontSize:"15px",lineHeight:"1",color:r.colors.surface.mutedForeground,pointerEvents:"none"},".cm-search .cm-button:hover":{backgroundColor:r.colors.interactive.hover},".cm-search .cm-button:hover::after":{color:r.colors.surface.foreground},".cm-search .cm-button:active":{backgroundColor:r.colors.interactive.active},".cm-search .cm-button:focus-visible":{outline:"none",boxShadow:`0 0 0 1px ${r.colors.interactive.focusRing}`},".cm-search .cm-button:disabled":{opacity:.4,cursor:"default",pointerEvents:"none"},'.cm-search .cm-button[name="prev"]':{order:21,marginTop:"2px"},'.cm-search .cm-button[name="prev"]::after':{content:'"↑"'},'.cm-search .cm-button[name="next"]':{order:22,marginTop:"2px"},'.cm-search .cm-button[name="next"]::after':{content:'"↓"'},'.cm-search .cm-button[name="select"]':{order:23,marginTop:"2px"},'.cm-search .cm-button[name="select"]::after':{content:'"≡"',fontSize:"17px"},'.cm-panel.cm-search button[name="close"]':{order:5,appearance:"none",WebkitAppearance:"none",display:"inline-flex",alignItems:"center",justifyContent:"center",width:"26px",height:"26px",minWidth:"26px",flexShrink:"0",margin:"0 0 0 auto",padding:"0",borderRadius:"4px",border:"none",backgroundColor:"transparent",backgroundImage:"none",color:r.colors.surface.mutedForeground,cursor:"pointer",fontSize:"16px",lineHeight:"1",boxShadow:"none",position:"relative",overflow:"visible",transition:"background-color 120ms ease, color 120ms ease"},'.cm-panel.cm-search button[name="close"]:hover':{backgroundColor:r.colors.interactive.hover,color:r.colors.surface.foreground},'.cm-search .cm-button[name="replace"]':{order:24,marginTop:"2px"},'.cm-search .cm-button[name="replace"]::after':{content:'"⇄"'},'.cm-search .cm-button[name="replaceAll"], .cm-search .cm-button[name="replace-all"]':{order:25,marginTop:"2px"},'.cm-search .cm-button[name="replaceAll"]::after, .cm-search .cm-button[name="replace-all"]::after':{content:'"⇉"'},'.cm-search .cm-textfield[name="replace"]':{order:20,flex:"1 1 100%",maxWidth:"calc(100% - 142px)",minWidth:"80px",marginTop:"2px"},".cm-searchMatch":{backgroundColor:r.colors.status.infoBackground,boxShadow:`inset 0 0 0 1px ${r.colors.status.infoBorder}`,borderRadius:"2px"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:r.colors.interactive.selection,color:r.colors.interactive.selectionForeground,boxShadow:`inset 0 0 0 1px ${r.colors.interactive.borderFocus}`},"&.cm-focused":{outline:"none"}},{dark:u}),y=Is.define([{tag:[d.comment,d.docComment,d.meta,d.documentMeta],class:"cm-comment"},{tag:[d.keyword,d.controlKeyword,d.moduleKeyword,d.definitionKeyword,d.modifier],class:"cm-keyword"},{tag:[d.operatorKeyword,d.operator,d.derefOperator,d.updateOperator,d.definitionOperator,d.typeOperator,d.controlOperator,d.logicOperator,d.bitwiseOperator,d.arithmeticOperator,d.compareOperator],class:"cm-operator"},{tag:[d.punctuation,d.separator,d.bracket,d.paren,d.brace,d.squareBracket,d.angleBracket],class:"cm-punctuation"},{tag:[d.string,d.regexp,d.attributeValue,d.special(d.string),d.monospace],class:"cm-string"},{tag:d.escape,class:"cm-string-2"},{tag:[d.number,d.bool,d.atom,d.null,d.self],class:"cm-number"},{tag:[d.function(d.variableName),d.function(d.definition(d.variableName)),d.function(d.propertyName),d.standard(d.variableName),d.special(d.variableName)],class:"cm-builtin"},{tag:d.definition(d.variableName),class:"cm-def"},{tag:[d.variableName,d.local(d.variableName),d.constant(d.variableName),d.literal],class:"cm-variable"},{tag:d.propertyName,class:"cm-property"},{tag:d.attributeName,class:"cm-attribute"},{tag:[d.className,d.typeName,d.namespace],class:"cm-variable-3"},{tag:[d.tagName,d.labelName,d.annotation,d.macroName],class:"cm-tag"},{tag:d.link,class:"cm-link"},{tag:[d.heading,d.heading1,d.heading2,d.heading3,d.heading4,d.heading5,d.heading6],class:"cm-keyword"}]),E=Is.define([{tag:[d.comment,d.docComment,d.meta,d.documentMeta],color:r.colors.syntax.base.comment},{tag:[d.keyword,d.controlKeyword,d.moduleKeyword,d.definitionKeyword,d.modifier],color:r.colors.syntax.base.keyword},{tag:[d.operatorKeyword,d.operator,d.derefOperator,d.updateOperator,d.definitionOperator,d.typeOperator,d.controlOperator,d.logicOperator,d.bitwiseOperator,d.arithmeticOperator,d.compareOperator],color:r.colors.syntax.base.operator},{tag:[d.string,d.regexp,d.attributeValue,d.special(d.string),d.monospace],color:r.colors.syntax.base.string},{tag:d.escape,color:p.stringEscape||r.colors.syntax.base.string},{tag:[d.number,d.bool,d.atom,d.null,d.self],color:r.colors.syntax.base.number},{tag:[d.function(d.variableName),d.function(d.definition(d.variableName)),d.function(d.propertyName),d.standard(d.variableName),d.special(d.variableName)],color:r.colors.syntax.base.function},{tag:d.definition(d.variableName),color:p.variableGlobal||r.colors.syntax.base.variable},{tag:[d.variableName,d.local(d.variableName),d.constant(d.variableName),d.literal],color:r.colors.syntax.base.variable},{tag:d.propertyName,color:p.variableProperty||r.colors.syntax.base.variable},{tag:d.attributeName,color:p.variableOther||r.colors.syntax.base.variable},{tag:[d.className,d.typeName,d.namespace],color:r.colors.syntax.base.type},{tag:[d.tagName,d.labelName,d.annotation,d.macroName],color:p.tag||r.colors.syntax.base.keyword},{tag:d.link,color:p.url||r.colors.syntax.base.function,textDecoration:"underline"},{tag:[d.punctuation,d.separator,d.bracket,d.paren,d.brace,d.squareBracket,d.angleBracket],color:p.punctuation||r.colors.syntax.base.comment}]);return a?.syntaxColors===!1?[g]:[g,pr(di,{fallback:!0}),pr(vi),pr(y),pr(E)]}const Ai=180,ba=ei.define(),Ii=1,Bi=2,$i=4,oa=new Map,Vi=(r,a)=>{const u=`${r}|${a}`,f=oa.get(u);if(f)return f;let x="";r&&(x+=`color:${r};`),a&Ii&&(x+="font-style:italic;"),a&Bi&&(x+="font-weight:bold;"),a&$i&&(x+="text-decoration:underline;");const p=yr.mark({attributes:{style:x}});return oa.set(u,p),p},Wi=(r,a)=>{const u=new xn,f=r.state.doc,x=Math.min(a.length,f.lines);for(let p=0;p<x;p+=1){const b=a[p];if(!b||b.length===0)continue;const g=f.line(p+1);let y=g.from;for(const[E,k,L]of b){if(E<=0)continue;const M=y,R=Math.min(y+E,g.to);y+=E,!(R<=M)&&(!k&&!L||u.add(M,R,Vi(k,L)))}}return u.finish()},_i=xa.define({create(){return yr.none},update(r,a){let u=r.map(a.changes);for(const f of a.effects)f.is(ba)&&(u=f.value);return u},provide:r=>se.decorations.from(r)}),qi=r=>va.fromClass(class{timer;generation=0;constructor(a){this.tokenize(a)}update(a){a.docChanged&&this.schedule(a.view)}schedule(a){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.tokenize(a)},Ai)}async tokenize(a){const u=++this.generation,f=a.state.doc.toString(),x=await Do(f,r.language,r.themeName,r.theme);x&&u===this.generation&&a.state.doc.length===f.length&&a.dispatch({effects:ba.of(Wi(a,x))})}destroy(){this.timer&&clearTimeout(this.timer)}}),Hi=r=>[_i,qi(r)];function Ki(r){return!(!r.autoSaveEnabled||!r.isDirty||!r.canWrite||r.isSaving||r.fileLoading||r.isNonEditableBinary||!r.selectedFilePath||r.loadedFilePath!==r.selectedFilePath)}function Gi(r){return r.selectedFilePath?r.isDirty?!(r.fileLoading||r.loadedFilePath!==r.selectedFilePath||r.isNonEditableBinary||r.draftContent===""&&r.fileContent!==""&&r.loadedFilePath!==r.selectedFilePath):!0:!1}const Ui=r=>{const a=I(r);if(!a)return"";if(a==="/"||/^[A-Za-z]:\/$/.test(a))return a;const u=a.lastIndexOf("/");if(u<0)return a;if(u===0)return"/";const f=a.slice(0,u);return/^[A-Za-z]:$/.test(f)?`${f}/`:f},Ji=({label:r,iconDataUrl:a})=>{const[u,f]=n.useState(!1),x=r.trim().slice(0,1).toUpperCase()||"?";return a&&!u?t.jsx("img",{src:a,alt:"",className:"size-4 rounded-sm",onError:()=>f(!0)}):t.jsx("span",{className:$("size-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:x})},Yi=r=>r.slice().sort((a,u)=>a.type!==u.type?a.type==="directory"?-1:1:a.name.localeCompare(u.name)),I=r=>{if(!r)return"";const a=r.replace(/\\/g,"/"),u=a.startsWith("//");let f=a.replace(/\/+/g,"/");u&&!f.startsWith("//")&&(f=`/${f}`);const x=f==="/",p=/^[A-Za-z]:\/$/.test(f);return!x&&!p&&(f=f.replace(/\/+$/,"")),f},Xi=r=>r.startsWith("/")||r.startsWith("//")||/^[A-Za-z]:\//.test(r),Et=r=>/^[A-Za-z]:\//.test(r)?r.toLowerCase():r,Ht=(r,a)=>{const u=I(a),f=I(r);if(!u||!f)return!1;const x=Et(u),p=Et(f);return p===x||p.startsWith(`${x}/`)},ia=(r,a)=>{const u=I(a),f=I(r);if(!Ht(f,u))return[];const p=f.slice(u.length).replace(/^\//,"").split("/"),b=[];let g=u;for(let y=0;y<p.length-1;y++)g=g?`${g}/${p[y]}`:p[y],b.push(g);return b},xr=(r,a)=>{if(!a)return"";const u=I(a);if(!r||!Ht(u,r))return u;const f=u.slice(r.length);return f.startsWith("/")?f.slice(1):f},Zi=new Set(["node_modules"]),Qi=({status:r})=>{const a={open:"var(--status-info)",modified:"var(--status-warning)","git-modified":"var(--status-warning)","git-added":"var(--status-success)","git-deleted":"var(--status-error)"}[r];return t.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:a}})},ca=({name:r})=>{const a=n.useRef(null),u=n.useRef(null),[f,x]=n.useState(!1);return n.useLayoutEffect(()=>{const p=a.current,b=u.current;if(!p||!b)return;const g=()=>{x(b.scrollWidth>p.clientWidth+1)};g();const y=new ResizeObserver(g);return y.observe(p),y.observe(b),()=>{y.disconnect()}},[r]),t.jsxs("span",{ref:a,className:"relative block min-w-0 flex-1 overflow-hidden whitespace-nowrap",children:[t.jsx("span",{ref:u,"aria-hidden":"true",className:"invisible absolute whitespace-nowrap",children:r}),f?t.jsxs("span",{className:"open-file-name-marquee-track",children:[t.jsx("span",{className:"open-file-name-marquee-item",children:r}),t.jsx("span",{className:"open-file-name-marquee-item","aria-hidden":"true",children:r})]}):t.jsx("span",{className:"block min-w-0 truncate",children:r})]})},ec=r=>Zi.has(r),tc=r=>{const a=I(r);return a==="node_modules"||a.endsWith("/node_modules")||a.includes("/node_modules/")},rc=r=>{const u=(r instanceof Error?r.message:String(r??"")).toLowerCase();return u.includes("is a directory")||u.includes("eisdir")},la=r=>{const u=(r instanceof Error?r.message:String(r??"")).toLowerCase();return u.includes("file not found")||u.includes("enoent")||u.includes("no such file")||u.includes("does not exist")},qt=2e5,nc=r=>{let a=0,u=0;for(let f=0;f<r.length;f+=1)r.charCodeAt(f)===10&&(f>0&&r.charCodeAt(f-1)===13?a+=1:u+=1);return a>u?`\r
2
2
  `:`
3
3
  `},wa=r=>r.replace(/\r\n/g,`
4
4
  `).replace(/\r/g,`
5
5
  `),sc=(r,a)=>{const u=wa(r);return a===`\r
6
6
  `?u.replace(/\n/g,`\r
7
- `):u},ya=(r,a)=>t.jsx(hr,{filePath:r,extension:a}),ua=r=>{if(!r)return!1;const a=r.toLowerCase().split(".").pop();return a==="md"||a==="markdown"},ac=r=>{if(!r)return!1;const a=r.toLowerCase().split(".").pop();return a==="json"||a==="jsonc"||a==="json5"||a==="geojson"},fn=r=>{if(!r)return!1;const a=r.toLowerCase().split(".").pop();return a==="html"||a==="htm"},oc=({node:r,root:a,isExpanded:u,isActive:f,isMobile:x,isBrowserClient:p,alwaysShowActions:b,status:g,badge:y,permissions:E,downloadFile:k,contextMenuPath:L,setContextMenuPath:M,rightClickMenuPath:R,setRightClickMenuPath:P,onSelect:o,onToggle:G,onRevealPath:xe,onOpenDialog:de})=>{const B=r.type==="directory",{canRename:Ne,canCreateFile:ae,canCreateFolder:Re,canDelete:Oe,canReveal:dt}=E,K=!B&&!!k,V=dt&&!p,fe=Ne||ae||Re||Oe||K||V,w=n.useCallback(C=>{fe&&(C?.preventDefault(),P(r.path))},[fe,r.path,P]),U=n.useCallback(()=>{B?G(r.path):o(r)},[B,r,o,G]),N=n.useCallback(C=>{C.stopPropagation(),P(null),M(r.path)},[r.path,M,P]),T=({Item:C,Separator:oe})=>t.jsxs(t.Fragment,{children:[Ne&&t.jsxs(C,{onClick:O=>{O.stopPropagation(),de("rename",r)},children:[t.jsx(v,{name:"edit",className:"mr-2 size-4"})," ","Rename"]}),t.jsxs(C,{onClick:O=>{O.stopPropagation(),br(r.path).then(ze=>{if(ze.ok){A.success("Path copied");return}A.error("Copy failed")})},children:[t.jsx(v,{name:"file-copy",className:"mr-2 size-4"})," ","Copy Path"]}),t.jsxs(C,{onClick:O=>{O.stopPropagation();const ze=xr(a,r.path)||r.path;br(ze).then(jr=>{if(jr.ok){A.success("Relative path copied");return}A.error("Copy failed")})},children:[t.jsx(v,{name:"file-copy-2",className:"mr-2 size-4"})," ","Copy Relative Path"]}),!B&&k&&t.jsxs(C,{onClick:O=>{O.stopPropagation(),k(r.path).catch(ze=>{console.error("Download failed:",ze),A.error("Operation failed")})},children:[t.jsx(v,{name:"download",className:"mr-2 size-4"})," ",p?"Download":"Save"]}),V&&t.jsxs(C,{onClick:O=>{O.stopPropagation(),xe(r.path)},children:[t.jsx(v,{name:"folder-received",className:"mr-2 size-4"})," ",Ho()]}),B&&(ae||Re)&&t.jsxs(t.Fragment,{children:[t.jsx(oe,{}),ae&&t.jsxs(C,{onClick:O=>{O.stopPropagation(),de("createFile",r)},children:[t.jsx(v,{name:"file-add",className:"mr-2 size-4"})," ","New File"]}),Re&&t.jsxs(C,{onClick:O=>{O.stopPropagation(),de("createFolder",r)},children:[t.jsx(v,{name:"folder-add",className:"mr-2 size-4"})," ","New Folder"]})]}),Oe&&t.jsxs(t.Fragment,{children:[t.jsx(oe,{}),t.jsxs(C,{onClick:O=>{O.stopPropagation(),de("delete",r)},className:"text-destructive focus:text-destructive",children:[t.jsx(v,{name:"delete-bin",className:"mr-2 size-4"})," ","Delete"]})]})]});return t.jsxs(Ko,{open:R===r.path,onOpenChange:C=>P(C?r.path:null),children:[t.jsxs(Uo,{render:t.jsx("div",{className:"group relative flex items-center",onContextMenu:x?void 0:w}),children:[t.jsxs("button",{type:"button",onClick:U,onContextMenu:x?void 0:w,className:$("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",f?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[B?u?t.jsx(v,{name:"folder-open",className:"size-4 flex-shrink-0 text-muted-foreground"}):t.jsx(v,{name:"folder-3",className:"size-4 flex-shrink-0 text-muted-foreground"}):ya(r.path,r.extension),t.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:r.path,children:r.name}),!B&&g&&t.jsx(Qi,{status:g}),B&&y&&t.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[y.modified>0&&t.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",y.modified]}),y.added>0&&t.jsxs("span",{className:"text-[var(--status-success)]",children:["+",y.added]})]})]}),fe&&t.jsx("div",{className:$("absolute right-1 top-1/2 -translate-y-1/2",b?"opacity-100":"opacity-0 focus-within:opacity-100 group-hover:opacity-100"),children:t.jsxs(pn,{open:L===r.path,onOpenChange:C=>M(C?r.path:null),children:[t.jsx(hn,{asChild:!0,children:t.jsx(S,{variant:"ghost",size:"icon",className:"size-6",onClick:N,children:t.jsx(v,{name:"more-2-fill",className:"size-4"})})}),t.jsx(gn,{align:"end",side:"bottom",onCloseAutoFocus:()=>M(null),children:T({Item:gr,Separator:Go})})]})})]}),t.jsx(Jo,{className:"min-w-[180px]",children:T({Item:Yo,Separator:Xo})})]})},ic=({activeDialog:r,dialogData:a,dialogInputValue:u,onDialogInputChange:f,isDialogSubmitting:x,onDialogSubmit:p,onClose:b,inputRef:g})=>t.jsx(da,{open:!!r,onOpenChange:y=>!y&&b(),children:t.jsxs(fa,{initialFocus:g,children:[t.jsxs(ma,{children:[t.jsxs(pa,{children:[r==="createFile"&&"Create File",r==="createFolder"&&"Create Folder",r==="rename"&&"Rename",r==="delete"&&"Delete"]}),t.jsxs(ha,{children:[r==="createFile"&&`Create a new file in ${a?.path??"root"}`,r==="createFolder"&&`Create a new folder in ${a?.path??"root"}`,r==="rename"&&`Rename ${a?.name??""}`,r==="delete"&&`Are you sure you want to delete ${a?.name??""}? This action cannot be undone.`]})]}),r!=="delete"&&t.jsx("div",{className:"py-4",children:t.jsx(vr,{value:u,onChange:y=>f(y.target.value),placeholder:r==="rename"?"New name":"Name",onKeyDown:y=>{y.key==="Enter"&&p()},ref:g})}),t.jsxs(ga,{children:[t.jsx(S,{variant:"outline",onClick:b,disabled:x,children:"Cancel"}),t.jsx(S,{variant:r==="delete"?"destructive":"default",onClick:()=>{p()},disabled:x||r!=="delete"&&!u.trim(),children:x?t.jsx(v,{name:"loader-4",className:"size-4 animate-spin"}):r==="delete"?"Delete":"Confirm"})]})]})}),mn=(r,a,u)=>{const[f,x]=n.useState(""),[p,b]=n.useState(0);return n.useEffect(()=>{if(!r){x("");return}let g=!1;x("");const y=So(),E=Fo(y);Eo(y).then(L=>{g||!L||(x(r),a(null))}).catch(L=>{g||(a(L instanceof Error?L.message:u),x(r))});const k=Ro(()=>{g||(x(r),b(L=>L+1),a(null))});return()=>{g=!0,E(),k()}},[r,a,u]),{readyKey:f,nonce:p}},yu=({mode:r="full"})=>{const{files:a,runtime:u}=Do(),{currentTheme:f,availableThemes:x,lightThemeId:p,darkThemeId:b}=Po(),{isMobile:g,isTablet:y,screenWidth:E}=Mo(),k=wo(u.platform),L=g||y,M=yo(),R=jo(),P=To()??"",o=I(P.trim()),G=r!=="editor-only",xe=r==="editor-only"&&!g,de=No(e=>e.searchFiles),B=Lo(P),[Ne,ae]=n.useState(""),Re=Oo(Ne,200),Oe=n.useRef(null),[dt,K]=n.useState(!1),[V,fe]=n.useState(!0),[w,U]=n.useState(!1),[N,T]=n.useState(!1),[C,oe]=n.useState(!1),O=n.useRef(null),ze=n.useRef(0),jr=n.useCallback(e=>{ze.current=Math.max(0,ze.current+(e?1:-1))},[]),vn=n.useCallback(e=>e instanceof Element?e.closest('[data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-item"]')!==null:!1,[]);n.useEffect(()=>{if(!C)return;const e=s=>{ze.current>0||vn(s.target)||O.current&&!O.current.contains(s.target)&&oe(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[vn,C]);const[ie,Rt]=n.useState("edit"),[Nr,kr]=n.useState("edit"),[ft,Cr]=n.useState("tree"),[mt,Sr]=n.useState("edit"),[Qe,zt]=n.useState("preview"),[ja,Na]=n.useState(0),Fr=n.useRef({}),Er=n.useRef({}),Rr=n.useRef({}),zr=n.useRef({}),Gt=n.useMemo(()=>x.find(e=>e.metadata.id===p)??Es(!1),[x,p]),Kt=n.useMemo(()=>x.find(e=>e.metadata.id===b)??Es(!0),[x,b]);n.useEffect(()=>{Ws(Gt),Ws(Kt)},[Gt,Kt]);const Ut=n.useMemo(()=>[],[]),Q=Ee(e=>o?e.byRoot[o]?.openPaths??Ut:Ut),et=Ee(e=>o?e.byRoot[o]?.selectedPath??null:null),tt=Ee(e=>o?e.byRoot[o]?.expandedPaths??Ut:Ut),pt=Ee(e=>e.removeOpenPath),qe=Ee(e=>e.removeOpenPathsByPrefix),bn=Ee(e=>e.removeExpandedPathsByPrefix),ee=Ee(e=>e.setSelectedPath),wn=Ee(e=>e.toggleExpandedPath),Jt=Ee(e=>e.expandPaths),ht=n.useCallback(e=>{const s=I(e),i=s.split("/"),c=i[i.length-1]||s,m=c.includes(".")?c.split(".").pop()?.toLowerCase():void 0;return{name:c,path:s,type:"file",extension:m}},[]),gt=n.useMemo(()=>Q.map(ht),[Q,ht]),Dr=n.useMemo(()=>{if(et){const e=Et(et);if(Q.some(s=>Et(s)===e))return et}return Q[0]??null},[Q,et]),l=n.useMemo(()=>Dr?ht(Dr):null,[Dr,ht]),De=l?.path??"";n.useEffect(()=>{if(!o||!et)return;const e=Et(et);Q.some(i=>Et(i)===e)||ee(o,Q[0]??null)},[Q,o,et,ee]);const Yt=!!(o&&De&&!Ht(De,o)),yn=Yt?Ds(De):void 0,J=n.useMemo(()=>({allowOutsideWorkspace:r==="editor-only"&&Yt,outsideFileGrant:yn,directory:o||void 0}),[r,Yt,yn,o]),Pr=n.useRef(null),[jn,ka]=n.useState({left:!1,right:!1}),Nn=n.useCallback(()=>{const e=Pr.current;e&&ka({left:e.scrollLeft>2,right:e.scrollLeft+e.clientWidth<e.scrollWidth-2})},[]),kn=n.useRef(Nn);kn.current=Nn,n.useEffect(()=>{const e=Pr.current;if(!e)return;const s=()=>kn.current();s(),e.addEventListener("scroll",s,{passive:!0});const i=new ResizeObserver(s);return i.observe(e),()=>{e.removeEventListener("scroll",s),i.disconnect()}},[gt.length]);const[Cn,Mr]=n.useState({}),[Xt,Dt]=n.useState({}),ve=n.useRef(new Set),be=n.useRef(new Set),Ae=n.useRef(new Map),Sn=n.useRef(0),[Fn,Zt]=n.useState([]),[Ca,Qt]=n.useState(!1),[z,q]=n.useState(""),[ke,Ie]=n.useState(!1),[Be,Y]=n.useState(null),[Sa,Ce]=n.useState(""),me=n.useRef(""),[pe,H]=n.useState(null),[W,X]=n.useState(""),[xt,Tr]=n.useState(!1),[En,Fa]=n.useState(`
8
- `),Ea=n.useRef(null),Pe=n.useRef(null),he=n.useRef(null),He=n.useRef(""),Pt=n.useRef(""),$e=n.useRef(null),Rn=n.useRef(null),Ve=n.useRef(null),er=n.useRef(0),Mt=n.useRef(null),[Ra,vt]=n.useState("idle"),[za,tr]=n.useState(!1),[Tt,zn]=n.useState(!1),te=ue(e=>e.autoSaveEnabled),Da=ue(e=>e.setAutoSaveEnabled),[Lr,bt]=n.useState(!1),wt=n.useRef(null),Lt=n.useRef(null),Ot=n.useRef(null),rt=n.useRef(!1),At=n.useRef(null),It=n.useRef(null),Se=n.useRef(null),Pa=n.useRef(null),[Ma,Or]=n.useState(0),yt=n.useRef(null),nt=n.useRef({key:"",attempts:0});n.useEffect(()=>()=>{yt.current!==null&&typeof window<"u"&&(window.cancelAnimationFrame(yt.current),yt.current=null)},[]);const[st,Ar]=n.useState(null),[at,Ta]=n.useState(null),[Ge,Dn]=n.useState(""),[La,Ir]=n.useState(!1),[Oa,Aa]=n.useState(null),[Ia,Ba]=n.useState(null),[$a,Pn]=n.useState(!1),[Va,Mn]=n.useState(!1),[Wa,Br]=n.useState(!1),Tn=!!a.writeFile,Ln=!!a.createDirectory,On=!!a.rename,An=!!a.delete,In=!!a.revealPath,_a=mr(e=>e.availableApps),qa=mr(e=>e.isCacheStale),Bn=mr(e=>e.initialize),Ha=mr(e=>e.loadInstalledApps);n.useEffect(()=>{Bn()},[Bn]);const Ga=n.useCallback(e=>{a.revealPath&&a.revealPath(e).catch(()=>{A.error("Failed to reveal path")})},[a]),Ka=n.useCallback(async e=>{if(!l?.path||await ko(l.path,e.id,e.appName)||await Rs(l.path,e.appName))return;const c=Ui(l.path)||o;c&&await Rs(c,e.appName)||A.error(`Failed to open in ${e.appName}`)},[o,l?.path]),$r=n.useCallback((e,s)=>{Ar(e),Ta(s),Dn(e==="rename"&&s.name||""),Ir(!1)},[]),[D,Fe]=n.useState(null),jt=n.useRef(!1),Ke=n.useRef(null),[$n,Nt]=n.useState(!1),Me=ue(e=>e.setMainTabGuard),Te=ue(e=>e.pendingFileNavigation),rr=ue(e=>e.setPendingFileNavigation),Vr=ue(e=>e.pendingFileFocusPath),Wr=ue(e=>e.setPendingFileFocusPath),Vn=ue(e=>e.shortcutOverrides),Wn=ue(e=>e.fileEditorKeymap),Bt=Ao(e=>e.settingsDefaultFileViewerPreview),_n=ue(e=>e.expandedEditorToolbar);n.useEffect(()=>{const e=()=>{jt.current=!1,Ke.current=null,Nt(!1)};return document.addEventListener("mouseup",e),()=>document.removeEventListener("mouseup",e)},[]),n.useEffect(()=>()=>{At.current!==null&&window.clearTimeout(At.current),It.current!==null&&window.clearTimeout(It.current)},[]);const Ua=n.useCallback((e,s)=>{const i=e.split(`
7
+ `):u},ya=(r,a)=>t.jsx(hr,{filePath:r,extension:a}),ua=r=>{if(!r)return!1;const a=r.toLowerCase().split(".").pop();return a==="md"||a==="markdown"},ac=r=>{if(!r)return!1;const a=r.toLowerCase().split(".").pop();return a==="json"||a==="jsonc"||a==="json5"||a==="geojson"},fn=r=>{if(!r)return!1;const a=r.toLowerCase().split(".").pop();return a==="html"||a==="htm"},oc=({node:r,root:a,isExpanded:u,isActive:f,isMobile:x,isBrowserClient:p,alwaysShowActions:b,status:g,badge:y,permissions:E,downloadFile:k,contextMenuPath:L,setContextMenuPath:M,rightClickMenuPath:R,setRightClickMenuPath:P,onSelect:o,onToggle:K,onRevealPath:xe,onOpenDialog:de})=>{const B=r.type==="directory",{canRename:Ne,canCreateFile:ae,canCreateFolder:Re,canDelete:Oe,canReveal:dt}=E,G=!B&&!!k,V=dt&&!p,fe=Ne||ae||Re||Oe||G||V,w=n.useCallback(C=>{fe&&(C?.preventDefault(),P(r.path))},[fe,r.path,P]),U=n.useCallback(()=>{B?K(r.path):o(r)},[B,r,o,K]),N=n.useCallback(C=>{C.stopPropagation(),P(null),M(r.path)},[r.path,M,P]),T=({Item:C,Separator:oe})=>t.jsxs(t.Fragment,{children:[Ne&&t.jsxs(C,{onClick:O=>{O.stopPropagation(),de("rename",r)},children:[t.jsx(v,{name:"edit",className:"mr-2 size-4"})," ","Rename"]}),t.jsxs(C,{onClick:O=>{O.stopPropagation(),br(r.path).then(De=>{if(De.ok){A.success("Path copied");return}A.error("Copy failed")})},children:[t.jsx(v,{name:"file-copy",className:"mr-2 size-4"})," ","Copy Path"]}),t.jsxs(C,{onClick:O=>{O.stopPropagation();const De=xr(a,r.path)||r.path;br(De).then(jr=>{if(jr.ok){A.success("Relative path copied");return}A.error("Copy failed")})},children:[t.jsx(v,{name:"file-copy-2",className:"mr-2 size-4"})," ","Copy Relative Path"]}),!B&&k&&t.jsxs(C,{onClick:O=>{O.stopPropagation(),k(r.path).catch(De=>{console.error("Download failed:",De),A.error("Operation failed")})},children:[t.jsx(v,{name:"download",className:"mr-2 size-4"})," ",p?"Download":"Save"]}),V&&t.jsxs(C,{onClick:O=>{O.stopPropagation(),xe(r.path)},children:[t.jsx(v,{name:"folder-received",className:"mr-2 size-4"})," ",Ho()]}),B&&(ae||Re)&&t.jsxs(t.Fragment,{children:[t.jsx(oe,{}),ae&&t.jsxs(C,{onClick:O=>{O.stopPropagation(),de("createFile",r)},children:[t.jsx(v,{name:"file-add",className:"mr-2 size-4"})," ","New File"]}),Re&&t.jsxs(C,{onClick:O=>{O.stopPropagation(),de("createFolder",r)},children:[t.jsx(v,{name:"folder-add",className:"mr-2 size-4"})," ","New Folder"]})]}),Oe&&t.jsxs(t.Fragment,{children:[t.jsx(oe,{}),t.jsxs(C,{onClick:O=>{O.stopPropagation(),de("delete",r)},className:"text-destructive focus:text-destructive",children:[t.jsx(v,{name:"delete-bin",className:"mr-2 size-4"})," ","Delete"]})]})]});return t.jsxs(Go,{open:R===r.path,onOpenChange:C=>P(C?r.path:null),children:[t.jsxs(Uo,{render:t.jsx("div",{className:"group relative flex items-center",onContextMenu:x?void 0:w}),children:[t.jsxs("button",{type:"button",onClick:U,onContextMenu:x?void 0:w,className:$("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",f?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[B?u?t.jsx(v,{name:"folder-open",className:"size-4 flex-shrink-0 text-muted-foreground"}):t.jsx(v,{name:"folder-3",className:"size-4 flex-shrink-0 text-muted-foreground"}):ya(r.path,r.extension),t.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:r.path,children:r.name}),!B&&g&&t.jsx(Qi,{status:g}),B&&y&&t.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[y.modified>0&&t.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",y.modified]}),y.added>0&&t.jsxs("span",{className:"text-[var(--status-success)]",children:["+",y.added]})]})]}),fe&&t.jsx("div",{className:$("absolute right-1 top-1/2 -translate-y-1/2",b?"opacity-100":"opacity-0 focus-within:opacity-100 group-hover:opacity-100"),children:t.jsxs(pn,{open:L===r.path,onOpenChange:C=>M(C?r.path:null),children:[t.jsx(hn,{asChild:!0,children:t.jsx(S,{variant:"ghost",size:"icon",className:"size-6",onClick:N,children:t.jsx(v,{name:"more-2-fill",className:"size-4"})})}),t.jsx(gn,{align:"end",side:"bottom",onCloseAutoFocus:()=>M(null),children:T({Item:gr,Separator:Ko})})]})})]}),t.jsx(Jo,{className:"min-w-[180px]",children:T({Item:Yo,Separator:Xo})})]})},ic=({activeDialog:r,dialogData:a,dialogInputValue:u,onDialogInputChange:f,isDialogSubmitting:x,onDialogSubmit:p,onClose:b,inputRef:g})=>t.jsx(da,{open:!!r,onOpenChange:y=>!y&&b(),children:t.jsxs(fa,{initialFocus:g,children:[t.jsxs(ma,{children:[t.jsxs(pa,{children:[r==="createFile"&&"Create File",r==="createFolder"&&"Create Folder",r==="rename"&&"Rename",r==="delete"&&"Delete"]}),t.jsxs(ha,{children:[r==="createFile"&&`Create a new file in ${a?.path??"root"}`,r==="createFolder"&&`Create a new folder in ${a?.path??"root"}`,r==="rename"&&`Rename ${a?.name??""}`,r==="delete"&&`Are you sure you want to delete ${a?.name??""}? This action cannot be undone.`]})]}),r!=="delete"&&t.jsx("div",{className:"py-4",children:t.jsx(vr,{value:u,onChange:y=>f(y.target.value),placeholder:r==="rename"?"New name":"Name",onKeyDown:y=>{y.key==="Enter"&&p()},ref:g})}),t.jsxs(ga,{children:[t.jsx(S,{variant:"outline",onClick:b,disabled:x,children:"Cancel"}),t.jsx(S,{variant:r==="delete"?"destructive":"default",onClick:()=>{p()},disabled:x||r!=="delete"&&!u.trim(),children:x?t.jsx(v,{name:"loader-4",className:"size-4 animate-spin"}):r==="delete"?"Delete":"Confirm"})]})]})}),mn=(r,a,u)=>{const[f,x]=n.useState(""),[p,b]=n.useState(0);return n.useEffect(()=>{if(!r){x("");return}let g=!1;x("");const y=So(),E=Fo(y);Eo(y).then(L=>{g||!L||(x(r),a(null))}).catch(L=>{g||(a(L instanceof Error?L.message:u),x(r))});const k=Ro(()=>{g||(x(r),b(L=>L+1),a(null))});return()=>{g=!0,E(),k()}},[r,a,u]),{readyKey:f,nonce:p}},yu=({mode:r="full"})=>{const{files:a,runtime:u}=zo(),{currentTheme:f,availableThemes:x,lightThemeId:p,darkThemeId:b}=Po(),{isMobile:g,isTablet:y,screenWidth:E}=Mo(),k=wo(u.platform),L=g||y,M=yo(),R=jo(),P=To()??"",o=I(P.trim()),K=r!=="editor-only",xe=r==="editor-only"&&!g,de=No(e=>e.searchFiles),B=Lo(P),[Ne,ae]=n.useState(""),Re=Oo(Ne,200),Oe=n.useRef(null),[dt,G]=n.useState(!1),[V,fe]=n.useState(!0),[w,U]=n.useState(!1),[N,T]=n.useState(!1),[C,oe]=n.useState(!1),O=n.useRef(null),De=n.useRef(0),jr=n.useCallback(e=>{De.current=Math.max(0,De.current+(e?1:-1))},[]),vn=n.useCallback(e=>e instanceof Element?e.closest('[data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-item"]')!==null:!1,[]);n.useEffect(()=>{if(!C)return;const e=s=>{De.current>0||vn(s.target)||O.current&&!O.current.contains(s.target)&&oe(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[vn,C]);const[ie,Rt]=n.useState("edit"),[Nr,kr]=n.useState("edit"),[ft,Cr]=n.useState("tree"),[mt,Sr]=n.useState("edit"),[Qe,Dt]=n.useState("preview"),[ja,Na]=n.useState(0),Fr=n.useRef({}),Er=n.useRef({}),Rr=n.useRef({}),Dr=n.useRef({}),Kt=n.useMemo(()=>x.find(e=>e.metadata.id===p)??Es(!1),[x,p]),Gt=n.useMemo(()=>x.find(e=>e.metadata.id===b)??Es(!0),[x,b]);n.useEffect(()=>{Ws(Kt),Ws(Gt)},[Kt,Gt]);const Ut=n.useMemo(()=>[],[]),Q=Ee(e=>o?e.byRoot[o]?.openPaths??Ut:Ut),et=Ee(e=>o?e.byRoot[o]?.selectedPath??null:null),tt=Ee(e=>o?e.byRoot[o]?.expandedPaths??Ut:Ut),pt=Ee(e=>e.removeOpenPath),qe=Ee(e=>e.removeOpenPathsByPrefix),bn=Ee(e=>e.removeExpandedPathsByPrefix),ee=Ee(e=>e.setSelectedPath),wn=Ee(e=>e.toggleExpandedPath),Jt=Ee(e=>e.expandPaths),ht=n.useCallback(e=>{const s=I(e),i=s.split("/"),c=i[i.length-1]||s,m=c.includes(".")?c.split(".").pop()?.toLowerCase():void 0;return{name:c,path:s,type:"file",extension:m}},[]),gt=n.useMemo(()=>Q.map(ht),[Q,ht]),zr=n.useMemo(()=>{if(et){const e=Et(et);if(Q.some(s=>Et(s)===e))return et}return Q[0]??null},[Q,et]),l=n.useMemo(()=>zr?ht(zr):null,[zr,ht]),ze=l?.path??"";n.useEffect(()=>{if(!o||!et)return;const e=Et(et);Q.some(i=>Et(i)===e)||ee(o,Q[0]??null)},[Q,o,et,ee]);const Yt=!!(o&&ze&&!Ht(ze,o)),yn=Yt?zs(ze):void 0,J=n.useMemo(()=>({allowOutsideWorkspace:r==="editor-only"&&Yt,outsideFileGrant:yn,directory:o||void 0}),[r,Yt,yn,o]),Pr=n.useRef(null),[jn,ka]=n.useState({left:!1,right:!1}),Nn=n.useCallback(()=>{const e=Pr.current;e&&ka({left:e.scrollLeft>2,right:e.scrollLeft+e.clientWidth<e.scrollWidth-2})},[]),kn=n.useRef(Nn);kn.current=Nn,n.useEffect(()=>{const e=Pr.current;if(!e)return;const s=()=>kn.current();s(),e.addEventListener("scroll",s,{passive:!0});const i=new ResizeObserver(s);return i.observe(e),()=>{e.removeEventListener("scroll",s),i.disconnect()}},[gt.length]);const[Cn,Mr]=n.useState({}),[Xt,zt]=n.useState({}),ve=n.useRef(new Set),be=n.useRef(new Set),Ae=n.useRef(new Map),Sn=n.useRef(0),[Fn,Zt]=n.useState([]),[Ca,Qt]=n.useState(!1),[D,q]=n.useState(""),[ke,Ie]=n.useState(!1),[Be,Y]=n.useState(null),[Sa,Ce]=n.useState(""),me=n.useRef(""),[pe,H]=n.useState(null),[W,X]=n.useState(""),[xt,Tr]=n.useState(!1),[En,Fa]=n.useState(`
8
+ `),Ea=n.useRef(null),Pe=n.useRef(null),he=n.useRef(null),He=n.useRef(""),Pt=n.useRef(""),$e=n.useRef(null),Rn=n.useRef(null),Ve=n.useRef(null),er=n.useRef(0),Mt=n.useRef(null),[Ra,vt]=n.useState("idle"),[Da,tr]=n.useState(!1),[Tt,Dn]=n.useState(!1),te=ue(e=>e.autoSaveEnabled),za=ue(e=>e.setAutoSaveEnabled),[Lr,bt]=n.useState(!1),wt=n.useRef(null),Lt=n.useRef(null),Ot=n.useRef(null),rt=n.useRef(!1),At=n.useRef(null),It=n.useRef(null),Se=n.useRef(null),Pa=n.useRef(null),[Ma,Or]=n.useState(0),yt=n.useRef(null),nt=n.useRef({key:"",attempts:0});n.useEffect(()=>()=>{yt.current!==null&&typeof window<"u"&&(window.cancelAnimationFrame(yt.current),yt.current=null)},[]);const[st,Ar]=n.useState(null),[at,Ta]=n.useState(null),[Ke,zn]=n.useState(""),[La,Ir]=n.useState(!1),[Oa,Aa]=n.useState(null),[Ia,Ba]=n.useState(null),[$a,Pn]=n.useState(!1),[Va,Mn]=n.useState(!1),[Wa,Br]=n.useState(!1),Tn=!!a.writeFile,Ln=!!a.createDirectory,On=!!a.rename,An=!!a.delete,In=!!a.revealPath,_a=mr(e=>e.availableApps),qa=mr(e=>e.isCacheStale),Bn=mr(e=>e.initialize),Ha=mr(e=>e.loadInstalledApps);n.useEffect(()=>{Bn()},[Bn]);const Ka=n.useCallback(e=>{a.revealPath&&a.revealPath(e).catch(()=>{A.error("Failed to reveal path")})},[a]),Ga=n.useCallback(async e=>{if(!l?.path||await ko(l.path,e.id,e.appName)||await Rs(l.path,e.appName))return;const c=Ui(l.path)||o;c&&await Rs(c,e.appName)||A.error(`Failed to open in ${e.appName}`)},[o,l?.path]),$r=n.useCallback((e,s)=>{Ar(e),Ta(s),zn(e==="rename"&&s.name||""),Ir(!1)},[]),[z,Fe]=n.useState(null),jt=n.useRef(!1),Ge=n.useRef(null),[$n,Nt]=n.useState(!1),Me=ue(e=>e.setMainTabGuard),Te=ue(e=>e.pendingFileNavigation),rr=ue(e=>e.setPendingFileNavigation),Vr=ue(e=>e.pendingFileFocusPath),Wr=ue(e=>e.setPendingFileFocusPath),Vn=ue(e=>e.shortcutOverrides),Wn=ue(e=>e.fileEditorKeymap),Bt=Ao(e=>e.settingsDefaultFileViewerPreview),_n=ue(e=>e.expandedEditorToolbar);n.useEffect(()=>{const e=()=>{jt.current=!1,Ge.current=null,Nt(!1)};return document.addEventListener("mouseup",e),()=>document.removeEventListener("mouseup",e)},[]),n.useEffect(()=>()=>{At.current!==null&&window.clearTimeout(At.current),It.current!==null&&window.clearTimeout(It.current)},[]);const Ua=n.useCallback((e,s)=>{const i=e.split(`
9
9
  `),c=Math.max(1,s.start),m=Math.min(i.length,s.end);return c>m?"":i.slice(c-1,m).join(`
10
- `)},[]),Ja=ji({source:"file",fileLabel:l?.path??null,language:l?.path&&nn(l.path)||"text",getCodeForRange:e=>Ua(z,Ni(e)),toStoreRange:e=>({startLine:e.start,endLine:e.end}),fromDraftRange:e=>({start:e.startLine,end:e.endLine})}),{drafts:qn,commentText:nr,setCommentText:Hn,editingDraftId:sr,setSelection:Gn,saveComment:Kn,cancel:$t,reset:Un,startEdit:Jn,deleteDraft:Yn}=Ja;n.useEffect(()=>{Fe(null),Un(),Me(null),X(""),Tr(!1)},[l?.path,Un,Me]),n.useEffect(()=>{Gn(D)},[D,Gn]),n.useEffect(()=>{if(!D&&!sr)return;const e=i=>{const c=i.target;c.closest('[data-comment-input="true"]')||c.closest('[data-comment-card="true"]')||c.closest(".cm-gutterElement")||c.closest("[data-sonner-toast]")||c.closest("[data-sonner-toaster]")||nr.trim()||(Fe(null),$t())},s=setTimeout(()=>{document.addEventListener("click",e)},100);return()=>{clearTimeout(s),document.removeEventListener("click",e)}},[$t,nr,sr,D]);const Xn=n.useCallback((e,s)=>{const i=s??D??void 0;s&&Fe(s),Kn(e,i),Fe(null)},[D,Kn]),Zn=n.useCallback((e,s)=>{const i=[];for(const c of s){if(!(c&&typeof c.name=="string"&&c.name.length>0)||!M&&c.name.startsWith(".")||!R&&ec(c.name))continue;const m=c.name,h=I(c.path||""),j=h?Xi(h)?h:I(`${e}/${h}`):I(`${e}/${m}`),F=c.isDirectory?"directory":"file",_=F==="file"&&m.includes(".")?m.split(".").pop()?.toLowerCase():void 0;i.push({name:m,path:j,type:F,extension:_})}return Yi(i)},[R,M]),we=n.useCallback(async e=>{const s=I(e.trim());if(!s||ve.current.has(s)||be.current.has(s))return;be.current=new Set(be.current),be.current.add(s);const i=Sn.current+1;Sn.current=i,Ae.current=new Map(Ae.current),Ae.current.set(s,i);const c=()=>Ae.current.get(s)===i;await(a.listDirectory?a.listDirectory(s).then(h=>h.entries.map(j=>({name:j.name,path:j.path,isDirectory:j.isDirectory}))):Co(s).then(h=>h.map(j=>({name:j.name,path:j.path,isDirectory:j.isDirectory})))).then(h=>{if(!c())return;const j=Zn(s,h);ve.current=new Set(ve.current),ve.current.add(s),Dt(F=>{if(!F[s])return F;const _={...F};return delete _[s],_}),Mr(F=>({...F,[s]:j}))}).catch(h=>{if(!c())return;const j=h instanceof Error?h.message:String(h??"");if(j==="Directory not found"&&o&&s!==o){bn(o,s),Dt(F=>{if(!F[s])return F;const _={...F};return delete _[s],_});return}console.error("Failed to load files directory:",h),Dt(F=>({...F,[s]:j}))}).finally(()=>{c()&&(Ae.current=new Map(Ae.current),Ae.current.delete(s),be.current=new Set(be.current),be.current.delete(s))})},[a,Zn,bn,o]),ar=n.useCallback(async()=>{o&&(ve.current=new Set,be.current=new Set,Ae.current=new Map,Dt({}),Mr(e=>Object.keys(e).length===0?e:{}),await we(o))},[we,o]),Le=n.useCallback(async e=>{if(!e){await ar();return}const s=I(e);ve.current=new Set(ve.current),ve.current.delete(s),be.current=new Set(be.current),be.current.delete(s),await we(s)},[we,ar]),Qn=n.useRef(""),es=n.useRef("");n.useEffect(()=>{if(!o)return;const e=`${o}|h${M?"1":"0"}|g${R?"1":"0"}`,s=Qn.current!==o,i=es.current!==e;!s&&!i||(s&&(Qn.current=o,q(""),Y(null),Ce(""),H(null),K(!1)),i&&(es.current=e,ve.current=new Set,be.current=new Set,Ae.current=new Map,Dt({}),Mr(c=>Object.keys(c).length===0?c:{}),we(o)))},[we,o,R,M]),n.useEffect(()=>{if(!a.listDirectory)return;const e=()=>{if(!document.hidden&&tt.length>0)for(const s of tt)Le(s)};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[tt,a.listDirectory,Le]),n.useEffect(()=>{if(!a.listDirectory||tt.length===0)return;const e=setInterval(()=>{if(!document.hidden)for(const s of tt)Le(s)},8e3);return()=>clearInterval(e)},[tt,a.listDirectory,Le]);const Ya=n.useCallback(async e=>{if(e?.preventDefault(),!at||!st)return;Ir(!0);const s=()=>{Ar(null)},i=m=>{A.error(m)},c=()=>{Ir(!1)};if(st==="createFile"){if(!Ge.trim()){i("Filename is required"),c();return}if(!a.writeFile){i("Write not supported"),c();return}const m=at.path,h=m?`${m}/`:"",j=I(`${h}${Ge.trim()}`);await a.writeFile(j,"").then(async F=>{F.success&&(A.success("File created"),await Le(m)),s()}).catch(()=>i("Operation failed")).finally(c);return}if(st==="createFolder"){if(!Ge.trim()){i("Folder name is required"),c();return}const m=at.path,h=m?`${m}/`:"",j=I(`${h}${Ge.trim()}`);await a.createDirectory(j).then(async F=>{F.success&&(A.success("Folder created"),await Le(m)),s()}).catch(()=>i("Operation failed")).finally(c);return}if(st==="rename"){if(!Ge.trim()){i("Name is required"),c();return}if(!a.rename){i("Rename not supported"),c();return}const m=at.path,h=m.split("/").slice(0,-1).join("/"),j=h?`${h}/`:"",F=I(`${j}${Ge.trim()}`);await a.rename(m,F).then(async _=>{_.success&&(A.success("Renamed successfully"),await Le(h),o&&qe(o,m),(l?.path===m||l?.path.startsWith(`${m}/`))&&(o&&ee(o,null),q(""),Y(null),Ce(""),H(null),g&&K(!1))),s()}).catch(()=>i("Operation failed")).finally(c);return}if(st==="delete"){if(!a.delete){i("Delete not supported"),c();return}const m=at.path,h=m.split("/").slice(0,-1).join("/");await a.delete(m).then(async j=>{j.success&&(A.success("Deleted successfully"),await Le(h),o&&qe(o,m),(l?.path===m||l?.path.startsWith(`${m}/`))&&(o&&ee(o,null),q(""),Y(null),Ce(""),H(null),g&&K(!1))),s()}).catch(()=>i("Operation failed")).finally(c);return}c()},[st,at,Ge,a,Le,g,qe,o,l?.path,ee]);n.useEffect(()=>{if(!P){Zt([]),Qt(!1);return}const e=Re.trim();if(!e){Zt([]),Qt(!1);return}let s=!1;return Qt(!0),de(P,e,150,{includeHidden:M,respectGitignore:!R,type:"file"}).then(i=>{if(s)return;const m=i.filter(h=>R||!tc(h.path)).map(h=>({name:h.name,path:I(h.path),type:"file",extension:h.extension,relativePath:h.relativePath}));Zt(m)}).catch(()=>{s||Zt([])}).finally(()=>{s||Qt(!1)}),()=>{s=!0}},[P,Re,de,M,R]);const ts=n.useCallback(async(e,s)=>{if(a.readFile)return(await a.readFile(e,{...s??{},directory:o||void 0})).content??"";const i=new URLSearchParams({path:e});s?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),s?.outsideFileGrant&&i.set("outsideFileGrant",s.outsideFileGrant),s?.optional&&i.set("optional","true"),o&&i.set("directory",o);const c=await zs(`/api/fs/read?${i.toString()}`,{cache:s?.optional?"no-store":"default"});if(!c.ok){const m=await c.json().catch(()=>({error:c.statusText}));throw new Error(m.error||"Failed to read file")}return c.text()},[a,o]),Ue=n.useCallback(async(e,s)=>{if(a.statFile){const i=await a.statFile(e,{...s??{},directory:o||void 0});return{path:i.path,size:i.size,mtimeMs:i.mtimeMs}}return null},[a,o]);n.useEffect(()=>{if(!o||!a.statFile||Q.length===0)return;let e=!1;const s=[...Q];return Promise.all(s.map(async i=>{try{const c=await a.statFile?.(i,{directory:o||void 0});!e&&c&&!c.isFile&&qe(o,i)}catch(c){!e&&la(c)&&qe(o,i)}})),()=>{e=!0}},[a,Q,qe,o]);const _r=n.useMemo(()=>z.length>qt?`${z.slice(0,qt)}
10
+ `)},[]),Ja=ji({source:"file",fileLabel:l?.path??null,language:l?.path&&nn(l.path)||"text",getCodeForRange:e=>Ua(D,Ni(e)),toStoreRange:e=>({startLine:e.start,endLine:e.end}),fromDraftRange:e=>({start:e.startLine,end:e.endLine})}),{drafts:qn,commentText:nr,setCommentText:Hn,editingDraftId:sr,setSelection:Kn,saveComment:Gn,cancel:$t,reset:Un,startEdit:Jn,deleteDraft:Yn}=Ja;n.useEffect(()=>{Fe(null),Un(),Me(null),X(""),Tr(!1)},[l?.path,Un,Me]),n.useEffect(()=>{Kn(z)},[z,Kn]),n.useEffect(()=>{if(!z&&!sr)return;const e=i=>{const c=i.target;c.closest('[data-comment-input="true"]')||c.closest('[data-comment-card="true"]')||c.closest(".cm-gutterElement")||c.closest("[data-sonner-toast]")||c.closest("[data-sonner-toaster]")||nr.trim()||(Fe(null),$t())},s=setTimeout(()=>{document.addEventListener("click",e)},100);return()=>{clearTimeout(s),document.removeEventListener("click",e)}},[$t,nr,sr,z]);const Xn=n.useCallback((e,s)=>{const i=s??z??void 0;s&&Fe(s),Gn(e,i),Fe(null)},[z,Gn]),Zn=n.useCallback((e,s)=>{const i=[];for(const c of s){if(!(c&&typeof c.name=="string"&&c.name.length>0)||!M&&c.name.startsWith(".")||!R&&ec(c.name))continue;const m=c.name,h=I(c.path||""),j=h?Xi(h)?h:I(`${e}/${h}`):I(`${e}/${m}`),F=c.isDirectory?"directory":"file",_=F==="file"&&m.includes(".")?m.split(".").pop()?.toLowerCase():void 0;i.push({name:m,path:j,type:F,extension:_})}return Yi(i)},[R,M]),we=n.useCallback(async e=>{const s=I(e.trim());if(!s||ve.current.has(s)||be.current.has(s))return;be.current=new Set(be.current),be.current.add(s);const i=Sn.current+1;Sn.current=i,Ae.current=new Map(Ae.current),Ae.current.set(s,i);const c=()=>Ae.current.get(s)===i;await(a.listDirectory?a.listDirectory(s).then(h=>h.entries.map(j=>({name:j.name,path:j.path,isDirectory:j.isDirectory}))):Co(s).then(h=>h.map(j=>({name:j.name,path:j.path,isDirectory:j.isDirectory})))).then(h=>{if(!c())return;const j=Zn(s,h);ve.current=new Set(ve.current),ve.current.add(s),zt(F=>{if(!F[s])return F;const _={...F};return delete _[s],_}),Mr(F=>({...F,[s]:j}))}).catch(h=>{if(!c())return;const j=h instanceof Error?h.message:String(h??"");if(j==="Directory not found"&&o&&s!==o){bn(o,s),zt(F=>{if(!F[s])return F;const _={...F};return delete _[s],_});return}console.error("Failed to load files directory:",h),zt(F=>({...F,[s]:j}))}).finally(()=>{c()&&(Ae.current=new Map(Ae.current),Ae.current.delete(s),be.current=new Set(be.current),be.current.delete(s))})},[a,Zn,bn,o]),ar=n.useCallback(async()=>{o&&(ve.current=new Set,be.current=new Set,Ae.current=new Map,zt({}),Mr(e=>Object.keys(e).length===0?e:{}),await we(o))},[we,o]),Le=n.useCallback(async e=>{if(!e){await ar();return}const s=I(e);ve.current=new Set(ve.current),ve.current.delete(s),be.current=new Set(be.current),be.current.delete(s),await we(s)},[we,ar]),Qn=n.useRef(""),es=n.useRef("");n.useEffect(()=>{if(!o)return;const e=`${o}|h${M?"1":"0"}|g${R?"1":"0"}`,s=Qn.current!==o,i=es.current!==e;!s&&!i||(s&&(Qn.current=o,q(""),Y(null),Ce(""),H(null),G(!1)),i&&(es.current=e,ve.current=new Set,be.current=new Set,Ae.current=new Map,zt({}),Mr(c=>Object.keys(c).length===0?c:{}),we(o)))},[we,o,R,M]),n.useEffect(()=>{if(!a.listDirectory)return;const e=()=>{if(!document.hidden&&tt.length>0)for(const s of tt)Le(s)};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[tt,a.listDirectory,Le]),n.useEffect(()=>{if(!a.listDirectory||tt.length===0)return;const e=setInterval(()=>{if(!document.hidden)for(const s of tt)Le(s)},8e3);return()=>clearInterval(e)},[tt,a.listDirectory,Le]);const Ya=n.useCallback(async e=>{if(e?.preventDefault(),!at||!st)return;Ir(!0);const s=()=>{Ar(null)},i=m=>{A.error(m)},c=()=>{Ir(!1)};if(st==="createFile"){if(!Ke.trim()){i("Filename is required"),c();return}if(!a.writeFile){i("Write not supported"),c();return}const m=at.path,h=m?`${m}/`:"",j=I(`${h}${Ke.trim()}`);await a.writeFile(j,"").then(async F=>{F.success&&(A.success("File created"),await Le(m)),s()}).catch(()=>i("Operation failed")).finally(c);return}if(st==="createFolder"){if(!Ke.trim()){i("Folder name is required"),c();return}const m=at.path,h=m?`${m}/`:"",j=I(`${h}${Ke.trim()}`);await a.createDirectory(j).then(async F=>{F.success&&(A.success("Folder created"),await Le(m)),s()}).catch(()=>i("Operation failed")).finally(c);return}if(st==="rename"){if(!Ke.trim()){i("Name is required"),c();return}if(!a.rename){i("Rename not supported"),c();return}const m=at.path,h=m.split("/").slice(0,-1).join("/"),j=h?`${h}/`:"",F=I(`${j}${Ke.trim()}`);await a.rename(m,F).then(async _=>{_.success&&(A.success("Renamed successfully"),await Le(h),o&&qe(o,m),(l?.path===m||l?.path.startsWith(`${m}/`))&&(o&&ee(o,null),q(""),Y(null),Ce(""),H(null),g&&G(!1))),s()}).catch(()=>i("Operation failed")).finally(c);return}if(st==="delete"){if(!a.delete){i("Delete not supported"),c();return}const m=at.path,h=m.split("/").slice(0,-1).join("/");await a.delete(m).then(async j=>{j.success&&(A.success("Deleted successfully"),await Le(h),o&&qe(o,m),(l?.path===m||l?.path.startsWith(`${m}/`))&&(o&&ee(o,null),q(""),Y(null),Ce(""),H(null),g&&G(!1))),s()}).catch(()=>i("Operation failed")).finally(c);return}c()},[st,at,Ke,a,Le,g,qe,o,l?.path,ee]);n.useEffect(()=>{if(!P){Zt([]),Qt(!1);return}const e=Re.trim();if(!e){Zt([]),Qt(!1);return}let s=!1;return Qt(!0),de(P,e,150,{includeHidden:M,respectGitignore:!R,type:"file"}).then(i=>{if(s)return;const m=i.filter(h=>R||!tc(h.path)).map(h=>({name:h.name,path:I(h.path),type:"file",extension:h.extension,relativePath:h.relativePath}));Zt(m)}).catch(()=>{s||Zt([])}).finally(()=>{s||Qt(!1)}),()=>{s=!0}},[P,Re,de,M,R]);const ts=n.useCallback(async(e,s)=>{if(a.readFile)return(await a.readFile(e,{...s??{},directory:o||void 0})).content??"";const i=new URLSearchParams({path:e});s?.allowOutsideWorkspace&&i.set("allowOutsideWorkspace","true"),s?.outsideFileGrant&&i.set("outsideFileGrant",s.outsideFileGrant),s?.optional&&i.set("optional","true"),o&&i.set("directory",o);const c=await Ds(`/api/fs/read?${i.toString()}`,{cache:s?.optional?"no-store":"default"});if(!c.ok){const m=await c.json().catch(()=>({error:c.statusText}));throw new Error(m.error||"Failed to read file")}return c.text()},[a,o]),Ue=n.useCallback(async(e,s)=>{if(a.statFile){const i=await a.statFile(e,{...s??{},directory:o||void 0});return{path:i.path,size:i.size,mtimeMs:i.mtimeMs}}return null},[a,o]);n.useEffect(()=>{if(!o||!a.statFile||Q.length===0)return;let e=!1;const s=[...Q];return Promise.all(s.map(async i=>{try{const c=await a.statFile?.(i,{directory:o||void 0});!e&&c&&!c.isFile&&qe(o,i)}catch(c){!e&&la(c)&&qe(o,i)}})),()=>{e=!0}},[a,Q,qe,o]);const _r=n.useMemo(()=>D.length>qt?`${D.slice(0,qt)}
11
11
 
12
- … truncated …`:z,[z]),re=W!==_r,ot=n.useCallback(async()=>{if(!l||!a.writeFile)return A.error("Saving not supported"),!1;const e=fr(l.path)||Tt;if(!Ki({selectedFilePath:l.path,loadedFilePath:pe,fileLoading:ke,isDirty:re,draftContent:W,fileContent:z,isNonEditableBinary:e}))return e?console.warn(`[saveDraft] refusing to save binary file "${l.path}".`):W===""&&z!==""&&pe!==l.path&&console.warn(`[saveDraft] refusing to save empty draft for "${l.path}" (${z.length} bytes were expected). The file may have been read during a concurrent write (O_TRUNC race). Try again after content finishes loading if the save was intentional.`),!1;if(!re)return!0;Tr(!0);try{const s=sc(W,En);if(!(await a.writeFile(l.path,s))?.success)return A.error("Failed to write file"),!1;if(q(W),o&&Ht(l.path,o)){const c=xr(o,l.path);c&&Io.requestGitRefresh({directory:o,paths:[c]})}return l?.path&&sn(l.path)&&(He.current=W,Pt.current=W),Ue(l.path).then(c=>{c&&(Ve.current=c)}).catch(()=>{}),!0}catch(s){return A.error(s instanceof Error?s.message:"Save failed"),!1}finally{Tr(!1)}},[Tt,W,z,ke,a,re,En,pe,Ue,o,l]);n.useEffect(()=>{if(!re){Me(null);return}const e=s=>rt.current?(rt.current=!1,!0):(bt(!0),Lt.current=s,!1);return Me(e),()=>{ue.getState().mainTabGuard===e&&Me(null)}},[re,Me]),n.useEffect(()=>{te||(vt("idle"),Pe.current&&(clearTimeout(Pe.current),Pe.current=null))},[te]);const rs=1500;n.useEffect(()=>{const e=!!(l&&a.writeFile),s=!!(l?.path&&(fr(l.path)||Tt));if(Gi({autoSaveEnabled:te,isDirty:re,canWrite:e,isSaving:xt,fileLoading:ke,selectedFilePath:l?.path,loadedFilePath:pe,isNonEditableBinary:s}))return Pe.current=setTimeout(()=>{ot().then(i=>{i&&(vt("saved"),setTimeout(()=>vt("idle"),2e3))})},rs),()=>{Pe.current&&(clearTimeout(Pe.current),Pe.current=null)}},[te,Tt,W,ke,re,pe,l,a.writeFile,xt,ot]),n.useEffect(()=>{vt("idle")},[l?.path]),n.useEffect(()=>{const e=s=>{_o(s)&&(s.key.toLowerCase()==="s"?(s.preventDefault(),Pe.current&&(clearTimeout(Pe.current),Pe.current=null),xt||ot().then(i=>{i&&(vt("saved"),setTimeout(()=>vt("idle"),2e3))})):s.key.toLowerCase()==="f"&&(s.preventDefault(),T(!0)))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[xt,ot]);const ns=n.useCallback(async e=>{const s=er.current+1;er.current=s;const i=()=>{if(!o)return!1;const ge=Ee.getState().byRoot[o],ne=ge?.selectedPath??ge?.openPaths[0]??null;return er.current===s&&ne===e.path};Y(null),Ce(""),H(null),zn(!1);const c=Ps(e.path),m=Ms(e.path),h=Ts(e.path),j=fr(e.path);if(g&&K(!0),u.isDesktop&&c&&!m){q(""),X(""),Ie(!0);return}if(!u.isDesktop&&c&&!m){q(""),X(""),H(e.path),Ie(!1);return}if(h){q(""),X(""),H(e.path),Ie(!1);return}if(j){q(""),X(""),H(e.path),Ie(!1);return}Ie(!0);const F=Ds(e.path),_={allowOutsideWorkspace:r==="editor-only"&&!!o&&!Ht(e.path,o),outsideFileGrant:F};await ts(e.path,_).then(ge=>{if(!i())return;if(Bo(ge)){zn(!0),q(""),X(""),H(e.path);return}const ne=wa(ge);Fa(nc(ge)),q(ne),He.current=ne,Pt.current=ne,X(ne.length>qt?`${ne.slice(0,qt)}
12
+ … truncated …`:D,[D]),re=W!==_r,ot=n.useCallback(async()=>{if(!l||!a.writeFile)return A.error("Saving not supported"),!1;const e=fr(l.path)||Tt;if(!Gi({selectedFilePath:l.path,loadedFilePath:pe,fileLoading:ke,isDirty:re,draftContent:W,fileContent:D,isNonEditableBinary:e}))return e?console.warn(`[saveDraft] refusing to save binary file "${l.path}".`):W===""&&D!==""&&pe!==l.path&&console.warn(`[saveDraft] refusing to save empty draft for "${l.path}" (${D.length} bytes were expected). The file may have been read during a concurrent write (O_TRUNC race). Try again after content finishes loading if the save was intentional.`),!1;if(!re)return!0;Tr(!0);try{const s=sc(W,En);if(!(await a.writeFile(l.path,s))?.success)return A.error("Failed to write file"),!1;if(q(W),o&&Ht(l.path,o)){const c=xr(o,l.path);c&&Io.requestGitRefresh({directory:o,paths:[c]})}return l?.path&&sn(l.path)&&(He.current=W,Pt.current=W),Ue(l.path).then(c=>{c&&(Ve.current=c)}).catch(()=>{}),!0}catch(s){return A.error(s instanceof Error?s.message:"Save failed"),!1}finally{Tr(!1)}},[Tt,W,D,ke,a,re,En,pe,Ue,o,l]);n.useEffect(()=>{if(!re){Me(null);return}const e=s=>rt.current?(rt.current=!1,!0):(bt(!0),Lt.current=s,!1);return Me(e),()=>{ue.getState().mainTabGuard===e&&Me(null)}},[re,Me]),n.useEffect(()=>{te||(vt("idle"),Pe.current&&(clearTimeout(Pe.current),Pe.current=null))},[te]);const rs=1500;n.useEffect(()=>{const e=!!(l&&a.writeFile),s=!!(l?.path&&(fr(l.path)||Tt));if(Ki({autoSaveEnabled:te,isDirty:re,canWrite:e,isSaving:xt,fileLoading:ke,selectedFilePath:l?.path,loadedFilePath:pe,isNonEditableBinary:s}))return Pe.current=setTimeout(()=>{ot().then(i=>{i&&(vt("saved"),setTimeout(()=>vt("idle"),2e3))})},rs),()=>{Pe.current&&(clearTimeout(Pe.current),Pe.current=null)}},[te,Tt,W,ke,re,pe,l,a.writeFile,xt,ot]),n.useEffect(()=>{vt("idle")},[l?.path]),n.useEffect(()=>{const e=s=>{_o(s)&&(s.key.toLowerCase()==="s"?(s.preventDefault(),Pe.current&&(clearTimeout(Pe.current),Pe.current=null),xt||ot().then(i=>{i&&(vt("saved"),setTimeout(()=>vt("idle"),2e3))})):s.key.toLowerCase()==="f"&&(s.preventDefault(),T(!0)))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[xt,ot]);const ns=n.useCallback(async e=>{const s=er.current+1;er.current=s;const i=()=>{if(!o)return!1;const ge=Ee.getState().byRoot[o],ne=ge?.selectedPath??ge?.openPaths[0]??null;return er.current===s&&ne===e.path};Y(null),Ce(""),H(null),Dn(!1);const c=Ps(e.path),m=Ms(e.path),h=Ts(e.path),j=fr(e.path);if(g&&G(!0),u.isDesktop&&c&&!m){q(""),X(""),Ie(!0);return}if(!u.isDesktop&&c&&!m){q(""),X(""),H(e.path),Ie(!1);return}if(h){q(""),X(""),H(e.path),Ie(!1);return}if(j){q(""),X(""),H(e.path),Ie(!1);return}Ie(!0);const F=zs(e.path),_={allowOutsideWorkspace:r==="editor-only"&&!!o&&!Ht(e.path,o),outsideFileGrant:F};await ts(e.path,_).then(ge=>{if(!i())return;if(Bo(ge)){Dn(!0),q(""),X(""),H(e.path);return}const ne=wa(ge);Fa(nc(ge)),q(ne),He.current=ne,Pt.current=ne,X(ne.length>qt?`${ne.slice(0,qt)}
13
13
 
14
- … truncated …`:ne),H(e.path),Ue(e.path,_).then(ct=>{ct&&i()&&(Ve.current=ct)}).catch(()=>{})}).catch(ge=>{if(i()){if(rc(ge)){if(Ie(!1),o&&ee(o,null),Y(null),q(""),X(""),H(null),Ve.current=null,Ne.trim().length>0&&ae(""),g&&K(!1),o){const ct=[...ia(e.path,o),e.path];ct.length>0&&Jt(o,ct);for(const en of ct)ve.current.has(en)||we(en)}return}if(la(ge)){o&&qe(o,e.path),q(""),X(""),Y(null),Ve.current=null,g&&K(!1);return}q(""),X(""),Y(ge instanceof Error?ge.message:"Failed to read file"),Ve.current=null}}).finally(()=>{i()&&Ie(!1)})},[Jt,g,we,r,ts,Ue,qe,o,u.isDesktop,Ne,ee]),or=n.useCallback(async(e,s)=>{if(!o)return;const i=ia(e,o),c=s?[...i,e]:i;c.length>0&&Jt(o,c);const m=c.map(h=>{if(!ve.current.has(h))return we(h)}).filter(Boolean);await Promise.all(m)},[Jt,we,o]),ss=n.useCallback((e,s)=>{const i=s.findIndex(c=>c.path===e);return i===-1||s.length<=1?null:s[i+1]??s[i-1]??null},[]),ce=n.useCallback(async e=>{if(rt.current)rt.current=!1;else if(re){bt(!0),wt.current=e;return}o&&(ee(o,e.path),or(e.path,!1)),Y(null),Ce(""),q(""),He.current="",Pt.current="",X(""),H(null),g&&K(!0)},[or,re,g,o,ee]);n.useEffect(()=>{l?.path&&or(l.path,!1)},[or,l?.path]),n.useEffect(()=>{if(!l){er.current+=1,Mt.current=null,Ie(!1);return}if(pe===l.path||Mt.current===l.path)return;const e=l.path;Mt.current=e,ns(l).finally(()=>{Mt.current===e&&(Mt.current=null)})},[ns,pe,l]);const as=n.useRef(re);as.current=re,n.useEffect(()=>{if(!l?.path||pe!==l.path)return;let e=!1;const s=window.setInterval(()=>{document.hidden||Ue(l.path,J).then(i=>{if(e||!i)return;const c=Ve.current;if(!c||c.path!==l.path){Ve.current=i;return}const m=i.mtimeMs!==void 0&&c.mtimeMs!==void 0&&i.mtimeMs!==c.mtimeMs,h=i.size!==c.size;!m&&!h||as.current||(Ve.current=i,H(null))}).catch(()=>{})},2e3);return()=>{e=!0,window.clearInterval(s)}},[pe,Ue,l?.path,J]);const Xa=n.useCallback(()=>{const e=wt.current,s=Lt.current,i=Ot.current;if(wt.current=null,Lt.current=null,Ot.current=null,rt.current=!0,bt(!1),X(_r),i){o&&pt(o,i),l?.path===i&&(e?ce(e):(o&&ee(o,null),q(""),Y(null),Ce(""),H(null),g&&K(!1)));return}if(e){ce(e);return}s&&(Me(null),ue.getState().setActiveMainTab(s))},[_r,ce,g,pt,o,l?.path,Me,ee]),Za=n.useCallback(async()=>{const e=wt.current,s=Lt.current,i=Ot.current;if(!await ot()){rt.current=!1;return}if(wt.current=null,Lt.current=null,Ot.current=null,rt.current=!0,bt(!1),i){o&&pt(o,i),l?.path===i&&(e?await ce(e):(o&&ee(o,null),q(""),Y(null),Ce(""),H(null),g&&K(!1)));return}if(e){await ce(e);return}s&&(Me(null),ue.getState().setActiveMainTab(s))},[ce,g,pt,o,ot,l?.path,Me,ee]),os=n.useCallback(e=>{const s=l?.path===e,i=ss(e,gt);if(s&&re){bt(!0),wt.current=i,Ot.current=e;return}if(o&&pt(o,e),!!s){if(i){ce(i);return}o&&ee(o,null),q(""),Y(null),Ce(""),H(null),g&&K(!1)}},[ss,ce,re,g,gt,pt,o,l?.path,ee]),Qa=n.useCallback(e=>{if(Q.includes(e))return"open";if(B?.files){const s=e.startsWith(o+"/")?e.slice(o.length+1):e,i=B.files.find(c=>c.path===s);if(i){if(i.index==="A"||i.working_dir==="?")return"git-added";if(i.index==="D")return"git-deleted";if(i.index==="M"||i.working_dir==="M")return"git-modified"}}return null},[Q,B,o]),eo=n.useCallback(e=>{if(!B?.files)return null;const s=e.startsWith(o+"/")?e.slice(o.length+1):e,i=s?`${s}/`:"";let c=0,m=0;for(const h of B.files)h.path.startsWith(i)&&((h.index==="M"||h.working_dir==="M")&&c++,(h.index==="A"||h.working_dir==="?")&&m++);return c+m>0?{modified:c,added:m}:null},[B,o]),to=n.useCallback(async e=>{const s=I(e);o&&(wn(o,s),ve.current.has(s)||await we(s))},[we,o,wn]),ro=n.useMemo(()=>({canRename:On,canCreateFile:Tn,canCreateFolder:Ln,canDelete:An,canReveal:In}),[On,Tn,Ln,An,In]);function is(e,s){const i=Cn[e]??[];return i.map((c,m)=>{const h=c.type==="directory",j=h&&tt.includes(c.path),F=l?.path===c.path,_=m===i.length-1;return t.jsxs("li",{className:"relative",children:[s>0&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),_&&t.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-background"})]}),t.jsx(oc,{node:c,root:o,isExpanded:j,isActive:F,isMobile:g,isBrowserClient:k,alwaysShowActions:L,status:h?void 0:Qa(c.path),badge:h?eo(c.path):void 0,permissions:ro,downloadFile:a.downloadFile,contextMenuPath:Oa,setContextMenuPath:Aa,rightClickMenuPath:Ia,setRightClickMenuPath:Ba,onSelect:ce,onToggle:to,onRevealPath:Ga,onOpenDialog:$r}),h&&j&&t.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[Xt[c.path]?t.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[t.jsx("span",{className:"min-w-0 flex-1 truncate text-[var(--status-error)]",title:Xt[c.path],children:Xt[c.path]}),t.jsxs(S,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{Le(c.path)},children:[t.jsx(v,{name:"refresh",className:"size-3.5"}),"Refresh"]})]}):null,is(c.path,s+1)]})]},c.path)})}const Z=!!(l?.path&&Ps(l.path)),kt=!!(l?.path&&Ms(l.path)),ye=!!(l?.path&&Ts(l.path)),qr=!!(l?.path&&(fr(l.path)||Tt)),We=qr&&!Z&&!ye,cs=n.useMemo(()=>I(Te?.path??""),[Te?.path]),Ct=!!(Te&&cs&&De&&De===cs&&!ke&&!Be&&!Z&&!ye&&!We),Je=n.useMemo(()=>xr(o,De),[De,o]),no=!!(l&&(!Z||kt)&&!ye&&!We&&z.length>0),so=!!(l&&Je.length>0),je=!!(l&&!Yt&&!qr&&!Z&&a.writeFile&&z.length<=qt),it=!!(l?.path&&ua(l.path)),Vt=!!(l?.path&&ac(l.path)),St=!!(l?.path&&fn(l.path)),Wt=!!(l?.path&&sn(l.path)),Hr=!!(l&&!qr&&!Z)&&!it&&!Wt&&!(St&&mt==="preview"),ao=it&&Nr==="edit"||St&&mt==="edit"||Vt&&ft==="text"||!it&&!St&&!Vt&&ie==="edit",ir=n.useMemo(()=>De?$o(De):null,[De]),[ls,Gr]=n.useState(null);n.useEffect(()=>{let e=!1;const s=l?.path;if(!s||ir){Gr(null);return}return Gr(null),Vo(s).then(i=>{e||Gr(i)}),()=>{e=!0}},[l?.path,ir]),n.useEffect(()=>{!je&&ie==="edit"&&Rt("view")},[je,ie]);const Kr="pichamber:files:md-viewer-mode",Ur="pichamber:files:html-viewer-mode",Jr="pichamber:files:json-viewer-mode";n.useEffect(()=>{const e=l?.path;if(!e)return;Rt(Fr.current[e]??"edit");let s=Bt?"preview":"edit";try{const m=localStorage.getItem(Kr);(m==="preview"||m==="edit")&&(s=m)}catch{}kr(Er.current[e]??s);let i=Bt?"preview":"edit";try{const m=localStorage.getItem(Ur);(m==="preview"||m==="edit")&&(i=m)}catch{}Sr(Rr.current[e]??i),zt(zr.current[e]??(Bt?"preview":"edit"));let c=Bt?"tree":"text";try{const m=localStorage.getItem(Jr);(m==="tree"||m==="text")&&(c=m)}catch{}Cr(c)},[l?.path,Bt]);const oo=n.useCallback(e=>{const s=l?.path;s&&(Fr.current[s]=e),Rt(e)},[l?.path]),us=n.useCallback(e=>{const s=l?.path;s&&(Er.current[s]=e),kr(e);try{localStorage.setItem(Kr,e)}catch{}},[l?.path]),le=n.useCallback(()=>Nr,[Nr]),io=n.useCallback(e=>{Cr(e);try{localStorage.setItem(Jr,e)}catch{}},[]),co=n.useCallback(e=>{const s=l?.path;s&&(Rr.current[s]=e),Sr(e);try{localStorage.setItem(Ur,e)}catch{}},[l?.path]),lo=n.useCallback(e=>{const s=l?.path;if(s&&(zr.current[s]=e),he.current&&(clearTimeout(he.current),he.current=null),$e.current!==null&&(cancelAnimationFrame($e.current),$e.current=null),e==="edit")X(He.current||z),zt(e);else{He.current=W;const i=s;zt("edit"),$e.current=requestAnimationFrame(()=>{$e.current=requestAnimationFrame(()=>{$e.current=null,!(o&&i&&Ee.getState().byRoot[o]?.selectedPath!==i)&&(Na(c=>c+1),zt("preview"))})});return}},[W,z,o,l?.path]),Yr=n.useCallback(async(e,s)=>{if(!a.writeFile||s===Pt.current)return!1;if(!(await a.writeFile(e,s))?.success)return A.error("Failed to write file"),!1;He.current=s,Pt.current=s,X(s);const c=await Ue(e,J).catch(()=>null);return c&&(Ve.current=c),!0},[a,Ue,J]);n.useEffect(()=>()=>{he.current&&(clearTimeout(he.current),he.current=null),$e.current!==null&&(cancelAnimationFrame($e.current),$e.current=null)},[Qe,l?.path]);const uo=n.useCallback(e=>{if(He.current=e,!te||!l?.path||Qe!=="preview"||!a.writeFile)return;he.current&&clearTimeout(he.current);const s=l.path;he.current=setTimeout(()=>{he.current=null,Yr(s,e).then(i=>{i&&(tr(!0),setTimeout(()=>tr(!1),1500))}).catch(i=>{A.error(i instanceof Error?i.message:"Save failed")})},rs)},[te,Qe,a.writeFile,Yr,l?.path]),fo=n.useMemo(()=>Wt&&(He.current||W)||z,[W,z,Wt]),ds=n.useCallback(()=>mt,[mt]);n.useEffect(()=>{const e=i=>{const c=i?"preview":"edit",m=i?"tree":"text";for(const h of Q)Fr.current[h]="edit",ua(h)&&(Er.current[h]=c),fn(h)&&(Rr.current[h]=c),sn(h)&&(zr.current[h]=c);Rt("edit"),kr(c),Sr(c),zt(c),Cr(m);try{localStorage.setItem(Kr,c),localStorage.setItem(Ur,c),localStorage.setItem(Jr,m)}catch{}},s=i=>{const c=!!i.detail?.enabled;e(c)};return window.addEventListener("pichamber:file-viewer-preview-mode-changed",s),()=>{window.removeEventListener("pichamber:file-viewer-preview-mode-changed",s)}},[Q]),n.useEffect(()=>{if(!Te||!o)return;const e=()=>{typeof window>"u"||yt.current===null&&(yt.current=window.requestAnimationFrame(()=>{yt.current=null,Or(_e=>_e+1)}))},s=(_e,lt)=>{if(_e.state.doc.length!==lt.length)return!1;if(lt.length===0)return!0;const tn=Math.min(128,lt.length);if(_e.state.sliceDoc(0,tn)!==lt.slice(0,tn))return!1;const Fs=Math.max(0,lt.length-tn);return _e.state.sliceDoc(Fs,lt.length)===lt.slice(Fs)},i=I(Te.path);if(!i){rr(null),nt.current={key:"",attempts:0};return}const c=`${i}:${Te.line}:${Te.column??1}`;if(nt.current.key!==c&&(nt.current={key:c,attempts:0}),l?.path!==i){if(Lr)return;ce(ht(i));return}if(ke||pe!==i)return;if(Be||Z||ye||We){rr(null),nt.current={key:"",attempts:0};return}if(!je)return;if(ie!=="edit"){Rt("edit");return}const m=Se.current;if(!m){e();return}if(!s(m,W)){e();return}const h=Math.max(1,Math.min(Te.line,m.state.doc.lines)),j=m.state.doc.line(h),F=Math.max(1,Te.column||1),_=Math.max(0,j.to-j.from),ge=Math.min(_,F-1),ne=j.from+ge;if(!(m.state.selection.main.head===ne)||nt.current.attempts===0){nt.current.attempts+=1,m.dispatch({selection:{anchor:ne},effects:se.scrollIntoView(ne,{y:"center"})}),m.focus(),e();return}typeof window<"u"&&window.requestAnimationFrame(()=>{const _e=Se.current;_e&&(_e.dispatch({selection:{anchor:ne},effects:se.scrollIntoView(ne,{y:"center"})}),_e.focus())}),rr(null),nt.current={key:"",attempts:0}},[je,Lr,W,Ma,Be,ke,Z,ye,We,pe,ce,Te,o,l?.path,rr,ie,ht]),n.useEffect(()=>{if(!Vr||!o)return;const e=I(Vr);if(!e){Wr(null);return}l?.path===e&&(ke||pe!==e||(!Be&&!Z&&!ye&&!We&&je&&ie==="edit"&&Se.current?.focus(),Wr(null)))},[je,Be,ke,Z,ye,We,pe,Vr,o,l?.path,Wr,ie]);const Ft=n.useCallback(e=>{if(!g||!e||!e.hasFocus||typeof window>"u")return;const s=window.visualViewport;if(!s)return;const i=document.documentElement.clientHeight||window.innerHeight;if(Math.max(0,i-(s.offsetTop+s.height))<=0)return;const m=e.state.selection.main.head,h=e.coordsAtPos(m);if(!h)return;const j=Math.round(s.offsetTop+s.height),_=h.bottom+20-j;_<=0||(e.scrollDOM.scrollTop+=_)},[g]);n.useEffect(()=>{if(!g||typeof window>"u")return;const e=()=>{window.requestAnimationFrame(()=>{Ft(Se.current)})},s=window.visualViewport;return s?.addEventListener("resize",e),s?.addEventListener("scroll",e,{passive:!0}),document.addEventListener("selectionchange",e),()=>{s?.removeEventListener("resize",e),s?.removeEventListener("scroll",e),document.removeEventListener("selectionchange",e)}},[g,Ft]),n.useEffect(()=>{if(!je||ie!=="edit"||g)return;const e=Wo("open_go_to_line",Vn),s=i=>{const c=i.target;if(c?.closest('[role="dialog"]'))return;const m=!!c?.closest(".cm-editor");c?.closest('input, textarea, [contenteditable="true"], [role="textbox"]')&&!m||!document.activeElement?.closest(".cm-editor")||qo(i,e)&&(i.preventDefault(),Br(!0))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[je,g,Vn,ie]);const cr=ue(e=>e.editorFontSize),fs=n.useMemo(()=>{if(!l?.path)return[aa(f,{fontSize:cr})];const e=nn(l.path),s=[aa(f,e?{syntaxColors:!1,fontSize:cr}:{fontSize:cr})],i=ir??ls;return i&&s.push(i),e&&s.push(Hi({language:e,themeName:f.metadata.id,theme:bi(f)})),V&&s.push(se.lineWrapping),g&&s.push(se.updateListener.of(c=>{c.view.hasFocus&&(c.selectionSet||c.focusChanged||c.viewportChanged||c.geometryChanged)&&window.requestAnimationFrame(()=>{Ft(c.view)})})),s},[f,l?.path,ir,ls,V,g,Ft,cr]),ms=n.useMemo(()=>({light:Gt.metadata.id,dark:Kt.metadata.id}),[Gt.metadata.id,Kt.metadata.id]),lr=l?.path&&Z&&!u.isDesktop&&!kt?`${l.path}|${J.allowOutsideWorkspace?"outside":"workspace"}|${J.outsideFileGrant??""}`:"",ur=l?.path&&ye?`${l.path}|${J.allowOutsideWorkspace?"outside":"workspace"}|${J.outsideFileGrant??""}`:"",dr=l?.path&&St&&mt==="preview"?l.path:"",Xr="Failed to read file",{readyKey:ps,nonce:hs}=mn(lr,Y,Xr),{readyKey:gs,nonce:mo}=mn(dr,Y,Xr),{readyKey:xs,nonce:vs}=mn(ur,Y,Xr),bs=!!(lr&&ps!==lr),po=!!(dr&&gs!==dr),ws=!!(ur&&xs!==ur),ys=l?.path&&Z?u.isDesktop?kt?`data:${Ls(l.path)};utf8,${encodeURIComponent(z)}`:Sa:kt?`data:${Ls(l.path)};utf8,${encodeURIComponent(z)}`:ps===lr?rn().authenticatedAsset("/api/fs/raw",{path:l.path,allowOutsideWorkspace:J.allowOutsideWorkspace?"true":void 0,outsideFileGrant:J.outsideFileGrant,directory:o||void 0}):"":"",js=l?.path&&ye&&xs===ur?rn().authenticatedAsset("/api/fs/raw",{path:l.path,allowOutsideWorkspace:J.allowOutsideWorkspace?"true":void 0,outsideFileGrant:J.outsideFileGrant,directory:o||void 0}):"",Ns=n.useCallback(e=>t.jsx("div",{className:"h-full overflow-hidden bg-[var(--surface-background)]",children:t.jsx("iframe",{src:js,className:"h-full w-full border-0",title:e.name},vs)}),[js,vs]);n.useEffect(()=>{let e=!1;return(async()=>{if(!u.isDesktop||!l?.path||!Z||kt){me.current&&(URL.revokeObjectURL(me.current),me.current=""),Ce("");return}Y(null),me.current&&(URL.revokeObjectURL(me.current),me.current=""),await(a.readFileBinary?a.readFileBinary(l.path,J).then(c=>c.dataUrl):(async()=>{const c=await zs("/api/fs/raw",{query:{path:l.path,allowOutsideWorkspace:J.allowOutsideWorkspace?"true":void 0,outsideFileGrant:J.outsideFileGrant,directory:o||void 0}});if(!c.ok)throw new Error("Failed to read file");const m=await c.blob(),h=URL.createObjectURL(m);return e?(URL.revokeObjectURL(h),""):(me.current=h,h)})()).then(c=>{e||(Ce(c),H(l.path))}).catch(c=>{me.current&&(URL.revokeObjectURL(me.current),me.current=""),e||(Ce(""),Y(c instanceof Error?c.message:"Failed to read file"),H(null))}).finally(()=>{e||Ie(!1)})})(),()=>{e=!0}},[a,Z,kt,o,u.isDesktop,l?.path,J]),n.useEffect(()=>()=>{me.current&&(URL.revokeObjectURL(me.current),me.current="")},[]);const ho=n.useCallback(()=>Ar(null),[]),go=n.useMemo(()=>ki({drafts:qn,editingDraftId:sr,commentText:nr,onTextChange:Hn,selection:D,isDragging:$n,fileLabel:l?.path??"",newWidgetId:"files-new-comment-input",mapDraftToRange:e=>({start:e.startLine,end:e.endLine}),onSave:Xn,onCancel:()=>{Fe(null),$t()},onEdit:e=>{Jn(e),Fe({start:e.startLine,end:e.endLine})},onDelete:Yn}),[$t,nr,Yn,sr,qn,Xn,$n,D,l?.path,Hn,Jn]),ks=n.useCallback((e,s)=>t.jsx("div",{className:"h-full",children:t.jsx(gi,{file:{name:e.name,contents:s,lang:nn(e.path)||void 0},options:{disableFileHeader:!0,overflow:V?"wrap":"scroll",theme:ms,themeType:f.metadata.variant==="dark"?"dark":"light"},className:"block h-full w-full",style:{height:"100%"}})}),[f.metadata.variant,ms,V]),Zr=({exitFullscreenOnly:e=!1,layout:s="floating"}={})=>{if(!l)return null;const c=s==="docked"?"pointer-events-auto flex flex-wrap items-center gap-1":"pointer-events-auto flex items-center gap-1 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-1 shadow-sm",m=(h,j)=>t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx("span",{className:"inline-flex",children:j})}),t.jsx(Ze,{side:"bottom",sideOffset:6,children:h})]});return t.jsxs("div",{className:c,children:[je&&ao&&t.jsxs(t.Fragment,{children:[xt?t.jsxs("span",{className:"flex items-center gap-1 px-1 text-muted-foreground typography-meta",children:[t.jsx(v,{name:"loader-4",className:"size-3.5 animate-spin"}),"Saving..."]}):te&&Ra==="saved"&&!re?t.jsxs("span",{className:"flex items-center gap-1 px-1 text-[color:var(--status-success)] typography-meta",children:[t.jsx(v,{name:"check",className:"size-3.5"}),"Saved"]}):re?m(te?`Save now (${_t()}+S) - auto-saves after 1.5s`:`Save now (${_t()}+S)`,t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>{ot()},className:"h-6 gap-1 px-1 text-muted-foreground opacity-80 hover:bg-transparent hover:opacity-100 focus-visible:bg-transparent active:bg-transparent",title:te?`Save now (${_t()}+S) - auto-saves after 1.5s`:`Save now (${_t()}+S)`,"aria-label":`Save (${_t()}+S)`,children:t.jsx(v,{name:"save-3",className:"size-4"})})):null,m(te?"Auto-save on":"Manual save",t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>Da(!te),className:$("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",te?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:te?"Auto-save on":"Manual save","aria-label":te?"Auto-save on":"Manual save",children:te?t.jsx(v,{name:"file-check-fill",className:"size-4"}):t.jsx(v,{name:"file-check",className:"size-4"})}))]}),t.jsxs(pn,{onOpenChange:jr,children:[t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx("span",{className:"inline-flex",children:t.jsx(hn,{asChild:!0,children:t.jsx(S,{variant:"ghost",size:"sm",className:"size-6 p-0 text-foreground opacity-100 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Open in desktop app","aria-label":"Open in desktop app",children:t.jsx(v,{name:"file-transfer",className:"size-4"})})})})}),t.jsx(Ze,{side:"bottom",sideOffset:6,children:"Open in desktop app"})]}),t.jsxs(gn,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[_a.map(h=>t.jsxs(gr,{className:"flex items-center gap-2",onClick:()=>{Ka(h)},children:[t.jsx(Ji,{label:h.label,iconDataUrl:h.iconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:h.label})]},h.id)),qa?t.jsxs(gr,{className:"flex items-center gap-2",onClick:()=>{Ha(!0)},children:[t.jsx(v,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]}),!Z&&!ye&&!We&&t.jsxs(t.Fragment,{children:[m(V?"Disable line wrap":"Enable line wrap",t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>fe(!V),className:$("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",V?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:V?"Disable line wrap":"Enable line wrap",children:t.jsx(v,{name:"text-wrap",className:"size-4"})})),ie==="edit"&&t.jsxs(t.Fragment,{children:[m("Find in file",t.jsx(S,{variant:"ghost",size:"sm",onClick:h=>{T(!N),h.currentTarget.blur()},className:"size-6 p-0 text-foreground opacity-100 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Find in file",children:t.jsx(v,{name:"search",className:"size-4"})})),m("Go to line",t.jsx(S,{variant:"ghost",size:"sm",onClick:h=>{Br(j=>!j),h.currentTarget.blur()},className:"size-6 p-0 text-foreground opacity-100 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Go to line",children:t.jsx(v,{name:"menu-fold-2",className:"size-4"})})),t.jsx(Oi,{open:Wa,onOpenChange:Br,view:Se.current,variant:"inline"})]})]}),Hr&&je&&!Vt&&!St&&t.jsx(dn,{currentMode:ie==="view"?"preview":"edit",onToggle:()=>{oo(ie==="view"?"edit":"view")}}),it&&m(le()==="preview"?"Switch to edit mode":"Switch to preview mode",t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>us(le()==="preview"?"edit":"preview"),className:$("size-6 p-0 transition-colors hover:bg-[var(--interactive-hover)] focus-visible:bg-[var(--interactive-hover)] active:bg-[var(--interactive-hover)]",le()==="preview"?"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)] hover:bg-[var(--interactive-selection)] focus-visible:bg-[var(--interactive-selection)] active:bg-[var(--interactive-selection)]":"text-muted-foreground opacity-65 hover:opacity-100"),title:le()==="preview"?"Switch to edit mode":"Switch to preview mode","aria-label":le()==="preview"?"Switch to edit mode":"Switch to preview mode",children:t.jsx(v,{name:le()==="preview"?"eye":"eye-off",className:"size-4"})})),fn(l?.path??"")&&t.jsx(dn,{currentMode:ds(),onToggle:()=>{co(ds()==="preview"?"edit":"preview")}}),Wt&&t.jsxs(t.Fragment,{children:[t.jsx(dn,{currentMode:Qe,onToggle:()=>lo(Qe==="preview"?"edit":"preview")}),Qe==="preview"&&t.jsx(S,{variant:"ghost",size:"sm",onClick:async()=>{const h=Rn.current?.getXml();if(he.current&&(clearTimeout(he.current),he.current=null),l?.path&&h){if(!await Yr(l.path,h))return;tr(!0),setTimeout(()=>tr(!1),1500)}},className:"size-6 p-0 text-foreground hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Save diagram",children:za?t.jsx(v,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):t.jsx(v,{name:"save-3",className:"size-4"})})]}),Vt&&m(ft==="tree"?"Switch to Text View":"Switch to Tree View",t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>io(ft==="tree"?"text":"tree"),className:"size-6 p-0 text-muted-foreground opacity-65 hover:bg-transparent hover:opacity-100 focus-visible:bg-transparent active:bg-transparent",title:ft==="tree"?"Switch to Text View":"Switch to Tree View",children:ft==="tree"?t.jsx(v,{name:"code-sslash",className:"size-4"}):t.jsx(v,{name:"node-tree",className:"size-4"})})),no&&m("Copy file contents",t.jsx(S,{variant:"ghost",size:"sm",onClick:async()=>{(await br(z)).ok?(Pn(!0),At.current!==null&&window.clearTimeout(At.current),At.current=window.setTimeout(()=>{Pn(!1)},1200)):A.error("Copy failed")},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Copy file contents","aria-label":"Copy file contents",children:$a?t.jsx(v,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):t.jsx(v,{name:"clipboard",className:"size-4"})})),so&&m(`Copy file path (${Je})`,t.jsx(S,{variant:"ghost",size:"sm",onClick:async()=>{(await br(Je)).ok?(Mn(!0),It.current!==null&&window.clearTimeout(It.current),It.current=window.setTimeout(()=>{Mn(!1)},1200)):A.error("Copy failed")},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:`Copy file path (${Je})`,"aria-label":`Copy file path (${Je})`,children:Va?t.jsx(v,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):t.jsx(v,{name:"file-copy-2",className:"size-4"})})),a.downloadFile&&m("Save file",t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>{const h=a.downloadFile;h&&h(l.path).catch(j=>{console.error("Download failed:",j),A.error("Operation failed")})},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Save file","aria-label":"Save file",children:t.jsx(v,{name:"download",className:"size-4"})})),e?m("Exit fullscreen",t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>U(!1),className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Exit fullscreen","aria-label":"Exit fullscreen",children:t.jsx(v,{name:"fullscreen-exit",className:"size-4"})})):!g&&r==="full"&&m(w?"Exit fullscreen":"Fullscreen",t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>U(!w),className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:w?"Exit fullscreen":"Fullscreen","aria-label":w?"Exit fullscreen":"Fullscreen",children:w?t.jsx(v,{name:"fullscreen-exit",className:"size-4"}):t.jsx(v,{name:"fullscreen",className:"size-4"})}))]})},Qr=t.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[t.jsx(da,{open:Lr,onOpenChange:e=>{e||bt(!0)},children:t.jsxs(fa,{showCloseButton:!1,className:"max-w-md",children:[t.jsxs(ma,{children:[t.jsx(pa,{children:"Unsaved changes"}),t.jsx(ha,{children:"Save your edits before continuing?"})]}),t.jsxs(ga,{children:[t.jsx(S,{variant:"outline",onClick:()=>{Za()},disabled:xt,className:"border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]",children:"Save changes"}),t.jsx(S,{variant:"destructive",onClick:Xa,children:"Discard"})]})]})}),t.jsxs("div",{className:$("flex flex-col flex-shrink-0",G&&"border-b border-border/40"),children:[G?t.jsxs("div",{className:"flex min-w-0 items-center px-3 py-1.5",children:[g&&dt&&t.jsx("button",{type:"button",onClick:()=>K(!1),"aria-label":"Back",className:"inline-flex size-7 flex-shrink-0 items-center justify-center mr-1 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:t.jsx(v,{name:"arrow-left-s",className:"size-5"})}),g?l?t.jsxs(pn,{children:[t.jsx(hn,{asChild:!0,children:t.jsxs("button",{type:"button",className:"inline-flex min-w-0 max-w-full items-center gap-1 text-left typography-ui-label font-medium","aria-label":"Open files",children:[t.jsx(hr,{filePath:l.path,extension:l.extension,className:"size-3.5 flex-shrink-0"}),t.jsx(ca,{name:l.name}),t.jsx(v,{name:"arrow-down-s",className:"size-4 flex-shrink-0 text-muted-foreground"})]})}),t.jsx(gn,{align:"start",className:"w-[min(24rem,calc(100vw-2rem))] max-w-[calc(100vw-2rem)]",children:gt.map(e=>{const s=l?.path===e.path;return t.jsxs(gr,{onSelect:i=>{if(i.target.closest("[data-close-open-file]")){i.preventDefault();return}s||ce(e)},className:$("flex min-w-0 items-center justify-between gap-2 overflow-hidden",s&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-hidden",children:[t.jsx(hr,{filePath:e.path,extension:e.extension,className:"size-3.5 flex-shrink-0"}),t.jsx(ca,{name:e.name})]}),t.jsx("button",{type:"button","data-close-open-file":!0,onPointerDown:i=>{i.preventDefault(),i.stopPropagation()},onClick:i=>{i.preventDefault(),i.stopPropagation(),os(e.path)},className:"inline-flex size-6 shrink-0 items-center justify-center rounded-md text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]","aria-label":`Close ${e.name}`,children:t.jsx(v,{name:"close",className:"size-3.5"})})]},e.path)})})]}):t.jsx("div",{className:"typography-ui-label font-medium truncate",children:"Select a file"}):gt.length>0?t.jsxs("div",{className:"relative min-w-0 flex-1",children:[jn.left&&t.jsx("div",{className:"pointer-events-none absolute left-0 top-0 bottom-0 w-6 z-10 bg-gradient-to-r from-background to-transparent"}),jn.right&&t.jsx("div",{className:"pointer-events-none absolute right-0 top-0 bottom-0 w-6 z-10 bg-gradient-to-l from-background to-transparent"}),t.jsx("div",{ref:Pr,className:"flex min-w-0 items-center gap-1 overflow-x-auto scrollbar-none",style:{scrollbarWidth:"none",msOverflowStyle:"none"},"data-no-drawer-swipe":"true",children:gt.map(e=>{const s=l?.path===e.path;return t.jsxs("div",{title:xr(o,e.path),className:$("group inline-flex items-center gap-1 rounded-md border px-2 py-1 typography-ui-label transition-colors whitespace-nowrap",s?"bg-[var(--interactive-selection)] border-[var(--primary-muted)] text-[var(--interactive-selection-foreground)]":"bg-transparent border-[var(--interactive-border)] text-[var(--surface-muted-foreground)] hover:bg-[var(--interactive-hover)] hover:text-[var(--surface-foreground)]"),children:[t.jsx(hr,{filePath:e.path,extension:e.extension,className:"size-3.5 flex-shrink-0"}),t.jsx("button",{type:"button",onClick:()=>{s||ce(e)},className:"max-w-[12rem] truncate text-left",children:e.name}),t.jsx("button",{type:"button",onClick:i=>{i.stopPropagation(),os(e.path)},className:$("rounded-sm p-0.5 text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]",!s&&!L&&"opacity-0 group-hover:opacity-100"),"aria-label":`Close ${e.name}`,children:t.jsx(v,{name:"close",className:"size-3.5"})})]},e.path)})})]}):t.jsx("div",{className:"typography-ui-label font-medium truncate",children:"Select a file"})]}):null,(_n||g)&&l?t.jsxs("div",{className:"flex min-w-0 items-center gap-3 border-t border-border/40 bg-[var(--surface-subtle)] px-3 py-1",children:[Je&&!g?t.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta text-muted-foreground",title:Je,children:Je}):null,t.jsx("div",{className:"ml-auto min-w-0 shrink-0 overflow-x-auto",children:Zr({layout:"docked"})})]}):null]}),t.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[l&&!N&&!(_n||g)&&t.jsx("div",{ref:O,className:"absolute right-3 top-3 z-30",onMouseLeave:()=>{ze.current>0||oe(!1)},children:C?Zr():t.jsxs("div",{className:"flex items-center gap-1",children:[it?t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx("span",{className:"inline-flex",children:t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>us(le()==="preview"?"edit":"preview"),className:$("size-8 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-0 shadow-sm transition-colors",le()==="preview"?"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)] hover:bg-[var(--interactive-selection)]":"text-muted-foreground hover:text-foreground"),"aria-label":le()==="preview"?"Switch to edit mode":"Switch to preview mode",title:le()==="preview"?"Switch to edit mode":"Switch to preview mode",children:t.jsx(v,{name:le()==="preview"?"eye":"eye-off",className:"size-4"})})})}),t.jsx(Ze,{side:"bottom",sideOffset:6,children:le()==="preview"?"Switch to edit mode":"Switch to preview mode"})]}):null,t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx("span",{className:"inline-flex",onMouseEnter:()=>oe(!0),children:t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>oe(!0),className:"size-8 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-0 text-muted-foreground shadow-sm hover:text-foreground","aria-label":"Show editor controls",title:"Editor controls",children:t.jsx(v,{name:"more-2-fill",className:"size-4"})})})}),t.jsx(Ze,{side:"bottom",sideOffset:6,children:"Editor controls"})]})]})}),t.jsx(an,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:l?ke||bs||ws?xe?t.jsx("div",{className:"p-3"}):t.jsxs("div",{className:"p-3 flex items-center gap-2 typography-ui text-muted-foreground",children:[t.jsx(v,{name:"loader-4",className:"size-4 animate-spin"}),"Loading..."]}):Be?t.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:Be}):Z?t.jsx("div",{className:"flex h-full items-center justify-center p-3",children:t.jsx("img",{src:ys,alt:l?.name??"Image",className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border/30 bg-primary/10"},hs)}):ye?Ns(l):We?t.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[t.jsx("div",{className:"typography-ui-header text-foreground",children:"Cannot preview binary file"}),t.jsx("div",{className:"max-w-md typography-ui text-muted-foreground",children:"This file is binary and cannot be edited in PiChamber. Download it to open with another app."}),a.downloadFile?t.jsxs(S,{type:"button",variant:"outline",size:"sm",onClick:()=>{const e=a.downloadFile;!e||!l||e(l.path).catch(s=>{console.error("Download failed:",s),A.error("Operation failed")})},children:[t.jsx(v,{name:"download",className:"mr-2 size-4"}),"Save file"]}):null]}):l&&Wt&&Qe==="preview"?t.jsx("div",{className:"h-full overflow-hidden",style:{minHeight:"400px"},children:t.jsx(wi,{ref:Rn,xml:fo,onChange:uo},`${l.path}:${ja}`)}):l&&Vt&&ft==="tree"?t.jsx(on,{fallback:t.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[t.jsx("div",{className:"mb-1 font-medium text-destructive",children:"JSON viewer unavailable"}),t.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to text mode to view raw content."})]}),children:t.jsx("div",{className:"h-full overflow-auto",children:t.jsx(xi,{jsonString:z,maxHeight:"100%",initiallyExpandedDepth:2})})}):l&&it&&le()==="preview"?t.jsxs("div",{className:"h-full overflow-auto p-3",children:[z.length>500*1024&&t.jsx("div",{className:"mb-3 rounded-md border border-status-warning/20 bg-status-warning/10 px-3 py-2 text-sm text-status-warning",children:`This file is large (${Math.round(z.length/1024)}KB). Preview may be limited.`}),t.jsx(on,{fallback:t.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[t.jsx("div",{className:"mb-1 font-medium text-destructive",children:"Preview unavailable"}),t.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to edit mode to fix the issue."})]}),children:t.jsx(Os,{content:z,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):l&&St&&mt==="preview"?po?t.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground typography-ui-label",children:"Loading..."}):t.jsx("div",{className:"h-full overflow-hidden",children:t.jsx("iframe",{src:gs===dr?(()=>{const e=l.path.split("/").map(s=>encodeURIComponent(s)).join("/");return rn().authenticatedAsset(`/api/fs/serve${e.startsWith("/")?e:`/${e}`}`)})():void 0,className:"w-full h-full border-none",sandbox:"allow-scripts allow-same-origin allow-forms",title:"HTML Preview"},mo)}):l&&Hr&&ie==="view"?ks(l,W):t.jsxs("div",{className:$("relative h-full",Ct&&"overflow-hidden"),ref:Pa,children:[t.jsx("div",{className:$("h-full",Ct&&"invisible"),children:t.jsx(ra,{value:W,onChange:X,readOnly:!je,vimMode:Wn==="vim",extensions:fs,className:"h-full",blockWidgets:go,onViewReady:e=>{Se.current=e,Or(s=>s+1),window.requestAnimationFrame(()=>{Ft(e)})},onViewDestroy:()=>{Se.current&&(Se.current=null),Or(e=>e+1)},enableSearch:!0,searchOpen:N,onSearchOpenChange:T,highlightLines:D?{start:Math.min(D.start,D.end),end:Math.max(D.start,D.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(e,s,i)=>{if(!(i instanceof MouseEvent)||i.button!==0)return!1;i.preventDefault();const c=e.state.doc.lineAt(s.from).number;if(D&&!i.shiftKey&&Math.min(D.start,D.end)===c&&Math.max(D.start,D.end)===c)return Fe(null),$t(),jt.current=!1,Ke.current=null,Nt(!1),!0;if(g&&D&&!i.shiftKey){const m=Math.min(D.start,D.end,c),h=Math.max(D.start,D.end,c);return Fe({start:m,end:h}),jt.current=!1,Ke.current=null,Nt(!1),!0}if(jt.current=!0,Ke.current=c,Nt(!0),D&&i.shiftKey){const m=Math.min(D.start,c),h=Math.max(D.end,c);Fe({start:m,end:h})}else Fe({start:c,end:c});return!0},mouseover:(e,s,i)=>{if(!(i instanceof MouseEvent)||i.buttons!==1||!jt.current||Ke.current===null)return!1;const c=e.state.doc.lineAt(s.from).number,m=Math.min(Ke.current,c),h=Math.max(Ke.current,c);return Fe({start:m,end:h}),Nt(!0),!1},mouseup:()=>(jt.current=!1,Ke.current=null,Nt(!1),!1)}}})}),Ct&&t.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-background",children:t.jsxs("div",{className:"flex items-center gap-2 typography-ui text-muted-foreground",children:[t.jsx(v,{name:"loader-4",className:"size-4 animate-spin"}),"Opening file at change..."]})})]}):t.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:"Pick a file from the tree."})})]})]}),xo=!!(o&&Cn[o]),Cs=o?Xt[o]:null,Ss=t.jsxs("section",{className:$("flex min-h-0 flex-col overflow-hidden",g?"h-full w-full bg-background":"h-full rounded-xl border border-border/60 bg-background/70"),children:[t.jsx("div",{className:$("flex flex-col gap-2 py-2",g?"px-3":"px-2"),children:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("div",{className:"relative flex-1 min-w-0",children:[t.jsx(v,{name:"search",className:"pointer-events-none absolute left-2 top-2 size-4 text-muted-foreground"}),t.jsx(vr,{ref:Oe,value:Ne,onChange:e=>ae(e.target.value),placeholder:"Search files...",className:"h-8 pl-8 pr-8 typography-meta"}),Ne.trim().length>0&&t.jsx("button",{type:"button","aria-label":"Clear search",className:"absolute right-2 top-2 inline-flex size-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{ae(""),Oe.current?.focus()},children:t.jsx(v,{name:"close",className:"size-4"})})]}),t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx("span",{className:"inline-flex flex-shrink-0",children:t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>$r("createFile",{path:P,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:"New File","aria-label":"New File",children:t.jsx(v,{name:"file-add",className:"size-4"})})})}),t.jsx(Ze,{side:"bottom",sideOffset:6,children:"New File"})]}),t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx("span",{className:"inline-flex flex-shrink-0",children:t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>$r("createFolder",{path:P,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:"New Folder","aria-label":"New Folder",children:t.jsx(v,{name:"folder-add",className:"size-4"})})})}),t.jsx(Ze,{side:"bottom",sideOffset:6,children:"New Folder"})]}),t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx("span",{className:"inline-flex flex-shrink-0",children:t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>{ar()},className:"size-8 p-0 flex-shrink-0",title:"Refresh","aria-label":"Refresh",children:t.jsx(v,{name:"refresh",className:"size-4"})})})}),t.jsx(Ze,{side:"bottom",sideOffset:6,children:"Refresh"})]})]})}),t.jsx(an,{outerClassName:"flex-1 min-h-0",className:$("py-2",g?"px-3":"px-2"),children:t.jsx("ul",{className:"flex flex-col",children:Ca?t.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[t.jsx(v,{name:"loader-4",className:"size-4 animate-spin"}),"Searching..."]}):Fn.length>0?Fn.map(e=>{const s=l?.path===e.path;return t.jsx("li",{children:t.jsxs("button",{type:"button",onClick:()=>{ce(e)},className:$("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",s?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[ya(e.path,e.extension),t.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:e.path,children:e.relativePath??e.path})]})},e.path)}):Cs?t.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[t.jsx("span",{className:"text-[var(--status-error)]",children:Cs}),t.jsxs(S,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{ar()},children:[t.jsx(v,{name:"refresh",className:"size-3.5"}),"Refresh"]})]}):xo?is(o,0):t.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading..."})})})]}),vo=r==="full"&&w&&l&&t.jsx("div",{className:"absolute inset-0 z-50 flex flex-col bg-background",children:t.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[t.jsx("div",{className:"absolute right-4 top-4 z-30",children:Zr({exitFullscreenOnly:!0})}),t.jsx(an,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:ke||bs||ws?xe?t.jsx("div",{className:"p-4"}):t.jsxs("div",{className:"p-4 flex items-center gap-2 typography-ui text-muted-foreground",children:[t.jsx(v,{name:"loader-4",className:"size-4 animate-spin"}),"Loading…"]}):Be?t.jsx("div",{className:"p-4 typography-ui text-[color:var(--status-error)]",children:Be}):Z?t.jsx("div",{className:"flex h-full items-center justify-center p-4",children:t.jsx("img",{src:ys,alt:l.name,className:"max-w-full max-h-full object-contain rounded-md border border-border/30 bg-primary/10"},hs)}):ye?Ns(l):We?t.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[t.jsx("div",{className:"typography-ui-header text-foreground",children:"Cannot preview binary file"}),t.jsx("div",{className:"max-w-md typography-ui text-muted-foreground",children:"This file is binary and cannot be edited in PiChamber. Download it to open with another app."}),a.downloadFile?t.jsxs(S,{type:"button",variant:"outline",size:"sm",onClick:()=>{const e=a.downloadFile;!e||!l||e(l.path).catch(s=>{console.error("Download failed:",s),A.error("Operation failed")})},children:[t.jsx(v,{name:"download",className:"mr-2 size-4"}),"Save file"]}):null]}):it&&le()==="preview"?t.jsxs("div",{className:"h-full overflow-auto p-4",children:[z.length>500*1024&&t.jsx("div",{className:"mb-3 rounded-md border border-status-warning/20 bg-status-warning/10 px-3 py-2 text-sm text-status-warning",children:`This file is large (${Math.round(z.length/1024)}KB). Preview may be limited.`}),t.jsx(on,{fallback:t.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[t.jsx("div",{className:"mb-1 font-medium text-destructive",children:"Preview unavailable"}),t.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to edit mode to fix the issue."})]}),children:t.jsx(Os,{content:z,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):Hr&&ie==="view"?ks(l,W):t.jsxs("div",{className:$("relative h-full",Ct&&"overflow-hidden"),children:[t.jsx("div",{className:$("h-full",Ct&&"invisible"),children:t.jsx(ra,{value:W,onChange:X,readOnly:!je,vimMode:Wn==="vim",extensions:fs,className:"h-full",onViewReady:e=>{Se.current=e,window.requestAnimationFrame(()=>{Ft(e)})},onViewDestroy:()=>{Se.current&&(Se.current=null)}})}),Ct&&t.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-background",children:t.jsxs("div",{className:"flex items-center gap-2 typography-ui text-muted-foreground",children:[t.jsx(v,{name:"loader-4",className:"size-4 animate-spin"}),"Opening file at change..."]})})]})})]})});return t.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden bg-background relative",children:[t.jsx(ic,{activeDialog:st,dialogData:at,dialogInputValue:Ge,onDialogInputChange:Dn,isDialogSubmitting:La,onDialogSubmit:Ya,onClose:ho,inputRef:Ea}),vo,g?dt?Qr:Ss:r==="editor-only"?t.jsx("div",{className:"flex flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden bg-background",children:Qr})}):t.jsxs("div",{className:"flex flex-1 min-h-0 min-w-0 gap-3 px-3 pb-3 pt-2",children:[E>=700&&t.jsx("div",{className:"w-72 flex-shrink-0 min-h-0 overflow-hidden",children:Ss}),t.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:Qr})]})]})};export{yu as FilesView};
14
+ … truncated …`:ne),H(e.path),Ue(e.path,_).then(ct=>{ct&&i()&&(Ve.current=ct)}).catch(()=>{})}).catch(ge=>{if(i()){if(rc(ge)){if(Ie(!1),o&&ee(o,null),Y(null),q(""),X(""),H(null),Ve.current=null,Ne.trim().length>0&&ae(""),g&&G(!1),o){const ct=[...ia(e.path,o),e.path];ct.length>0&&Jt(o,ct);for(const en of ct)ve.current.has(en)||we(en)}return}if(la(ge)){o&&qe(o,e.path),q(""),X(""),Y(null),Ve.current=null,g&&G(!1);return}q(""),X(""),Y(ge instanceof Error?ge.message:"Failed to read file"),Ve.current=null}}).finally(()=>{i()&&Ie(!1)})},[Jt,g,we,r,ts,Ue,qe,o,u.isDesktop,Ne,ee]),or=n.useCallback(async(e,s)=>{if(!o)return;const i=ia(e,o),c=s?[...i,e]:i;c.length>0&&Jt(o,c);const m=c.map(h=>{if(!ve.current.has(h))return we(h)}).filter(Boolean);await Promise.all(m)},[Jt,we,o]),ss=n.useCallback((e,s)=>{const i=s.findIndex(c=>c.path===e);return i===-1||s.length<=1?null:s[i+1]??s[i-1]??null},[]),ce=n.useCallback(async e=>{if(rt.current)rt.current=!1;else if(re){bt(!0),wt.current=e;return}o&&(ee(o,e.path),or(e.path,!1)),Y(null),Ce(""),q(""),He.current="",Pt.current="",X(""),H(null),g&&G(!0)},[or,re,g,o,ee]);n.useEffect(()=>{l?.path&&or(l.path,!1)},[or,l?.path]),n.useEffect(()=>{if(!l){er.current+=1,Mt.current=null,Ie(!1);return}if(pe===l.path||Mt.current===l.path)return;const e=l.path;Mt.current=e,ns(l).finally(()=>{Mt.current===e&&(Mt.current=null)})},[ns,pe,l]);const as=n.useRef(re);as.current=re,n.useEffect(()=>{if(!l?.path||pe!==l.path)return;let e=!1;const s=window.setInterval(()=>{document.hidden||Ue(l.path,J).then(i=>{if(e||!i)return;const c=Ve.current;if(!c||c.path!==l.path){Ve.current=i;return}const m=i.mtimeMs!==void 0&&c.mtimeMs!==void 0&&i.mtimeMs!==c.mtimeMs,h=i.size!==c.size;!m&&!h||as.current||(Ve.current=i,H(null))}).catch(()=>{})},2e3);return()=>{e=!0,window.clearInterval(s)}},[pe,Ue,l?.path,J]);const Xa=n.useCallback(()=>{const e=wt.current,s=Lt.current,i=Ot.current;if(wt.current=null,Lt.current=null,Ot.current=null,rt.current=!0,bt(!1),X(_r),i){o&&pt(o,i),l?.path===i&&(e?ce(e):(o&&ee(o,null),q(""),Y(null),Ce(""),H(null),g&&G(!1)));return}if(e){ce(e);return}s&&(Me(null),ue.getState().setActiveMainTab(s))},[_r,ce,g,pt,o,l?.path,Me,ee]),Za=n.useCallback(async()=>{const e=wt.current,s=Lt.current,i=Ot.current;if(!await ot()){rt.current=!1;return}if(wt.current=null,Lt.current=null,Ot.current=null,rt.current=!0,bt(!1),i){o&&pt(o,i),l?.path===i&&(e?await ce(e):(o&&ee(o,null),q(""),Y(null),Ce(""),H(null),g&&G(!1)));return}if(e){await ce(e);return}s&&(Me(null),ue.getState().setActiveMainTab(s))},[ce,g,pt,o,ot,l?.path,Me,ee]),os=n.useCallback(e=>{const s=l?.path===e,i=ss(e,gt);if(s&&re){bt(!0),wt.current=i,Ot.current=e;return}if(o&&pt(o,e),!!s){if(i){ce(i);return}o&&ee(o,null),q(""),Y(null),Ce(""),H(null),g&&G(!1)}},[ss,ce,re,g,gt,pt,o,l?.path,ee]),Qa=n.useCallback(e=>{if(Q.includes(e))return"open";if(B?.files){const s=e.startsWith(o+"/")?e.slice(o.length+1):e,i=B.files.find(c=>c.path===s);if(i){if(i.index==="A"||i.working_dir==="?")return"git-added";if(i.index==="D")return"git-deleted";if(i.index==="M"||i.working_dir==="M")return"git-modified"}}return null},[Q,B,o]),eo=n.useCallback(e=>{if(!B?.files)return null;const s=e.startsWith(o+"/")?e.slice(o.length+1):e,i=s?`${s}/`:"";let c=0,m=0;for(const h of B.files)h.path.startsWith(i)&&((h.index==="M"||h.working_dir==="M")&&c++,(h.index==="A"||h.working_dir==="?")&&m++);return c+m>0?{modified:c,added:m}:null},[B,o]),to=n.useCallback(async e=>{const s=I(e);o&&(wn(o,s),ve.current.has(s)||await we(s))},[we,o,wn]),ro=n.useMemo(()=>({canRename:On,canCreateFile:Tn,canCreateFolder:Ln,canDelete:An,canReveal:In}),[On,Tn,Ln,An,In]);function is(e,s){const i=Cn[e]??[];return i.map((c,m)=>{const h=c.type==="directory",j=h&&tt.includes(c.path),F=l?.path===c.path,_=m===i.length-1;return t.jsxs("li",{className:"relative",children:[s>0&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),_&&t.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-background"})]}),t.jsx(oc,{node:c,root:o,isExpanded:j,isActive:F,isMobile:g,isBrowserClient:k,alwaysShowActions:L,status:h?void 0:Qa(c.path),badge:h?eo(c.path):void 0,permissions:ro,downloadFile:a.downloadFile,contextMenuPath:Oa,setContextMenuPath:Aa,rightClickMenuPath:Ia,setRightClickMenuPath:Ba,onSelect:ce,onToggle:to,onRevealPath:Ka,onOpenDialog:$r}),h&&j&&t.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[Xt[c.path]?t.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[t.jsx("span",{className:"min-w-0 flex-1 truncate text-[var(--status-error)]",title:Xt[c.path],children:Xt[c.path]}),t.jsxs(S,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{Le(c.path)},children:[t.jsx(v,{name:"refresh",className:"size-3.5"}),"Refresh"]})]}):null,is(c.path,s+1)]})]},c.path)})}const Z=!!(l?.path&&Ps(l.path)),kt=!!(l?.path&&Ms(l.path)),ye=!!(l?.path&&Ts(l.path)),qr=!!(l?.path&&(fr(l.path)||Tt)),We=qr&&!Z&&!ye,cs=n.useMemo(()=>I(Te?.path??""),[Te?.path]),Ct=!!(Te&&cs&&ze&&ze===cs&&!ke&&!Be&&!Z&&!ye&&!We),Je=n.useMemo(()=>xr(o,ze),[ze,o]),no=!!(l&&(!Z||kt)&&!ye&&!We&&D.length>0),so=!!(l&&Je.length>0),je=!!(l&&!Yt&&!qr&&!Z&&a.writeFile&&D.length<=qt),it=!!(l?.path&&ua(l.path)),Vt=!!(l?.path&&ac(l.path)),St=!!(l?.path&&fn(l.path)),Wt=!!(l?.path&&sn(l.path)),Hr=!!(l&&!qr&&!Z)&&!it&&!Wt&&!(St&&mt==="preview"),ao=it&&Nr==="edit"||St&&mt==="edit"||Vt&&ft==="text"||!it&&!St&&!Vt&&ie==="edit",ir=n.useMemo(()=>ze?$o(ze):null,[ze]),[ls,Kr]=n.useState(null);n.useEffect(()=>{let e=!1;const s=l?.path;if(!s||ir){Kr(null);return}return Kr(null),Vo(s).then(i=>{e||Kr(i)}),()=>{e=!0}},[l?.path,ir]),n.useEffect(()=>{!je&&ie==="edit"&&Rt("view")},[je,ie]);const Gr="pichamber:files:md-viewer-mode",Ur="pichamber:files:html-viewer-mode",Jr="pichamber:files:json-viewer-mode";n.useEffect(()=>{const e=l?.path;if(!e)return;Rt(Fr.current[e]??"edit");let s=Bt?"preview":"edit";try{const m=localStorage.getItem(Gr);(m==="preview"||m==="edit")&&(s=m)}catch{}kr(Er.current[e]??s);let i=Bt?"preview":"edit";try{const m=localStorage.getItem(Ur);(m==="preview"||m==="edit")&&(i=m)}catch{}Sr(Rr.current[e]??i),Dt(Dr.current[e]??(Bt?"preview":"edit"));let c=Bt?"tree":"text";try{const m=localStorage.getItem(Jr);(m==="tree"||m==="text")&&(c=m)}catch{}Cr(c)},[l?.path,Bt]);const oo=n.useCallback(e=>{const s=l?.path;s&&(Fr.current[s]=e),Rt(e)},[l?.path]),us=n.useCallback(e=>{const s=l?.path;s&&(Er.current[s]=e),kr(e);try{localStorage.setItem(Gr,e)}catch{}},[l?.path]),le=n.useCallback(()=>Nr,[Nr]),io=n.useCallback(e=>{Cr(e);try{localStorage.setItem(Jr,e)}catch{}},[]),co=n.useCallback(e=>{const s=l?.path;s&&(Rr.current[s]=e),Sr(e);try{localStorage.setItem(Ur,e)}catch{}},[l?.path]),lo=n.useCallback(e=>{const s=l?.path;if(s&&(Dr.current[s]=e),he.current&&(clearTimeout(he.current),he.current=null),$e.current!==null&&(cancelAnimationFrame($e.current),$e.current=null),e==="edit")X(He.current||D),Dt(e);else{He.current=W;const i=s;Dt("edit"),$e.current=requestAnimationFrame(()=>{$e.current=requestAnimationFrame(()=>{$e.current=null,!(o&&i&&Ee.getState().byRoot[o]?.selectedPath!==i)&&(Na(c=>c+1),Dt("preview"))})});return}},[W,D,o,l?.path]),Yr=n.useCallback(async(e,s)=>{if(!a.writeFile||s===Pt.current)return!1;if(!(await a.writeFile(e,s))?.success)return A.error("Failed to write file"),!1;He.current=s,Pt.current=s,X(s);const c=await Ue(e,J).catch(()=>null);return c&&(Ve.current=c),!0},[a,Ue,J]);n.useEffect(()=>()=>{he.current&&(clearTimeout(he.current),he.current=null),$e.current!==null&&(cancelAnimationFrame($e.current),$e.current=null)},[Qe,l?.path]);const uo=n.useCallback(e=>{if(He.current=e,!te||!l?.path||Qe!=="preview"||!a.writeFile)return;he.current&&clearTimeout(he.current);const s=l.path;he.current=setTimeout(()=>{he.current=null,Yr(s,e).then(i=>{i&&(tr(!0),setTimeout(()=>tr(!1),1500))}).catch(i=>{A.error(i instanceof Error?i.message:"Save failed")})},rs)},[te,Qe,a.writeFile,Yr,l?.path]),fo=n.useMemo(()=>Wt&&(He.current||W)||D,[W,D,Wt]),ds=n.useCallback(()=>mt,[mt]);n.useEffect(()=>{const e=i=>{const c=i?"preview":"edit",m=i?"tree":"text";for(const h of Q)Fr.current[h]="edit",ua(h)&&(Er.current[h]=c),fn(h)&&(Rr.current[h]=c),sn(h)&&(Dr.current[h]=c);Rt("edit"),kr(c),Sr(c),Dt(c),Cr(m);try{localStorage.setItem(Gr,c),localStorage.setItem(Ur,c),localStorage.setItem(Jr,m)}catch{}},s=i=>{const c=!!i.detail?.enabled;e(c)};return window.addEventListener("pichamber:file-viewer-preview-mode-changed",s),()=>{window.removeEventListener("pichamber:file-viewer-preview-mode-changed",s)}},[Q]),n.useEffect(()=>{if(!Te||!o)return;const e=()=>{typeof window>"u"||yt.current===null&&(yt.current=window.requestAnimationFrame(()=>{yt.current=null,Or(_e=>_e+1)}))},s=(_e,lt)=>{if(_e.state.doc.length!==lt.length)return!1;if(lt.length===0)return!0;const tn=Math.min(128,lt.length);if(_e.state.sliceDoc(0,tn)!==lt.slice(0,tn))return!1;const Fs=Math.max(0,lt.length-tn);return _e.state.sliceDoc(Fs,lt.length)===lt.slice(Fs)},i=I(Te.path);if(!i){rr(null),nt.current={key:"",attempts:0};return}const c=`${i}:${Te.line}:${Te.column??1}`;if(nt.current.key!==c&&(nt.current={key:c,attempts:0}),l?.path!==i){if(Lr)return;ce(ht(i));return}if(ke||pe!==i)return;if(Be||Z||ye||We){rr(null),nt.current={key:"",attempts:0};return}if(!je)return;if(ie!=="edit"){Rt("edit");return}const m=Se.current;if(!m){e();return}if(!s(m,W)){e();return}const h=Math.max(1,Math.min(Te.line,m.state.doc.lines)),j=m.state.doc.line(h),F=Math.max(1,Te.column||1),_=Math.max(0,j.to-j.from),ge=Math.min(_,F-1),ne=j.from+ge;if(!(m.state.selection.main.head===ne)||nt.current.attempts===0){nt.current.attempts+=1,m.dispatch({selection:{anchor:ne},effects:se.scrollIntoView(ne,{y:"center"})}),m.focus(),e();return}typeof window<"u"&&window.requestAnimationFrame(()=>{const _e=Se.current;_e&&(_e.dispatch({selection:{anchor:ne},effects:se.scrollIntoView(ne,{y:"center"})}),_e.focus())}),rr(null),nt.current={key:"",attempts:0}},[je,Lr,W,Ma,Be,ke,Z,ye,We,pe,ce,Te,o,l?.path,rr,ie,ht]),n.useEffect(()=>{if(!Vr||!o)return;const e=I(Vr);if(!e){Wr(null);return}l?.path===e&&(ke||pe!==e||(!Be&&!Z&&!ye&&!We&&je&&ie==="edit"&&Se.current?.focus(),Wr(null)))},[je,Be,ke,Z,ye,We,pe,Vr,o,l?.path,Wr,ie]);const Ft=n.useCallback(e=>{if(!g||!e||!e.hasFocus||typeof window>"u")return;const s=window.visualViewport;if(!s)return;const i=document.documentElement.clientHeight||window.innerHeight;if(Math.max(0,i-(s.offsetTop+s.height))<=0)return;const m=e.state.selection.main.head,h=e.coordsAtPos(m);if(!h)return;const j=Math.round(s.offsetTop+s.height),_=h.bottom+20-j;_<=0||(e.scrollDOM.scrollTop+=_)},[g]);n.useEffect(()=>{if(!g||typeof window>"u")return;const e=()=>{window.requestAnimationFrame(()=>{Ft(Se.current)})},s=window.visualViewport;return s?.addEventListener("resize",e),s?.addEventListener("scroll",e,{passive:!0}),document.addEventListener("selectionchange",e),()=>{s?.removeEventListener("resize",e),s?.removeEventListener("scroll",e),document.removeEventListener("selectionchange",e)}},[g,Ft]),n.useEffect(()=>{if(!je||ie!=="edit"||g)return;const e=Wo("open_go_to_line",Vn),s=i=>{const c=i.target;if(c?.closest('[role="dialog"]'))return;const m=!!c?.closest(".cm-editor");c?.closest('input, textarea, [contenteditable="true"], [role="textbox"]')&&!m||!document.activeElement?.closest(".cm-editor")||qo(i,e)&&(i.preventDefault(),Br(!0))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[je,g,Vn,ie]);const cr=ue(e=>e.editorFontSize),fs=n.useMemo(()=>{if(!l?.path)return[aa(f,{fontSize:cr})];const e=nn(l.path),s=[aa(f,e?{syntaxColors:!1,fontSize:cr}:{fontSize:cr})],i=ir??ls;return i&&s.push(i),e&&s.push(Hi({language:e,themeName:f.metadata.id,theme:bi(f)})),V&&s.push(se.lineWrapping),g&&s.push(se.updateListener.of(c=>{c.view.hasFocus&&(c.selectionSet||c.focusChanged||c.viewportChanged||c.geometryChanged)&&window.requestAnimationFrame(()=>{Ft(c.view)})})),s},[f,l?.path,ir,ls,V,g,Ft,cr]),ms=n.useMemo(()=>({light:Kt.metadata.id,dark:Gt.metadata.id}),[Kt.metadata.id,Gt.metadata.id]),lr=l?.path&&Z&&!u.isDesktop&&!kt?`${l.path}|${J.allowOutsideWorkspace?"outside":"workspace"}|${J.outsideFileGrant??""}`:"",ur=l?.path&&ye?`${l.path}|${J.allowOutsideWorkspace?"outside":"workspace"}|${J.outsideFileGrant??""}`:"",dr=l?.path&&St&&mt==="preview"?l.path:"",Xr="Failed to read file",{readyKey:ps,nonce:hs}=mn(lr,Y,Xr),{readyKey:gs,nonce:mo}=mn(dr,Y,Xr),{readyKey:xs,nonce:vs}=mn(ur,Y,Xr),bs=!!(lr&&ps!==lr),po=!!(dr&&gs!==dr),ws=!!(ur&&xs!==ur),ys=l?.path&&Z?u.isDesktop?kt?`data:${Ls(l.path)};utf8,${encodeURIComponent(D)}`:Sa:kt?`data:${Ls(l.path)};utf8,${encodeURIComponent(D)}`:ps===lr?rn().authenticatedAsset("/api/fs/raw",{path:l.path,allowOutsideWorkspace:J.allowOutsideWorkspace?"true":void 0,outsideFileGrant:J.outsideFileGrant,directory:o||void 0}):"":"",js=l?.path&&ye&&xs===ur?rn().authenticatedAsset("/api/fs/raw",{path:l.path,allowOutsideWorkspace:J.allowOutsideWorkspace?"true":void 0,outsideFileGrant:J.outsideFileGrant,directory:o||void 0}):"",Ns=n.useCallback(e=>t.jsx("div",{className:"h-full overflow-hidden bg-[var(--surface-background)]",children:t.jsx("iframe",{src:js,className:"h-full w-full border-0",title:e.name},vs)}),[js,vs]);n.useEffect(()=>{let e=!1;return(async()=>{if(!u.isDesktop||!l?.path||!Z||kt){me.current&&(URL.revokeObjectURL(me.current),me.current=""),Ce("");return}Y(null),me.current&&(URL.revokeObjectURL(me.current),me.current=""),await(a.readFileBinary?a.readFileBinary(l.path,J).then(c=>c.dataUrl):(async()=>{const c=await Ds("/api/fs/raw",{query:{path:l.path,allowOutsideWorkspace:J.allowOutsideWorkspace?"true":void 0,outsideFileGrant:J.outsideFileGrant,directory:o||void 0}});if(!c.ok)throw new Error("Failed to read file");const m=await c.blob(),h=URL.createObjectURL(m);return e?(URL.revokeObjectURL(h),""):(me.current=h,h)})()).then(c=>{e||(Ce(c),H(l.path))}).catch(c=>{me.current&&(URL.revokeObjectURL(me.current),me.current=""),e||(Ce(""),Y(c instanceof Error?c.message:"Failed to read file"),H(null))}).finally(()=>{e||Ie(!1)})})(),()=>{e=!0}},[a,Z,kt,o,u.isDesktop,l?.path,J]),n.useEffect(()=>()=>{me.current&&(URL.revokeObjectURL(me.current),me.current="")},[]);const ho=n.useCallback(()=>Ar(null),[]),go=n.useMemo(()=>ki({drafts:qn,editingDraftId:sr,commentText:nr,onTextChange:Hn,selection:z,isDragging:$n,fileLabel:l?.path??"",newWidgetId:"files-new-comment-input",mapDraftToRange:e=>({start:e.startLine,end:e.endLine}),onSave:Xn,onCancel:()=>{Fe(null),$t()},onEdit:e=>{Jn(e),Fe({start:e.startLine,end:e.endLine})},onDelete:Yn}),[$t,nr,Yn,sr,qn,Xn,$n,z,l?.path,Hn,Jn]),ks=n.useCallback((e,s)=>t.jsx("div",{className:"h-full",children:t.jsx(gi,{file:{name:e.name,contents:s,lang:nn(e.path)||void 0},options:{disableFileHeader:!0,overflow:V?"wrap":"scroll",theme:ms,themeType:f.metadata.variant==="dark"?"dark":"light"},className:"block h-full w-full",style:{height:"100%"}})}),[f.metadata.variant,ms,V]),Zr=({exitFullscreenOnly:e=!1,layout:s="floating"}={})=>{if(!l)return null;const c=s==="docked"?"pointer-events-auto flex flex-wrap items-center gap-1":"pointer-events-auto flex items-center gap-1 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-1 shadow-sm",m=(h,j)=>t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx("span",{className:"inline-flex",children:j})}),t.jsx(Ze,{side:"bottom",sideOffset:6,children:h})]});return t.jsxs("div",{className:c,children:[je&&ao&&t.jsxs(t.Fragment,{children:[xt?t.jsxs("span",{className:"flex items-center gap-1 px-1 text-muted-foreground typography-meta",children:[t.jsx(v,{name:"loader-4",className:"size-3.5 animate-spin"}),"Saving..."]}):te&&Ra==="saved"&&!re?t.jsxs("span",{className:"flex items-center gap-1 px-1 text-[color:var(--status-success)] typography-meta",children:[t.jsx(v,{name:"check",className:"size-3.5"}),"Saved"]}):re?m(te?`Save now (${_t()}+S) - auto-saves after 1.5s`:`Save now (${_t()}+S)`,t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>{ot()},className:"h-6 gap-1 px-1 text-muted-foreground opacity-80 hover:bg-transparent hover:opacity-100 focus-visible:bg-transparent active:bg-transparent",title:te?`Save now (${_t()}+S) - auto-saves after 1.5s`:`Save now (${_t()}+S)`,"aria-label":`Save (${_t()}+S)`,children:t.jsx(v,{name:"save-3",className:"size-4"})})):null,m(te?"Auto-save on":"Manual save",t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>za(!te),className:$("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",te?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:te?"Auto-save on":"Manual save","aria-label":te?"Auto-save on":"Manual save",children:te?t.jsx(v,{name:"file-check-fill",className:"size-4"}):t.jsx(v,{name:"file-check",className:"size-4"})}))]}),t.jsxs(pn,{onOpenChange:jr,children:[t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx("span",{className:"inline-flex",children:t.jsx(hn,{asChild:!0,children:t.jsx(S,{variant:"ghost",size:"sm",className:"size-6 p-0 text-foreground opacity-100 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Open in desktop app","aria-label":"Open in desktop app",children:t.jsx(v,{name:"file-transfer",className:"size-4"})})})})}),t.jsx(Ze,{side:"bottom",sideOffset:6,children:"Open in desktop app"})]}),t.jsxs(gn,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[_a.map(h=>t.jsxs(gr,{className:"flex items-center gap-2",onClick:()=>{Ga(h)},children:[t.jsx(Ji,{label:h.label,iconDataUrl:h.iconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:h.label})]},h.id)),qa?t.jsxs(gr,{className:"flex items-center gap-2",onClick:()=>{Ha(!0)},children:[t.jsx(v,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]}),!Z&&!ye&&!We&&t.jsxs(t.Fragment,{children:[m(V?"Disable line wrap":"Enable line wrap",t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>fe(!V),className:$("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",V?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:V?"Disable line wrap":"Enable line wrap",children:t.jsx(v,{name:"text-wrap",className:"size-4"})})),ie==="edit"&&t.jsxs(t.Fragment,{children:[m("Find in file",t.jsx(S,{variant:"ghost",size:"sm",onClick:h=>{T(!N),h.currentTarget.blur()},className:"size-6 p-0 text-foreground opacity-100 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Find in file",children:t.jsx(v,{name:"search",className:"size-4"})})),m("Go to line",t.jsx(S,{variant:"ghost",size:"sm",onClick:h=>{Br(j=>!j),h.currentTarget.blur()},className:"size-6 p-0 text-foreground opacity-100 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Go to line",children:t.jsx(v,{name:"menu-fold-2",className:"size-4"})})),t.jsx(Oi,{open:Wa,onOpenChange:Br,view:Se.current,variant:"inline"})]})]}),Hr&&je&&!Vt&&!St&&t.jsx(dn,{currentMode:ie==="view"?"preview":"edit",onToggle:()=>{oo(ie==="view"?"edit":"view")}}),it&&m(le()==="preview"?"Switch to edit mode":"Switch to preview mode",t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>us(le()==="preview"?"edit":"preview"),className:$("size-6 p-0 transition-colors hover:bg-[var(--interactive-hover)] focus-visible:bg-[var(--interactive-hover)] active:bg-[var(--interactive-hover)]",le()==="preview"?"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)] hover:bg-[var(--interactive-selection)] focus-visible:bg-[var(--interactive-selection)] active:bg-[var(--interactive-selection)]":"text-muted-foreground opacity-65 hover:opacity-100"),title:le()==="preview"?"Switch to edit mode":"Switch to preview mode","aria-label":le()==="preview"?"Switch to edit mode":"Switch to preview mode",children:t.jsx(v,{name:le()==="preview"?"eye":"eye-off",className:"size-4"})})),fn(l?.path??"")&&t.jsx(dn,{currentMode:ds(),onToggle:()=>{co(ds()==="preview"?"edit":"preview")}}),Wt&&t.jsxs(t.Fragment,{children:[t.jsx(dn,{currentMode:Qe,onToggle:()=>lo(Qe==="preview"?"edit":"preview")}),Qe==="preview"&&t.jsx(S,{variant:"ghost",size:"sm",onClick:async()=>{const h=Rn.current?.getXml();if(he.current&&(clearTimeout(he.current),he.current=null),l?.path&&h){if(!await Yr(l.path,h))return;tr(!0),setTimeout(()=>tr(!1),1500)}},className:"size-6 p-0 text-foreground hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Save diagram",children:Da?t.jsx(v,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):t.jsx(v,{name:"save-3",className:"size-4"})})]}),Vt&&m(ft==="tree"?"Switch to Text View":"Switch to Tree View",t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>io(ft==="tree"?"text":"tree"),className:"size-6 p-0 text-muted-foreground opacity-65 hover:bg-transparent hover:opacity-100 focus-visible:bg-transparent active:bg-transparent",title:ft==="tree"?"Switch to Text View":"Switch to Tree View",children:ft==="tree"?t.jsx(v,{name:"code-sslash",className:"size-4"}):t.jsx(v,{name:"node-tree",className:"size-4"})})),no&&m("Copy file contents",t.jsx(S,{variant:"ghost",size:"sm",onClick:async()=>{(await br(D)).ok?(Pn(!0),At.current!==null&&window.clearTimeout(At.current),At.current=window.setTimeout(()=>{Pn(!1)},1200)):A.error("Copy failed")},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Copy file contents","aria-label":"Copy file contents",children:$a?t.jsx(v,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):t.jsx(v,{name:"clipboard",className:"size-4"})})),so&&m(`Copy file path (${Je})`,t.jsx(S,{variant:"ghost",size:"sm",onClick:async()=>{(await br(Je)).ok?(Mn(!0),It.current!==null&&window.clearTimeout(It.current),It.current=window.setTimeout(()=>{Mn(!1)},1200)):A.error("Copy failed")},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:`Copy file path (${Je})`,"aria-label":`Copy file path (${Je})`,children:Va?t.jsx(v,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):t.jsx(v,{name:"file-copy-2",className:"size-4"})})),a.downloadFile&&m("Save file",t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>{const h=a.downloadFile;h&&h(l.path).catch(j=>{console.error("Download failed:",j),A.error("Operation failed")})},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Save file","aria-label":"Save file",children:t.jsx(v,{name:"download",className:"size-4"})})),e?m("Exit fullscreen",t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>U(!1),className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Exit fullscreen","aria-label":"Exit fullscreen",children:t.jsx(v,{name:"fullscreen-exit",className:"size-4"})})):!g&&r==="full"&&m(w?"Exit fullscreen":"Fullscreen",t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>U(!w),className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:w?"Exit fullscreen":"Fullscreen","aria-label":w?"Exit fullscreen":"Fullscreen",children:w?t.jsx(v,{name:"fullscreen-exit",className:"size-4"}):t.jsx(v,{name:"fullscreen",className:"size-4"})}))]})},Qr=t.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[t.jsx(da,{open:Lr,onOpenChange:e=>{e||bt(!0)},children:t.jsxs(fa,{showCloseButton:!1,className:"max-w-md",children:[t.jsxs(ma,{children:[t.jsx(pa,{children:"Unsaved changes"}),t.jsx(ha,{children:"Save your edits before continuing?"})]}),t.jsxs(ga,{children:[t.jsx(S,{variant:"outline",onClick:()=>{Za()},disabled:xt,className:"border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]",children:"Save changes"}),t.jsx(S,{variant:"destructive",onClick:Xa,children:"Discard"})]})]})}),t.jsxs("div",{className:$("flex flex-col flex-shrink-0",K&&"border-b border-border/40"),children:[K?t.jsxs("div",{className:"flex min-w-0 items-center px-3 py-1.5",children:[g&&dt&&t.jsx("button",{type:"button",onClick:()=>G(!1),"aria-label":"Back",className:"inline-flex size-7 flex-shrink-0 items-center justify-center mr-1 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:t.jsx(v,{name:"arrow-left-s",className:"size-5"})}),g?l?t.jsxs(pn,{children:[t.jsx(hn,{asChild:!0,children:t.jsxs("button",{type:"button",className:"inline-flex min-w-0 max-w-full items-center gap-1 text-left typography-ui-label font-medium","aria-label":"Open files",children:[t.jsx(hr,{filePath:l.path,extension:l.extension,className:"size-3.5 flex-shrink-0"}),t.jsx(ca,{name:l.name}),t.jsx(v,{name:"arrow-down-s",className:"size-4 flex-shrink-0 text-muted-foreground"})]})}),t.jsx(gn,{align:"start",className:"w-[min(24rem,calc(100vw-2rem))] max-w-[calc(100vw-2rem)]",children:gt.map(e=>{const s=l?.path===e.path;return t.jsxs(gr,{onSelect:i=>{if(i.target.closest("[data-close-open-file]")){i.preventDefault();return}s||ce(e)},className:$("flex min-w-0 items-center justify-between gap-2 overflow-hidden",s&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-hidden",children:[t.jsx(hr,{filePath:e.path,extension:e.extension,className:"size-3.5 flex-shrink-0"}),t.jsx(ca,{name:e.name})]}),t.jsx("button",{type:"button","data-close-open-file":!0,onPointerDown:i=>{i.preventDefault(),i.stopPropagation()},onClick:i=>{i.preventDefault(),i.stopPropagation(),os(e.path)},className:"inline-flex size-6 shrink-0 items-center justify-center rounded-md text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]","aria-label":`Close ${e.name}`,children:t.jsx(v,{name:"close",className:"size-3.5"})})]},e.path)})})]}):t.jsx("div",{className:"typography-ui-label font-medium truncate",children:"Select a file"}):gt.length>0?t.jsxs("div",{className:"relative min-w-0 flex-1",children:[jn.left&&t.jsx("div",{className:"pointer-events-none absolute left-0 top-0 bottom-0 w-6 z-10 bg-gradient-to-r from-background to-transparent"}),jn.right&&t.jsx("div",{className:"pointer-events-none absolute right-0 top-0 bottom-0 w-6 z-10 bg-gradient-to-l from-background to-transparent"}),t.jsx("div",{ref:Pr,className:"flex min-w-0 items-center gap-1 overflow-x-auto scrollbar-none",style:{scrollbarWidth:"none",msOverflowStyle:"none"},"data-no-drawer-swipe":"true",children:gt.map(e=>{const s=l?.path===e.path;return t.jsxs("div",{title:xr(o,e.path),className:$("group inline-flex items-center gap-1 rounded-md border px-2 py-1 typography-ui-label transition-colors whitespace-nowrap",s?"bg-[var(--interactive-selection)] border-[var(--primary-muted)] text-[var(--interactive-selection-foreground)]":"bg-transparent border-[var(--interactive-border)] text-[var(--surface-muted-foreground)] hover:bg-[var(--interactive-hover)] hover:text-[var(--surface-foreground)]"),children:[t.jsx(hr,{filePath:e.path,extension:e.extension,className:"size-3.5 flex-shrink-0"}),t.jsx("button",{type:"button",onClick:()=>{s||ce(e)},className:"max-w-[12rem] truncate text-left",children:e.name}),t.jsx("button",{type:"button",onClick:i=>{i.stopPropagation(),os(e.path)},className:$("rounded-sm p-0.5 text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]",!s&&!L&&"opacity-0 group-hover:opacity-100"),"aria-label":`Close ${e.name}`,children:t.jsx(v,{name:"close",className:"size-3.5"})})]},e.path)})})]}):t.jsx("div",{className:"typography-ui-label font-medium truncate",children:"Select a file"})]}):null,(_n||g)&&l?t.jsxs("div",{className:"flex min-w-0 items-center gap-3 border-t border-border/40 bg-[var(--surface-subtle)] px-3 py-1",children:[Je&&!g?t.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta text-muted-foreground",title:Je,children:Je}):null,t.jsx("div",{className:"ml-auto min-w-0 shrink-0 overflow-x-auto",children:Zr({layout:"docked"})})]}):null]}),t.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[l&&!N&&!(_n||g)&&t.jsx("div",{ref:O,className:"absolute right-3 top-3 z-30",onMouseLeave:()=>{De.current>0||oe(!1)},children:C?Zr():t.jsxs("div",{className:"flex items-center gap-1",children:[it?t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx("span",{className:"inline-flex",children:t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>us(le()==="preview"?"edit":"preview"),className:$("size-8 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-0 shadow-sm transition-colors",le()==="preview"?"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)] hover:bg-[var(--interactive-selection)]":"text-muted-foreground hover:text-foreground"),"aria-label":le()==="preview"?"Switch to edit mode":"Switch to preview mode",title:le()==="preview"?"Switch to edit mode":"Switch to preview mode",children:t.jsx(v,{name:le()==="preview"?"eye":"eye-off",className:"size-4"})})})}),t.jsx(Ze,{side:"bottom",sideOffset:6,children:le()==="preview"?"Switch to edit mode":"Switch to preview mode"})]}):null,t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx("span",{className:"inline-flex",onMouseEnter:()=>oe(!0),children:t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>oe(!0),className:"size-8 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-0 text-muted-foreground shadow-sm hover:text-foreground","aria-label":"Show editor controls",title:"Editor controls",children:t.jsx(v,{name:"more-2-fill",className:"size-4"})})})}),t.jsx(Ze,{side:"bottom",sideOffset:6,children:"Editor controls"})]})]})}),t.jsx(an,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:l?ke||bs||ws?xe?t.jsx("div",{className:"p-3"}):t.jsxs("div",{className:"p-3 flex items-center gap-2 typography-ui text-muted-foreground",children:[t.jsx(v,{name:"loader-4",className:"size-4 animate-spin"}),"Loading..."]}):Be?t.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:Be}):Z?t.jsx("div",{className:"flex h-full items-center justify-center p-3",children:t.jsx("img",{src:ys,alt:l?.name??"Image",className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border/30 bg-primary/10"},hs)}):ye?Ns(l):We?t.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[t.jsx("div",{className:"typography-ui-header text-foreground",children:"Cannot preview binary file"}),t.jsx("div",{className:"max-w-md typography-ui text-muted-foreground",children:"This file is binary and cannot be edited in PiChamber. Download it to open with another app."}),a.downloadFile?t.jsxs(S,{type:"button",variant:"outline",size:"sm",onClick:()=>{const e=a.downloadFile;!e||!l||e(l.path).catch(s=>{console.error("Download failed:",s),A.error("Operation failed")})},children:[t.jsx(v,{name:"download",className:"mr-2 size-4"}),"Save file"]}):null]}):l&&Wt&&Qe==="preview"?t.jsx("div",{className:"h-full overflow-hidden",style:{minHeight:"400px"},children:t.jsx(wi,{ref:Rn,xml:fo,onChange:uo},`${l.path}:${ja}`)}):l&&Vt&&ft==="tree"?t.jsx(on,{fallback:t.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[t.jsx("div",{className:"mb-1 font-medium text-destructive",children:"JSON viewer unavailable"}),t.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to text mode to view raw content."})]}),children:t.jsx("div",{className:"h-full overflow-auto",children:t.jsx(xi,{jsonString:D,maxHeight:"100%",initiallyExpandedDepth:2})})}):l&&it&&le()==="preview"?t.jsxs("div",{className:"h-full overflow-auto p-3",children:[D.length>500*1024&&t.jsx("div",{className:"mb-3 rounded-md border border-status-warning/20 bg-status-warning/10 px-3 py-2 text-sm text-status-warning",children:`This file is large (${Math.round(D.length/1024)}KB). Preview may be limited.`}),t.jsx(on,{fallback:t.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[t.jsx("div",{className:"mb-1 font-medium text-destructive",children:"Preview unavailable"}),t.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to edit mode to fix the issue."})]}),children:t.jsx(Os,{content:D,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):l&&St&&mt==="preview"?po?t.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground typography-ui-label",children:"Loading..."}):t.jsx("div",{className:"h-full overflow-hidden",children:t.jsx("iframe",{src:gs===dr?(()=>{const e=l.path.split("/").map(s=>encodeURIComponent(s)).join("/");return rn().authenticatedAsset(`/api/fs/serve${e.startsWith("/")?e:`/${e}`}`)})():void 0,className:"w-full h-full border-none",sandbox:"allow-scripts allow-same-origin allow-forms",title:"HTML Preview"},mo)}):l&&Hr&&ie==="view"?ks(l,W):t.jsxs("div",{className:$("relative h-full",Ct&&"overflow-hidden"),ref:Pa,children:[t.jsx("div",{className:$("h-full",Ct&&"invisible"),children:t.jsx(ra,{value:W,onChange:X,readOnly:!je,vimMode:Wn==="vim",extensions:fs,className:"h-full",blockWidgets:go,onViewReady:e=>{Se.current=e,Or(s=>s+1),window.requestAnimationFrame(()=>{Ft(e)})},onViewDestroy:()=>{Se.current&&(Se.current=null),Or(e=>e+1)},enableSearch:!0,searchOpen:N,onSearchOpenChange:T,highlightLines:z?{start:Math.min(z.start,z.end),end:Math.max(z.start,z.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(e,s,i)=>{if(!(i instanceof MouseEvent)||i.button!==0)return!1;i.preventDefault();const c=e.state.doc.lineAt(s.from).number;if(z&&!i.shiftKey&&Math.min(z.start,z.end)===c&&Math.max(z.start,z.end)===c)return Fe(null),$t(),jt.current=!1,Ge.current=null,Nt(!1),!0;if(g&&z&&!i.shiftKey){const m=Math.min(z.start,z.end,c),h=Math.max(z.start,z.end,c);return Fe({start:m,end:h}),jt.current=!1,Ge.current=null,Nt(!1),!0}if(jt.current=!0,Ge.current=c,Nt(!0),z&&i.shiftKey){const m=Math.min(z.start,c),h=Math.max(z.end,c);Fe({start:m,end:h})}else Fe({start:c,end:c});return!0},mouseover:(e,s,i)=>{if(!(i instanceof MouseEvent)||i.buttons!==1||!jt.current||Ge.current===null)return!1;const c=e.state.doc.lineAt(s.from).number,m=Math.min(Ge.current,c),h=Math.max(Ge.current,c);return Fe({start:m,end:h}),Nt(!0),!1},mouseup:()=>(jt.current=!1,Ge.current=null,Nt(!1),!1)}}})}),Ct&&t.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-background",children:t.jsxs("div",{className:"flex items-center gap-2 typography-ui text-muted-foreground",children:[t.jsx(v,{name:"loader-4",className:"size-4 animate-spin"}),"Opening file at change..."]})})]}):t.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:"Pick a file from the tree."})})]})]}),xo=!!(o&&Cn[o]),Cs=o?Xt[o]:null,Ss=t.jsxs("section",{className:$("flex min-h-0 flex-col overflow-hidden",g?"h-full w-full bg-background":"h-full rounded-xl border border-border/60 bg-background/70"),children:[t.jsx("div",{className:$("flex flex-col gap-2 py-2",g?"px-3":"px-2"),children:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("div",{className:"relative flex-1 min-w-0",children:[t.jsx(v,{name:"search",className:"pointer-events-none absolute left-2 top-2 size-4 text-muted-foreground"}),t.jsx(vr,{ref:Oe,value:Ne,onChange:e=>ae(e.target.value),placeholder:"Search files...",className:"h-8 pl-8 pr-8 typography-meta"}),Ne.trim().length>0&&t.jsx("button",{type:"button","aria-label":"Clear search",className:"absolute right-2 top-2 inline-flex size-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{ae(""),Oe.current?.focus()},children:t.jsx(v,{name:"close",className:"size-4"})})]}),t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx("span",{className:"inline-flex flex-shrink-0",children:t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>$r("createFile",{path:P,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:"New File","aria-label":"New File",children:t.jsx(v,{name:"file-add",className:"size-4"})})})}),t.jsx(Ze,{side:"bottom",sideOffset:6,children:"New File"})]}),t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx("span",{className:"inline-flex flex-shrink-0",children:t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>$r("createFolder",{path:P,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:"New Folder","aria-label":"New Folder",children:t.jsx(v,{name:"folder-add",className:"size-4"})})})}),t.jsx(Ze,{side:"bottom",sideOffset:6,children:"New Folder"})]}),t.jsxs(Ye,{children:[t.jsx(Xe,{asChild:!0,children:t.jsx("span",{className:"inline-flex flex-shrink-0",children:t.jsx(S,{variant:"ghost",size:"sm",onClick:()=>{ar()},className:"size-8 p-0 flex-shrink-0",title:"Refresh","aria-label":"Refresh",children:t.jsx(v,{name:"refresh",className:"size-4"})})})}),t.jsx(Ze,{side:"bottom",sideOffset:6,children:"Refresh"})]})]})}),t.jsx(an,{outerClassName:"flex-1 min-h-0",className:$("py-2",g?"px-3":"px-2"),children:t.jsx("ul",{className:"flex flex-col",children:Ca?t.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[t.jsx(v,{name:"loader-4",className:"size-4 animate-spin"}),"Searching..."]}):Fn.length>0?Fn.map(e=>{const s=l?.path===e.path;return t.jsx("li",{children:t.jsxs("button",{type:"button",onClick:()=>{ce(e)},className:$("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",s?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[ya(e.path,e.extension),t.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:e.path,children:e.relativePath??e.path})]})},e.path)}):Cs?t.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[t.jsx("span",{className:"text-[var(--status-error)]",children:Cs}),t.jsxs(S,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{ar()},children:[t.jsx(v,{name:"refresh",className:"size-3.5"}),"Refresh"]})]}):xo?is(o,0):t.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading..."})})})]}),vo=r==="full"&&w&&l&&t.jsx("div",{className:"absolute inset-0 z-50 flex flex-col bg-background",children:t.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[t.jsx("div",{className:"absolute right-4 top-4 z-30",children:Zr({exitFullscreenOnly:!0})}),t.jsx(an,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:ke||bs||ws?xe?t.jsx("div",{className:"p-4"}):t.jsxs("div",{className:"p-4 flex items-center gap-2 typography-ui text-muted-foreground",children:[t.jsx(v,{name:"loader-4",className:"size-4 animate-spin"}),"Loading…"]}):Be?t.jsx("div",{className:"p-4 typography-ui text-[color:var(--status-error)]",children:Be}):Z?t.jsx("div",{className:"flex h-full items-center justify-center p-4",children:t.jsx("img",{src:ys,alt:l.name,className:"max-w-full max-h-full object-contain rounded-md border border-border/30 bg-primary/10"},hs)}):ye?Ns(l):We?t.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[t.jsx("div",{className:"typography-ui-header text-foreground",children:"Cannot preview binary file"}),t.jsx("div",{className:"max-w-md typography-ui text-muted-foreground",children:"This file is binary and cannot be edited in PiChamber. Download it to open with another app."}),a.downloadFile?t.jsxs(S,{type:"button",variant:"outline",size:"sm",onClick:()=>{const e=a.downloadFile;!e||!l||e(l.path).catch(s=>{console.error("Download failed:",s),A.error("Operation failed")})},children:[t.jsx(v,{name:"download",className:"mr-2 size-4"}),"Save file"]}):null]}):it&&le()==="preview"?t.jsxs("div",{className:"h-full overflow-auto p-4",children:[D.length>500*1024&&t.jsx("div",{className:"mb-3 rounded-md border border-status-warning/20 bg-status-warning/10 px-3 py-2 text-sm text-status-warning",children:`This file is large (${Math.round(D.length/1024)}KB). Preview may be limited.`}),t.jsx(on,{fallback:t.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[t.jsx("div",{className:"mb-1 font-medium text-destructive",children:"Preview unavailable"}),t.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to edit mode to fix the issue."})]}),children:t.jsx(Os,{content:D,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):Hr&&ie==="view"?ks(l,W):t.jsxs("div",{className:$("relative h-full",Ct&&"overflow-hidden"),children:[t.jsx("div",{className:$("h-full",Ct&&"invisible"),children:t.jsx(ra,{value:W,onChange:X,readOnly:!je,vimMode:Wn==="vim",extensions:fs,className:"h-full",onViewReady:e=>{Se.current=e,window.requestAnimationFrame(()=>{Ft(e)})},onViewDestroy:()=>{Se.current&&(Se.current=null)}})}),Ct&&t.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-background",children:t.jsxs("div",{className:"flex items-center gap-2 typography-ui text-muted-foreground",children:[t.jsx(v,{name:"loader-4",className:"size-4 animate-spin"}),"Opening file at change..."]})})]})})]})});return t.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden bg-background relative",children:[t.jsx(ic,{activeDialog:st,dialogData:at,dialogInputValue:Ke,onDialogInputChange:zn,isDialogSubmitting:La,onDialogSubmit:Ya,onClose:ho,inputRef:Ea}),vo,g?dt?Qr:Ss:r==="editor-only"?t.jsx("div",{className:"flex flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden bg-background",children:Qr})}):t.jsxs("div",{className:"flex flex-1 min-h-0 min-w-0 gap-3 px-3 pb-3 pt-2",children:[E>=700&&t.jsx("div",{className:"w-72 flex-shrink-0 min-h-0 overflow-hidden",children:Ss}),t.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:Qr})]})]})};export{yu as FilesView};