@pi-chamber/web 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/bin/cli.js +5 -2
  2. package/bin/cli.test.js +44 -0
  3. package/bin/lib/DOCUMENTATION.md +5 -5
  4. package/bin/lib/cli-args.js +19 -4
  5. package/bin/lib/commands-lifecycle.js +14 -0
  6. package/bin/lib/commands-logs.js +2 -1
  7. package/bin/lib/commands-serve.js +166 -2
  8. package/bin/lib/commands-tunnel.js +21 -0
  9. package/bin/lib/commands-update.js +97 -33
  10. package/bin/lib/commands-update.test.js +96 -1
  11. package/dist/assets/{DiagramEditor-D_3eJVSw.js → DiagramEditor-CcbnMl1H.js} +1 -1
  12. package/dist/assets/{DiagramView-pGYm0-DR.js → DiagramView-DTW5jwK3.js} +1 -1
  13. package/dist/assets/DiffView-CZyHHAOB.js +18 -0
  14. package/dist/assets/FilesView-BJYLFR3H.js +6 -0
  15. package/dist/assets/GitView-Cg_5UU7E.js +8 -0
  16. package/dist/assets/{JsonTreeView-CpgqCk9_.js → JsonTreeView-GTdKGEdy.js} +1 -1
  17. package/dist/assets/{MarkdownRendererImpl-fI6n3kqT.js → MarkdownRendererImpl-WqBwxlso.js} +1 -1
  18. package/dist/assets/{PatchDiff-BRloGXPs.js → PatchDiff-BRi23N1l.js} +1 -1
  19. package/dist/assets/{SessionSwitcherContent-BQc-vW4s.js → SessionSwitcherContent-7VAU5pwZ.js} +1 -1
  20. package/dist/assets/{SessionSwitcherDropdown-v_8TaIZm.js → SessionSwitcherDropdown-BslRtccE.js} +2 -2
  21. package/dist/assets/{SessionUnreadDot-A7vSfll2.js → SessionUnreadDot-1nV0Z2ZA.js} +1 -1
  22. package/dist/assets/SettingsView-UIaAyjTo.js +2 -0
  23. package/dist/assets/{SettingsWindow-D7UDhYd4.js → SettingsWindow-D4jZHl8X.js} +1 -1
  24. package/dist/assets/{ToolOutputDialog-wpU0ylYS.js → ToolOutputDialog-BoeJONiR.js} +1 -1
  25. package/dist/assets/{ToolPartDiffPreview-BvoQK5Gm.js → ToolPartDiffPreview-9FLv2fWD.js} +1 -1
  26. package/dist/assets/{VirtualizedFileDiff-DdPbLdh7.js → VirtualizedFileDiff-ywmPBXAG.js} +4 -4
  27. package/dist/assets/{collapsible-BO6FIjvn.js → collapsible-6mCYf7Ky.js} +1 -1
  28. package/dist/assets/{computeVirtualFileMetrics-DMvXzUJh.js → computeVirtualFileMetrics-3H6mg13G.js} +1 -1
  29. package/dist/assets/{contextFileOpenGuard-BwXQVjtS.js → contextFileOpenGuard-CKyf-TZ7.js} +1 -1
  30. package/dist/assets/gitStatusPredicates-UsytDMy_.js +134 -0
  31. package/dist/assets/index-C8NYcA8-.css +1 -0
  32. package/dist/assets/{index-C3SyF-cA.js → index-D1IaU-Q7.js} +1 -1
  33. package/dist/assets/index-yWgKW2Fx.js +8 -0
  34. package/dist/assets/{isDiffPlainText-BboRbmcm.js → isDiffPlainText-DPCilEx_.js} +1 -1
  35. package/dist/assets/{isFilePlainText-BpTnLRyI.js → isFilePlainText-XdCAgm8R.js} +1 -1
  36. package/dist/assets/main-DcAMXRSi.js +135 -0
  37. package/dist/assets/{main-xLwCWLu-.js → main-DhvLreEl.js} +2 -2
  38. package/dist/assets/{markdownCore-CmFv4H-w.js → markdownCore-BF0Dqwm4.js} +1 -1
  39. package/dist/assets/{miniChat-Vwo4K1IK.js → miniChat-DsCx0dsW.js} +2 -2
  40. package/dist/assets/{mobile-BRaxtEoC.js → mobile-C-IN49xX.js} +2 -2
  41. package/dist/assets/{renderElectronMiniChatApp-DM4rRUUz.js → renderElectronMiniChatApp-C13HXGZL.js} +2 -2
  42. package/dist/assets/renderMobileApp-xCdVzvyf.js +11 -0
  43. package/dist/assets/runtimeEndpointReset-CT3WShpj.js +54 -0
  44. package/dist/assets/{runtimeSurface-SmPSdfop.js → runtimeSurface-C_3mcJ01.js} +1 -1
  45. package/dist/assets/{useAppFontEffects-Bg-8jtrQ.js → useAppFontEffects-BgK55NDM.js} +105 -105
  46. package/dist/assets/{useFilesViewSearch-GLcYNIUV.js → useFilesViewSearch-CWx24PZg.js} +1 -1
  47. package/dist/assets/{usePushVisibilityBeacon-VSYBfNoY.js → usePushVisibilityBeacon-swMQLm-i.js} +1 -1
  48. package/dist/assets/{useSwitcherItems-BkEt9K-N.js → useSwitcherItems-CrS-F6DY.js} +1 -1
  49. package/dist/assets/{vendor-codemirror-language-data-B5cJDWBR.js → vendor-codemirror-language-data-BzeePAPn.js} +2 -2
  50. package/dist/assets/{vendor-dnd-kit-core-CP8ck10N.js → vendor-dnd-kit-core-C9qcAm_1.js} +1 -1
  51. package/dist/assets/{vendor-dnd-kit-sortable-B-Icjoj4.js → vendor-dnd-kit-sortable-D8ozj8M-.js} +1 -1
  52. package/dist/assets/vendor-xterm-addon-fit-DX4qG4td.js +1 -0
  53. package/dist/assets/vendor-xterm-xterm-CrXqRur4.js +16 -0
  54. package/dist/assets/vendor-xterm-xterm-DDGTF8rc.css +1 -0
  55. package/dist/assets/{web-components-0H9kvZwn.js → web-components-DAkBDXRk.js} +3 -3
  56. package/dist/index.html +4 -4
  57. package/dist/mini-chat.html +3 -3
  58. package/dist/mobile.html +3 -3
  59. package/package.json +1 -2
  60. package/server/lib/pi/routes.test.js +39 -0
  61. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
  62. package/server/lib/pi/session-daemon/extension-bridge.js +14 -11
  63. package/server/lib/pi/session-daemon/prompt-operations.test.js +73 -6
  64. package/server/lib/pi/session-daemon/session-daemon.js +163 -21
  65. package/server/lib/relay/host-client.test.js +3 -1
  66. package/server/lib/stt/DOCUMENTATION.md +1 -1
  67. package/server/lib/terminal/DOCUMENTATION.md +2 -2
  68. package/server/lib/ui-auth/DOCUMENTATION.md +1 -1
  69. package/server/lib/ui-auth/ui-auth.js +23 -26
  70. package/server/lib/ui-auth/ui-auth.test.js +27 -0
  71. package/dist/assets/DiffView-BApPTLGp.js +0 -18
  72. package/dist/assets/FilesView-CiPpuGiF.js +0 -6
  73. package/dist/assets/GitView-uW3w_LlQ.js +0 -8
  74. package/dist/assets/SettingsView-CphlZvfd.js +0 -2
  75. package/dist/assets/gitStatusPredicates-CgNk6M2_.js +0 -134
  76. package/dist/assets/index-BebQicw3.css +0 -1
  77. package/dist/assets/index-Bkz23mZq.js +0 -8
  78. package/dist/assets/main-CMOAwZnJ.js +0 -135
  79. package/dist/assets/renderMobileApp-DWWewNhc.js +0 -11
  80. package/dist/assets/runtimeEndpointReset-BF60eHSx.js +0 -54
  81. package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
@@ -1,18 +0,0 @@
1
- import{R as i,j as e}from"./vendor-react-B5Z1Mdn3.js";import{c as J,u as Q,w as Qe,n as Be}from"./index-Bkz23mZq.js";import{b3 as Ft,D as Nt,a as vt,I as U,b as Ct,b4 as Lt,b5 as Ne,a$ as Dt,aa as kt,ao as Ye,b6 as Je,aP as Rt,p as ve,U as Ce,j as Ze,Q as ne,t as et,aS as tt,aA as Et,b7 as At,b8 as Tt,aB as Mt,b9 as It,ba as $t,bb as Pt,bc as _t,k as Bt,bd as Wt,be as Ot,E as zt,F as Gt,G as Ht}from"./useAppFontEffects-Bg-8jtrQ.js";import{d as nt,P as Ut,i as We,a as Oe,b as Vt}from"./gitStatusPredicates-CgNk6M2_.js";import{p as Kt}from"./VirtualizedFileDiff-DdPbLdh7.js";import{v as qt,g as Xt}from"./contextFileOpenGuard-BwXQVjtS.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-GVb4H8HE.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-base-ui-vkqQ2P9o.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-BZOGXAGe.js";import"./vendor-floating-ui-dom-WyXykhNi.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-D0AXkdQC.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-sonner-BDtm25td.js";import"./vendor-codemirror-view-Ct4T37Ue.js";import"./vendor-codemirror-state-CNWM3Q8V.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./runtimeSurface-SmPSdfop.js";import"./vendor-dnd-kit-core-CP8ck10N.js";import"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-dnd-kit-sortable-B-Icjoj4.js";import"./vendor-cmdk-zXx6sGnS.js";import"./vendor-radix-ui-react-dialog-D2yhEu2p.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-8xy6TJML.js";import"./vendor-radix-ui-react-context-CFsX-AUC.js";import"./vendor-radix-ui-react-id-D2kS9K1j.js";import"./vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js";import"./vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js";import"./vendor-radix-ui-react-dismissable-layer-DrorBNg9.js";import"./vendor-radix-ui-react-primitive-DkH8dMOR.js";import"./vendor-radix-ui-react-slot-BIDFZX0-.js";import"./vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js";import"./vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js";import"./vendor-radix-ui-react-focus-scope-D2BkImwt.js";import"./vendor-radix-ui-react-portal-YgCRIyi7.js";import"./vendor-radix-ui-react-presence-D432pCMB.js";import"./vendor-radix-ui-react-focus-guards-BfdFmL7c.js";import"./vendor-react-remove-scroll-vR1dy1aP.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-CSAHp1YF.js";import"./vendor-react-style-singleton-Ctw6HnYx.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-Vv4V8Nd1.js";import"./vendor-use-callback-ref-CVVuCyLj.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BByA_dGF.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-DuOEwJ3f.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-wd6iRebq.js";import"./vendor-codemirror-lang-json-CZ07HmNC.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-djiuoTi8.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-CKHqhW5R.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-DtcZDGqe.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-B5cJDWBR.js";import"./vendor-codemirror-lang-python-DzzokVau.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-DYppkHEk.js";import"./vendor-tanstack-react-virtual-2skouoFw.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-CfplGuM0.js";import"./vendor-motion-dom-DhJ-sYS5.js";import"./vendor-motion-utils-CKEGc_YG.js";import"./web-components-0H9kvZwn.js";import"./computeVirtualFileMetrics-DMvXzUJh.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-yJ9XpNMI.js";import"./vendor-pierre-theming-Dgp7B_O4.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"./runtimeEndpointReset-BF60eHSx.js";import"./SessionUnreadDot-A7vSfll2.js";import"./permissionStore-iKN1K2_x.js";import"./appThemeRegistry-gegrE2dq.js";import"./registerCustomTheme-DmolaWWZ.js";import"./isDiffPlainText-BboRbmcm.js";import"./vendor-diff-C3JhlQdm.js";function Qt(s,n=10){const t=[];let r;for(const l of s.split(`
2
- `)){const p=l.match(Ft);if(p!=null){r!=null&&(r.hunkLines.length>0&&(De(r,n,"trailing"),Ae(r,t)),r=void 0);const d=parseInt(p[3]),x=parseInt(p[1]),h=parseInt(p[4]??"1"),c=parseInt(p[2]??"1");isNaN(d)||isNaN(x)||isNaN(h)||isNaN(c)?t.push(l):r={additionStart:d,deletionStart:x,additionCount:0,deletionCount:0,hunkLines:[],contextLines:[]};continue}if(r==null){t.push(l);continue}if(l.startsWith(" "))r.contextLines.push(l);else if(l!==""){if(r.hunkLines.length>0&&r.contextLines.length>n*2){const d=r.contextLines.length-n*2,x=r.contextLines.slice(-n);De(r,n,"trailing");const{additionCount:h,deletionCount:c}=r;Ae(r,t),r={additionStart:r.additionStart+h+d,deletionStart:r.deletionStart+c+d,deletionCount:0,additionCount:0,contextLines:x,hunkLines:[]}}De(r,n,r.hunkLines.length===0?"leading":"before-change"),r.hunkLines.push(l),l.startsWith("+")?r.additionCount+=1:l.startsWith("-")&&(r.deletionCount+=1)}}r!=null&&r.hunkLines.length>0&&(De(r,n,"trailing"),Ae(r,t));const a=t.join(`
3
- `);return s.endsWith(`
4
- `)?`${a}
5
- `:a}function De(s,n,t){if(t==="leading"&&s.contextLines.length>n){const r=s.contextLines.length-n;s.contextLines.splice(0,r),s.additionStart+=r,s.deletionStart+=r}return t==="trailing"&&s.contextLines.length>n&&(s.contextLines.length=n),s.contextLines.length>0&&(s.hunkLines.push(...s.contextLines),s.additionCount+=s.contextLines.length,s.deletionCount+=s.contextLines.length,s.contextLines.length=0),s}function Ae(s,n){n.push(`@@ -${ze(s.deletionStart,s.deletionCount)} +${ze(s.additionStart,s.additionCount)} @@`),n.push(...s.hunkLines)}function ze(s,n){return n===1?`${s}`:`${s},${n}`}const Yt=i.memo(function({scope:n,isGitRepo:t,branchAvailable:r,allCount:a,workingCount:l,stagedCount:p,turnCount:d,branchCount:x,onScopeChange:h}){const[c,f]=i.useState(!1),b=n==="all"?a:n==="staged"?p:n==="turn"?d:n==="branch"?x:l,L=n==="staged"?"Staged":n==="turn"?"Last turn":n==="branch"?"Branch":n==="all"?"All":"Changed";return e.jsxs(Nt,{open:c,onOpenChange:f,children:[e.jsx(vt,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex h-7 flex-shrink-0 items-center gap-1.5 rounded-md px-2 typography-ui-label font-semibold text-foreground outline-none hover:bg-interactive-hover focus-visible:ring-2 focus-visible:ring-ring","aria-label":"Select change mode",children:[e.jsxs("span",{className:"whitespace-nowrap",children:[L,e.jsxs("span",{className:"diff-toolbar__scope-count",children:[": ",b]})]}),e.jsx(U,{name:"arrow-down-s",className:"size-4 flex-shrink-0 opacity-60"})]})}),e.jsx(Ct,{align:"start",className:"w-40",children:e.jsxs(Lt,{value:n,onValueChange:u=>{(u==="all"||u==="working"||u==="staged"||u==="turn"||u==="branch")&&(h?.(u),f(!1))},children:[t!==!1?e.jsx(Ne,{value:"all",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[e.jsx("span",{children:"All"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:a})]})}):null,t!==!1?e.jsx(Ne,{value:"working",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[e.jsx("span",{children:"Changed"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:l})]})}):null,t!==!1?e.jsx(Ne,{value:"staged",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[e.jsx("span",{children:"Staged"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:p})]})}):null,e.jsx(Ne,{value:"turn",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[e.jsx("span",{children:"Last turn"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:d})]})}),r?e.jsx(Ne,{value:"branch",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[e.jsx("span",{children:"Branch"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:x})]})}):null]})})]})}),Jt=64,Zt=3,ae=new Map,en=(s,n,t=Zt)=>{const r=`${s}\0${t}\0${n}`,a=ae.get(r);if(a)return ae.delete(r),ae.set(r,a),a;const l=nn(n),p=l?Dt(Qt(n,t),{oldFile:{name:s,contents:l.before},newFile:{name:s,contents:l.after}})??He(s):kt(tn(s,n))[0]?.files[0]??He(s);for(ae.set(r,p);ae.size>Jt;){const d=ae.keys().next().value;if(!d)break;ae.delete(d)}return p},tn=(s,n)=>!n.trim()||n.startsWith("diff --git ")||/^--- [^\n]*\r?\n\+\+\+ /m.test(n)?n:`Index: ${s}
6
- ===================================================================
7
- --- ${s}
8
- +++ ${s}
9
- ${n}`,nn=s=>{if(!s.startsWith("diff --git ")&&!/^--- [^\n]*\t?\r?\n\+\+\+ [^\n]*\t?(?:\r?\n|$)/m.test(s))return;const n=[...s.matchAll(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@[^\n]*(?:\r?\n|$)/gm)];if(n.length!==1)return;const t=n[0],r=Number.parseInt(t[1]??"",10),a=Number.parseInt(t[2]??"",10);if(r>1||a>1||!Number.isFinite(r)||!Number.isFinite(a))return;const l=(t.index??0)+t[0].length,p=s.slice(l),d=[],x=[];let h;for(const c of p.split(/\r?\n/)){if(c.startsWith("diff --git ")||c.startsWith("@@ "))break;if(c.startsWith("\\")){if(h==="-"||h===" "){const f=d.at(-1);f&&(f.newline=!1)}if(h==="+"||h===" "){const f=x.at(-1);f&&(f.newline=!1)}continue}if(c.startsWith("-")){d.push({text:c.slice(1),newline:!0}),h="-";continue}if(c.startsWith("+")){x.push({text:c.slice(1),newline:!0}),h="+";continue}c.startsWith(" ")&&(d.push({text:c.slice(1),newline:!0}),x.push({text:c.slice(1),newline:!0}),h=" ")}return{before:Ge(d),after:Ge(x)}},Ge=s=>s.map(n=>n.text+(n.newline?`
10
- `:"")).join(""),He=s=>Kt({name:s,contents:""},{name:s,contents:""}),sn=s=>/^Binary files .+ differ$/m.test(s)||/^GIT binary patch$/m.test(s),Me=(s,n,t)=>sn(n)?{original:"",modified:"",isBinary:!0,patch:n,contextMode:t}:{original:"",modified:"",patch:n,fileDiff:en(s,n),contextMode:t},st=(s,n,t)=>{const r=s??0,a=n??0;return!r&&!a?null:e.jsxs("span",{className:J("typography-meta flex items-center gap-1 text-xs whitespace-nowrap","flex-shrink-0",t?.className),children:[r?e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",r]}):null,a?e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",a]}):null]})},rn=i.memo(function({changedFiles:n,selectedFile:t,onSelectFile:r}){return n.length===0?null:e.jsx(Ye,{outerClassName:"flex-1 min-h-0",className:"px-2 py-2",children:e.jsx("ul",{className:"flex flex-col gap-1",children:n.map(a=>{const l=nt(a),p=t===a.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>r(a.path),className:J("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",p?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[e.jsx(Je,{filePath:a.path,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:l.color},title:l.description,"aria-label":l.description,children:l.code}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:a.path,children:a.path}),st(a.insertions,a.deletions)]})},a.path)})})})}),on=i.memo(function(){return e.jsx("div",{className:"rounded-lg border border-border/60 bg-background px-3 py-2",children:e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Content of this file cannot be viewed."})})}),an=i.memo(function({filePath:n,diff:t,renderSideBySide:r}){const a=t.original.length>0,l=t.modified.length>0,p=r?"flex flex-row gap-6 items-start justify-center":"flex flex-col gap-4 items-center",d=r?"flex flex-col items-center gap-2 flex-1 min-w-0":"flex flex-col items-center gap-2";return e.jsx("div",{className:"w-full overflow-auto p-4",style:{contain:"layout"},children:e.jsxs("div",{className:p,children:[a&&e.jsxs("div",{className:d,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:t.original,alt:`Original: ${n}`,className:r?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),l&&e.jsxs("div",{className:d,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:a?"Modified":"New"}),e.jsx("img",{src:t.modified,alt:`Modified: ${n}`,className:r?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),ln=i.memo(function({filePath:n,diff:t,renderSideBySide:r,wrapLines:a}){const l=i.useMemo(()=>Rt(n)||"text",[n]);return t.isBinary?e.jsx(on,{}):ve(n)?e.jsx(an,{filePath:n,diff:t,renderSideBySide:r}):e.jsx("div",{className:"w-full",style:{contain:"layout"},children:e.jsx(Ut,{original:t.original,modified:t.modified,fileDiff:t.fileDiff,language:l,fileName:n,renderSideBySide:r,wrapLines:a,layout:"inline"})})}),Te=({label:s,icon:n,loading:t,disabled:r,tone:a,onClick:l})=>e.jsx(Ce,{variant:"ghost",size:"sm",className:J("h-6 w-6 rounded-none bg-transparent p-0 text-muted-foreground opacity-70 hover:bg-transparent hover:text-foreground hover:opacity-100",a==="failure"&&"text-[var(--status-error)] hover:text-[var(--status-error)]",a==="success"&&"text-[var(--status-success)] hover:text-[var(--status-success)]"),disabled:r,title:s,"aria-label":s,onClick:p=>{p.stopPropagation(),l()},children:t?e.jsx(U,{name:"loader-4",className:"size-3.5 animate-spin"}):e.jsx(U,{name:n,className:n==="add"?"size-4":"size-3.5"})}),cn=i.memo(function({filePath:n,staged:t,busyAction:r,disabled:a,onAction:l}){return e.jsx("div",{className:"flex items-center gap-0.5 rounded-full border border-[var(--interactive-border)]/45 bg-[var(--surface-background)]/95 px-1 py-0.5 shadow-sm backdrop-blur-md",children:t?e.jsx(Te,{label:`Unstage ${n}`,icon:"arrow-go-back",loading:r==="unstage",disabled:a,onClick:()=>l("unstage")}):e.jsxs(e.Fragment,{children:[e.jsx(Te,{label:`Revert changes in ${n}`,icon:"arrow-go-back",loading:r==="discard",disabled:a,tone:"failure",onClick:()=>l("discard")}),e.jsx(Te,{label:`Stage ${n}`,icon:"add",loading:r==="stage",disabled:a,tone:"success",onClick:()=>l("stage")})]})})}),rt=3,un=1e6,dn=15e3,Ue=500,fn=i.memo(function({directory:n,file:t,layout:r,wrapLines:a,isSelected:l,isExpanded:p,isMounted:d,onSelect:x,onExpandedChange:h,registerSectionRef:c,showOpenInEditorAction:f=!1,isOpeningInEditor:b=!1,onOpenInEditor:L,staged:u=!1,showFileActions:C=!0,loadFullFiles:g=!1,initialDiffData:R=null}){const{git:I}=Ze(),k=ne(i.useCallback(m=>m.directories.get(n)?.diffCache.get(t.path)??null,[n,t.path])),V=ne(m=>m.setDiff),E=ne(m=>m.fetchStatus),y=Q(m=>m.setDiffFileLayout),[w,j]=i.useState(0),[A,F]=i.useState(null),[q,N]=i.useState(!1),[_,B]=i.useState(null),[Z,se]=i.useState(!1),[P,le]=i.useState(null),[T,ee]=i.useState(null),W=i.useRef(null),ce=i.useRef(null),O=i.useMemo(()=>nt(t),[t]),re=r==="side-by-side",Y=g?"full":"patch",te=`${t.index}:${t.working_dir}:${t.insertions}:${t.deletions}`,z=i.useMemo(()=>R||(u?T:P||(k?{original:k.original,modified:k.modified,isBinary:k.isBinary,contextMode:"full"}:null)),[k,R,P,u,T]),ue=z?.contextMode===Y,ye=i.useCallback(m=>{ce.current=m,c(t.path,m)},[t.path,c]),de=i.useCallback(m=>{h(t.path,m)},[t.path,h]),fe=i.useCallback(()=>{x(t.path)},[t.path,x]);i.useEffect(()=>{u?ee(null):le(null),F(null),W.current=null},[te,u]),i.useEffect(()=>{if(!p||!d)return;if(!n||R||z&&ue){W.current=null,N(!1);return}const m=`${n}::${t.path}::${u?"staged":"unstaged"}::${te}::${Y}::${w}`;if(W.current===m)return;W.current=m,F(null),N(!0);let D=!1;const $=Qe(),je=g?un:rt,me=ve(t.path)?I.getGitFileDiff(n,{path:t.path,staged:u}):I.getGitDiff(n,{path:t.path,staged:u,contextLines:je}),ie=dn,ke=new Promise((K,G)=>{setTimeout(()=>G(new Error(`Timed out after ${ie}ms`)),ie)});return Promise.race([me,ke]).then(K=>{if(!D){if("diff"in K){const G=Me(t.path,K.diff,Y);u?ee(G):le(G)}else{const G={original:K.original??"",modified:K.modified??"",isBinary:K.isBinary,contextMode:"full"};u?ee(G):V(n,t.path,G,$)}N(!1)}}).catch(K=>{if(D)return;const G=K instanceof Error?K.message:String(K);F(G),N(!1)}),()=>{D=!0,W.current===m&&(W.current=null)}},[Y,z,ue,w,n,t.path,te,I,R,p,d,g,V,u]);const pe=i.useCallback(()=>{de(!p),fe()},[de,fe,p]),we=i.useCallback(async m=>{if(!(!n||_!==null)){B(m);try{m==="stage"?await I.stageGitFile(n,t.path):m==="unstage"?await I.unstageGitFile(n,t.path):await I.revertGitFile(n,t.path,{scope:"working"}),j(D=>D+1),await E(n,I)}catch(D){const $=m==="unstage"?"Failed to unstage changes":m==="stage"?"Failed to stage changes":"Failed to revert changes";et.error(D instanceof Error?D.message:$)}finally{B(D=>D===m?null:D)}}},[n,E,t.path,_,I]);return e.jsxs("div",{ref:ye,className:J("scroll-mt-9 border-b border-[var(--interactive-border)]/40 last:border-b-0"),children:[e.jsx("div",{className:J("z-30 border-b border-[var(--interactive-border)]/35 bg-[var(--surface-elevated)]/90 backdrop-blur-md supports-[backdrop-filter]:bg-[var(--surface-elevated)]/80","sticky top-0"),children:e.jsxs("div",{role:"button",tabIndex:0,onClick:pe,onKeyDown:m=>{m.target===m.currentTarget&&(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),pe())},className:J("cursor-pointer","group/header relative grid min-h-9 w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 overflow-hidden px-3 py-2","bg-transparent","text-muted-foreground hover:text-foreground",l?"bg-[var(--interactive-selection)]/35":null),children:[e.jsx("div",{className:"absolute inset-0 pointer-events-none group-hover/header:bg-[var(--interactive-hover)]/50"}),e.jsxs("div",{className:"relative flex min-w-0 flex-1 items-center gap-2",children:[e.jsx("span",{className:"flex size-5 items-center justify-center opacity-70 group-hover/header:opacity-100",children:p?e.jsx(U,{name:"arrow-down-s",className:"size-4"}):e.jsx(U,{name:"arrow-right-s",className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold leading-none w-4 text-center uppercase",style:{color:O.color},title:O.description,"aria-label":O.description,children:O.code}),e.jsx("span",{className:"min-w-0 flex-1 overflow-hidden typography-ui-label",title:t.path,children:e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(Je,{filePath:t.path,className:"h-3.5 w-3.5 flex-shrink-0 align-middle"}),(()=>{const m=t.path.lastIndexOf("/");if(m===-1)return e.jsx("span",{className:"block min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:t.path});const D=t.path.slice(0,m),$=t.path.slice(m+1);return e.jsxs("span",{className:"flex min-w-0 items-baseline overflow-hidden",children:[e.jsx("span",{className:"min-w-0 truncate typography-ui-label text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:D}),e.jsxs("span",{className:"flex-shrink-0 typography-ui-label",children:[e.jsx("span",{className:"text-muted-foreground",children:"/"}),e.jsx("span",{className:"text-foreground",children:$})]})]})})()]})})]}),e.jsxs("div",{className:"relative flex shrink-0 items-center justify-self-end gap-2",children:[st(t.insertions,t.deletions),f&&L?e.jsx(Ce,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-70 hover:opacity-100",title:"Open this file in editor at change",onClick:m=>{m.stopPropagation(),L(t.path,z)},disabled:b,children:b?e.jsx(U,{name:"loader-4",className:"size-3.5 animate-spin"}):e.jsx(U,{name:"edit",className:"size-3.5"})}):null,e.jsx(tt,{mode:re?"side-by-side":"unified",onModeChange:m=>{const D=m==="side-by-side"?"side-by-side":"inline";y(t.path,D)},className:"opacity-70"})]})]})}),p&&e.jsxs("div",{className:"relative overflow-hidden bg-background",children:[!d&&!A?e.jsx("div",{className:"h-40 border border-border/40 bg-background/40"}):null,A?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),e.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:A}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>j(m=>m+1),children:"Retry"})]}):null,d&&q&&!z&&!A?e.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx(U,{name:"loader-4",className:"size-4 animate-spin"}),"Loading diff..."]}):null,d&&z&&!Z&&t.insertions+t.deletions>Ue?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:`Large diff (${t.insertions+t.deletions} changed lines)`}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Rendering may be slow. You can still view the diff by clicking below."}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>se(!0),children:"Render anyway"})]}):null,d&&z&&(Z||t.insertions+t.deletions<=Ue)?e.jsxs(e.Fragment,{children:[e.jsx(ln,{filePath:t.path,diff:z,renderSideBySide:re,wrapLines:a}),C?e.jsx("div",{className:"pointer-events-none absolute bottom-3 right-3 z-20",children:e.jsx("div",{className:"pointer-events-auto",children:e.jsx(cn,{filePath:t.path,staged:u,busyAction:_,disabled:_!==null,onAction:we})})}):null]}):null]})]})}),pn=1100,Ve=300,mn=s=>s<=6?s:s<=12?6:s<=25?4:2,hn=(s,n)=>Et(s,n),Ke=(s,n)=>{const t=s.split(`
11
- `),r=n.split(`
12
- `),a=Math.min(t.length,r.length);for(let l=0;l<a;l+=1)if(t[l]!==r[l])return l+1;return r.length>t.length?t.length+1:t.length>r.length?Math.max(1,r.length):1},gn=s=>Array.isArray(s)?s.filter(n=>!n||typeof n!="object"?!1:typeof n.file=="string"):[],xn=s=>s.split(/^diff --git /m).slice(1).flatMap(t=>{const[r=""]=t.split(`
13
- `,1),a=r.lastIndexOf(" b/");if(a<=2)return[];const l=r.slice(2,a),p=r.slice(a+3).trim(),d=`diff --git ${t}`,x=d.includes(`
14
- new file mode `)?"added":d.includes(`
15
- deleted file mode `)?"deleted":d.includes(`
16
- rename from `)?"renamed":"modified";let h=0,c=0;for(const f of d.split(`
17
- `))f.startsWith("+")&&!f.startsWith("+++")&&(h+=1),f.startsWith("-")&&!f.startsWith("---")&&(c+=1);return[{file:x==="deleted"?l:p,status:x,additions:h,deletions:c,patch:d}]}),bn=s=>s==="added"?"A":s==="deleted"?"D":"M";function yn({activeDiffScope:s,effectiveDirectory:n,branchBase:t,branchHead:r,git:a,sessionMessageRecords:l}){const[p,d]=i.useState([]),[x,h]=i.useState(null),[c,f]=i.useState(!1),b=i.useMemo(()=>{const C=At(l,{showTextJustificationActivity:!1,showTurnChangedFiles:!0,mergeHiddenUserTurns:!0});for(let g=C.turns.length-1;g>=0;g-=1){const R=C.turns[g];if(!R)continue;const I=R.activityParts.map(E=>E.part).filter(E=>E.type==="tool"),k=Tt(I);if(k.length>0)return k.map(E=>({file:E.path,status:"modified",additions:E.additions,deletions:E.deletions,patch:E.patch}));const V=gn(R.userMessage.info?.summary?.diffs);if(V.length>0)return V}return[]},[l]);i.useEffect(()=>{if(s!=="branch"||!n||!t||!r||!a.getGitRangeDiff){d([]),h(null),f(!1);return}let C=!1;return f(!0),h(null),a.getGitRangeDiff(n,{base:t,head:r,contextLines:rt}).then(g=>{C||(d(xn(g.diff??"")),f(!1))}).catch(g=>{C||(d([]),f(!1),h(g instanceof Error?g.message:String(g)))}),()=>{C=!0}},[s,t,r,n,a]);const L=i.useMemo(()=>{const C=new Map;for(const g of b)if(g.file){if(typeof g.patch=="string"){C.set(g.file,Me(g.file,g.patch,"patch"));continue}C.set(g.file,{original:g.before??"",modified:g.after??"",contextMode:"full"})}return C},[b]),u=i.useMemo(()=>{const C=new Map;for(const g of p)!g.file||typeof g.patch!="string"||C.set(g.file,Me(g.file,g.patch,"patch"));return C},[p]);return{branchDiffs:p,branchDiffError:x,branchDiffLoading:c,lastTurnDiffs:b,lastTurnDiffData:L,branchDiffData:u}}const qe=(s,n)=>{if(n.length===0)return null;let t=null,r=null;for(const l of n)l.top<=s?(!t||l.top>t.top)&&(t=l):(!r||l.top<r.top)&&(r=l);const a=t??r;return a?{path:a.path,topOffset:a.top-s}:null},wn=(s,n,t,r)=>Math.min(Math.max(0,r),Math.max(0,s+t-n));function jn({pinSelectedFileHeaderToTopOnNavigate:s,scrollRequestNonce:n,changedFiles:t,expandedFiles:r,setMountedStackedFiles:a,fileDiffRefreshNonce:l}){const p=i.useRef(null),d=i.useRef(new Map),[x,h]=i.useState(null),c=i.useRef(null),f=i.useRef(null),b=i.useRef(!1),L=i.useRef(null),u=i.useRef(null),C=i.useRef(null),g=i.useCallback(()=>{const y=p.current;if(!y)return null;const w=y.getBoundingClientRect().top,j=[];for(const[A,F]of d.current)F&&j.push({path:A,top:F.getBoundingClientRect().top});return qe(w,j)},[]),R=i.useCallback(()=>{c.current=null,b.current=!1,h(null),f.current!==null&&(window.cancelAnimationFrame(f.current),f.current=null)},[]),I=i.useCallback(()=>{L.current=null;const y=p.current;if(!y)return;const w=y.getBoundingClientRect(),j=w.top-Ve,A=w.bottom+Ve,F={},q=[];for(const[N,_]of d.current){if(!_)continue;const B=_.getBoundingClientRect();q.push({path:N,top:B.top}),r.has(N)&&(B.bottom<j||B.top>A||(F[N]=!0))}u.current=qe(w.top,q),a(N=>{let _=!1;const B=new Set(N);for(const Z of Object.keys(F))B.has(Z)||(B.add(Z),_=!0);return _?B:N})},[r,a]),k=i.useCallback(()=>{typeof window>"u"||L.current===null&&(L.current=window.requestAnimationFrame(I))},[I]);i.useEffect(()=>{const y=p.current;if(y)return k(),y.addEventListener("scroll",k,{passive:!0}),window.addEventListener("resize",k),()=>{y.removeEventListener("scroll",k),window.removeEventListener("resize",k),L.current!==null&&(window.cancelAnimationFrame(L.current),L.current=null)}},[t,r,k]),i.useLayoutEffect(()=>{const y=C.current;if(!y)return;C.current=null;const w=p.current,j=d.current.get(y.path);if(!w||!j)return;const A=w.getBoundingClientRect().top,F=j.getBoundingClientRect().top-A;w.scrollTop=wn(w.scrollTop,y.topOffset,F,w.scrollHeight-w.clientHeight),u.current=y},[l]);const V=i.useCallback((y,w)=>{const j=d.current;w?j.set(y,w):j.delete(y),k()},[k]),E=i.useCallback(y=>{const w=d.current.get(y),j=p.current;if(!w||!j)return!1;const A=w.getBoundingClientRect().top-j.getBoundingClientRect().top;return j.scrollTo({top:j.scrollTop+A,behavior:"auto"}),!0},[]);return i.useEffect(()=>{if(!c.current)return;let w=0;const j=20;let A=!1;const F=(N=!0)=>{A||(A=!0,c.current=null,b.current=!1,N&&h(null),f.current!==null&&(window.cancelAnimationFrame(f.current),f.current=null))},q=()=>{if(A){f.current=null;return}const N=c.current;if(!N){F(),f.current=null;return}if(!E(N)){w+=1,w<j?f.current=window.requestAnimationFrame(q):(F(),f.current=null);return}if(s&&b.current){h(N),F(!1);return}F()};return f.current=window.requestAnimationFrame(q),()=>{A=!0,f.current!==null&&(window.cancelAnimationFrame(f.current),f.current=null)}},[s,n,E]),{diffScrollRef:p,fileSectionRefs:d,pinnedStackedTarget:x,pendingScrollTargetRef:c,shouldPinAfterAlignRef:b,pendingScrollAnchorRestoreRef:C,lastScrollAnchorRef:u,captureScrollAnchor:g,cancelPendingScrollAlignment:R,queueVisibleStackedFilesSync:k,registerSectionRef:V,scrollToFile:E}}const Xe=s=>{if(!s)return null;const n=s.split(`
18
- `);let t=null;for(const r of n){const a=r.match(/^@@\s*-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s*@@/);if(a){const l=Number.parseInt(a[1]??"",10);t=Number.isFinite(l)&&l>=1?l:null;continue}if(t!==null){if(r.startsWith(" ")){t+=1;continue}if(r.startsWith("+"))return t;if(r.startsWith("-"))return Math.max(1,t)}}return null};function Sn({effectiveDirectory:s,activeDiffStaged:n,git:t,files:r,setDiff:a,openContextFileAtLine:l}){const[p,d]=i.useState(null),x=i.useCallback(async(h,c)=>{if(!s||!h)return;d(h);const f=Qe();try{let b=null;if(c?.patch&&!c.isBinary&&!ve(h)?b=Xe(c.patch):c&&c.contextMode==="full"&&!c.isBinary&&!ve(h)&&(b=Ke(c.original,c.modified)),b===null)try{const R=await t.getGitDiff(s,{path:h,staged:n,contextLines:3});b=Xe(R.diff)}catch{b=null}let L=c;if(b===null||!L){const R=await t.getGitFileDiff(s,{path:h,staged:n});L={original:R.original??"",modified:R.modified??"",isBinary:R.isBinary},n||a(s,h,L,f??void 0)}const u=b??(L.isBinary||ve(h)?1:Ke(L.original,L.modified)),C=hn(s,h),g=await qt(r,C,{directory:s});if(!g.ok){et.error(Xt(g.reason));return}l(s,C,u,1)}finally{d(b=>b===h?null:b)}},[n,s,r,t,l,a]);return{openingEditorFilePath:p,openFileInEditorAtChange:x}}function Fn(s){const{hideStackedFileSidebar:n=!1,stackedDefaultCollapsedAll:t=!1,pinSelectedFileHeaderToTopOnNavigate:r=!1,diffScope:a="all",branchBase:l=null,branchHead:p=null,targetFilePath:d=null}=s,{git:x,files:h}=Ze(),c=Mt(),{screenWidth:f,isMobile:b}=It(),L=$t(c??null),u=Pt(c??null),C=_t(c??null),g=ne(o=>o.setActiveDirectory),R=ne(o=>o.ensureStatus),I=ne(o=>o.fetchStatus),k=ne(o=>o.clearDiffCache),V=ne(o=>o.setDiff),[E,y]=i.useState(null),[w,j]=i.useState(!1),[A,F]=i.useState(()=>new Set),[q,N]=i.useState(()=>new Set),[_,B]=i.useState(!1),[Z,se]=i.useState(0),[P,le]=i.useState(()=>new Map),[T,ee]=i.useState(a);i.useEffect(()=>{ee(a)},[a]);const W=Q(o=>o.pendingDiffFile),ce=Q(o=>o.pendingDiffStaged),O=Q(o=>o.pendingDiffScope),re=Q(o=>o.setPendingDiffFile),Y=Q(o=>o.diffLayoutPreference),te=Q(o=>o.diffFileLayout),z=Q(o=>o.setDiffFileLayout),ue=Q(o=>o.diffWrapLines),ye=Q(o=>o.setDiffWrapLines),de=Q(o=>o.openContextFileAtLine),fe=Bt(o=>o.currentSessionId),pe=Wt(fe??""),we=ue,m=T==="staged"?!0:T==="working"?!1:null,D=m??w,$=b||f<=768,je=!n&&!$&&f>=1024,me=i.useRef(null),{branchDiffs:ie,branchDiffError:ke,branchDiffLoading:K,lastTurnDiffs:G,lastTurnDiffData:it,branchDiffData:ot}=yn({activeDiffScope:T,effectiveDirectory:c,branchBase:l,branchHead:p,git:x,sessionMessageRecords:pe}),H=i.useMemo(()=>{if(T==="turn"||T==="branch")return(T==="branch"?ie:G).map(M=>({path:M.file??"",index:"",working_dir:bn(M.status),insertions:M.additions??0,deletions:M.deletions??0,isNew:M.status==="added"})).filter(M=>M.path).sort((M,X)=>M.path.localeCompare(X.path));if(!u?.files)return[];const o=u.diffStats??{},v=T==="staged"?We:T==="working"?Oe:()=>!0;return u.files.filter(v).map(S=>({...S,insertions:o[S.path]?.insertions??0,deletions:o[S.path]?.deletions??0,isNew:Vt(S)})).sort((S,M)=>S.path.localeCompare(M.path))},[T,ie,G,u]),at=i.useMemo(()=>u?.files?u.files.filter(Oe).length:0,[u]),lt=i.useMemo(()=>u?.files?u.files.filter(We).length:0,[u]),ct=G.length,ut=u?.files?.length??0,dt=ie.length,{diffScrollRef:ft,pinnedStackedTarget:pt,pendingScrollTargetRef:he,shouldPinAfterAlignRef:ge,pendingScrollAnchorRestoreRef:Ie,lastScrollAnchorRef:$e,captureScrollAnchor:Pe,cancelPendingScrollAlignment:xe,queueVisibleStackedFilesSync:Le,registerSectionRef:mt,scrollToFile:_e}=jn({pinSelectedFileHeaderToTopOnNavigate:r,scrollRequestNonce:Z,changedFiles:H,expandedFiles:A,setMountedStackedFiles:N,fileDiffRefreshNonce:P}),be=i.useCallback(o=>{F(v=>{if(v.has(o))return v;const S=new Set(v);return S.add(o),S})},[]),Re=i.useMemo(()=>H.map(o=>o.path).join("\0"),[H]);i.useEffect(()=>{const o=Re?Re.split("\0"):[],v=new Set(o),S=`${c??""}:${T}:${t?"collapsed":"default"}`,M=me.current!==S;me.current=S,F(X=>{if(M){const oe=t?0:mn(o.length);return new Set(o.slice(0,oe))}let Se=!1;const Fe=new Set;for(const oe of X){if(!v.has(oe)){Se=!0;continue}Fe.add(oe)}return Se?Fe:X}),N(X=>{if(M)return new Set;let Se=!1;const Fe=new Set;for(const oe of X){if(!v.has(oe)){Se=!0;continue}Fe.add(oe)}return Se?Fe:X})},[T,Re,c,N,t]);const Ee=i.useCallback(o=>{const v=te[o.path];if(v)return v;if(Y==="inline")return"inline";if(Y==="side-by-side")return"side-by-side";const S=f<pn;return o.isNew||S?"inline":"side-by-side"},[te,Y,f]),ht=i.useMemo(()=>H.length===0?null:H.every(o=>Ee(o)==="side-by-side")?"side-by-side":"inline",[H,Ee]);i.useEffect(()=>{c&&(g(c),R(c,x))},[c,g,R,x]),i.useEffect(()=>{if(c)return Ot.onGitRefreshHint(o=>{Be(o.directory)===Be(c)&&(o.paths?.length&&(Ie.current=Pe()??$e.current,k(c,o.paths),le(v=>{const S=new Map(v);for(const M of o.paths??[])S.set(M,(S.get(M)??0)+1);return S})),I(c,x,{silent:!0}))})},[Pe,k,c,I,x,$e,Ie]),i.useEffect(()=>{T!=="all"&&!O||W&&(O&&ee(O),y(W),j(O==="staged"||!O&&ce),re(null),ge.current=!0,he.current=W,be(W),se(o=>o+1))},[T,be,W,O,ce,he,re,ge]),i.useEffect(()=>{if(T==="all")return;const o=d?.trim();o&&(y(o),j(T==="staged"),ge.current=!0,he.current=o,be(o),se(v=>v+1))},[T,be,he,ge,d]),i.useEffect(()=>{if(!E)return;H.some(v=>v.path===E)||(y(null),j(!1))},[H,E]);const gt=i.useCallback((o,v)=>{xe(),F(S=>{const M=S.has(o);if(v===M)return S;const X=new Set(S);return v?X.add(o):X.delete(o),X}),v||N(S=>{if(!S.has(o))return S;const M=new Set(S);return M.delete(o),M}),Le()},[xe,Le,N]),xt=i.useCallback(()=>{xe(),F(o=>o.size>0?new Set:new Set(H.map(v=>v.path))),N(new Set),Le()},[xe,H,Le,N]),bt=i.useCallback(o=>{},[]),yt=i.useCallback(o=>{xe(),y(o),j(!1),ge.current=!0,he.current=o,be(o),se(v=>v+1),_e(o)},[xe,be,he,_e,ge]),wt=i.useCallback(o=>{const v=o==="side-by-side"?"side-by-side":"inline";H.forEach(S=>{z(S.path,v)})},[H,z]),{openingEditorFilePath:jt,openFileInEditorAtChange:St}=Sn({effectiveDirectory:c,activeDiffStaged:D,git:x,files:h,setDiff:V,openContextFileAtLine:de});return{git:x,files:h,effectiveDirectory:c,screenWidth:f,isMobile:b,isGitRepo:L,status:u,isLoadingStatus:C,activeDiffScope:T,setActiveDiffScope:ee,branchDiffs:ie,branchDiffError:ke,branchDiffLoading:K,diffWrapLines:we,setDiffWrapLines:ye,forcedStaged:m,displayFileStaged:w,displayFile:E,pinnedStackedTarget:pt,expandedFiles:A,mountedStackedFiles:q,loadFullFiles:_,setLoadFullFiles:B,fileDiffRefreshNonce:P,showFileSidebar:je,diffScrollRef:ft,lastTurnDiffData:it,branchDiffData:ot,changedFiles:H,workingFileCount:at,stagedFileCount:lt,turnFileCount:ct,allFileCount:ut,branchFileCount:dt,currentLayoutForAllFiles:ht,openingEditorFilePath:jt,registerSectionRef:mt,handleStackedEntryExpandedChange:gt,handleExpandOrCollapseAll:xt,handleSelectFile:bt,handleSelectFileAndScroll:yt,handleHeaderLayoutChange:wt,openFileInEditorAtChange:St,getLayoutForFile:Ee}}const Er=({hideStackedFileSidebar:s=!1,stackedDefaultCollapsedAll:n=!1,pinSelectedFileHeaderToTopOnNavigate:t=!1,showOpenInEditorAction:r=!1,diffScope:a="all",onDiffScopeChange:l,branchBase:p=null,branchHead:d=null,targetFilePath:x=null,flushContent:h=!1})=>{const{effectiveDirectory:c,isGitRepo:f,status:b,isLoadingStatus:L,activeDiffScope:u,setActiveDiffScope:C,branchDiffError:g,branchDiffLoading:R,diffWrapLines:I,setDiffWrapLines:k,forcedStaged:V,displayFileStaged:E,displayFile:y,pinnedStackedTarget:w,expandedFiles:j,mountedStackedFiles:A,loadFullFiles:F,setLoadFullFiles:q,fileDiffRefreshNonce:N,showFileSidebar:_,diffScrollRef:B,lastTurnDiffData:Z,branchDiffData:se,changedFiles:P,workingFileCount:le,stagedFileCount:T,turnFileCount:ee,allFileCount:W,branchFileCount:ce,currentLayoutForAllFiles:O,openingEditorFilePath:re,registerSectionRef:Y,handleStackedEntryExpandedChange:te,handleExpandOrCollapseAll:z,handleSelectFile:ue,handleSelectFileAndScroll:ye,handleHeaderLayoutChange:de,openFileInEditorAtChange:fe,getLayoutForFile:pe}=Fn({hideStackedFileSidebar:s,stackedDefaultCollapsedAll:n,pinSelectedFileHeaderToTopOnNavigate:t,diffScope:a,branchBase:p,branchHead:d,targetFilePath:x}),we=()=>{if(!c)return null;const D=$=>V!==null?V:E&&$===y;return e.jsxs("div",{className:J("flex min-w-0 flex-1 min-h-0 h-full",h?"gap-0":"gap-3 px-3 pb-3 pt-2"),children:[_&&e.jsxs("section",{className:"hidden lg:flex w-72 flex-col rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/40",children:[e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Files"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:P.length})]}),e.jsx(rn,{changedFiles:P,selectedFile:null,onSelectFile:ye})]}),e.jsx("div",{className:"relative flex-1 min-w-0 min-h-0 h-full",children:e.jsx(Ye,{ref:B,outerClassName:"min-h-0 h-full",className:"[overflow-anchor:none] pb-16",disableHorizontal:!0,observeMutations:!1,preventOverscroll:!0,"data-diff-virtual-root":!0,children:e.jsx("div",{className:"flex flex-col [overflow-anchor:none]","data-diff-virtual-content":!0,children:P.map($=>e.jsx(fn,{directory:c,file:$,layout:pe($),wrapLines:I,isSelected:!1,isExpanded:j.has($.path),isMounted:A.has($.path)||$.path===w,onSelect:ue,onExpandedChange:te,registerSectionRef:Y,showOpenInEditorAction:r&&u!=="turn"&&u!=="branch",isOpeningInEditor:re===$.path,onOpenInEditor:(je,me)=>{fe(je,me)},staged:D($.path),showFileActions:u!=="turn"&&u!=="branch",loadFullFiles:F,initialDiffData:u==="turn"?Z.get($.path)??null:u==="branch"?se.get($.path)??null:null},`${$.path}:${N.get($.path)??0}`))})})})]})},m=()=>c?u!=="turn"&&L&&!b?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(U,{name:"loader-4",className:"size-4 animate-spin"}),"Loading repository status..."]}):u!=="turn"&&u!=="branch"&&f===!1?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Not a git repository. Use the Git tab to initialize or change directories."}):u==="branch"&&R?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(U,{name:"loader-4",className:"size-4 animate-spin"}),"Loading branch changes..."]}):u==="branch"&&g?e.jsx("div",{className:"flex flex-1 items-center justify-center px-4 text-center text-sm text-muted-foreground",children:`Failed to load branch changes: ${g}`}):P.length===0?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:u==="turn"?"No last turn changes to display":"Working tree clean, no changes to display"}):we():e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Select a session directory to view diffs"});return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"@container/diff-toolbar flex min-w-0 items-center gap-2 px-3 py-2 bg-background",children:[(f!==!1||u==="turn")&&(u==="all"||u==="working"||u==="staged"||u==="turn"||u==="branch")?e.jsx(Yt,{scope:u,isGitRepo:f,branchAvailable:!!(p&&d),allCount:W,workingCount:le,stagedCount:T,turnCount:ee,branchCount:ce,onScopeChange:D=>{C(D),l?.(D)}}):e.jsx("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:L&&!b?"Loading changes...":P.length===1?`${P.length} file changed`:`${P.length} files changed`})}),P.length>0&&e.jsxs(Ce,{variant:"ghost",size:"sm",onClick:z,className:J("diff-toolbar__expand-button h-7 flex-shrink-0 gap-1 px-1.5 text-muted-foreground hover:text-foreground","ml-auto"),title:j.size>0?"Collapse all":"Expand all",children:[e.jsx(U,{name:"expand-up-down",className:"size-4"}),e.jsx("span",{className:"diff-toolbar__expand-label typography-ui-label",children:j.size>0?"Collapse all":"Expand all"})]}),P.length>0&&u!=="turn"&&u!=="branch"&&e.jsxs(zt,{children:[e.jsx(Gt,{asChild:!0,children:e.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>q(D=>!D),"aria-pressed":F,"aria-label":F?"Unload full files":"Load full files",className:J("h-7 w-7 flex-shrink-0 p-0 text-muted-foreground hover:text-foreground",F&&"bg-interactive-selection text-interactive-selection-foreground"),children:e.jsx(U,{name:"file-download",className:"size-4"})})}),e.jsx(Ht,{children:e.jsx("p",{children:F?"Unload full files":"Load full files"})})]}),P.length>0&&e.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>k(!I),className:J("h-5 w-5 p-0 transition-opacity",I?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:I?"Disable line wrap":"Enable line wrap",children:e.jsx(U,{name:"text-wrap",className:"size-4"})}),O&&e.jsx(tt,{mode:O==="side-by-side"?"side-by-side":"unified",onModeChange:de})]}),m()]})};export{Er as DiffView};
@@ -1,6 +0,0 @@
1
- import{j as e,R as o,b as Ds,r as k}from"./vendor-react-B5Z1Mdn3.js";import{c as H,G as As,H as Os,I as Ps,J as Ls,K as Is,u as he,L as ke,M as Vs,N as lt,O as Bs,P as $s,Q as Ws,g as cn,R as _s,T as ln,r as un,m as qs,U as rr,V as Us,k as Hs}from"./index-Bkz23mZq.js";import{bf as Ks,I as j,bg as mt,bh as Gs,b6 as ut,aQ as _n,aR as qn,bi as Un,bj as Hn,bk as Kn,bl as Gn,U,D as hr,a as gr,b as xr,af as Lt,t as ie,bm as It,bn as Js,bo as pt,ao as Jn,$ as dn,aL as Ys,aP as Yn,p as Xn,bp as Qn,o as Zn,n as mr,q as Xs,E as Le,F as Ie,G as Ve,j as Qs,aN as Zs,b9 as eo,aB as to,bb as ro,bq as fn,br as mn,L as no,be as ao,bs as so,bt as oo,bu as pn}from"./useAppFontEffects-Bg-8jtrQ.js";import{E as ce,D as $t,V as ea,s as io,d as co,e as lo,f as hn,k as nr,W as uo}from"./vendor-codemirror-view-Ct4T37Ue.js";import{H as gn,x as At,y as fo,i as mo,z as po}from"./vendor-codemirror-language-BByA_dGF.js";import{a as c,c as ho}from"./vendor-lezer-highlight-CDMHUZ74.js";import{i as ta,S as go,k as br,E as xo,o as Ue,a as bo}from"./vendor-codemirror-state-CNWM3Q8V.js";import{ensurePierreThemeRegistered as xn,getResolvedShikiTheme as vo}from"./appThemeRegistry-gegrE2dq.js";import{D as wo}from"./DiagramEditor-D_3eJVSw.js";import{C as yo,a as ko,b as jo,c as No,d as Co,e as Ot}from"./runtimeEndpointReset-BF60eHSx.js";import{s as ra,b as pr,c as na}from"./SessionUnreadDot-A7vSfll2.js";import{g as Vt,i as aa,a as vr,b as Wt,n as So,d as Ro,M as dt,c as de,s as Fo,e as Eo,f as zo,h as Mo,t as Pt,j as ar,u as To,k as Do,l as Ao,m as bn,o as Oo,p as vn}from"./useFilesViewSearch-GLcYNIUV.js";import{J as Po,F as Lo}from"./JsonTreeView-CpgqCk9_.js";import{h as Io,j as Vo,k as Bo,l as $o}from"./vendor-codemirror-commands-DYppkHEk.js";import{a as wn,g as Bt,b as yn,c as kn,o as Wo,d as _o}from"./vendor-codemirror-search-BV44140v.js";import{v as qo,g as Uo}from"./vendor-replit-codemirror-vim-CGHHNQxC.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-GVb4H8HE.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-base-ui-vkqQ2P9o.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-BZOGXAGe.js";import"./vendor-floating-ui-dom-WyXykhNi.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-D0AXkdQC.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-sonner-BDtm25td.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./runtimeSurface-SmPSdfop.js";import"./vendor-dnd-kit-core-CP8ck10N.js";import"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-dnd-kit-sortable-B-Icjoj4.js";import"./vendor-cmdk-zXx6sGnS.js";import"./vendor-radix-ui-react-dialog-D2yhEu2p.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-8xy6TJML.js";import"./vendor-radix-ui-react-context-CFsX-AUC.js";import"./vendor-radix-ui-react-id-D2kS9K1j.js";import"./vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js";import"./vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js";import"./vendor-radix-ui-react-dismissable-layer-DrorBNg9.js";import"./vendor-radix-ui-react-primitive-DkH8dMOR.js";import"./vendor-radix-ui-react-slot-BIDFZX0-.js";import"./vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js";import"./vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js";import"./vendor-radix-ui-react-focus-scope-D2BkImwt.js";import"./vendor-radix-ui-react-portal-YgCRIyi7.js";import"./vendor-radix-ui-react-presence-D432pCMB.js";import"./vendor-radix-ui-react-focus-guards-BfdFmL7c.js";import"./vendor-react-remove-scroll-vR1dy1aP.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-CSAHp1YF.js";import"./vendor-react-style-singleton-Ctw6HnYx.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-Vv4V8Nd1.js";import"./vendor-use-callback-ref-CVVuCyLj.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-lang-javascript-DuOEwJ3f.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-codemirror-autocomplete-wd6iRebq.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-CZ07HmNC.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-djiuoTi8.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-CKHqhW5R.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-DtcZDGqe.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-B5cJDWBR.js";import"./vendor-codemirror-lang-python-DzzokVau.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-tanstack-react-virtual-2skouoFw.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-CfplGuM0.js";import"./vendor-motion-dom-DhJ-sYS5.js";import"./vendor-motion-utils-CKEGc_YG.js";import"./registerCustomTheme-DmolaWWZ.js";import"./themeResolver-yJ9XpNMI.js";import"./vendor-pierre-theming-Dgp7B_O4.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-react-drawio-BYDptOsj.js";import"./permissionStore-iKN1K2_x.js";import"./web-components-0H9kvZwn.js";import"./computeVirtualFileMetrics-DMvXzUJh.js";import"./vendor-shiki-Bbf2GEcE.js";import"./vendor-shikijs-engine-oniguruma-DPWuIF1G.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-BSHVMKgK.js";import"./isFilePlainText-BpTnLRyI.js";function jn(t,r){const n=t.metadata.variant==="dark",s=t.config?.fonts?.mono||"monospace",i=t.colors.syntax.highlights||{},u=t.colors.syntax.tokens||{},d=r?.fontSize?`${r.fontSize}px`:"var(--text-code)",p=ce.theme({"&":{backgroundColor:"var(--background)",color:t.colors.syntax.base.foreground,fontSize:d,lineHeight:"1.5",position:"relative"},".cm-scroller":{fontFamily:s,backgroundColor:"var(--background)"},".cm-comment":{color:t.colors.syntax.base.comment},".cm-keyword":{color:t.colors.syntax.base.keyword},".cm-string":{color:t.colors.syntax.base.string},".cm-string-2":{color:u.stringEscape||t.colors.syntax.base.string},".cm-number":{color:t.colors.syntax.base.number},".cm-operator":{color:t.colors.syntax.base.operator},".cm-punctuation":{color:u.punctuation||t.colors.syntax.base.comment},".cm-atom":{color:u.boolean||t.colors.syntax.base.number},".cm-builtin":{color:u.functionCall||t.colors.syntax.base.function},".cm-def":{color:u.variableGlobal||t.colors.syntax.base.variable},".cm-attribute":{color:u.variableOther||u.variableProperty||t.colors.syntax.base.operator},".cm-meta":{color:t.colors.syntax.base.comment},".cm-property":{color:u.variableProperty||t.colors.syntax.base.keyword},".cm-variable":{color:t.colors.syntax.base.variable},".cm-variable-2":{color:u.variableOther||t.colors.syntax.base.function},".cm-variable-3":{color:u.variableGlobal||t.colors.syntax.base.type},".cm-tag":{color:u.tag||t.colors.syntax.base.keyword},".cm-link":{color:u.url||t.colors.syntax.base.keyword,textDecoration:"underline"},".cm-content":{caretColor:t.colors.interactive.cursor},".cm-cursor, .cm-dropCursor":{borderLeftColor:t.colors.interactive.cursor},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:t.colors.interactive.selection},".cm-gutters":{backgroundColor:"var(--background)",color:i.lineNumber||t.colors.syntax.base.comment,borderRight:`1px solid ${t.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:i.lineNumberActive||t.colors.syntax.base.foreground},".cm-activeLine":{backgroundColor:t.colors.surface.overlay},".cm-panels":{backgroundColor:"transparent",color:t.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 ${t.colors.interactive.border}`,backgroundColor:t.colors.surface.elevated,color:t.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, ${t.colors.surface.elevated} 85%, transparent)`,border:`1px solid ${t.colors.interactive.border}`,borderRadius:"10px",boxShadow:`0 2px 8px color-mix(in srgb, ${t.colors.surface.background} 60%, transparent)`,width:"auto",minWidth:"360px",maxWidth:"480px"},".cm-search":{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"0",width:"100%",color:t.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 ${t.colors.interactive.border}`,backgroundColor:t.colors.surface.background,color:t.colors.surface.foreground,fontFamily:"inherit",fontSize:"12px",lineHeight:"1",outline:"none",transition:"border-color 150ms ease"},".cm-search .cm-textfield::placeholder":{color:t.colors.surface.mutedForeground,opacity:1},".cm-search .cm-textfield:focus":{borderColor:t.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:t.colors.interactive.hover},'.cm-search label:has(input[type="checkbox"]:checked)':{backgroundColor:t.colors.interactive.hover,borderColor:t.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:t.colors.surface.mutedForeground,pointerEvents:"none"},".cm-search label:hover::after":{color:t.colors.surface.foreground},'.cm-search label:has(input[type="checkbox"]:checked)::after':{color:t.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:t.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:t.colors.surface.mutedForeground,pointerEvents:"none"},".cm-search .cm-button:hover":{backgroundColor:t.colors.interactive.hover},".cm-search .cm-button:hover::after":{color:t.colors.surface.foreground},".cm-search .cm-button:active":{backgroundColor:t.colors.interactive.active},".cm-search .cm-button:focus-visible":{outline:"none",boxShadow:`0 0 0 1px ${t.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:t.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:t.colors.interactive.hover,color:t.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:t.colors.status.infoBackground,boxShadow:`inset 0 0 0 1px ${t.colors.status.infoBorder}`,borderRadius:"2px"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:t.colors.interactive.selection,color:t.colors.interactive.selectionForeground,boxShadow:`inset 0 0 0 1px ${t.colors.interactive.borderFocus}`},"&.cm-focused":{outline:"none"}},{dark:n}),x=gn.define([{tag:[c.comment,c.docComment,c.meta,c.documentMeta],class:"cm-comment"},{tag:[c.keyword,c.controlKeyword,c.moduleKeyword,c.definitionKeyword,c.modifier],class:"cm-keyword"},{tag:[c.operatorKeyword,c.operator,c.derefOperator,c.updateOperator,c.definitionOperator,c.typeOperator,c.controlOperator,c.logicOperator,c.bitwiseOperator,c.arithmeticOperator,c.compareOperator],class:"cm-operator"},{tag:[c.punctuation,c.separator,c.bracket,c.paren,c.brace,c.squareBracket,c.angleBracket],class:"cm-punctuation"},{tag:[c.string,c.regexp,c.attributeValue,c.special(c.string),c.monospace],class:"cm-string"},{tag:c.escape,class:"cm-string-2"},{tag:[c.number,c.bool,c.atom,c.null,c.self],class:"cm-number"},{tag:[c.function(c.variableName),c.function(c.definition(c.variableName)),c.function(c.propertyName),c.standard(c.variableName),c.special(c.variableName)],class:"cm-builtin"},{tag:c.definition(c.variableName),class:"cm-def"},{tag:[c.variableName,c.local(c.variableName),c.constant(c.variableName),c.literal],class:"cm-variable"},{tag:c.propertyName,class:"cm-property"},{tag:c.attributeName,class:"cm-attribute"},{tag:[c.className,c.typeName,c.namespace],class:"cm-variable-3"},{tag:[c.tagName,c.labelName,c.annotation,c.macroName],class:"cm-tag"},{tag:c.link,class:"cm-link"},{tag:[c.heading,c.heading1,c.heading2,c.heading3,c.heading4,c.heading5,c.heading6],class:"cm-keyword"}]),N=gn.define([{tag:[c.comment,c.docComment,c.meta,c.documentMeta],color:t.colors.syntax.base.comment},{tag:[c.keyword,c.controlKeyword,c.moduleKeyword,c.definitionKeyword,c.modifier],color:t.colors.syntax.base.keyword},{tag:[c.operatorKeyword,c.operator,c.derefOperator,c.updateOperator,c.definitionOperator,c.typeOperator,c.controlOperator,c.logicOperator,c.bitwiseOperator,c.arithmeticOperator,c.compareOperator],color:t.colors.syntax.base.operator},{tag:[c.string,c.regexp,c.attributeValue,c.special(c.string),c.monospace],color:t.colors.syntax.base.string},{tag:c.escape,color:u.stringEscape||t.colors.syntax.base.string},{tag:[c.number,c.bool,c.atom,c.null,c.self],color:t.colors.syntax.base.number},{tag:[c.function(c.variableName),c.function(c.definition(c.variableName)),c.function(c.propertyName),c.standard(c.variableName),c.special(c.variableName)],color:t.colors.syntax.base.function},{tag:c.definition(c.variableName),color:u.variableGlobal||t.colors.syntax.base.variable},{tag:[c.variableName,c.local(c.variableName),c.constant(c.variableName),c.literal],color:t.colors.syntax.base.variable},{tag:c.propertyName,color:u.variableProperty||t.colors.syntax.base.variable},{tag:c.attributeName,color:u.variableOther||t.colors.syntax.base.variable},{tag:[c.className,c.typeName,c.namespace],color:t.colors.syntax.base.type},{tag:[c.tagName,c.labelName,c.annotation,c.macroName],color:u.tag||t.colors.syntax.base.keyword},{tag:c.link,color:u.url||t.colors.syntax.base.function,textDecoration:"underline"},{tag:[c.punctuation,c.separator,c.bracket,c.paren,c.brace,c.squareBracket,c.angleBracket],color:u.punctuation||t.colors.syntax.base.comment}]);return r?.syntaxColors===!1?[p]:[p,At(fo,{fallback:!0}),At(ho),At(x),At(N)]}const Ho=180,sa=go.define(),Ko=1,Go=2,Jo=4,Nn=new Map,Yo=(t,r)=>{const n=`${t}|${r}`,s=Nn.get(n);if(s)return s;let i="";t&&(i+=`color:${t};`),r&Ko&&(i+="font-style:italic;"),r&Go&&(i+="font-weight:bold;"),r&Jo&&(i+="text-decoration:underline;");const u=$t.mark({attributes:{style:i}});return Nn.set(n,u),u},Xo=(t,r)=>{const n=new br,s=t.state.doc,i=Math.min(r.length,s.lines);for(let u=0;u<i;u+=1){const d=r[u];if(!d||d.length===0)continue;const p=s.line(u+1);let x=p.from;for(const[N,g,z]of d){if(N<=0)continue;const m=x,R=Math.min(x+N,p.to);x+=N,!(R<=m)&&(!g&&!z||n.add(m,R,Yo(g,z)))}}return n.finish()},Qo=ta.define({create(){return $t.none},update(t,r){let n=t.map(r.changes);for(const s of r.effects)s.is(sa)&&(n=s.value);return n},provide:t=>ce.decorations.from(t)}),Zo=t=>ea.fromClass(class{timer;generation=0;constructor(r){this.tokenize(r)}update(r){r.docChanged&&this.schedule(r.view)}schedule(r){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.tokenize(r)},Ho)}async tokenize(r){const n=++this.generation,s=r.state.doc.toString(),i=await Ks(s,t.language,t.themeName,t.theme);i&&n===this.generation&&r.state.doc.length===s.length&&r.dispatch({effects:sa.of(Xo(r,i))})}destroy(){this.timer&&clearTimeout(this.timer)}}),ei=t=>[Qo,Zo(t)],Me=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/g,""),tt=t=>{const r=Me(t);return!r||r==="/"?r||"/":r.split("/").filter(Boolean).at(-1)??r},oa=t=>{const r=Me(t);if(!r||r==="/")return null;const n=r.lastIndexOf("/");if(n<0)return null;if(n===0)return"/";const s=r.slice(0,n);return/^[A-Za-z]:$/.test(s)?`${s}/`:s},Cn=(t,r)=>{const n=Me(t),s=Me(r);return!n||!s?!1:n===s||n.startsWith(`${s}/`)},Sn=(t,r)=>{const n=Me(t);if(!n)return Me(r);if(n.startsWith("/")||/^[A-Za-z]:(\/|$)/.test(n))return n;const s=Me(r);return s?`${s}/${n}`:n},ti=(t,r)=>{const n=Me(t),s=Me(r);if(!n||n===s)return!1;const i=oa(n);return i?s&&Cn(n,s)?Cn(i,s):!0:!1},ri=t=>{if(typeof t!="number"||!Number.isFinite(t)||t<0)return"";if(t<1024)return`${t} B`;const r=["KB","MB","GB"];let n=t/1024;for(const s of r){if(n<1024||s===r[r.length-1])return`${n.toFixed(n>=10?0:1)} ${s}`;n/=1024}return""},ni=(t,r)=>!r||t===r?tt(t):t.startsWith(`${r}/`)?t.slice(r.length+1):t,ai=({root:t,directory:r,entries:n,query:s,searchResults:i,isSearching:u,directoryError:d,refreshing:p,editorPath:x,editor:N,onClose:g,onQueryChange:z,onOpenDirectory:m,onOpenFile:R,onBackFromEditor:C,onRefresh:w})=>{if(!t)return e.jsx(ft,{message:"Select a project to browse files."});if(x)return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-transparent text-foreground",children:[e.jsxs("header",{className:"flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-1 px-2 text-foreground",children:[e.jsx("button",{type:"button",className:"flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Back",onClick:C,style:{touchAction:"manipulation"},children:e.jsx(j,{name:"arrow-left",className:"size-5"})}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx("h2",{className:"truncate typography-ui-label text-foreground",children:tt(x)})})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:N})]});const $=r===t?"Project files":tt(r),E=ti(r,t)?oa(r):null,l=!!E&&!s.trim(),V=E===t?"Project files":tt(E??"");return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-transparent text-foreground",children:[e.jsxs("header",{className:"flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-1 px-2 text-foreground",children:[g?e.jsx("button",{type:"button",className:"flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Close",onClick:g,style:{touchAction:"manipulation"},children:e.jsx(j,{name:"close",className:"size-5"})}):null,l&&E?e.jsx("button",{type:"button",className:"flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":`Back to ${tt(E)}`,onClick:()=>m(E),style:{touchAction:"manipulation"},children:e.jsx(j,{name:"arrow-left",className:"size-5"})}):null,e.jsx("div",{className:"min-w-0 flex-1 px-1",children:e.jsx("h2",{className:"truncate typography-ui-label text-foreground",children:$})}),e.jsx("button",{type:"button",className:"flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Refresh files",onClick:w,style:{touchAction:"manipulation"},children:e.jsx(j,{name:"refresh",className:H("size-5",p&&"animate-spin")})})]}),e.jsx("div",{className:"shrink-0 px-3 pb-2 pt-1",children:e.jsxs("div",{className:"relative",children:[e.jsx(j,{name:"search",className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(mt,{value:s,onChange:B=>z(B.target.value),placeholder:"Search files",className:"h-11 pl-9"})]})}),e.jsx(Gs,{className:"min-h-0 w-full flex-1 overflow-y-auto pb-3",children:d?e.jsx(ft,{message:d}):s.trim()?e.jsx(si,{root:t,results:i,isSearching:u,onOpenFile:R}):n===void 0?e.jsx(ft,{loading:!0,message:"Loading..."}):e.jsxs("div",{className:"flex w-full min-w-0 flex-col",children:[l&&E?e.jsxs("button",{type:"button",className:ra,"aria-label":`Up one level to ${V}`,onClick:()=>m(E),style:{touchAction:"manipulation"},children:[e.jsx(j,{name:"arrow-left",className:H(pr(!0),"text-muted-foreground")}),e.jsx("span",{className:H(na(!0),"flex-1 text-muted-foreground"),children:"Up one level"})]}):null,n.length===0?e.jsx("div",{className:"px-3 py-8 text-center typography-ui-label text-muted-foreground",children:"This directory is empty."}):null,n.map(B=>e.jsx(ia,{name:B.name,path:B.path,directory:B.type==="directory",meta:B.type==="directory"?void 0:ri(B.size),onClick:()=>B.type==="directory"?m(Sn(B.path,r||t)):R(Sn(B.path,r||t))},B.path))]})})]})},ia=({name:t,path:r,directory:n,meta:s,onClick:i})=>e.jsxs("button",{type:"button",className:ra,onClick:i,style:{touchAction:"manipulation"},children:[n?e.jsx(j,{name:"folder-3-fill",className:H(pr(!0),"text-primary/80")}):e.jsx(ut,{filePath:r,className:pr(!0)}),e.jsx("span",{className:H(na(!0),"flex-1 text-foreground"),children:t}),s?e.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground",children:s}):null,n?e.jsx(j,{name:"arrow-right-s",className:"size-4 shrink-0 text-muted-foreground/60"}):null]}),si=({root:t,results:r,isSearching:n,onOpenFile:s})=>n?e.jsx(ft,{loading:!0,message:"Loading..."}):r.length===0?e.jsx(ft,{message:"No files found."}):e.jsx("div",{className:"flex w-full min-w-0 flex-col",children:r.map(i=>e.jsx(ia,{name:tt(i.path),path:i.path,directory:!1,meta:i.relativePath??ni(i.path,t),onClick:()=>s(i.path)},i.path))}),ft=({message:t,loading:r=!1})=>e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center",children:e.jsxs("div",{className:"flex max-w-sm flex-col items-center gap-2",children:[r?e.jsx(j,{name:"loader-4",className:"size-5 animate-spin text-muted-foreground"}):e.jsx(j,{name:"folder-open-fill",className:"size-6 text-muted-foreground"}),e.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:t})]})}),oi=({activeDialog:t,dialogData:r,dialogInputValue:n,onDialogInputChange:s,isDialogSubmitting:i,onDialogSubmit:u,onClose:d,inputRef:p})=>e.jsx(_n,{open:!!t,onOpenChange:x=>!x&&d(),children:e.jsxs(qn,{initialFocus:p,children:[e.jsxs(Un,{children:[e.jsxs(Hn,{children:[t==="createFile"&&"Create File",t==="createFolder"&&"Create Folder",t==="rename"&&"Rename",t==="delete"&&"Delete"]}),e.jsxs(Kn,{children:[t==="createFile"&&`Create a new file in ${r?.path??"root"}`,t==="createFolder"&&`Create a new folder in ${r?.path??"root"}`,t==="rename"&&`Rename ${r?.name??""}`,t==="delete"&&`Are you sure you want to delete ${r?.name??""}? This action cannot be undone.`]})]}),t!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(mt,{value:n,onChange:x=>s(x.target.value),placeholder:t==="rename"?"New name":"Name",onKeyDown:x=>{x.key==="Enter"&&u()},ref:p})}),e.jsxs(Gn,{children:[e.jsx(U,{variant:"outline",onClick:d,disabled:i,children:"Cancel"}),e.jsx(U,{variant:t==="delete"?"destructive":"default",onClick:()=>{u()},disabled:i||t!=="delete"&&!n.trim(),children:i?e.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}):t==="delete"?"Delete":"Confirm"})]})]})}),ii=({label:t,iconDataUrl:r})=>{const[n,s]=o.useState(!1),i=t.trim().slice(0,1).toUpperCase()||"?";return r&&!n?e.jsx("img",{src:r,alt:"",className:"size-4 rounded-sm",onError:()=>s(!0)}):e.jsx("span",{className:H("size-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:i})},ca=({filePath:t,extension:r})=>e.jsx(ut,{filePath:t,extension:r}),ci=({status:t})=>{const r={open:"var(--status-info)",modified:"var(--status-warning)","git-modified":"var(--status-warning)","git-added":"var(--status-success)","git-deleted":"var(--status-error)"}[t];return e.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:r}})},Rn=({name:t})=>{const r=o.useRef(null),n=o.useRef(null),[s,i]=o.useState(!1);return o.useLayoutEffect(()=>{const u=r.current,d=n.current;if(!u||!d)return;const p=()=>{i(d.scrollWidth>u.clientWidth+1)};p();const x=new ResizeObserver(p);return x.observe(u),x.observe(d),()=>{x.disconnect()}},[t]),e.jsxs("span",{ref:r,className:"relative block min-w-0 flex-1 overflow-hidden whitespace-nowrap",children:[e.jsx("span",{ref:n,"aria-hidden":"true",className:"invisible absolute whitespace-nowrap",children:t}),s?e.jsxs("span",{className:"open-file-name-marquee-track",children:[e.jsx("span",{className:"open-file-name-marquee-item",children:t}),e.jsx("span",{className:"open-file-name-marquee-item","aria-hidden":"true",children:t})]}):e.jsx("span",{className:"block min-w-0 truncate",children:t})]})},li=({node:t,root:r,isExpanded:n,isActive:s,isMobile:i,isBrowserClient:u,alwaysShowActions:d,status:p,badge:x,permissions:N,downloadFile:g,contextMenuPath:z,setContextMenuPath:m,rightClickMenuPath:R,setRightClickMenuPath:C,onSelect:w,onToggle:$,onRevealPath:E,onOpenDialog:l})=>{const V=t.type==="directory",{canRename:B,canCreateFile:I,canCreateFolder:_,canDelete:K,canReveal:W}=N,T=!V&&!!g,S=W&&!u,D=B||I||_||K||T||S,b=o.useCallback(O=>{D&&(O?.preventDefault(),C(t.path))},[D,t.path,C]),M=o.useCallback(()=>{V?$(t.path):w(t)},[V,t,w,$]),y=o.useCallback(O=>{O.stopPropagation(),C(null),m(t.path)},[t.path,m,C]),F=({Item:O,Separator:q})=>e.jsxs(e.Fragment,{children:[B&&e.jsxs(O,{onClick:P=>{P.stopPropagation(),l("rename",t)},children:[e.jsx(j,{name:"edit",className:"mr-2 size-4"})," ","Rename"]}),e.jsxs(O,{onClick:P=>{P.stopPropagation(),Lt(t.path).then(J=>{if(J.ok){ie.success("Path copied");return}ie.error("Copy failed")})},children:[e.jsx(j,{name:"file-copy",className:"mr-2 size-4"})," ","Copy Path"]}),e.jsxs(O,{onClick:P=>{P.stopPropagation();const J=Vt(r,t.path)||t.path;Lt(J).then(Q=>{if(Q.ok){ie.success("Relative path copied");return}ie.error("Copy failed")})},children:[e.jsx(j,{name:"file-copy-2",className:"mr-2 size-4"})," ","Copy Relative Path"]}),!V&&g&&e.jsxs(O,{onClick:P=>{P.stopPropagation(),g(t.path).catch(J=>{console.error("Download failed:",J),ie.error("Operation failed")})},children:[e.jsx(j,{name:"download",className:"mr-2 size-4"})," ",u?"Download":"Save"]}),S&&e.jsxs(O,{onClick:P=>{P.stopPropagation(),E(t.path)},children:[e.jsx(j,{name:"folder-received",className:"mr-2 size-4"})," ",As()]}),V&&(I||_)&&e.jsxs(e.Fragment,{children:[e.jsx(q,{}),I&&e.jsxs(O,{onClick:P=>{P.stopPropagation(),l("createFile",t)},children:[e.jsx(j,{name:"file-add",className:"mr-2 size-4"})," ","New File"]}),_&&e.jsxs(O,{onClick:P=>{P.stopPropagation(),l("createFolder",t)},children:[e.jsx(j,{name:"folder-add",className:"mr-2 size-4"})," ","New Folder"]})]}),K&&e.jsxs(e.Fragment,{children:[e.jsx(q,{}),e.jsxs(O,{onClick:P=>{P.stopPropagation(),l("delete",t)},className:"text-destructive focus:text-destructive",children:[e.jsx(j,{name:"delete-bin",className:"mr-2 size-4"})," ","Delete"]})]})]});return e.jsxs(yo,{open:R===t.path,onOpenChange:O=>C(O?t.path:null),children:[e.jsxs(ko,{render:e.jsx("div",{className:"group relative flex items-center",onContextMenu:i?void 0:b}),children:[e.jsxs("button",{type:"button",onClick:M,onContextMenu:i?void 0:b,className:H("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",s?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[V?n?e.jsx(j,{name:"folder-open",className:"size-4 flex-shrink-0 text-muted-foreground"}):e.jsx(j,{name:"folder-3",className:"size-4 flex-shrink-0 text-muted-foreground"}):e.jsx(ca,{filePath:t.path,extension:t.extension}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:t.path,children:t.name}),!V&&p&&e.jsx(ci,{status:p}),V&&x&&e.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[x.modified>0&&e.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",x.modified]}),x.added>0&&e.jsxs("span",{className:"text-[var(--status-success)]",children:["+",x.added]})]})]}),D&&e.jsx("div",{className:H("absolute right-1 top-1/2 -translate-y-1/2",d?"opacity-100":"opacity-0 focus-within:opacity-100 group-hover:opacity-100"),children:e.jsxs(hr,{open:z===t.path,onOpenChange:O=>m(O?t.path:null),children:[e.jsx(gr,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"icon",className:"size-6",onClick:y,children:e.jsx(j,{name:"more-2-fill",className:"size-4"})})}),e.jsx(xr,{align:"end",side:"bottom",onCloseAutoFocus:()=>m(null),children:F({Item:It,Separator:Js})})]})})]}),e.jsx(jo,{className:"min-w-[180px]",children:F({Item:No,Separator:Co})})]})},sr=(t,r,n)=>{const[s,i]=o.useState(""),[u,d]=o.useState(0);return o.useEffect(()=>{if(!t){i("");return}let p=!1;i("");const x=Os(),N=Ps(x);Ls(x).then(z=>{p||!z||(i(t),r(null))}).catch(z=>{p||(r(z instanceof Error?z.message:n),i(t))});const g=Is(()=>{p||(i(t),d(z=>z+1),r(null))});return()=>{p=!0,N(),g()}},[t,r,n]),{readyKey:s,nonce:u}},ui=t=>t!==null&&typeof t=="object"&&"updateStatus"in t&&typeof t.updateStatus=="function",di=t=>{const r=document.createElement("div");r.className="cm-vim-panel";const n=Uo(t);if(!n)return{top:!1,dom:r};n.state.statusbar=r;const s=n.state.vimPlugin;return ui(s)&&s.updateStatus(),{top:!1,dom:r,destroy(){n.state.statusbar===r&&(n.state.statusbar=null)}}};function Fn(t){return t?[qo(),io.of(di),co()]:[]}const fi={next:"Next match",prev:"Previous match",select:"Select all matches",replace:"Replace",replaceAll:"Replace all",close:"Close"},mi={case:"Match case",re:"Regular expression",word:"Match whole word"};function pi(t){const r=t.querySelector(".cm-search");if(r){for(const[n,s]of Object.entries(fi)){const i=r.querySelector(`button[name="${n}"]`);i&&!i.title&&(i.title=s)}for(const[n,s]of Object.entries(mi)){const u=r.querySelector(`input[name="${n}"]`)?.parentElement;u&&!u.title&&(u.title=s)}}}const or=new WeakMap;function hi(t,r){const n=Bt(t.state);if(!n.valid)return or.delete(t),0;const s=or.get(t);if(!r&&s?.doc===t.state.doc&&s.query.eq(n))return s.total;const i=n.getCursor(t.state);let u=0;for(let d=i.next();!d.done;d=i.next())u+=1;return or.set(t,{query:n,doc:t.state.doc,total:u}),u}function gi(t){const r=Bt(t.state);if(!r.valid)return 0;const n=t.state.selection.main,s=r.getCursor(t.state);let i=0,u=0;for(let d=s.next();!d.done;d=s.next()){const p=d.value;if(i+=1,u===0&&(u=i),n.from===p.from&&n.to===p.to||n.from<p.to&&n.to>p.from||p.from>=n.head)return i}return u}function En(t,r,n=!1){const s=t.querySelector(".cm-search");if(!s)return;let i=s.querySelector(".cm-search-message");if(!i){i=document.createElement("span"),i.className="cm-search-message",i.setAttribute("aria-live","polite");const p=s.querySelector('button[name="next"]'),x=p?.parentNode===s?p:s.firstChild;s.insertBefore(i,x)}const u=hi(r,n),d=u===0?0:gi(r);i.textContent=u===0?"":`${d}/${u}`}const zn=new Ue,Mn=new Ue,Tn=new Ue,Dn=new Ue,An=new Ue,On=new Ue,Pn=new Ue,Ln=t=>t,ir=po,xi=Wo,bi=_o;class vi extends uo{constructor(r,n){super(),this.id=r,this.containerMap=n}toDOM(){let r=this.containerMap.get(this.id);return r||(r=document.createElement("div"),r.className="oc-block-widget",r.dataset.widgetId=this.id,this.containerMap.set(this.id,r)),r}eq(r){return r.id===this.id}destroy(){}}const In=(t,r)=>!t||t.length===0?[]:ta.define({create(n){const s=new br,i=[...t].sort((u,d)=>u.afterLine-d.afterLine);for(const u of i){const d=n.doc.lines;if(u.afterLine>d)continue;const p=n.doc.line(u.afterLine);s.add(p.to,p.to,$t.widget({widget:new vi(u.id,r),block:!0,side:1}))}return s.finish()},update(n,s){return n.map(s.changes)},provide:n=>ce.decorations.from(n)}),Vn=t=>{if(!t)return[];const r=Math.max(1,t.start),n=Math.max(r,t.end);return ea.fromClass(class{decorations;constructor(s){this.decorations=this.build(s)}update(s){(s.docChanged||s.viewportChanged)&&(this.decorations=this.build(s.view))}build(s){const i=new br;for(let u=r;u<=n&&u<=s.state.doc.lines;u+=1){const d=s.state.doc.line(u);i.add(d.from,d.from,$t.line({class:"oc-cm-selected-line"}))}return i.finish()}},{decorations:s=>s.decorations})};function wi({value:t,onChange:r,extensions:n,className:s,readOnly:i,lineNumbersConfig:u,highlightLines:d,onViewReady:p,onViewDestroy:x,blockWidgets:N,enableSearch:g,searchOpen:z,onSearchOpenChange:m,vimMode:R}){const C=o.useRef(null),w=o.useRef(null),$=o.useRef(t),E=o.useRef(r),l=o.useRef(p),V=o.useRef(x),B=o.useRef(m),I=o.useRef(N),_=o.useRef(R),K=o.useRef(new Map),[W,T]=o.useState([]),S=o.useCallback(b=>{const M=(b??[]).map(y=>{const F=K.current.get(y.id);return F?{id:y.id,content:y.content,container:F}:null}).filter(y=>y!==null);T(y=>y.length===M.length&&y.every((F,O)=>{const q=M[O];return F.id===q.id&&F.content===q.content&&F.container===q.container})?y:M)},[]),D=o.useCallback(b=>{const M=C.current,y=b??w.current;if(!M||!y)return;const F=y.dom.querySelector(".cm-gutters"),O=F instanceof HTMLElement?F.getBoundingClientRect().width:0;M.style.setProperty("--oc-editor-gutter-width",`${O}px`)},[]);return o.useEffect(()=>{$.current=t},[t]),o.useEffect(()=>{E.current=r},[r]),o.useEffect(()=>{l.current=p,V.current=x},[p,x]),o.useEffect(()=>{B.current=m},[m]),o.useEffect(()=>{I.current=N,S(N)},[N,S]),o.useEffect(()=>{if(!C.current)return;const b=(()=>{if(typeof document>"u")return null;const y=document.querySelector('meta[name="csp-nonce"]')?.getAttribute("content");if(y)return y;const F=window.__PICHAMBER_CSP_NONCE__;return typeof F=="string"&&F.length>0?F:null})(),M=xo.create({doc:$.current,extensions:[...b?[ce.cspNonce.of(b)]:[],lo({fixed:!0}),zn.of(hn(u)),Io(),mo.of(" "),Pn.of(Fn(R)),nr.of([Vo,...Bo,...$o]),ce.updateListener.of(y=>{D(y.view),(y.viewportChanged||y.geometryChanged)&&S(I.current);const F=wn(y.startState),O=wn(y.state);F!==O&&B.current?.(O);const q=!Bt(y.startState).eq(Bt(y.state));if(O&&(F!==O||q||y.docChanged||y.selectionSet)&&En(y.view.dom,y.view,F!==O||q||y.docChanged),!y.docChanged)return;const P=y.state.doc.toString();$.current=P,E.current(P),S(I.current)}),Mn.of(ce.editable.of(!i)),Tn.of(n??[]),Dn.of(Vn(d)),An.of(In(N,K.current)),On.of(g?[yn({top:!0}),nr.of(Ln(kn))]:[])]});return w.current=new ce({state:M,parent:C.current}),ir(w.current,w.current.state.doc.length,200),w.current.requestMeasure(),requestAnimationFrame(()=>{D(w.current),S(I.current)}),w.current&&l.current?.(w.current),()=>{V.current?.(),w.current?.destroy(),w.current=null,T([])}},[I,D,S]),o.useEffect(()=>{const b=w.current;b&&(b.dispatch({effects:[zn.reconfigure(hn(u)),Mn.reconfigure(ce.editable.of(!i)),Tn.reconfigure(n??[]),Dn.reconfigure(Vn(d)),An.reconfigure(In(N,K.current)),On.reconfigure(g?[yn({top:!0}),nr.of(Ln(kn))]:[])]}),ir(b,b.state.doc.length,200),b.requestMeasure(),requestAnimationFrame(()=>{D(b),S(I.current)}))},[n,d,u,i,N,g,D,S]),o.useEffect(()=>{const b=w.current;if(!b){_.current=R;return}_.current!==R&&(_.current=R,b.dispatch({effects:Pn.reconfigure(Fn(R))}))},[R]),o.useEffect(()=>{const b=w.current;!b||g===!1||(z?(xi(b),requestAnimationFrame(()=>{pi(b.dom),En(b.dom,b,!0)})):bi(b))},[z,g]),o.useEffect(()=>{const b=w.current;if(!b)return;const M=b.state.doc.toString();M!==t&&(b.dispatch({changes:{from:0,to:M.length,insert:t}}),ir(b,b.state.doc.length,300),b.requestMeasure(),requestAnimationFrame(()=>D(b)))},[t,D]),e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:C,className:H("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)]",s)}),W.map(b=>Ds.createPortal(b.content,b.container,b.id))]})}const Bn=({variant:t,selectedFile:r,loading:n,suppressLoadingIndicator:s,fileError:i,isSelectedImage:u,imageSrc:d,imagePreviewNonce:p,isSelectedPdf:x,pdfSrc:N,pdfPreviewNonce:g,isUnsupportedBinary:z,onDownload:m,enableRichPreviews:R,drawioViewMode:C,drawioRemountNonce:w,diagramEditorRef:$,diagramEditorXml:E,onDiagramChange:l,jsonViewMode:V,markdownViewMode:B,htmlViewMode:I,htmlLoading:_,htmlPreviewNonce:K,htmlPreviewSrc:W,fileContent:T,canUseShikiFileView:S,textViewMode:D,draftContent:b,onDraftChange:M,canEdit:y,vimMode:F,editorExtensions:O,editorWrapperRef:q,shouldMaskEditorForPendingNavigation:P,onEditorViewReady:J,onEditorViewDestroy:Q,enableSearch:ge=!1,searchOpen:xe,onSearchOpenChange:fe,pierreTheme:je,shikiThemeType:Be,wrapLines:be})=>{const ae=t==="fullscreen",se=ae?"p-4":"p-3",Ne=!!(r?.path&&pt(r.path)),Z=!!(r?.path&&aa(r.path)),L=!!(r?.path&&vr(r.path)),G=!!(r?.path&&Wt(r.path)),ne=()=>r?e.jsx("div",{className:"h-full",children:e.jsx(Lo,{file:{name:r.name,contents:b,lang:Yn(r.path)||void 0},options:{disableFileHeader:!0,overflow:be?"wrap":"scroll",theme:je,themeType:Be},className:"block h-full w-full",style:{height:"100%"}})}):null;return e.jsx(Jn,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:r?n?s?e.jsx("div",{className:se}):e.jsxs("div",{className:`${se} flex items-center gap-2 typography-ui text-muted-foreground`,children:[e.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}),ae?"Loading…":"Loading..."]}):i?e.jsx("div",{className:`${se} typography-ui text-[color:var(--status-error)]`,children:i}):u?e.jsx("div",{className:H("flex h-full items-center justify-center",se),children:e.jsx("img",{src:d,alt:r.name||"Image",className:H("max-w-full object-contain rounded-md border border-border/30 bg-primary/10",ae?"max-h-full":"max-h-[70vh]")},p)}):x?e.jsx("div",{className:"h-full overflow-hidden bg-[var(--surface-background)]",children:e.jsx("iframe",{src:N,className:"h-full w-full border-0",title:r.name},g)}):z?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx("div",{className:"typography-ui-header text-foreground",children:"Cannot preview binary file"}),e.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."}),m?e.jsxs(U,{type:"button",variant:"outline",size:"sm",onClick:m,children:[e.jsx(j,{name:"download",className:"mr-2 size-4"}),"Save file"]}):null]}):R&&Ne&&C==="preview"?e.jsx("div",{className:"h-full overflow-hidden",style:{minHeight:"400px"},children:e.jsx(wo,{ref:$,xml:E,onChange:l},`${r.path}:${w}`)}):R&&Z&&V==="tree"?e.jsx(dn,{fallback:e.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[e.jsx("div",{className:"mb-1 font-medium text-destructive",children:"JSON viewer unavailable"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to text mode to view raw content."})]}),children:e.jsx("div",{className:"h-full overflow-auto",children:e.jsx(Po,{jsonString:T,maxHeight:"100%",initiallyExpandedDepth:2})})}):L&&B==="preview"?e.jsxs("div",{className:H("h-full overflow-auto",se),children:[T.length>500*1024?e.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(T.length/1024)}KB). Preview may be limited.`}):null,e.jsx(dn,{fallback:e.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[e.jsx("div",{className:"mb-1 font-medium text-destructive",children:"Preview unavailable"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to edit mode to fix the issue."})]}),children:e.jsx(Ys,{content:T,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):R&&G&&I==="preview"?_?e.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground typography-ui-label",children:"Loading..."}):e.jsx("div",{className:"h-full overflow-hidden",children:e.jsx("iframe",{src:W,className:"w-full h-full border-none",sandbox:"allow-scripts allow-same-origin allow-forms",title:"HTML Preview"},K)}):S&&D==="view"?ne():e.jsxs("div",{className:H("relative h-full",P&&"overflow-hidden"),ref:q,children:[e.jsx("div",{className:H("h-full",P&&"invisible"),children:e.jsx(wi,{value:b,onChange:M,readOnly:!y,vimMode:F,extensions:O,className:"h-full",onViewReady:J,onViewDestroy:Q,...ge?{enableSearch:!0,searchOpen:xe,onSearchOpenChange:fe}:{}})}),P?e.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-background",children:e.jsxs("div",{className:"flex items-center gap-2 typography-ui text-muted-foreground",children:[e.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}),"Opening file at change..."]})}):null]}):e.jsx("div",{className:`${se} typography-ui text-muted-foreground`,children:"Pick a file from the tree."})})};async function yi(t,r,n){if(Xn(t)&&!Qn(t))return{kind:r?"desktop-image":"asset-image"};if(Zn(t))return{kind:"pdf"};if(mr(t))return{kind:"binary",detectedFromContent:!1};const i=await n(t);if(Xs(i))return{kind:"binary",detectedFromContent:!0};const u=So(i);return{kind:"text",content:u,draft:u.length>dt?`${u.slice(0,dt)}
2
-
3
- … truncated …`:u,lineEnding:Ro(i)}}function ki({isDirty:t,saveDraft:r}){const n=he(m=>m.setMainTabGuard),[s,i]=k.useState(!1),u=k.useRef(null),d=k.useRef(!1),p=k.useCallback(m=>d.current?(d.current=!1,!1):t?(u.current=m,i(!0),!0):!1,[t]);k.useEffect(()=>{if(!t){n(null);return}const m=R=>!p({kind:"tab",tab:R});return n(m),()=>{he.getState().mainTabGuard===m&&n(null)}},[t,p,n]);const x=k.useCallback(()=>{const m=u.current;return u.current=null,d.current=!0,i(!1),m?.kind==="tab"&&n(null),m},[n]),N=k.useCallback(()=>x(),[x]),g=k.useCallback(async()=>await r()?x():(d.current=!1,null),[r,x]),z=k.useCallback(m=>{m||i(!0)},[]);return{confirmOpen:s,discardAndTakeIntent:N,keepModalOpen:z,requestNavigation:p,saveAndTakeIntent:g}}function ji(t,r){if(t.state.doc.length!==r.length)return!1;if(r.length===0)return!0;const n=Math.min(128,r.length);if(t.state.sliceDoc(0,n)!==r.slice(0,n))return!1;const s=Math.max(0,r.length-n);return t.state.sliceDoc(s,r.length)===r.slice(s)}function Ni({root:t,selectedPath:r,loadedPath:n,fileLoading:s,fileError:i,isImage:u,isPdf:d,isUnsupportedBinary:p,canEdit:x,textViewMode:N,setTextViewMode:g,draftContent:z,confirmDiscardOpen:m,selectFilePath:R}){const C=he(S=>S.pendingFileNavigation),w=he(S=>S.setPendingFileNavigation),$=he(S=>S.pendingFileFocusPath),E=he(S=>S.setPendingFileFocusPath),l=k.useRef(null),[V,B]=k.useState(0),I=k.useRef(null),_=k.useRef({key:"",attempts:0}),K=k.useCallback(()=>{B(S=>S+1)},[]);k.useEffect(()=>()=>{I.current!==null&&window.cancelAnimationFrame(I.current)},[]),k.useEffect(()=>{if(!C||!t)return;const S=()=>{I.current===null&&(I.current=window.requestAnimationFrame(()=>{I.current=null,K()}))},D=()=>{w(null),_.current={key:"",attempts:0}},b=de(C.path);if(!b){D();return}const M=`${b}:${C.line}:${C.column??1}`;if(_.current.key!==M&&(_.current={key:M,attempts:0}),r!==b){m||R(b);return}if(s||n!==b)return;if(i||u||d||p){D();return}if(!x)return;if(N!=="edit"){g("edit");return}const y=l.current;if(!y||!ji(y,z)){S();return}const F=Math.max(1,Math.min(C.line,y.state.doc.lines)),O=y.state.doc.line(F),q=Math.max(1,C.column||1),P=O.from+Math.min(Math.max(0,O.to-O.from),q-1);if(!(y.state.selection.main.head===P)||_.current.attempts===0){_.current.attempts+=1,y.dispatch({selection:{anchor:P},effects:ce.scrollIntoView(P,{y:"center"})}),y.focus(),S();return}window.requestAnimationFrame(()=>{const Q=l.current;Q&&(Q.dispatch({selection:{anchor:P},effects:ce.scrollIntoView(P,{y:"center"})}),Q.focus())}),D()},[x,m,z,V,i,s,u,d,p,n,K,C,t,r,R,w,g,N]),k.useEffect(()=>{if(!$||!t)return;const S=de($);if(!S){E(null);return}r!==S||s||n!==S||(!i&&!u&&!d&&!p&&x&&N==="edit"&&l.current?.focus(),E(null))},[x,i,s,u,d,p,n,$,t,r,E,N]);const W=de(C?.path??"");return{editorViewRef:l,notifyEditorViewChanged:K,shouldMaskEditor:!!(C&&W&&r===W&&!s&&!i&&!u&&!d&&!p)}}function Ci(t){return!(!t.autoSaveEnabled||!t.isDirty||!t.canWrite||t.isSaving||t.fileLoading||t.isNonEditableBinary||!t.selectedFilePath||t.loadedFilePath!==t.selectedFilePath)}function Si(t){return t.selectedFilePath?t.isDirty?!(t.fileLoading||t.loadedFilePath!==t.selectedFilePath||t.isNonEditableBinary||t.draftContent===""&&t.fileContent!==""&&t.loadedFilePath!==t.selectedFilePath):!0:!1}const Ri=1500,Fi=2e3;function Ei({autoSaveEnabled:t,selectedPath:r,loadedPath:n,fileLoading:s,isDirty:i,draftContent:u,fileContent:d,lineEnding:p,isNonEditableBinary:x,writeFile:N,onSaved:g}){const[z,m]=k.useState(!1),[R,C]=k.useState("idle"),w=k.useRef(null),$=k.useRef(null),E=k.useCallback(()=>{w.current&&(clearTimeout(w.current),w.current=null)},[]),l=k.useCallback(()=>{C("saved"),$.current&&clearTimeout($.current),$.current=setTimeout(()=>{$.current=null,C("idle")},Fi)},[]),V=k.useCallback(async()=>{if(!r||!N)return ie.error("Saving not supported"),!1;if(!Si({selectedFilePath:r,loadedFilePath:n,fileLoading:s,isDirty:i,draftContent:u,fileContent:d,isNonEditableBinary:x}))return x?console.warn(`[saveDraft] refusing to save binary file "${r}".`):u===""&&d!==""&&n!==r&&console.warn(`[saveDraft] refusing to save empty draft for "${r}" (${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(!i)return!0;m(!0);try{const I=Fo(u,p);return(await N(r,I))?.success?(g(r,u),!0):(ie.error("Failed to write file"),!1)}catch(I){return ie.error(I instanceof Error?I.message:"Save failed"),!1}finally{m(!1)}},[u,d,s,i,x,p,n,g,r,N]),B=k.useCallback(async()=>{if(E(),z)return!1;const I=await V();return I&&l(),I},[E,z,V,l]);return k.useEffect(()=>{t||(C("idle"),E())},[t,E]),k.useEffect(()=>{if(Ci({autoSaveEnabled:t,isDirty:i,canWrite:!!(r&&N),isSaving:z,fileLoading:s,selectedFilePath:r,loadedFilePath:n,isNonEditableBinary:x}))return w.current=setTimeout(()=>{w.current=null,V().then(I=>{I&&l()})},Ri),E},[t,E,u,s,i,x,z,n,V,r,l,N]),k.useEffect(()=>{C("idle"),m(!1)},[r]),k.useEffect(()=>()=>{E(),$.current&&clearTimeout($.current)},[E]),{autoSaveStatus:R,cancelPendingAutosave:E,isSaving:z,saveDraft:V,saveNow:B}}function zi(t,r){return r.mtimeMs!==void 0&&t.mtimeMs!==void 0&&r.mtimeMs!==t.mtimeMs||r.size!==t.size}function Mi({selectedPath:t,loadedPath:r,isDirty:n,readStat:s,onExternalChange:i,pollIntervalMs:u=2e3}){const d=k.useRef(null),p=k.useRef(n);p.current=n;const x=k.useCallback(N=>{d.current=N},[]);return k.useEffect(()=>{if(!t||r!==t)return;let N=!1;const g=window.setInterval(()=>{document.hidden||s(t).then(z=>{if(N||!z)return;const m=d.current;if(!m||m.path!==t){d.current=z;return}!zi(m,z)||p.current||(d.current=z,i())}).catch(()=>{})},u);return()=>{N=!0,window.clearInterval(g)}},[r,i,u,s,t]),{recordStat:x}}const cr="pichamber:files:md-viewer-mode",lr="pichamber:files:html-viewer-mode",ur="pichamber:files:json-viewer-mode",Ti=1500,Di=1500;function dr(t,r,n){try{const s=localStorage.getItem(t);if(s&&r.includes(s))return s}catch{}return n}function et(t,r){try{localStorage.setItem(t,r)}catch{}}function Ai({root:t,openPaths:r,selectedPath:n,defaultPreview:s,fileContent:i,draftContent:u,setDraftContent:d,autoSaveEnabled:p,writeFile:x,readStat:N,recordStat:g}){const[z,m]=k.useState("edit"),[R,C]=k.useState("edit"),[w,$]=k.useState("tree"),[E,l]=k.useState("edit"),[V,B]=k.useState("preview"),[I,_]=k.useState(0),[K,W]=k.useState(!1),T=k.useRef({}),S=k.useRef({}),D=k.useRef({}),b=k.useRef({}),M=k.useRef(""),y=k.useRef(""),F=k.useRef(null),O=k.useRef(null),q=k.useRef(null),P=k.useCallback(()=>{F.current&&(clearTimeout(F.current),F.current=null),q.current!==null&&(cancelAnimationFrame(q.current),q.current=null)},[]),J=k.useCallback(L=>{M.current=L,y.current=L},[]),Q=k.useCallback(()=>J(""),[J]);k.useEffect(()=>{if(!n)return;const L=s?"preview":"edit";m(T.current[n]??"edit"),C(S.current[n]??dr(cr,["preview","edit"],L)),l(D.current[n]??dr(lr,["preview","edit"],L)),B(b.current[n]??L),$(dr(ur,["tree","text"],s?"tree":"text"))},[s,n]);const ge=k.useCallback(L=>{n&&(T.current[n]=L),m(L)},[n]),xe=k.useCallback(L=>{n&&(S.current[n]=L),C(L),et(cr,L)},[n]),fe=k.useCallback(L=>{n&&(D.current[n]=L),l(L),et(lr,L)},[n]),je=k.useCallback(L=>{$(L),et(ur,L)},[]),Be=k.useCallback(L=>{if(n&&(b.current[n]=L),P(),L==="edit"){d(M.current||i),B(L);return}M.current=u;const G=n;B("edit"),q.current=requestAnimationFrame(()=>{q.current=requestAnimationFrame(()=>{q.current=null,!(t&&G&&ke.getState().byRoot[t]?.selectedPath!==G)&&(_(ne=>ne+1),B("preview"))})})},[P,u,i,t,n,d]),be=k.useCallback(async(L,G)=>{if(!x||G===y.current)return!1;if(!(await x(L,G))?.success)return ie.error("Failed to write file"),!1;J(G),d(G);const Y=await N(L).catch(()=>null);return Y&&g(Y),!0},[N,J,g,d,x]),ae=k.useCallback(()=>{W(!0),O.current&&clearTimeout(O.current),O.current=setTimeout(()=>W(!1),Di)},[]),se=k.useCallback(async(L,G)=>{F.current&&(clearTimeout(F.current),F.current=null);const ne=await be(L,G);return ne&&ae(),ne},[be,ae]),Ne=k.useCallback(L=>{M.current=L,!(!p||!n||V!=="preview"||!x)&&(F.current&&clearTimeout(F.current),F.current=setTimeout(()=>{F.current=null,be(n,L).then(G=>{G&&ae()}).catch(G=>{ie.error(G instanceof Error?G.message:"Save failed")})},Ti))},[p,V,be,n,ae,x]);k.useEffect(()=>P,[P,V,n]),k.useEffect(()=>()=>{O.current&&clearTimeout(O.current)},[]),k.useEffect(()=>{const L=ne=>{const Y=ne?"preview":"edit",He=ne?"tree":"text";for(const re of r)T.current[re]="edit",vr(re)&&(S.current[re]=Y),Wt(re)&&(D.current[re]=Y),pt(re)&&(b.current[re]=Y);m("edit"),C(Y),l(Y),B(Y),$(He),et(cr,Y),et(lr,Y),et(ur,He)},G=ne=>{L(!!ne.detail?.enabled)};return window.addEventListener("pichamber:file-viewer-preview-mode-changed",G),()=>window.removeEventListener("pichamber:file-viewer-preview-mode-changed",G)},[r]);const Z=pt(n??"")&&(M.current||u)||i;return{clearDiagramContent:Q,diagramEditorXml:Z,diagramSaved:K,drawioRemountNonce:I,drawioViewMode:V,handleDiagramChange:Ne,htmlViewMode:E,jsonViewMode:w,mdViewMode:R,recordDiagramContent:J,saveDiagramNow:se,saveDiagramXml:be,saveDrawioViewMode:Be,saveHtmlViewMode:fe,saveJsonViewMode:je,saveMdViewMode:xe,saveTextViewMode:ge,setTextViewMode:m,textViewMode:z}}function Oi({files:t,root:r,activeDirectory:n,expandedPaths:s,chrome:i,showHidden:u,showGitignored:d,removeExpandedPathsByPrefix:p}){const[x,N]=o.useState({}),[g,z]=o.useState({}),m=o.useRef(new Set),R=o.useRef(new Set),C=o.useRef(new Map),w=o.useRef(0),$=o.useCallback((W,T)=>{const S=[];for(const D of T){if(!D?.name||i==="desktop"&&!u&&D.name.startsWith(".")||i==="desktop"&&!d&&Eo(D.name))continue;const b=de(D.path||""),M=b?zo(b)?b:de(`${W}/${b}`):de(`${W}/${D.name}`),y=D.isDirectory?"directory":"file";S.push({name:D.name,path:M,type:y,extension:y==="file"&&D.name.includes(".")?D.name.split(".").pop()?.toLowerCase():void 0,size:D.size})}return Mo(S)},[i,d,u]),E=o.useCallback(async W=>{const T=de(W.trim());if(!T||m.current.has(T)||R.current.has(T))return;R.current=new Set(R.current).add(T);const S=w.current+1;w.current=S,C.current=new Map(C.current).set(T,S);const D=()=>C.current.get(T)===S;try{const b=t.listDirectory?(await t.listDirectory(T)).entries.map(M=>({name:M.name,path:M.path,isDirectory:M.isDirectory,size:M.size})):(await Vs(T)).map(M=>({name:M.name,path:M.path,isDirectory:M.isDirectory}));if(!D())return;m.current=new Set(m.current).add(T),z(M=>{if(!M[T])return M;const y={...M};return delete y[T],y}),N(M=>({...M,[T]:$(T,b)}))}catch(b){if(!D())return;const M=b instanceof Error?b.message:String(b??"");M==="Directory not found"&&r&&T!==r?(p(r,T),z(y=>{if(!y[T])return y;const F={...y};return delete F[T],F})):(console.error("Failed to load files directory:",b),z(y=>({...y,[T]:M})))}finally{D()&&(C.current=new Map(C.current),C.current.delete(T),R.current=new Set(R.current),R.current.delete(T))}},[t,$,p,r]),l=o.useCallback(()=>{m.current=new Set,R.current=new Set,C.current=new Map,z({}),N(W=>Object.keys(W).length===0?W:{})},[]),V=o.useCallback(async()=>{r&&(l(),await E(r))},[E,l,r]),B=o.useCallback(async W=>{if(!W){await V();return}const T=de(W);m.current=new Set(m.current),m.current.delete(T),R.current=new Set(R.current),R.current.delete(T),await E(T)},[E,V]),I=`${r}|h${u?"1":"0"}|g${d?"1":"0"}|${i}`,_=o.useRef("");o.useEffect(()=>{!r||_.current===I||(_.current=I,l(),E(r))},[E,l,r,I]),o.useEffect(()=>{n&&E(n)},[n,E]),o.useEffect(()=>{if(!t.listDirectory)return;const W=()=>{if(!document.hidden)for(const D of s)B(D)},T=()=>W();document.addEventListener("visibilitychange",T);const S=s.length>0?window.setInterval(W,8e3):null;return()=>{document.removeEventListener("visibilitychange",T),S!==null&&window.clearInterval(S)}},[s,t.listDirectory,B]);const K=o.useCallback(W=>m.current.has(de(W)),[]);return{childrenByDir:x,loadErrorsByDir:g,isLoaded:K,loadDirectory:E,refreshDirectory:B,refreshRoot:V}}const Pi=({showEditorTabsRow:t,isMobile:r,showMobilePageContent:n,onBackMobile:s,selectedFile:i,openFiles:u,root:d,alwaysShowActions:p,editorTabsOverflow:x,editorTabsScrollRef:N,onSelectFile:g,onCloseFile:z})=>t?e.jsxs("div",{className:"flex min-w-0 items-center px-3 py-1.5",children:[r&&n&&e.jsx("button",{type:"button",onClick:s,"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:e.jsx(j,{name:"arrow-left-s",className:"size-5"})}),r?i?e.jsxs(hr,{children:[e.jsx(gr,{asChild:!0,children:e.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:[e.jsx(ut,{filePath:i.path,extension:i.extension,className:"size-3.5 flex-shrink-0"}),e.jsx(Rn,{name:i.name}),e.jsx(j,{name:"arrow-down-s",className:"size-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(xr,{align:"start",className:"w-[min(24rem,calc(100vw-2rem))] max-w-[calc(100vw-2rem)]",children:u.map(m=>{const R=i?.path===m.path;return e.jsxs(It,{onSelect:C=>{if(C.target.closest("[data-close-open-file]")){C.preventDefault();return}R||g(m)},className:H("flex min-w-0 items-center justify-between gap-2 overflow-hidden",R&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),children:[e.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-hidden",children:[e.jsx(ut,{filePath:m.path,extension:m.extension,className:"size-3.5 flex-shrink-0"}),e.jsx(Rn,{name:m.name})]}),e.jsx("button",{type:"button","data-close-open-file":!0,onPointerDown:C=>{C.preventDefault(),C.stopPropagation()},onClick:C=>{C.preventDefault(),C.stopPropagation(),z(m.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 ${m.name}`,children:e.jsx(j,{name:"close",className:"size-3.5"})})]},m.path)})})]}):e.jsx("div",{className:"typography-ui-label font-medium truncate",children:"Select a file"}):u.length>0?e.jsxs("div",{className:"relative min-w-0 flex-1",children:[x.left&&e.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"}),x.right&&e.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"}),e.jsx("div",{ref:N,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:u.map(m=>{const R=i?.path===m.path;return e.jsxs("div",{title:Vt(d,m.path),className:H("group inline-flex items-center gap-1 rounded-md border px-2 py-1 typography-ui-label transition-colors whitespace-nowrap",R?"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:[e.jsx(ut,{filePath:m.path,extension:m.extension,className:"size-3.5 flex-shrink-0"}),e.jsx("button",{type:"button",onClick:()=>{R||g(m)},className:"max-w-[12rem] truncate text-left",children:m.name}),e.jsx("button",{type:"button",onClick:C=>{C.stopPropagation(),z(m.path)},className:H("rounded-sm p-0.5 text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]",!R&&!p&&"opacity-0 group-hover:opacity-100"),"aria-label":`Close ${m.name}`,children:e.jsx(j,{name:"close",className:"size-3.5"})})]},m.path)})})]}):e.jsx("div",{className:"typography-ui-label font-medium truncate",children:"Select a file"})]}):null,Li=(t,r)=>{if(!r)return null;const n=Number.parseInt(t.trim(),10);return!Number.isFinite(n)||n<1?null:Math.min(n,r.state.doc.lines)},$n=(t,r)=>{const n=t.state.doc.lineAt(r.main.head);return{lineNumber:n.number,character:r.main.head-n.from+1,selection:r}},Wn=(t,r,n)=>{const s=t.state.doc.line(r),i=Math.max(1,Math.min(n,s.length+1)),u=s.from+i-1;t.dispatch({selection:bo.cursor(u),effects:ce.scrollIntoView(u,{y:"center"})})};function Ii({open:t,onOpenChange:r,view:n,variant:s="overlay"}){const[i,u]=o.useState(""),d=o.useRef(null),p=o.useRef(!1),x=o.useRef(null),N=o.useRef(null),g=o.useMemo(()=>Li(i,n),[i,n]);o.useEffect(()=>{!t||!n||(p.current=!1,d.current=$n(n,n.state.selection),u(""))},[t,n]),o.useEffect(()=>{t&&window.requestAnimationFrame(()=>{N.current?.focus(),N.current?.select()})},[t]),o.useEffect(()=>{if(!(!t||!n||!d.current)){if(g===null){const{selection:w}=d.current;n.dispatch({selection:w,effects:ce.scrollIntoView(w.main.from,{y:"center"})});return}Wn(n,g,d.current.character)}},[g,t,n]);const z=o.useCallback(()=>{if(!n||p.current||!d.current)return;const{selection:w}=d.current;n.dispatch({selection:w,effects:ce.scrollIntoView(w.main.from,{y:"center"})})},[n]),m=o.useCallback(w=>{w||z(),r(w)},[r,z]),R=o.useCallback(()=>{!n||g===null||!d.current||(p.current=!0,Wn(n,g,d.current.character),r(!1),n.focus())},[g,r,n]);o.useEffect(()=>{if(!t)return;const w=E=>{const l=x.current,V=E.target;!l||!(V instanceof Node)||l.contains(V)||m(!1)},$=E=>{E.key==="Escape"&&(E.preventDefault(),m(!1))};return document.addEventListener("pointerdown",w,!0),document.addEventListener("keydown",$,!0),()=>{document.removeEventListener("pointerdown",w,!0),document.removeEventListener("keydown",$,!0)}},[m,t,s]);const C=o.useMemo(()=>n?g===null?`Current Line: ${(d.current??$n(n,n.state.selection)).lineNumber}. Type a line number between 1 and ${n.state.doc.lines} to navigate to.`:`Go to line ${g}`:"Editor unavailable.",[g,n]);return s==="inline"?t?e.jsxs("div",{ref:x,className:"ml-1 flex h-6 items-center gap-1",children:[e.jsx(mt,{ref:N,type:"number",min:1,step:1,inputMode:"numeric",value:i,onChange:w=>u(w.target.value),onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),R())},placeholder:"Line",className:"h-6 w-20 rounded-md border-border/70 bg-transparent px-2 typography-meta"}),e.jsx(U,{variant:"outline",size:"xs",onClick:R,disabled:!n||g===null,className:"h-6 px-2",children:"Go"})]}):null:e.jsx("div",{ref:x,className:H("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",t?"pointer-events-auto translate-y-0 opacity-100":"pointer-events-none -translate-y-1 opacity-0"),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx(mt,{ref:N,type:"number",min:1,step:1,inputMode:"numeric",value:i,onChange:w=>u(w.target.value),onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),R())},placeholder:"Line number",className:"h-8 w-full rounded-md border-border/70 bg-background/60 typography-ui-label"}),e.jsx("div",{className:"mt-2 rounded-md bg-primary/15 px-3 py-1.5 typography-ui-label text-foreground/95",children:C})]})})}const fr=({currentMode:t,onToggle:r})=>{const n=t==="preview",s=n?"Switch to edit mode":"Switch to preview mode",i=n?"Edit":"Preview";return e.jsxs(Le,{children:[e.jsx(Ie,{asChild:!0,children:e.jsx(U,{variant:"ghost",size:"sm",onClick:r,"aria-label":s,className:"h-5 w-5 p-0",children:n?e.jsx(j,{name:"eye",className:"size-4","aria-hidden":"true"}):e.jsx(j,{name:"eye-off",className:"size-4","aria-hidden":"true"})})}),e.jsx(Ve,{sideOffset:8,children:i})]})},Vi=({selectedFile:t,displaySelectedPath:r,layout:n="floating",exitFullscreenOnly:s=!1,canEdit:i,isEditingFile:u,isSaving:d,autoSaveEnabled:p,autoSaveStatus:x,isDirty:N,onSaveDraft:g,onToggleAutoSave:z,openInApps:m,openInCacheStale:R,onOpenInApp:C,onRefreshOpenInApps:w,onToolbarDropdownOpenChange:$,isSelectedImage:E,isSelectedPdf:l,isUnsupportedBinary:V,wrapLines:B,onToggleWrapLines:I,textViewMode:_,onToggleSearch:K,isGoToLineOpen:W,onOpenGoToLineChange:T,editorView:S,canUseShikiFileView:D,isJson:b,isHtml:M,onToggleTextViewMode:y,isMarkdown:F,mdViewMode:O,onToggleMdViewMode:q,isDrawio:P,drawioViewMode:J,onToggleDrawioViewMode:Q,diagramSaved:ge,onSaveDiagram:xe,jsonViewMode:fe,onToggleJsonViewMode:je,canCopy:Be,copiedContent:be,onCopyContent:ae,canCopyPath:se,copiedPath:Ne,onCopyPath:Z,onDownloadFile:L,isMobile:G,mode:ne,isFullscreen:Y,onToggleFullscreen:He,onExitFullscreen:re})=>{if(!t)return null;const Ke=n==="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",oe=(le,Te)=>e.jsxs(Le,{children:[e.jsx(Ie,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:Te})}),e.jsx(Ve,{side:"bottom",sideOffset:6,children:le})]});return e.jsxs("div",{className:Ke,children:[i&&u&&e.jsxs(e.Fragment,{children:[d?e.jsxs("span",{className:"flex items-center gap-1 px-1 text-muted-foreground typography-meta",children:[e.jsx(j,{name:"loader-4",className:"size-3.5 animate-spin"}),"Saving..."]}):p&&x==="saved"&&!N?e.jsxs("span",{className:"flex items-center gap-1 px-1 text-[color:var(--status-success)] typography-meta",children:[e.jsx(j,{name:"check",className:"size-3.5"}),"Saved"]}):N?oe(p?`Save now (${lt()}+S) - auto-saves after 1.5s`:`Save now (${lt()}+S)`,e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>{g()},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:p?`Save now (${lt()}+S) - auto-saves after 1.5s`:`Save now (${lt()}+S)`,"aria-label":`Save (${lt()}+S)`,children:e.jsx(j,{name:"save-3",className:"size-4"})})):null,oe(p?"Auto-save on":"Manual save",e.jsx(U,{variant:"ghost",size:"sm",onClick:z,className:H("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",p?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:p?"Auto-save on":"Manual save","aria-label":p?"Auto-save on":"Manual save",children:p?e.jsx(j,{name:"file-check-fill",className:"size-4"}):e.jsx(j,{name:"file-check",className:"size-4"})}))]}),e.jsxs(hr,{onOpenChange:$,children:[e.jsxs(Le,{children:[e.jsx(Ie,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(gr,{asChild:!0,children:e.jsx(U,{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:e.jsx(j,{name:"file-transfer",className:"size-4"})})})})}),e.jsx(Ve,{side:"bottom",sideOffset:6,children:"Open in desktop app"})]}),e.jsxs(xr,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[m.map(le=>e.jsxs(It,{className:"flex items-center gap-2",onClick:()=>{C(le)},children:[e.jsx(ii,{label:le.label,iconDataUrl:le.iconDataUrl}),e.jsx("span",{className:"typography-ui-label text-foreground",children:le.label})]},le.id)),R?e.jsxs(It,{className:"flex items-center gap-2",onClick:()=>{w()},children:[e.jsx(j,{name:"refresh",className:"size-4"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]}),!E&&!l&&!V&&e.jsxs(e.Fragment,{children:[oe(B?"Disable line wrap":"Enable line wrap",e.jsx(U,{variant:"ghost",size:"sm",onClick:I,className:H("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",B?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:B?"Disable line wrap":"Enable line wrap",children:e.jsx(j,{name:"text-wrap",className:"size-4"})})),_==="edit"&&e.jsxs(e.Fragment,{children:[oe("Find in file",e.jsx(U,{variant:"ghost",size:"sm",onClick:le=>{K(),le.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:e.jsx(j,{name:"search",className:"size-4"})})),oe("Go to line",e.jsx(U,{variant:"ghost",size:"sm",onClick:le=>{T(!W),le.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:e.jsx(j,{name:"menu-fold-2",className:"size-4"})})),e.jsx(Ii,{open:W,onOpenChange:T,view:S,variant:"inline"})]})]}),D&&i&&!b&&!M&&e.jsx(fr,{currentMode:_==="view"?"preview":"edit",onToggle:y}),F&&oe(O==="preview"?"Switch to edit mode":"Switch to preview mode",e.jsx(U,{variant:"ghost",size:"sm",onClick:q,className:H("size-6 p-0 transition-colors hover:bg-[var(--interactive-hover)] focus-visible:bg-[var(--interactive-hover)] active:bg-[var(--interactive-hover)]",O==="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:O==="preview"?"Switch to edit mode":"Switch to preview mode","aria-label":O==="preview"?"Switch to edit mode":"Switch to preview mode",children:e.jsx(j,{name:O==="preview"?"eye":"eye-off",className:"size-4"})})),Wt(t?.path??"")&&e.jsx(fr,{currentMode:M?"preview":"edit",onToggle:y}),P&&e.jsxs(e.Fragment,{children:[e.jsx(fr,{currentMode:J,onToggle:Q}),J==="preview"&&e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>{xe()},className:"size-6 p-0 text-foreground hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Save diagram",children:ge?e.jsx(j,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):e.jsx(j,{name:"save-3",className:"size-4"})})]}),b&&oe(fe==="tree"?"Switch to Text View":"Switch to Tree View",e.jsx(U,{variant:"ghost",size:"sm",onClick:je,className:"size-6 p-0 text-muted-foreground opacity-65 hover:bg-transparent hover:opacity-100 focus-visible:bg-transparent active:bg-transparent",title:fe==="tree"?"Switch to Text View":"Switch to Tree View",children:fe==="tree"?e.jsx(j,{name:"code-sslash",className:"size-4"}):e.jsx(j,{name:"node-tree",className:"size-4"})})),Be&&oe("Copy file contents",e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>{ae()},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:be?e.jsx(j,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):e.jsx(j,{name:"clipboard",className:"size-4"})})),se&&oe(`Copy file path (${r})`,e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>{Z()},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:`Copy file path (${r})`,"aria-label":`Copy file path (${r})`,children:Ne?e.jsx(j,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):e.jsx(j,{name:"file-copy-2",className:"size-4"})})),L&&oe("Save file",e.jsx(U,{variant:"ghost",size:"sm",onClick:L,className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Save file","aria-label":"Save file",children:e.jsx(j,{name:"download",className:"size-4"})})),s?oe("Exit fullscreen",e.jsx(U,{variant:"ghost",size:"sm",onClick:re,className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Exit fullscreen","aria-label":"Exit fullscreen",children:e.jsx(j,{name:"fullscreen-exit",className:"size-4"})})):!G&&ne==="full"&&oe(Y?"Exit fullscreen":"Fullscreen",e.jsx(U,{variant:"ghost",size:"sm",onClick:He,className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:Y?"Exit fullscreen":"Fullscreen","aria-label":Y?"Exit fullscreen":"Fullscreen",children:Y?e.jsx(j,{name:"fullscreen-exit",className:"size-4"}):e.jsx(j,{name:"fullscreen",className:"size-4"})}))]})},Bi=({open:t,onOpenChange:r,isSaving:n,onSaveAndContinue:s,onDiscardAndContinue:i})=>e.jsx(_n,{open:t,onOpenChange:r,children:e.jsxs(qn,{showCloseButton:!1,className:"max-w-md",children:[e.jsxs(Un,{children:[e.jsx(Hn,{children:"Unsaved changes"}),e.jsx(Kn,{children:"Save your edits before continuing?"})]}),e.jsxs(Gn,{children:[e.jsx(U,{variant:"outline",onClick:s,disabled:n,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"}),e.jsx(U,{variant:"destructive",onClick:i,children:"Discard"})]})]})}),$i=({root:t,isMobile:r,searchQuery:n,onSearchQueryChange:s,searchInputRef:i,searching:u,searchResults:d,selectedFile:p,onSelectFile:x,onOpenDialog:N,currentDirectory:g,refreshRoot:z,childrenByDir:m,loadErrorsByDir:R,expandedPaths:C,isBrowserClient:w,alwaysShowActions:$,getFileStatus:E,getFolderBadge:l,fileRowPermissions:V,downloadFile:B,contextMenuPath:I,setContextMenuPath:_,rightClickMenuPath:K,setRightClickMenuPath:W,toggleDirectory:T,handleRevealPath:S,refreshDirectory:D})=>{const b=!!(t&&m[t]),M=t?R[t]:null;function y(F,O){const q=m[F]??[];return q.map((P,J)=>{const Q=P.type==="directory",ge=Q&&C.includes(P.path),xe=p?.path===P.path,fe=J===q.length-1;return e.jsxs("li",{className:"relative",children:[O>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),fe&&e.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-background"})]}),e.jsx(li,{node:P,root:t,isExpanded:ge,isActive:xe,isMobile:r,isBrowserClient:w,alwaysShowActions:$,status:Q?void 0:E(P.path),badge:Q?l(P.path):void 0,permissions:V,downloadFile:B,contextMenuPath:I,setContextMenuPath:_,rightClickMenuPath:K,setRightClickMenuPath:W,onSelect:x,onToggle:T,onRevealPath:S,onOpenDialog:N}),Q&&ge&&e.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[R[P.path]?e.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate text-[var(--status-error)]",title:R[P.path],children:R[P.path]}),e.jsxs(U,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{D(P.path)},children:[e.jsx(j,{name:"refresh",className:"size-3.5"}),"Refresh"]})]}):null,y(P.path,O+1)]})]},P.path)})}return e.jsxs("section",{className:H("flex min-h-0 flex-col overflow-hidden",r?"h-full w-full bg-background":"h-full rounded-xl border border-border/60 bg-background/70"),children:[e.jsx("div",{className:H("flex flex-col gap-2 py-2",r?"px-3":"px-2"),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(j,{name:"search",className:"pointer-events-none absolute left-2 top-2 size-4 text-muted-foreground"}),e.jsx(mt,{ref:i,value:n,onChange:F=>s(F.target.value),placeholder:"Search files...",className:"h-8 pl-8 pr-8 typography-meta"}),n.trim().length>0&&e.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:()=>{s(""),i.current?.focus()},children:e.jsx(j,{name:"close",className:"size-4"})})]}),e.jsxs(Le,{children:[e.jsx(Ie,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>N("createFile",{path:g,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:"New File","aria-label":"New File",children:e.jsx(j,{name:"file-add",className:"size-4"})})})}),e.jsx(Ve,{side:"bottom",sideOffset:6,children:"New File"})]}),e.jsxs(Le,{children:[e.jsx(Ie,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>N("createFolder",{path:g,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:"New Folder","aria-label":"New Folder",children:e.jsx(j,{name:"folder-add",className:"size-4"})})})}),e.jsx(Ve,{side:"bottom",sideOffset:6,children:"New Folder"})]}),e.jsxs(Le,{children:[e.jsx(Ie,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>{z()},className:"size-8 p-0 flex-shrink-0",title:"Refresh","aria-label":"Refresh",children:e.jsx(j,{name:"refresh",className:"size-4"})})})}),e.jsx(Ve,{side:"bottom",sideOffset:6,children:"Refresh"})]})]})}),e.jsx(Jn,{outerClassName:"flex-1 min-h-0",className:H("py-2",r?"px-3":"px-2"),children:e.jsx("ul",{className:"flex flex-col",children:u?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}),"Searching..."]}):d.length>0?d.map(F=>{const O=p?.path===F.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{x(F)},className:H("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",O?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[e.jsx(ca,{filePath:F.path,extension:F.extension}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:F.path,children:F.relativePath??F.path})]})},F.path)}):M?e.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{className:"text-[var(--status-error)]",children:M}),e.jsxs(U,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{z()},children:[e.jsx(j,{name:"refresh",className:"size-3.5"}),"Refresh"]})]}):b?y(t,0):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading..."})})})]})},Ql=({mode:t="full",chrome:r="desktop",onClose:n})=>{const{files:s,runtime:i}=Qs(),u=r==="mobile",{currentTheme:d,availableThemes:p,lightThemeId:x,darkThemeId:N}=Zs(),{isMobile:g,isTablet:z,screenWidth:m}=eo(),R=Bs(i.platform),C=g||z,w=$s(),$=Ws(),E=to()??"",l=de(E.trim()),V=t!=="editor-only",B=t==="editor-only"&&!g,I=ro(E),[_,K]=o.useState(""),W=o.useRef(null),[T,S]=o.useState(!1),[D,b]=o.useState(l),[M,y]=o.useState(!1),[F,O]=o.useState(!0),[q,P]=o.useState(!1),[J,Q]=o.useState(!1),[ge,xe]=o.useState(!1),fe=o.useRef(null);o.useEffect(()=>{u&&(b(l),K(""),S(!1))},[u,l]);const je=o.useRef(0),Be=o.useCallback(a=>{je.current=Math.max(0,je.current+(a?1:-1))},[]),be=o.useCallback(a=>a instanceof Element?a.closest('[data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-item"]')!==null:!1,[]);o.useEffect(()=>{if(!ge)return;const a=f=>{je.current>0||be(f.target)||fe.current&&!fe.current.contains(f.target)&&xe(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[be,ge]);const ae=o.useMemo(()=>p.find(a=>a.metadata.id===x)??cn(!1),[p,x]),se=o.useMemo(()=>p.find(a=>a.metadata.id===N)??cn(!0),[p,N]);o.useEffect(()=>{xn(ae),xn(se)},[ae,se]);const Ne=o.useMemo(()=>[],[]),Z=ke(a=>l?a.byRoot[l]?.openPaths??Ne:Ne),L=ke(a=>l?a.byRoot[l]?.selectedPath??null:null),G=ke(a=>l?a.byRoot[l]?.expandedPaths??Ne:Ne),ne=ke(a=>a.removeOpenPath),Y=ke(a=>a.removeOpenPathsByPrefix),He=ke(a=>a.removeExpandedPathsByPrefix),re=ke(a=>a.setSelectedPath),_t=ke(a=>a.toggleExpandedPath),Ke=ke(a=>a.expandPaths),{childrenByDir:oe,loadErrorsByDir:le,isLoaded:Te,loadDirectory:Ge,refreshDirectory:ht,refreshRoot:la}=Oi({files:s,root:l,activeDirectory:u?D:void 0,expandedPaths:G,chrome:r,showHidden:w,showGitignored:$,removeExpandedPathsByPrefix:He}),De=o.useCallback(a=>{const f=de(a),v=f.split("/"),A=v[v.length-1]||f,ee=A.includes(".")?A.split(".").pop()?.toLowerCase():void 0;return{name:A,path:f,type:"file",extension:ee}},[]),gt=o.useMemo(()=>Z.map(De),[Z,De]),qt=o.useMemo(()=>{if(L){const a=Pt(L);if(Z.some(f=>Pt(f)===a))return L}return Z[0]??null},[Z,L]),h=o.useMemo(()=>qt?De(qt):null,[qt,De]),Re=h?.path??"";o.useEffect(()=>{if(!l||!L)return;const a=Pt(L);Z.some(v=>Pt(v)===a)||re(l,Z[0]??null)},[Z,l,L,re]);const xt=!!(l&&Re&&!ar(Re,l)),wr=xt?fn(Re):void 0,ue=o.useMemo(()=>({allowOutsideWorkspace:t==="editor-only"&&xt,outsideFileGrant:wr,directory:l||void 0}),[t,xt,wr,l]),Ut=o.useRef(null),[ua,da]=o.useState({left:!1,right:!1}),yr=o.useCallback(()=>{const a=Ut.current;a&&da({left:a.scrollLeft>2,right:a.scrollLeft+a.clientWidth<a.scrollWidth-2})},[]),kr=o.useRef(yr);kr.current=yr,o.useEffect(()=>{const a=Ut.current;if(!a)return;const f=()=>kr.current();f(),a.addEventListener("scroll",f,{passive:!0});const v=new ResizeObserver(f);return v.observe(a),()=>{a.removeEventListener("scroll",f),v.disconnect()}},[gt.length]);const[ve,Fe]=o.useState(""),[Ht,rt]=o.useState(!1),[jr,we]=o.useState(null),[fa,$e]=o.useState(""),me=o.useRef(""),[nt,Ce]=o.useState(null),[at,Se]=o.useState(""),[ma,pa]=o.useState(`
4
- `),Nr=o.useRef(null),bt=o.useRef(0),st=o.useRef(null),[Cr,Sr]=o.useState(!1),vt=he(a=>a.autoSaveEnabled),ha=he(a=>a.setAutoSaveEnabled),ga=o.useRef(null),[xa,ba]=o.useState(null),[va,wa]=o.useState(null),{value:ya,show:ka}=mn(!1,1200),{value:ja,show:Na}=mn(!1,1200),[Ca,Rr]=o.useState(!1),Kt=o.useCallback(()=>{l&&re(l,null),Fe(""),we(null),$e(""),Ce(null),g&&S(!1)},[g,l,re]),{operation:Sa,target:Ra,inputValue:Fa,setInputValue:Ea,submitting:za,inputRef:Ma,open:Ta,close:Da,submit:Aa,capabilities:{canCreateFile:Fr,canCreateFolder:Er,canRename:zr,canDelete:Mr}}=To({files:s,root:l,selectedPath:h?.path??"",refreshDirectory:ht,removeOpenPathsByPrefix:Y,clearSelectedPath:Kt}),Tr=!!s.revealPath,Oa=Ot(a=>a.availableApps),Pa=Ot(a=>a.isCacheStale),Dr=Ot(a=>a.initialize),La=Ot(a=>a.loadInstalledApps);o.useEffect(()=>{Dr()},[Dr]);const Ia=o.useCallback(a=>{s.revealPath&&s.revealPath(a).catch(()=>{ie.error("Failed to reveal path")})},[s]),Va=o.useCallback(async a=>{if(!h?.path||await _s(h.path,a.id,a.appName)||await ln(h.path,a.appName))return;const A=Do(h.path)||l;A&&await ln(A,a.appName)||ie.error(`Failed to open in ${a.appName}`)},[l,h?.path]),Ar=he(a=>a.shortcutOverrides),Ba=he(a=>a.fileEditorKeymap),$a=no(a=>a.settingsDefaultFileViewerPreview),Or=he(a=>a.expandedEditorToolbar);o.useEffect(()=>{Se("")},[h?.path]);const Pr=o.useRef("");o.useEffect(()=>{!l||Pr.current===l||(Pr.current=l,Fe(""),we(null),$e(""),Ce(null),S(!1))},[l]);const Wa=u?D:E,{results:Lr,searching:Ir}=Ao({directory:Wa,query:_,chrome:r,showHidden:w,showGitignored:$}),Vr=o.useCallback(async(a,f)=>{if(s.readFile)return(await s.readFile(a,{...f??{},directory:l||void 0})).content??"";const v=new URLSearchParams({path:a});f?.allowOutsideWorkspace&&v.set("allowOutsideWorkspace","true"),f?.outsideFileGrant&&v.set("outsideFileGrant",f.outsideFileGrant),f?.optional&&v.set("optional","true"),l&&v.set("directory",l);const A=await un(`/api/fs/read?${v.toString()}`,{cache:f?.optional?"no-store":"default"});if(!A.ok){const ee=await A.json().catch(()=>({error:A.statusText}));throw new Error(ee.error||"Failed to read file")}return A.text()},[s,l]),Je=o.useCallback(async(a,f)=>{if(s.statFile){const v=await s.statFile(a,{...f??{},directory:l||void 0});return{path:v.path,size:v.size,mtimeMs:v.mtimeMs}}return null},[s,l]);o.useEffect(()=>{if(!l||!s.statFile||Z.length===0)return;let a=!1;const f=[...Z];return Promise.all(f.map(async v=>{try{const A=await s.statFile?.(v,{directory:l||void 0});!a&&A&&!A.isFile&&Y(l,v)}catch(A){!a&&bn(A)&&Y(l,v)}})),()=>{a=!0}},[s,Z,Y,l]);const Gt=o.useMemo(()=>ve.length>dt?`${ve.slice(0,dt)}
5
-
6
- … truncated …`:ve,[ve]),wt=at!==Gt,Br=o.useCallback(a=>Je(a,ue),[Je,ue]),_a=o.useCallback(()=>{Ce(null)},[]),{recordStat:Ae}=Mi({selectedPath:h?.path??null,loadedPath:nt,isDirty:wt,readStat:Br,onExternalChange:_a}),{clearDiagramContent:$r,diagramEditorXml:qa,diagramSaved:Ua,drawioRemountNonce:Ha,drawioViewMode:Jt,handleDiagramChange:Ka,htmlViewMode:yt,jsonViewMode:kt,mdViewMode:jt,recordDiagramContent:Nt,saveDiagramNow:Ga,saveDrawioViewMode:Ja,saveJsonViewMode:Ya,saveMdViewMode:Wr,saveTextViewMode:Xa,setTextViewMode:Yt,textViewMode:Ee}=Ai({root:l,openPaths:Z,selectedPath:h?.path??null,defaultPreview:$a,fileContent:ve,draftContent:at,setDraftContent:Se,autoSaveEnabled:vt,writeFile:s.writeFile,readStat:Br,recordStat:Ae}),Oe=o.useCallback(()=>jt,[jt]),Qa=o.useCallback((a,f)=>{if(Fe(f),l&&ar(a,l)){const v=Vt(l,a);v&&ao.requestGitRefresh({directory:l,paths:[v]})}pt(a)&&Nt(f),Je(a).then(v=>{v&&Ae(v)}).catch(()=>{})},[Je,Nt,Ae,l]),{autoSaveStatus:Za,isSaving:_r,saveDraft:qr,saveNow:Ur}=Ei({autoSaveEnabled:vt,selectedPath:h?.path??null,loadedPath:nt,fileLoading:Ht,isDirty:wt,draftContent:at,fileContent:ve,lineEnding:ma,isNonEditableBinary:!!(h?.path&&(mr(h.path)||Cr)),writeFile:s.writeFile,onSaved:Qa}),{confirmOpen:Hr,discardAndTakeIntent:Kr,keepModalOpen:es,requestNavigation:Ct,saveAndTakeIntent:Gr}=ki({isDirty:wt,saveDraft:qr});o.useEffect(()=>{const a=f=>{Us(f)&&(f.key.toLowerCase()==="s"?(f.preventDefault(),Ur()):f.key.toLowerCase()==="f"&&(f.preventDefault(),Q(!0)))};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[Ur]);const Jr=o.useCallback(async a=>{const f=bt.current+1;bt.current=f;const v=()=>{if(!l)return!1;const X=ke.getState().byRoot[l],qe=X?.selectedPath??X?.openPaths[0]??null;return bt.current===f&&qe===a.path};we(null),$e(""),Ce(null),Sr(!1),g&&S(!0);const A=fn(a.path),ee={allowOutsideWorkspace:t==="editor-only"&&!!l&&!ar(a.path,l),outsideFileGrant:A};let te=!1;rt(!0),await yi(a.path,i.isDesktop,X=>Vr(X,ee)).then(X=>{if(v()){if(X.kind!=="text"){if(Fe(""),Se(""),X.kind==="desktop-image"){te=!0;return}X.kind==="binary"&&Sr(X.detectedFromContent),Ce(a.path);return}pa(X.lineEnding),Fe(X.content),Nt(X.content),Se(X.draft),Ce(a.path),Je(a.path,ee).then(qe=>{qe&&v()&&Ae(qe)}).catch(()=>{})}}).catch(X=>{if(v()){if(Oo(X)){if(rt(!1),l&&re(l,null),we(null),Fe(""),Se(""),Ce(null),Ae(null),_.trim().length>0&&K(""),g&&S(!1),l){const Ze=[...vn(a.path,l),a.path];Ze.length>0&&Ke(l,Ze);for(const on of Ze)Te(on)||Ge(on)}return}if(bn(X)){l&&Y(l,a.path),Fe(""),Se(""),we(null),Ae(null),g&&S(!1);return}Fe(""),Se(""),we(X instanceof Error?X.message:"Failed to read file"),Ae(null)}}).finally(()=>{v()&&!te&&rt(!1)})},[Ke,Te,g,Ge,t,Vr,Je,Nt,Ae,Y,l,i.isDesktop,_,re]),St=o.useCallback(async(a,f)=>{if(!l)return;const v=vn(a,l),A=f?[...v,a]:v;A.length>0&&Ke(l,A);const ee=A.map(te=>{if(!Te(te))return Ge(te)}).filter(Boolean);await Promise.all(ee)},[Ke,Te,Ge,l]),Yr=o.useCallback((a,f)=>{const v=f.findIndex(A=>A.path===a);return v===-1||f.length<=1?null:f[v+1]??f[v-1]??null},[]),ze=o.useCallback(async a=>{Ct({kind:"select",file:a})||(l&&(re(l,a.path),St(a.path,!1)),we(null),$e(""),Fe(""),$r(),Se(""),Ce(null),g&&S(!0))},[$r,St,g,Ct,l,re]),ts=o.useCallback(a=>{ze(De(a))},[ze,De]),rs=o.useCallback(a=>{const f=de(a);f&&(K(""),b(f),S(!1))},[]),ns=o.useCallback(a=>{const f=de(a);f&&(S(!0),ze(De(f)))},[ze,De]),as=o.useCallback(async()=>{if(!(!D||M)){y(!0);try{await ht(D)}finally{y(!1)}}},[D,M,ht]);o.useEffect(()=>{h?.path&&St(h.path,!1)},[St,h?.path]),o.useEffect(()=>{if(!h){bt.current+=1,st.current=null,rt(!1);return}if(nt===h.path||st.current===h.path)return;const a=h.path;st.current=a,Jr(h).finally(()=>{st.current===a&&(st.current=null)})},[Jr,nt,h]);const Ye=o.useCallback(async a=>{if(a.kind==="select"){await ze(a.file);return}if(a.kind==="tab"){he.getState().setActiveMainTab(a.tab);return}l&&ne(l,a.path),h?.path===a.path&&(a.nextFile?await ze(a.nextFile):Kt())},[Kt,ze,ne,l,h?.path]),ss=o.useCallback(()=>{const a=Kr();Se(Gt),a&&Ye(a)},[Ye,Kr,Gt]),os=o.useCallback(async()=>{const a=await Gr();a&&await Ye(a)},[Ye,Gr]),is=o.useCallback(a=>{const f=h?.path===a,v={kind:"close",path:a,nextFile:Yr(a,gt)};f&&Ct(v)||Ye(v)},[Ye,Yr,gt,Ct,h?.path]),cs=o.useCallback(a=>{if(Z.includes(a))return"open";if(I?.files){const f=a.startsWith(l+"/")?a.slice(l.length+1):a,v=I.files.find(A=>A.path===f);if(v){if(v.index==="A"||v.working_dir==="?")return"git-added";if(v.index==="D")return"git-deleted";if(v.index==="M"||v.working_dir==="M")return"git-modified"}}return null},[Z,I,l]),ls=o.useCallback(a=>{if(!I?.files)return null;const f=a.startsWith(l+"/")?a.slice(l.length+1):a,v=f?`${f}/`:"";let A=0,ee=0;for(const te of I.files)te.path.startsWith(v)&&((te.index==="M"||te.working_dir==="M")&&A++,(te.index==="A"||te.working_dir==="?")&&ee++);return A+ee>0?{modified:A,added:ee}:null},[I,l]),us=o.useCallback(async a=>{const f=de(a);l&&(_t(l,f),Te(f)||await Ge(f))},[Te,Ge,l,_t]),ds=o.useMemo(()=>({canRename:zr,canCreateFile:Fr,canCreateFolder:Er,canDelete:Mr,canReveal:Tr}),[zr,Fr,Er,Mr,Tr]),ye=!!(h?.path&&Xn(h.path)),Xe=!!(h?.path&&Qn(h.path)),We=!!(h?.path&&Zn(h.path)),Xt=!!(h?.path&&(mr(h.path)||Cr)),Rt=Xt&&!ye&&!We,Qe=o.useMemo(()=>Vt(l,Re),[Re,l]),fs=!!(h&&(!ye||Xe)&&!We&&!Rt&&ve.length>0),ms=!!(h&&Qe.length>0),_e=!!(h&&!xt&&!Xt&&!ye&&s.writeFile&&ve.length<=dt),ot=!!(h?.path&&vr(h.path)),Qt=!!(h?.path&&aa(h.path)),it=!!(h?.path&&Wt(h.path)),Xr=!!(h?.path&&pt(h.path)),ps=!!(h&&!Xt&&!ye),{editorViewRef:pe,notifyEditorViewChanged:Ft,shouldMaskEditor:hs}=Ni({root:l,selectedPath:Re||null,loadedPath:nt,fileLoading:Ht,fileError:jr,isImage:ye,isPdf:We,isUnsupportedBinary:Rt,canEdit:_e,textViewMode:Ee,setTextViewMode:Yt,draftContent:at,confirmDiscardOpen:Hr,selectFilePath:ts}),Qr=ps&&!ot&&!Xr&&!(it&&yt==="preview"),gs=ot&&jt==="edit"||it&&yt==="edit"||Qt&&kt==="text"||!ot&&!it&&!Qt&&Ee==="edit",Et=o.useMemo(()=>Re?so(Re):null,[Re]),[Zr,Zt]=o.useState(null);o.useEffect(()=>{let a=!1;const f=h?.path;if(!f||Et){Zt(null);return}return Zt(null),oo(f).then(v=>{a||Zt(v)}),()=>{a=!0}},[h?.path,Et]),o.useEffect(()=>{!_e&&Ee==="edit"&&Yt("view")},[_e,Yt,Ee]);const Pe=o.useCallback(a=>{if(!g||!a||!a.hasFocus||typeof window>"u")return;const f=window.visualViewport;if(!f)return;const v=document.documentElement.clientHeight||window.innerHeight;if(Math.max(0,v-(f.offsetTop+f.height))<=0)return;const ee=a.state.selection.main.head,te=a.coordsAtPos(ee);if(!te)return;const X=Math.round(f.offsetTop+f.height),Ze=te.bottom+20-X;Ze<=0||(a.scrollDOM.scrollTop+=Ze)},[g]);o.useEffect(()=>{if(!g||typeof window>"u")return;const a=()=>{window.requestAnimationFrame(()=>{Pe(pe.current)})},f=window.visualViewport;return f?.addEventListener("resize",a),f?.addEventListener("scroll",a,{passive:!0}),document.addEventListener("selectionchange",a),()=>{f?.removeEventListener("resize",a),f?.removeEventListener("scroll",a),document.removeEventListener("selectionchange",a)}},[pe,g,Pe]),o.useEffect(()=>{if(!_e||Ee!=="edit"||g)return;const a=qs("open_go_to_line",Ar),f=v=>{const A=v.target;if(A?.closest('[role="dialog"]'))return;const ee=!!A?.closest(".cm-editor");A?.closest('input, textarea, [contenteditable="true"], [role="textbox"]')&&!ee||!document.activeElement?.closest(".cm-editor")||Hs(v,a)&&(v.preventDefault(),Rr(!0))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[_e,g,Ar,Ee]);const zt=he(a=>a.editorFontSize),xs=o.useMemo(()=>{if(!h?.path)return[jn(d,{fontSize:zt})];const a=Yn(h.path),f=[jn(d,a?{syntaxColors:!1,fontSize:zt}:{fontSize:zt})],v=Et??Zr;return v&&f.push(v),a&&f.push(ei({language:a,themeName:d.metadata.id,theme:vo(d)})),F&&f.push(ce.lineWrapping),g&&f.push(ce.updateListener.of(A=>{A.view.hasFocus&&(A.selectionSet||A.focusChanged||A.viewportChanged||A.geometryChanged)&&window.requestAnimationFrame(()=>{Pe(A.view)})})),f},[d,h?.path,Et,Zr,F,g,Pe,zt]),bs=o.useMemo(()=>({light:ae.metadata.id,dark:se.metadata.id}),[ae.metadata.id,se.metadata.id]),Mt=h?.path&&ye&&!i.isDesktop&&!Xe?`${h.path}|${ue.allowOutsideWorkspace?"outside":"workspace"}|${ue.outsideFileGrant??""}`:"",Tt=h?.path&&We?`${h.path}|${ue.allowOutsideWorkspace?"outside":"workspace"}|${ue.outsideFileGrant??""}`:"",ct=h?.path&&it&&yt==="preview"?h.path:"",er="Failed to read file",{readyKey:en,nonce:vs}=sr(Mt,we,er),{readyKey:tn,nonce:ws}=sr(ct,we,er),{readyKey:rn,nonce:ys}=sr(Tt,we,er),ks=!!(Mt&&en!==Mt),js=!!(ct&&tn!==ct),Ns=!!(Tt&&rn!==Tt),Cs=h?.path&&ye?i.isDesktop?Xe?`data:${pn(h.path)};utf8,${encodeURIComponent(ve)}`:fa:Xe?`data:${pn(h.path)};utf8,${encodeURIComponent(ve)}`:en===Mt?rr().authenticatedAsset("/api/fs/raw",{path:h.path,allowOutsideWorkspace:ue.allowOutsideWorkspace?"true":void 0,outsideFileGrant:ue.outsideFileGrant,directory:l||void 0}):"":"",Ss=h?.path&&We&&rn===Tt?rr().authenticatedAsset("/api/fs/raw",{path:h.path,allowOutsideWorkspace:ue.allowOutsideWorkspace?"true":void 0,outsideFileGrant:ue.outsideFileGrant,directory:l||void 0}):"",Rs=ct&&tn===ct&&h?.path?(()=>{const a=h.path.split("/").map(f=>encodeURIComponent(f)).join("/");return rr().authenticatedAsset(`/api/fs/serve${a.startsWith("/")?a:`/${a}`}`)})():void 0;o.useEffect(()=>{let a=!1;return(async()=>{if(!i.isDesktop||!h?.path||!ye||Xe){me.current&&(URL.revokeObjectURL(me.current),me.current=""),$e("");return}we(null),me.current&&(URL.revokeObjectURL(me.current),me.current=""),await(s.readFileBinary?s.readFileBinary(h.path,ue).then(A=>A.dataUrl):(async()=>{const A=await un("/api/fs/raw",{query:{path:h.path,allowOutsideWorkspace:ue.allowOutsideWorkspace?"true":void 0,outsideFileGrant:ue.outsideFileGrant,directory:l||void 0}});if(!A.ok)throw new Error("Failed to read file");const ee=await A.blob(),te=URL.createObjectURL(ee);return a?(URL.revokeObjectURL(te),""):(me.current=te,te)})()).then(A=>{a||($e(A),Ce(h.path))}).catch(A=>{me.current&&(URL.revokeObjectURL(me.current),me.current=""),a||($e(""),we(A instanceof Error?A.message:"Failed to read file"),Ce(null))}).finally(()=>{a||rt(!1)})})(),()=>{a=!0}},[s,ye,Xe,l,i.isDesktop,h?.path,ue]),o.useEffect(()=>()=>{me.current&&(URL.revokeObjectURL(me.current),me.current="")},[]);const nn=o.useCallback(()=>{const a=s.downloadFile,f=h?.path;!a||!f||a(f).catch(v=>{console.error("Download failed:",v),ie.error("Operation failed")})},[s.downloadFile,h?.path]),tr=({exitFullscreenOnly:a=!1,layout:f="floating"}={})=>e.jsx(Vi,{selectedFile:h,displaySelectedPath:Qe,layout:f,exitFullscreenOnly:a,canEdit:_e,isEditingFile:gs,isSaving:_r,autoSaveEnabled:vt,autoSaveStatus:Za,isDirty:wt,onSaveDraft:qr,onToggleAutoSave:()=>ha(!vt),openInApps:Oa,openInCacheStale:Pa,onOpenInApp:Va,onRefreshOpenInApps:()=>La(!0),onToolbarDropdownOpenChange:Be,isSelectedImage:ye,isSelectedPdf:We,isUnsupportedBinary:Rt,wrapLines:F,onToggleWrapLines:()=>O(!F),textViewMode:Ee,onToggleSearch:()=>Q(!J),isGoToLineOpen:Ca,onOpenGoToLineChange:Rr,editorView:pe.current,canUseShikiFileView:Qr,isJson:Qt,isHtml:it,onToggleTextViewMode:()=>{Xa(Ee==="view"?"edit":"view")},isMarkdown:ot,mdViewMode:Oe(),onToggleMdViewMode:()=>Wr(Oe()==="preview"?"edit":"preview"),isDrawio:Xr,drawioViewMode:Jt,onToggleDrawioViewMode:()=>Ja(Jt==="preview"?"edit":"preview"),diagramSaved:Ua,onSaveDiagram:async()=>{const v=Nr.current?.getXml();h?.path&&v&&await Ga(h.path,v)},jsonViewMode:kt,onToggleJsonViewMode:()=>Ya(kt==="tree"?"text":"tree"),canCopy:fs,copiedContent:ya,onCopyContent:async()=>{(await Lt(ve)).ok?ka(!0):ie.error("Copy failed")},canCopyPath:ms,copiedPath:ja,onCopyPath:async()=>{(await Lt(Qe)).ok?Na(!0):ie.error("Copy failed")},onDownloadFile:s.downloadFile&&h?nn:void 0,isMobile:g,mode:t,isFullscreen:q,onToggleFullscreen:()=>P(!q),onExitFullscreen:()=>P(!1)}),Fs=o.useCallback(a=>{pe.current=a,Ft(),window.requestAnimationFrame(()=>{Pe(a)})},[pe,Ft,Pe]),Es=o.useCallback(()=>{pe.current&&(pe.current=null),Ft()},[pe,Ft]),zs=o.useCallback(a=>{pe.current=a,window.requestAnimationFrame(()=>{Pe(a)})},[pe,Pe]),Ms=o.useCallback(()=>{pe.current&&(pe.current=null)},[pe]),an={selectedFile:h,loading:Ht||ks||Ns,suppressLoadingIndicator:B,fileError:jr,isSelectedImage:ye,imageSrc:Cs,imagePreviewNonce:vs,isSelectedPdf:We,pdfSrc:Ss,pdfPreviewNonce:ys,isUnsupportedBinary:Rt,onDownload:s.downloadFile&&h?nn:void 0,drawioViewMode:Jt,drawioRemountNonce:Ha,diagramEditorRef:Nr,diagramEditorXml:qa,onDiagramChange:Ka,jsonViewMode:kt,markdownViewMode:jt,htmlViewMode:yt,htmlLoading:js,htmlPreviewNonce:ws,htmlPreviewSrc:Rs,fileContent:ve,canUseShikiFileView:Qr,textViewMode:Ee,draftContent:at,onDraftChange:Se,canEdit:_e,vimMode:Ba==="vim",editorExtensions:xs,shouldMaskEditorForPendingNavigation:hs,pierreTheme:bs,shikiThemeType:d.metadata.variant==="dark"?"dark":"light",wrapLines:F},Dt=e.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[e.jsx(Bi,{open:Hr,onOpenChange:es,isSaving:_r,onSaveAndContinue:()=>{os()},onDiscardAndContinue:ss}),e.jsxs("div",{className:H("flex flex-col flex-shrink-0",V&&"border-b border-border/40"),children:[e.jsx(Pi,{showEditorTabsRow:V,isMobile:g,showMobilePageContent:T,onBackMobile:()=>S(!1),selectedFile:h,openFiles:gt,root:l,alwaysShowActions:C,editorTabsOverflow:ua,editorTabsScrollRef:Ut,onSelectFile:ze,onCloseFile:is}),(Or||g)&&h?e.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:[Qe&&!g?e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta text-muted-foreground",title:Qe,children:Qe}):null,e.jsx("div",{className:"ml-auto min-w-0 shrink-0 overflow-x-auto",children:tr({layout:"docked"})})]}):null]}),e.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[h&&!J&&!(Or||g)&&e.jsx("div",{ref:fe,className:"absolute right-3 top-3 z-30",onMouseLeave:()=>{je.current>0||xe(!1)},children:ge?tr():e.jsxs("div",{className:"flex items-center gap-1",children:[ot?e.jsxs(Le,{children:[e.jsx(Ie,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>Wr(Oe()==="preview"?"edit":"preview"),className:H("size-8 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-0 shadow-sm transition-colors",Oe()==="preview"?"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)] hover:bg-[var(--interactive-selection)]":"text-muted-foreground hover:text-foreground"),"aria-label":Oe()==="preview"?"Switch to edit mode":"Switch to preview mode",title:Oe()==="preview"?"Switch to edit mode":"Switch to preview mode",children:e.jsx(j,{name:Oe()==="preview"?"eye":"eye-off",className:"size-4"})})})}),e.jsx(Ve,{side:"bottom",sideOffset:6,children:Oe()==="preview"?"Switch to edit mode":"Switch to preview mode"})]}):null,e.jsxs(Le,{children:[e.jsx(Ie,{asChild:!0,children:e.jsx("span",{className:"inline-flex",onMouseEnter:()=>xe(!0),children:e.jsx(U,{variant:"ghost",size:"sm",onClick:()=>xe(!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:e.jsx(j,{name:"more-2-fill",className:"size-4"})})})}),e.jsx(Ve,{side:"bottom",sideOffset:6,children:"Editor controls"})]})]})}),e.jsx(Bn,{variant:"embedded",...an,enableRichPreviews:!0,editorWrapperRef:ga,onEditorViewReady:Fs,onEditorViewDestroy:Es,enableSearch:!0,searchOpen:J,onSearchOpenChange:Q})]})]}),sn=e.jsx($i,{root:l,isMobile:g,searchQuery:_,onSearchQueryChange:K,searchInputRef:W,searching:Ir,searchResults:Lr,selectedFile:h,onSelectFile:ze,onOpenDialog:Ta,currentDirectory:E,refreshRoot:la,childrenByDir:oe,loadErrorsByDir:le,expandedPaths:G,isBrowserClient:R,alwaysShowActions:C,getFileStatus:cs,getFolderBadge:ls,fileRowPermissions:ds,downloadFile:s.downloadFile,contextMenuPath:xa,setContextMenuPath:ba,rightClickMenuPath:va,setRightClickMenuPath:wa,toggleDirectory:us,handleRevealPath:Ia,refreshDirectory:ht}),Ts=t==="full"&&q&&h&&e.jsx("div",{className:"absolute inset-0 z-50 flex flex-col bg-background",children:e.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[e.jsx("div",{className:"absolute right-4 top-4 z-30",children:tr({exitFullscreenOnly:!0})}),e.jsx(Bn,{variant:"fullscreen",...an,enableRichPreviews:!1,onEditorViewReady:zs,onEditorViewDestroy:Ms})]})});return u?e.jsx(ai,{root:l,directory:D||l,entries:D||l?oe[D||l]:void 0,query:_,searchResults:Lr,isSearching:Ir,directoryError:D||l?le[D||l]??null:null,refreshing:M,editorPath:T?h?.path??null:null,editor:Dt,onClose:n,onQueryChange:K,onOpenDirectory:rs,onOpenFile:ns,onBackFromEditor:()=>S(!1),onRefresh:()=>{as()}}):e.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden bg-background relative",children:[e.jsx(oi,{activeDialog:Sa,dialogData:Ra,dialogInputValue:Fa,onDialogInputChange:Ea,isDialogSubmitting:za,onDialogSubmit:Aa,onClose:Da,inputRef:Ma}),Ts,g?T?Dt:sn:t==="editor-only"?e.jsx("div",{className:"flex flex-1 min-h-0 min-w-0 overflow-hidden",children:e.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden bg-background",children:Dt})}):e.jsxs("div",{className:"flex flex-1 min-h-0 min-w-0 gap-3 px-3 pb-3 pt-2",children:[m>=700&&e.jsx("div",{className:"w-72 flex-shrink-0 min-h-0 overflow-hidden",children:sn}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:Dt})]})]})};export{Ql as FilesView};