@pi-chamber/web 0.9.3 → 0.9.5

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 (92) hide show
  1. package/README.md +16 -1
  2. package/dist/assets/{DiagramEditor-DuGmiPZ5.js → DiagramEditor-BPDkGHsj.js} +1 -1
  3. package/dist/assets/DiagramView-D_EfDz2d.js +1 -0
  4. package/dist/assets/{DiffView-DVd1MLPB.js → DiffView-BmIVvheE.js} +2 -2
  5. package/dist/assets/FilesView-CJytSUAX.js +6 -0
  6. package/dist/assets/GitView-BNkzec7G.js +8 -0
  7. package/dist/assets/{JsonTreeView-Cyy0lEZR.js → JsonTreeView-C1Kzaybf.js} +1 -1
  8. package/dist/assets/MarkdownRendererImpl-qmKiFVpO.js +12 -0
  9. package/dist/assets/PatchDiff-D9JesZL1.js +1 -0
  10. package/dist/assets/{SessionSwitcherContent-dr3g9DR7.js → SessionSwitcherContent-DplV_ApH.js} +1 -1
  11. package/dist/assets/SessionSwitcherDropdown-DdgDKT6K.js +2 -0
  12. package/dist/assets/SessionUnreadDot-BdSDgvhC.js +1 -0
  13. package/dist/assets/SettingsView-z8uf0XyM.js +2 -0
  14. package/dist/assets/SettingsWindow-CPDmgNg2.js +1 -0
  15. package/dist/assets/ToolOutputDialog-DaF1xcM0.js +8 -0
  16. package/dist/assets/ToolPartDiffPreview-Di6Uo0Dt.js +1 -0
  17. package/dist/assets/{VirtualizedFileDiff-iqwryMNU.js → VirtualizedFileDiff-wqcrY0yr.js} +3 -3
  18. package/dist/assets/collapsible-DBQnXTNm.js +1 -0
  19. package/dist/assets/computeVirtualFileMetrics-Cr3jh0d6.js +3 -0
  20. package/dist/assets/contextFileOpenGuard-C_AOTYQD.js +1 -0
  21. package/dist/assets/gitStatusPredicates-BvPOjeOy.js +134 -0
  22. package/dist/assets/index-B8Wt2aN3.js +1 -0
  23. package/dist/assets/index-DIF8b4bh.css +1 -0
  24. package/dist/assets/index-jrfQYSvP.js +8 -0
  25. package/dist/assets/isDiffPlainText-L9uvgz2F.js +1 -0
  26. package/dist/assets/isFilePlainText-C4yk5BOo.js +1 -0
  27. package/dist/assets/main-C1OSzD-E.js +135 -0
  28. package/dist/assets/{main-DMyWi0qs.js → main-DCK6lLCo.js} +2 -2
  29. package/dist/assets/{markdownCore-BD5WkOKU.js → markdownCore-Czb_lINQ.js} +2 -2
  30. package/dist/assets/{miniChat-CLMNhna4.js → miniChat-CXiSlptL.js} +2 -2
  31. package/dist/assets/{mobile-rWMDwhtQ.js → mobile-D0HVxiyJ.js} +2 -2
  32. package/dist/assets/renderElectronMiniChatApp-BcG209a4.js +2 -0
  33. package/dist/assets/renderMobileApp-B5x_PWlc.js +11 -0
  34. package/dist/assets/runtimeEndpointReset-CUiPe6dQ.js +53 -0
  35. package/dist/assets/{runtimeSurface-CySRuLbN.js → runtimeSurface-vilE4xyj.js} +1 -1
  36. package/dist/assets/{useAppFontEffects-DfuJVB15.js → useAppFontEffects-BP07Vl6M.js} +102 -103
  37. package/dist/assets/useFilesViewSearch-oxIKk-ea.js +7 -0
  38. package/dist/assets/usePushVisibilityBeacon-CChMvoTL.js +10 -0
  39. package/dist/assets/useSwitcherItems-_RSo3F-A.js +1 -0
  40. package/dist/assets/{vendor-base-ui-vkqQ2P9o.js → vendor-base-ui-CdaWtC7e.js} +1 -1
  41. package/dist/assets/vendor-beautiful-mermaid-D3YCkKz7.js +111 -0
  42. package/dist/assets/{vendor-codemirror-commands-DYppkHEk.js → vendor-codemirror-commands-CNlncqrr.js} +1 -1
  43. package/dist/assets/{vendor-codemirror-language-data-CDdfwzlS.js → vendor-codemirror-language-data-BJrrV83E.js} +2 -2
  44. package/dist/assets/{vendor-replit-codemirror-vim-CGHHNQxC.js → vendor-replit-codemirror-vim-DaSwPsXt.js} +1 -1
  45. package/dist/assets/{web-components-C9wXMuCp.js → web-components-B5sMa_kC.js} +3 -3
  46. package/dist/index.html +4 -4
  47. package/dist/mini-chat.html +3 -3
  48. package/dist/mobile.html +3 -3
  49. package/package.json +2 -2
  50. package/server/lib/pi/routes.js +13 -3
  51. package/server/lib/pi/routes.test.js +55 -1
  52. package/server/lib/pi/session-daemon/DOCUMENTATION.md +17 -6
  53. package/server/lib/pi/session-daemon/prompt-operations.test.js +193 -0
  54. package/server/lib/pi/session-daemon/sdk-upgrade.test.js +157 -0
  55. package/server/lib/pi/session-daemon/session-daemon.js +418 -129
  56. package/server/lib/pi/session-daemon/session-daemon.test.js +186 -0
  57. package/server/lib/pi/session-daemon/session-idle-residency.test.js +742 -0
  58. package/server/lib/pi/session-daemon/session-replay.js +98 -0
  59. package/server/lib/pi/session-daemon/session-replay.test.js +626 -0
  60. package/server/lib/pi/ui-settings-store.js +16 -10
  61. package/server/lib/pi/ui-settings-store.test.js +91 -0
  62. package/server/lib/stt/DOCUMENTATION.md +1 -1
  63. package/server/lib/stt/local/worker-client.js +11 -3
  64. package/server/lib/stt/local/worker-client.test.js +255 -0
  65. package/dist/assets/DiagramView-CV-iReyY.js +0 -1
  66. package/dist/assets/FilesView-CPnW4I90.js +0 -6
  67. package/dist/assets/GitView-Dj_7hgX_.js +0 -8
  68. package/dist/assets/MarkdownRendererImpl-BXN78Wu_.js +0 -12
  69. package/dist/assets/PatchDiff-C7dA3U29.js +0 -1
  70. package/dist/assets/SessionSwitcherDropdown-C3zdd82V.js +0 -2
  71. package/dist/assets/SessionUnreadDot-qeik5qtT.js +0 -1
  72. package/dist/assets/SettingsView-C57uV1YS.js +0 -2
  73. package/dist/assets/SettingsWindow-Bbay2W76.js +0 -1
  74. package/dist/assets/ToolOutputDialog-CRTiN1CH.js +0 -8
  75. package/dist/assets/ToolPartDiffPreview-CqnNcLPk.js +0 -1
  76. package/dist/assets/collapsible-szfZ0Syc.js +0 -1
  77. package/dist/assets/computeVirtualFileMetrics-Bbugxxtp.js +0 -3
  78. package/dist/assets/contextFileOpenGuard-BC3ie230.js +0 -1
  79. package/dist/assets/gitStatusPredicates-DbThKVSf.js +0 -134
  80. package/dist/assets/index-DNoEeZ2U.css +0 -1
  81. package/dist/assets/index-KIdiBFJs.js +0 -8
  82. package/dist/assets/index-v6K3L94m.js +0 -1
  83. package/dist/assets/isDiffPlainText-Dl0RBjPZ.js +0 -1
  84. package/dist/assets/isFilePlainText-CbrmvrM6.js +0 -1
  85. package/dist/assets/main-4PkIvzf4.js +0 -135
  86. package/dist/assets/renderElectronMiniChatApp-BRhGNRJ8.js +0 -2
  87. package/dist/assets/renderMobileApp-DLy2YoQg.js +0 -11
  88. package/dist/assets/runtimeEndpointReset-Z9YtcHxZ.js +0 -54
  89. package/dist/assets/useFilesViewSearch-BZBHrZ90.js +0 -7
  90. package/dist/assets/usePushVisibilityBeacon-BxTkEajM.js +0 -10
  91. package/dist/assets/useSwitcherItems-jITqE8PV.js +0 -1
  92. package/dist/assets/vendor-beautiful-mermaid-DneUawHp.js +0 -119
package/README.md CHANGED
@@ -39,12 +39,27 @@ tunnels, logs, pairing, and machine-readable output.
39
39
 
40
40
  - Pi session state and actions are served only through `/api/pi/*`. Session detail responses carry a bounded transcript tail; older history is available from `GET /api/pi/sessions/:sessionId/messages` with the opaque before-cursor returned by the previous page.
41
41
  - `POST /api/pi/attachments` accepts raw `application/octet-stream` bodies with bounded `X-PiChamber-Filename` and `X-PiChamber-Mime` metadata. It returns opaque attachment metadata plus `expiresAt`; filesystem paths remain private. The legacy base64 JSON body remains available for persisted clients. `DELETE /api/pi/attachments/:id` removes an unused upload. Prompt routes accept at most 20 attachment IDs and retire accepted uploads from the active 32-upload map while retaining their files until the one-hour expiry.
42
- - PiChamber-owned UI settings, snippets, custom themes, and updates use `/api/pi/ui-settings`, `/api/pi/snippets`, `/api/pi/themes`, `/api/pi/update-check`, and `/api/pi/update-install`. The settings route merges portable preferences from `settings.json` with host and device values from `runtime-state.json`; writes split fields through explicit allowlists. A flat legacy file migrates on first access. A scoped portable file never contributes paths, project registrations, device values, or secrets. Removed `/api/config/*` and `/api/pichamber/*` aliases are not required. Snippets persist in the PiChamber data root (`snippets.json`) and expand through literal `#name` replacement; Pi prompt templates remain Pi-owned `/name` commands in Pi's global and trusted-project prompt directories, discovered through the active runtime's resource loader and exposed through `/api/pi/resources`, `/api/pi/resources/prompts`, and `/api/pi/commands`. Pi skills invoke as `/skill:name` (bare `/name` never invokes a skill) and extension commands use their registered `/name` (including Pi-generated suffixes); `/api/pi/commands` exposes prompts as `name`, skills as `skill:name`, and extensions under their invocation names, executed via Pi's `session.prompt()` with extension-first precedence. Snippet, prompt-template, skill, and extension-command concepts stay distinct with separate Settings pages, stores, persistence, and caches; they share only `/` autocomplete presentation. New-session starters are pinned Pi prompt templates that insert `/name ` for editing (never submit or expand in PiChamber); legacy skill starters are removed without conversion.
42
+ - PiChamber-owned UI settings, snippets, custom themes, and updates use `/api/pi/ui-settings`, `/api/pi/snippets`, `/api/pi/themes`, `/api/pi/update-check`, and `/api/pi/update-install`. The settings route merges portable preferences from `settings.json` with host and device values from `runtime-state.json`; writes split fields through explicit allowlists. Pi-owned resource, trust, and provider-catalog changes are saved without interrupting active sessions and report deferred runtime activation when an idle edge is required. A flat legacy file migrates on first access. A scoped portable file never contributes paths, project registrations, device values, or secrets. Removed `/api/config/*` and `/api/pichamber/*` aliases are not required. Snippets persist in the PiChamber data root (`snippets.json`) and expand through literal `#name` replacement; Pi prompt templates remain Pi-owned `/name` commands in Pi's global and trusted-project prompt directories, discovered through the active runtime's resource loader and exposed through `/api/pi/resources`, `/api/pi/resources/prompts`, and `/api/pi/commands`. Pi skills invoke as `/skill:name` (bare `/name` never invokes a skill) and extension commands use their registered `/name` (including Pi-generated suffixes); `/api/pi/commands` exposes prompts as `name`, skills as `skill:name`, and extensions under their invocation names, executed via Pi's `session.prompt()` with extension-first precedence. Snippet, prompt-template, skill, and extension-command concepts stay distinct with separate Settings pages, stores, persistence, and caches; they share only `/` autocomplete presentation. New-session starters are pinned Pi prompt templates that insert `/name ` for editing (never submit or expand in PiChamber); legacy skill starters are removed without conversion.
43
43
  - Final-only speech-to-text uses authenticated `/api/stt/*` routes and `/api/stt/ws`. Local model inference runs in a forked worker, while remote provider credentials remain in server configuration.
44
44
  - Browser and paired clients authenticate with UI sessions or scoped client credentials.
45
45
  - `connect-url` creates a one-time pairing link; credentials are not written to URLs or logs.
46
46
  - The server owns its per-profile Pi daemon lifecycle (installed web, development web, and desktop use separate namespaces) and stops only its own daemon during shutdown.
47
47
 
48
+ ## SDK updates
49
+
50
+ This release pins Pi SDK `0.85.1`, including an updated bundled OpenCode model
51
+ catalog. Existing Pi sessions, credentials, settings, and custom models stay in
52
+ place; no manual migration or cache deletion is needed. Custom model additions
53
+ and overrides still apply to the updated catalog. If a saved default points to a
54
+ removed model, select an available replacement; the upgrade does not rewrite
55
+ your saved defaults or chat history.
56
+
57
+ Restart the PiChamber server after updating. The normal update command restarts
58
+ managed background instances; foreground instances must be stopped and started
59
+ manually. Desktop users must relaunch the updated app. Hosted and mobile clients
60
+ use their connected server's SDK, so updating only the client does not update its
61
+ model catalog.
62
+
48
63
  ## Development
49
64
 
50
65
  ```bash
@@ -1 +1 @@
1
- import{R as e,j as h}from"./vendor-react-B5Z1Mdn3.js";import{D as E}from"./vendor-react-drawio-BYDptOsj.js";import{c as x}from"./index-KIdiBFJs.js";const D='<mxfile><diagram id="new" name="Page-1"><mxGraphModel dx="0" dy="0" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0"><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel></diagram></mxfile>';function g(){if(typeof document>"u")return!1;const o=document.documentElement.getAttribute("data-theme");return o==="dark"||!o&&window.matchMedia("(prefers-color-scheme: dark)").matches}const X=e.forwardRef(function({xml:t,readOnly:a,className:R,onChange:c},v){const s=e.useRef(t),i=e.useRef(null),m=e.useRef(!1),[n,k]=e.useState(g),u=e.useRef(t),d=e.useRef(t);d.current!==t&&(d.current=t,u.current=t,s.current=t);const f=e.useRef(n);f.current!==n&&(f.current=n,u.current=s.current);const l=e.useRef(null);e.useEffect(()=>{const r=()=>k(g());r();const p=new MutationObserver(r);return p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>p.disconnect()},[]),e.useEffect(()=>{const r=setTimeout(()=>{l.current?.querySelector(".diagrams-iframe")?.focus()},600);return()=>clearTimeout(r)},[]),e.useImperativeHandle(v,()=>({getXml:()=>s.current}));const b=e.useCallback(()=>{!t&&!m.current&&(m.current=!0,setTimeout(()=>{i.current?.template({})},500))},[t]),w=e.useCallback(r=>{s.current=r.xml,c?.(r.xml)},[c]);return h.jsx("div",{ref:l,className:x("h-full w-full",R),children:h.jsx(E,{ref:i,xml:u.current||D,autosave:!0,urlParameters:{ui:a?"simple":n?"dark":"kennedy",spin:!0,libraries:!a,chrome:a,nav:a,layers:a,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:b,onAutoSave:w},n?"dark":"light")})});export{X as D};
1
+ import{R as e,j as h}from"./vendor-react-B5Z1Mdn3.js";import{D as E}from"./vendor-react-drawio-BYDptOsj.js";import{m as x}from"./index-jrfQYSvP.js";const D='<mxfile><diagram id="new" name="Page-1"><mxGraphModel dx="0" dy="0" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0"><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel></diagram></mxfile>';function g(){if(typeof document>"u")return!1;const o=document.documentElement.getAttribute("data-theme");return o==="dark"||!o&&window.matchMedia("(prefers-color-scheme: dark)").matches}const X=e.forwardRef(function({xml:t,readOnly:a,className:R,onChange:c},v){const s=e.useRef(t),i=e.useRef(null),m=e.useRef(!1),[n,k]=e.useState(g),u=e.useRef(t),d=e.useRef(t);d.current!==t&&(d.current=t,u.current=t,s.current=t);const f=e.useRef(n);f.current!==n&&(f.current=n,u.current=s.current);const l=e.useRef(null);e.useEffect(()=>{const r=()=>k(g());r();const p=new MutationObserver(r);return p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>p.disconnect()},[]),e.useEffect(()=>{const r=setTimeout(()=>{l.current?.querySelector(".diagrams-iframe")?.focus()},600);return()=>clearTimeout(r)},[]),e.useImperativeHandle(v,()=>({getXml:()=>s.current}));const b=e.useCallback(()=>{!t&&!m.current&&(m.current=!0,setTimeout(()=>{i.current?.template({})},500))},[t]),w=e.useCallback(r=>{s.current=r.xml,c?.(r.xml)},[c]);return h.jsx("div",{ref:l,className:x("h-full w-full",R),children:h.jsx(E,{ref:i,xml:u.current||D,autosave:!0,urlParameters:{ui:a?"simple":n?"dark":"kennedy",spin:!0,libraries:!a,chrome:a,nav:a,layers:a,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:b,onAutoSave:w},n?"dark":"light")})});export{X as D};
@@ -0,0 +1 @@
1
+ import{R as r,j as t}from"./vendor-react-B5Z1Mdn3.js";import{u as a}from"./index-jrfQYSvP.js";import{a9 as v,I as m}from"./useAppFontEffects-BP07Vl6M.js";import{D as j}from"./DiagramEditor-BPDkGHsj.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-CdaWtC7e.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-vilE4xyj.js";import"./vendor-dnd-kit-core-C9qcAm_1.js";import"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-dnd-kit-sortable-D8ozj8M-.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-BJrrV83E.js";import"./vendor-codemirror-lang-python-DzzokVau.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-CNlncqrr.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"./vendor-react-drawio-BYDptOsj.js";function Kt(){const{files:o}=v(),[e,d]=r.useState(null),[s,p]=r.useState(""),[x,n]=r.useState(!0),l=r.useRef(null),c=a(i=>i.pendingDiagramFile),u=r.useCallback(async i=>{n(!0),d(i);try{const f=await o?.readFile?.(i);f&&p(f.content)}catch{p("")}finally{n(!1)}},[o]);r.useEffect(()=>{if(!c)return;const i=a.getState().consumePendingDiagramFile();i&&u(i)},[u,c]);const g=r.useCallback(async()=>{const i=l.current?.getXml();e&&o?.writeFile&&i&&i!==s&&(await o.writeFile(e,i),p(i))},[e,o,s]),h=e?e.split("/").pop()||e:"";return e?x?t.jsx("div",{className:"flex h-full items-center justify-center p-3",children:t.jsx(m,{name:"loader-4",className:"size-4 animate-spin"})}):t.jsxs("div",{className:"flex h-full flex-col",children:[t.jsxs("div",{className:"flex items-center gap-2 border-b border-border/30 px-3 py-1.5",children:[t.jsx(m,{name:"file",className:"size-4 shrink-0 text-muted-foreground"}),t.jsx("span",{className:"typography-ui text-muted-foreground truncate flex-1",children:h}),t.jsx("button",{type:"button",onClick:()=>{g()},className:"size-6 flex items-center justify-center rounded-md text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:"Save diagram",children:t.jsx(m,{name:"save-3",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>a.getState().setActiveMainTab("chat"),className:"size-6 flex items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:"Close diagram view",children:t.jsx(m,{name:"close",className:"size-4"})})]}),t.jsx("div",{className:"flex-1 min-h-0",children:t.jsx(j,{ref:l,xml:s,className:"h-full"})})]}):t.jsx("div",{className:"flex h-full items-center justify-center p-3",children:t.jsx("div",{className:"typography-ui text-muted-foreground",children:"Pick a file from the tree."})})}export{Kt as DiagramView};
@@ -1,4 +1,4 @@
1
- import{j as n,R as r,b as St}from"./vendor-react-B5Z1Mdn3.js";import{c as te,u as J,h as Ze,n as ze}from"./index-KIdiBFJs.js";import{b3 as vt,b4 as Ct,am as jt,as as et,b5 as tt,aT as Nt,p as Ne,a4 as Le,I as q,j as nt,a0 as re,t as st,aW as it,aE as Lt,b6 as Dt,b7 as kt,aF as Rt,b8 as Et,b9 as At,ba as Tt,bb as Mt,k as It,bc as $t,bd as Pt,S as _t,U as Wt,V as Bt}from"./useAppFontEffects-DfuJVB15.js";import{d as rt,P as Ot,i as Ge,a as He,b as zt,C as Gt}from"./gitStatusPredicates-DbThKVSf.js";import{p as Ht}from"./VirtualizedFileDiff-iqwryMNU.js";import{v as Ut,g as Vt}from"./contextFileOpenGuard-BC3ie230.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-CySRuLbN.js";import"./vendor-dnd-kit-core-C9qcAm_1.js";import"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-dnd-kit-sortable-D8ozj8M-.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-CDdfwzlS.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-C9wXMuCp.js";import"./computeVirtualFileMetrics-Bbugxxtp.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-Z9YtcHxZ.js";import"./SessionUnreadDot-qeik5qtT.js";import"./vendor-xterm-xterm-CrXqRur4.js";import"./permissionStore-iKN1K2_x.js";import"./appThemeRegistry-gegrE2dq.js";import"./registerCustomTheme-DmolaWWZ.js";import"./isDiffPlainText-Dl0RBjPZ.js";import"./vendor-diff-C3JhlQdm.js";function Kt(t,s=10){const e=[];let i;for(const l of t.split(`
1
+ import{j as n,R as r,b as St}from"./vendor-react-B5Z1Mdn3.js";import{m as te,u as J,a as Ze,y as ze}from"./index-jrfQYSvP.js";import{du as vt,dn as Ct,ds as jt,ad as et,$ as tt,c7 as Nt,c8 as Ne,B as Le,I as q,a9 as nt,aw as re,t as st,cx as it,c1 as Lt,dv as Dt,dw as kt,aa as Rt,Y as Et,as as At,ab as Tt,cr as Mt,f as It,an as $t,aE as Pt,a1 as _t,a2 as Wt,a4 as Bt}from"./useAppFontEffects-BP07Vl6M.js";import{d as rt,P as Ot,i as Ge,a as He,b as zt,C as Gt}from"./gitStatusPredicates-BvPOjeOy.js";import{p as Ht}from"./VirtualizedFileDiff-wqcrY0yr.js";import{v as Ut,g as Vt}from"./contextFileOpenGuard-C_AOTYQD.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-CdaWtC7e.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-vilE4xyj.js";import"./vendor-dnd-kit-core-C9qcAm_1.js";import"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-dnd-kit-sortable-D8ozj8M-.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-BJrrV83E.js";import"./vendor-codemirror-lang-python-DzzokVau.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-CNlncqrr.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-B5sMa_kC.js";import"./computeVirtualFileMetrics-Cr3jh0d6.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-CUiPe6dQ.js";import"./SessionUnreadDot-BdSDgvhC.js";import"./vendor-xterm-xterm-CrXqRur4.js";import"./permissionStore-iKN1K2_x.js";import"./appThemeRegistry-gegrE2dq.js";import"./registerCustomTheme-DmolaWWZ.js";import"./isDiffPlainText-L9uvgz2F.js";import"./vendor-diff-C3JhlQdm.js";function Kt(t,s=10){const e=[];let i;for(const l of t.split(`
2
2
  `)){const p=l.match(vt);if(p!=null){i!=null&&(i.hunkLines.length>0&&(Re(i,s,"trailing"),Ie(i,e)),i=void 0);const u=parseInt(p[3]),b=parseInt(p[1]),h=parseInt(p[4]??"1"),c=parseInt(p[2]??"1");isNaN(u)||isNaN(b)||isNaN(h)||isNaN(c)?e.push(l):i={additionStart:u,deletionStart:b,additionCount:0,deletionCount:0,hunkLines:[],contextLines:[]};continue}if(i==null){e.push(l);continue}if(l.startsWith(" "))i.contextLines.push(l);else if(l!==""){if(i.hunkLines.length>0&&i.contextLines.length>s*2){const u=i.contextLines.length-s*2,b=i.contextLines.slice(-s);Re(i,s,"trailing");const{additionCount:h,deletionCount:c}=i;Ie(i,e),i={additionStart:i.additionStart+h+u,deletionStart:i.deletionStart+c+u,deletionCount:0,additionCount:0,contextLines:b,hunkLines:[]}}Re(i,s,i.hunkLines.length===0?"leading":"before-change"),i.hunkLines.push(l),l.startsWith("+")?i.additionCount+=1:l.startsWith("-")&&(i.deletionCount+=1)}}i!=null&&i.hunkLines.length>0&&(Re(i,s,"trailing"),Ie(i,e));const a=e.join(`
3
3
  `);return t.endsWith(`
4
4
  `)?`${a}
@@ -14,5 +14,5 @@ ${s}`,Qt=t=>{if(!t.startsWith("diff --git ")&&!/^--- [^\n]*\t?\r?\n\+\+\+ [^\n]*
14
14
  new file mode `)?"added":u.includes(`
15
15
  deleted file mode `)?"deleted":u.includes(`
16
16
  rename from `)?"renamed":"modified";let h=0,c=0;for(const m of u.split(`
17
- `))m.startsWith("+")&&!m.startsWith("+++")&&(h+=1),m.startsWith("-")&&!m.startsWith("---")&&(c+=1);return[{file:b==="deleted"?l:p,status:b,additions:h,deletions:c,patch:u}]}),mn=t=>t==="added"?"A":t==="deleted"?"D":"M";function hn({activeDiffScope:t,effectiveDirectory:s,branchBase:e,branchHead:i,git:a,sessionMessageRecords:l}){const[p,u]=r.useState([]),[b,h]=r.useState(null),[c,m]=r.useState(!1),F=r.useMemo(()=>{const C=Dt(l,{showTextJustificationActivity:!1,showTurnChangedFiles:!0,mergeHiddenUserTurns:!0});for(let g=C.turns.length-1;g>=0;g-=1){const d=C.turns[g];if(!d)continue;const _=d.activityParts.map(S=>S.part).filter(S=>S.type==="tool"),R=kt(_);if(R.length>0)return R.map(S=>({file:S.path,status:"modified",additions:S.additions,deletions:S.deletions,patch:S.patch}));const X=fn(d.userMessage.info?.summary?.diffs);if(X.length>0)return X}return[]},[l]);r.useEffect(()=>{if(t!=="branch"||!s||!e||!i||!a.getGitRangeDiff){u([]),h(null),m(!1);return}let C=!1;return m(!0),h(null),a.getGitRangeDiff(s,{base:e,head:i,contextLines:at}).then(g=>{C||(u(pn(g.diff??"")),m(!1))}).catch(g=>{C||(u([]),m(!1),h(g instanceof Error?g.message:String(g)))}),()=>{C=!0}},[t,e,i,s,a]);const k=r.useMemo(()=>{const C=new Map;for(const g of F)if(g.file){if(typeof g.patch=="string"){C.set(g.file,Pe(g.file,g.patch,"patch"));continue}C.set(g.file,{original:g.before??"",modified:g.after??"",contextMode:"full"})}return C},[F]),x=r.useMemo(()=>{const C=new Map;for(const g of p)!g.file||typeof g.patch!="string"||C.set(g.file,Pe(g.file,g.patch,"patch"));return C},[p]);return{branchDiffs:p,branchDiffError:b,branchDiffLoading:c,lastTurnDiffs:F,lastTurnDiffData:k,branchDiffData:x}}const Je=(t,s)=>{if(s.length===0)return null;let e=null,i=null;for(const l of s)l.top<=t?(!e||l.top>e.top)&&(e=l):(!i||l.top<i.top)&&(i=l);const a=e??i;return a?{path:a.path,topOffset:a.top-t}:null},gn=(t,s,e,i)=>Math.min(Math.max(0,i),Math.max(0,t+e-s));function xn({pinSelectedFileHeaderToTopOnNavigate:t,scrollRequestNonce:s,changedFiles:e,expandedFiles:i,setMountedStackedFiles:a,fileDiffRefreshNonce:l}){const p=r.useRef(null),u=r.useRef(new Map),[b,h]=r.useState(null),c=r.useRef(null),m=r.useRef(null),F=r.useRef(!1),k=r.useRef(null),x=r.useRef(null),C=r.useRef(null),g=r.useCallback(()=>{const y=p.current;if(!y)return null;const w=y.getBoundingClientRect().top,j=[];for(const[A,E]of u.current)E&&j.push({path:A,top:E.getBoundingClientRect().top});return Je(w,j)},[]),d=r.useCallback(()=>{c.current=null,F.current=!1,h(null),m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null)},[]),_=r.useCallback(()=>{k.current=null;const y=p.current;if(!y)return;const w=y.getBoundingClientRect(),j=w.top-Xe,A=w.bottom+Xe,E={},z=[];for(const[N,I]of u.current){if(!I)continue;const W=I.getBoundingClientRect();z.push({path:N,top:W.top}),i.has(N)&&(W.bottom<j||W.top>A||(E[N]=!0))}x.current=Je(w.top,z),a(N=>{let I=!1;const W=new Set(N);for(const ne of Object.keys(E))W.has(ne)||(W.add(ne),I=!0);return I?W:N})},[i,a]),R=r.useCallback(()=>{typeof window>"u"||k.current===null&&(k.current=window.requestAnimationFrame(_))},[_]);r.useEffect(()=>{const y=p.current;if(y)return R(),y.addEventListener("scroll",R,{passive:!0}),window.addEventListener("resize",R),()=>{y.removeEventListener("scroll",R),window.removeEventListener("resize",R),k.current!==null&&(window.cancelAnimationFrame(k.current),k.current=null)}},[e,i,R]),r.useLayoutEffect(()=>{const y=C.current;if(!y)return;C.current=null;const w=p.current,j=u.current.get(y.path);if(!w||!j)return;const A=w.getBoundingClientRect().top,E=j.getBoundingClientRect().top-A;w.scrollTop=gn(w.scrollTop,y.topOffset,E,w.scrollHeight-w.clientHeight),x.current=y},[l]);const X=r.useCallback((y,w)=>{const j=u.current;w?j.set(y,w):j.delete(y),R()},[R]),S=r.useCallback(y=>{const w=u.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 r.useEffect(()=>{if(!c.current)return;let w=0;const j=20;let A=!1;const E=(N=!0)=>{A||(A=!0,c.current=null,F.current=!1,N&&h(null),m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null))},z=()=>{if(A){m.current=null;return}const N=c.current;if(!N){E(),m.current=null;return}if(!S(N)){w+=1,w<j?m.current=window.requestAnimationFrame(z):(E(),m.current=null);return}if(t&&F.current){h(N),E(!1);return}E()};return m.current=window.requestAnimationFrame(z),()=>{A=!0,m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null)}},[t,s,S]),{diffScrollRef:p,fileSectionRefs:u,pinnedStackedTarget:b,pendingScrollTargetRef:c,shouldPinAfterAlignRef:F,pendingScrollAnchorRestoreRef:C,lastScrollAnchorRef:x,captureScrollAnchor:g,cancelPendingScrollAlignment:d,queueVisibleStackedFilesSync:R,registerSectionRef:X,scrollToFile:S}}const Qe=t=>{if(!t)return null;const s=t.split(`
17
+ `))m.startsWith("+")&&!m.startsWith("+++")&&(h+=1),m.startsWith("-")&&!m.startsWith("---")&&(c+=1);return[{file:b==="deleted"?l:p,status:b,additions:h,deletions:c,patch:u}]}),mn=t=>t==="added"?"A":t==="deleted"?"D":"M";function hn({activeDiffScope:t,effectiveDirectory:s,branchBase:e,branchHead:i,git:a,sessionMessageRecords:l}){const[p,u]=r.useState([]),[b,h]=r.useState(null),[c,m]=r.useState(!1),F=r.useMemo(()=>{const C=Dt(l,{showTextJustificationActivity:!1,mergeHiddenUserTurns:!0});for(let g=C.turns.length-1;g>=0;g-=1){const d=C.turns[g];if(!d)continue;const _=d.activityParts.map(S=>S.part).filter(S=>S.type==="tool"),R=kt(_);if(R.length>0)return R.map(S=>({file:S.path,status:"modified",additions:S.additions,deletions:S.deletions,patch:S.patch}));const X=fn(d.userMessage.info?.summary?.diffs);if(X.length>0)return X}return[]},[l]);r.useEffect(()=>{if(t!=="branch"||!s||!e||!i||!a.getGitRangeDiff){u([]),h(null),m(!1);return}let C=!1;return m(!0),h(null),a.getGitRangeDiff(s,{base:e,head:i,contextLines:at}).then(g=>{C||(u(pn(g.diff??"")),m(!1))}).catch(g=>{C||(u([]),m(!1),h(g instanceof Error?g.message:String(g)))}),()=>{C=!0}},[t,e,i,s,a]);const k=r.useMemo(()=>{const C=new Map;for(const g of F)if(g.file){if(typeof g.patch=="string"){C.set(g.file,Pe(g.file,g.patch,"patch"));continue}C.set(g.file,{original:g.before??"",modified:g.after??"",contextMode:"full"})}return C},[F]),x=r.useMemo(()=>{const C=new Map;for(const g of p)!g.file||typeof g.patch!="string"||C.set(g.file,Pe(g.file,g.patch,"patch"));return C},[p]);return{branchDiffs:p,branchDiffError:b,branchDiffLoading:c,lastTurnDiffs:F,lastTurnDiffData:k,branchDiffData:x}}const Je=(t,s)=>{if(s.length===0)return null;let e=null,i=null;for(const l of s)l.top<=t?(!e||l.top>e.top)&&(e=l):(!i||l.top<i.top)&&(i=l);const a=e??i;return a?{path:a.path,topOffset:a.top-t}:null},gn=(t,s,e,i)=>Math.min(Math.max(0,i),Math.max(0,t+e-s));function xn({pinSelectedFileHeaderToTopOnNavigate:t,scrollRequestNonce:s,changedFiles:e,expandedFiles:i,setMountedStackedFiles:a,fileDiffRefreshNonce:l}){const p=r.useRef(null),u=r.useRef(new Map),[b,h]=r.useState(null),c=r.useRef(null),m=r.useRef(null),F=r.useRef(!1),k=r.useRef(null),x=r.useRef(null),C=r.useRef(null),g=r.useCallback(()=>{const y=p.current;if(!y)return null;const w=y.getBoundingClientRect().top,j=[];for(const[A,E]of u.current)E&&j.push({path:A,top:E.getBoundingClientRect().top});return Je(w,j)},[]),d=r.useCallback(()=>{c.current=null,F.current=!1,h(null),m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null)},[]),_=r.useCallback(()=>{k.current=null;const y=p.current;if(!y)return;const w=y.getBoundingClientRect(),j=w.top-Xe,A=w.bottom+Xe,E={},z=[];for(const[N,I]of u.current){if(!I)continue;const W=I.getBoundingClientRect();z.push({path:N,top:W.top}),i.has(N)&&(W.bottom<j||W.top>A||(E[N]=!0))}x.current=Je(w.top,z),a(N=>{let I=!1;const W=new Set(N);for(const ne of Object.keys(E))W.has(ne)||(W.add(ne),I=!0);return I?W:N})},[i,a]),R=r.useCallback(()=>{typeof window>"u"||k.current===null&&(k.current=window.requestAnimationFrame(_))},[_]);r.useEffect(()=>{const y=p.current;if(y)return R(),y.addEventListener("scroll",R,{passive:!0}),window.addEventListener("resize",R),()=>{y.removeEventListener("scroll",R),window.removeEventListener("resize",R),k.current!==null&&(window.cancelAnimationFrame(k.current),k.current=null)}},[e,i,R]),r.useLayoutEffect(()=>{const y=C.current;if(!y)return;C.current=null;const w=p.current,j=u.current.get(y.path);if(!w||!j)return;const A=w.getBoundingClientRect().top,E=j.getBoundingClientRect().top-A;w.scrollTop=gn(w.scrollTop,y.topOffset,E,w.scrollHeight-w.clientHeight),x.current=y},[l]);const X=r.useCallback((y,w)=>{const j=u.current;w?j.set(y,w):j.delete(y),R()},[R]),S=r.useCallback(y=>{const w=u.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 r.useEffect(()=>{if(!c.current)return;let w=0;const j=20;let A=!1;const E=(N=!0)=>{A||(A=!0,c.current=null,F.current=!1,N&&h(null),m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null))},z=()=>{if(A){m.current=null;return}const N=c.current;if(!N){E(),m.current=null;return}if(!S(N)){w+=1,w<j?m.current=window.requestAnimationFrame(z):(E(),m.current=null);return}if(t&&F.current){h(N),E(!1);return}E()};return m.current=window.requestAnimationFrame(z),()=>{A=!0,m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null)}},[t,s,S]),{diffScrollRef:p,fileSectionRefs:u,pinnedStackedTarget:b,pendingScrollTargetRef:c,shouldPinAfterAlignRef:F,pendingScrollAnchorRestoreRef:C,lastScrollAnchorRef:x,captureScrollAnchor:g,cancelPendingScrollAlignment:d,queueVisibleStackedFilesSync:R,registerSectionRef:X,scrollToFile:S}}const Qe=t=>{if(!t)return null;const s=t.split(`
18
18
  `);let e=null;for(const i of s){const a=i.match(/^@@\s*-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s*@@/);if(a){const l=Number.parseInt(a[1]??"",10);e=Number.isFinite(l)&&l>=1?l:null;continue}if(e!==null){if(i.startsWith(" ")){e+=1;continue}if(i.startsWith("+"))return e;if(i.startsWith("-"))return Math.max(1,e)}}return null};function bn({effectiveDirectory:t,activeDiffStaged:s,git:e,files:i,setDiff:a,openContextFileAtLine:l}){const[p,u]=r.useState(null),b=r.useCallback(async(h,c)=>{if(!t||!h)return;u(h);const m=Ze();try{let F=null;if(c?.patch&&!c.isBinary&&!Ne(h)?F=Qe(c.patch):c&&c.contextMode==="full"&&!c.isBinary&&!Ne(h)&&(F=Ye(c.original,c.modified)),F===null)try{const d=await e.getGitDiff(t,{path:h,staged:s,contextLines:3});F=Qe(d.diff)}catch{F=null}let k=c;if(F===null||!k){const d=await e.getGitFileDiff(t,{path:h,staged:s});k={original:d.original??"",modified:d.modified??"",isBinary:d.isBinary},s||a(t,h,k,m??void 0)}const x=F??(k.isBinary||Ne(h)?1:Ye(k.original,k.modified)),C=dn(t,h),g=await Ut(i,C,{directory:t});if(!g.ok){st.error(Vt(g.reason));return}l(t,C,x,1)}finally{u(F=>F===h?null:F)}},[s,t,i,e,l,a]);return{openingEditorFilePath:p,openFileInEditorAtChange:b}}function yn(t){const{hideStackedFileSidebar:s=!1,stackedDefaultCollapsedAll:e=!1,pinSelectedFileHeaderToTopOnNavigate:i=!1,diffScope:a="all",branchBase:l=null,branchHead:p=null,targetFilePath:u=null}=t,{git:b,files:h}=nt(),c=Rt(),{screenWidth:m,isMobile:F}=Et(),k=At(c??null),x=Tt(c??null),C=Mt(c??null),g=re(o=>o.setActiveDirectory),d=re(o=>o.ensureStatus),_=re(o=>o.fetchStatus),R=re(o=>o.clearDiffCache),X=re(o=>o.setDiff),[S,y]=r.useState(null),[w,j]=r.useState(!1),[A,E]=r.useState(()=>new Set),[z,N]=r.useState(()=>new Set),[I,W]=r.useState(!1),[ne,oe]=r.useState(0),[se,fe]=r.useState(()=>new Map),[T,$]=r.useState(a);r.useEffect(()=>{$(a)},[a]);const G=J(o=>o.pendingDiffFile),pe=J(o=>o.pendingDiffStaged),B=J(o=>o.pendingDiffScope),ae=J(o=>o.setPendingDiffFile),K=J(o=>o.diffLayoutPreference),U=J(o=>o.diffFileLayout),V=J(o=>o.setDiffFileLayout),me=J(o=>o.diffWrapLines),ve=J(o=>o.setDiffWrapLines),ie=J(o=>o.openContextFileAtLine),he=It(o=>o.currentSessionId),ge=$t(he??""),le=me,f=T==="staged"?!0:T==="working"?!1:null,P=f??w,Q=F||m<=768,xe=!s&&!Q&&m>=1024,ce=r.useRef(null),{branchDiffs:Z,branchDiffError:be,branchDiffLoading:H,lastTurnDiffs:O,lastTurnDiffData:De,branchDiffData:ee}=hn({activeDiffScope:T,effectiveDirectory:c,branchBase:l,branchHead:p,git:b,sessionMessageRecords:ge}),L=r.useMemo(()=>{if(T==="turn"||T==="branch")return(T==="branch"?Z:O).map(M=>({path:M.file??"",index:"",working_dir:mn(M.status),insertions:M.additions??0,deletions:M.deletions??0,isNew:M.status==="added"})).filter(M=>M.path).sort((M,Y)=>M.path.localeCompare(Y.path));if(!x?.files)return[];const o=x.diffStats??{},D=T==="staged"?Ge:T==="working"?He:()=>!0;return x.files.filter(D).map(v=>({...v,insertions:o[v.path]?.insertions??0,deletions:o[v.path]?.deletions??0,isNew:zt(v)})).sort((v,M)=>v.path.localeCompare(M.path))},[T,Z,O,x]),Ee=r.useMemo(()=>x?.files?x.files.filter(He).length:0,[x]),Ae=r.useMemo(()=>x?.files?x.files.filter(Ge).length:0,[x]),lt=O.length,ct=x?.files?.length??0,ut=Z.length,{diffScrollRef:dt,pinnedStackedTarget:ft,pendingScrollTargetRef:ye,shouldPinAfterAlignRef:we,pendingScrollAnchorRestoreRef:_e,lastScrollAnchorRef:We,captureScrollAnchor:Be,cancelPendingScrollAlignment:Fe,queueVisibleStackedFilesSync:ke,registerSectionRef:pt,scrollToFile:Oe}=xn({pinSelectedFileHeaderToTopOnNavigate:i,scrollRequestNonce:ne,changedFiles:L,expandedFiles:A,setMountedStackedFiles:N,fileDiffRefreshNonce:se}),Se=r.useCallback(o=>{E(D=>{if(D.has(o))return D;const v=new Set(D);return v.add(o),v})},[]),Te=r.useMemo(()=>L.map(o=>o.path).join("\0"),[L]);r.useEffect(()=>{const o=Te?Te.split("\0"):[],D=new Set(o),v=`${c??""}:${T}:${e?"collapsed":"default"}`,M=ce.current!==v;ce.current=v,E(Y=>{if(M){const ue=e?0:un(o.length);return new Set(o.slice(0,ue))}let Ce=!1;const je=new Set;for(const ue of Y){if(!D.has(ue)){Ce=!0;continue}je.add(ue)}return Ce?je:Y}),N(Y=>{if(M)return new Set;let Ce=!1;const je=new Set;for(const ue of Y){if(!D.has(ue)){Ce=!0;continue}je.add(ue)}return Ce?je:Y})},[T,Te,c,N,e]);const Me=r.useCallback(o=>{const D=U[o.path];if(D)return D;if(K==="inline")return"inline";if(K==="side-by-side")return"side-by-side";const v=m<cn;return o.isNew||v?"inline":"side-by-side"},[U,K,m]),mt=r.useMemo(()=>L.length===0?null:L.every(o=>Me(o)==="side-by-side")?"side-by-side":"inline",[L,Me]);r.useEffect(()=>{c&&(g(c),d(c,b))},[c,g,d,b]),r.useEffect(()=>{if(c)return Pt.onGitRefreshHint(o=>{ze(o.directory)===ze(c)&&(o.paths?.length&&(_e.current=Be()??We.current,R(c,o.paths),fe(D=>{const v=new Map(D);for(const M of o.paths??[])v.set(M,(v.get(M)??0)+1);return v})),_(c,b,{silent:!0}))})},[Be,R,c,_,b,We,_e]),r.useEffect(()=>{T!=="all"&&!B||G&&(B&&$(B),y(G),j(B==="staged"||!B&&pe),ae(null),we.current=!0,ye.current=G,Se(G),oe(o=>o+1))},[T,Se,G,B,pe,ye,ae,we]),r.useEffect(()=>{if(T==="all")return;const o=u?.trim();o&&(y(o),j(T==="staged"),we.current=!0,ye.current=o,Se(o),oe(D=>D+1))},[T,Se,ye,we,u]),r.useEffect(()=>{if(!S)return;L.some(D=>D.path===S)||(y(null),j(!1))},[L,S]);const ht=r.useCallback((o,D)=>{Fe(),E(v=>{const M=v.has(o);if(D===M)return v;const Y=new Set(v);return D?Y.add(o):Y.delete(o),Y}),D||N(v=>{if(!v.has(o))return v;const M=new Set(v);return M.delete(o),M}),ke()},[Fe,ke,N]),gt=r.useCallback(()=>{Fe(),E(o=>o.size>0?new Set:new Set(L.map(D=>D.path))),N(new Set),ke()},[Fe,L,ke,N]),xt=r.useCallback(o=>{},[]),bt=r.useCallback(o=>{Fe(),y(o),j(!1),we.current=!0,ye.current=o,Se(o),oe(D=>D+1),Oe(o)},[Fe,Se,ye,Oe,we]),yt=r.useCallback(o=>{const D=o==="side-by-side"?"side-by-side":"inline";L.forEach(v=>{V(v.path,D)})},[L,V]),{openingEditorFilePath:wt,openFileInEditorAtChange:Ft}=bn({effectiveDirectory:c,activeDiffStaged:P,git:b,files:h,setDiff:X,openContextFileAtLine:ie});return{git:b,files:h,effectiveDirectory:c,screenWidth:m,isMobile:F,isGitRepo:k,status:x,isLoadingStatus:C,activeDiffScope:T,setActiveDiffScope:$,branchDiffs:Z,branchDiffError:be,branchDiffLoading:H,diffWrapLines:le,setDiffWrapLines:ve,forcedStaged:f,displayFileStaged:w,displayFile:S,pinnedStackedTarget:ft,expandedFiles:A,mountedStackedFiles:z,loadFullFiles:I,setLoadFullFiles:W,fileDiffRefreshNonce:se,showFileSidebar:xe,diffScrollRef:dt,lastTurnDiffData:De,branchDiffData:ee,changedFiles:L,workingFileCount:Ee,stagedFileCount:Ae,turnFileCount:lt,allFileCount:ct,branchFileCount:ut,currentLayoutForAllFiles:mt,openingEditorFilePath:wt,registerSectionRef:pt,handleStackedEntryExpandedChange:ht,handleExpandOrCollapseAll:gt,handleSelectFile:xt,handleSelectFileAndScroll:bt,handleHeaderLayoutChange:yt,openFileInEditorAtChange:Ft,getLayoutForFile:Me}}const Di=({hideStackedFileSidebar:t=!1,stackedDefaultCollapsedAll:s=!1,pinSelectedFileHeaderToTopOnNavigate:e=!1,showOpenInEditorAction:i=!1,diffScope:a="all",onDiffScopeChange:l,branchBase:p=null,branchHead:u=null,targetFilePath:b=null,flushContent:h=!1,hideToolbar:c=!1,onHeaderControlsStateChange:m,toolbarSlot:F=null})=>{const{effectiveDirectory:k,isGitRepo:x,status:C,isLoadingStatus:g,activeDiffScope:d,setActiveDiffScope:_,branchDiffError:R,branchDiffLoading:X,diffWrapLines:S,setDiffWrapLines:y,forcedStaged:w,displayFileStaged:j,displayFile:A,pinnedStackedTarget:E,expandedFiles:z,mountedStackedFiles:N,loadFullFiles:I,setLoadFullFiles:W,fileDiffRefreshNonce:ne,showFileSidebar:oe,diffScrollRef:se,lastTurnDiffData:fe,branchDiffData:T,changedFiles:$,workingFileCount:G,stagedFileCount:pe,turnFileCount:B,allFileCount:ae,branchFileCount:K,currentLayoutForAllFiles:U,openingEditorFilePath:V,registerSectionRef:me,handleStackedEntryExpandedChange:ve,handleExpandOrCollapseAll:ie,handleSelectFile:he,handleSelectFileAndScroll:ge,handleHeaderLayoutChange:le,openFileInEditorAtChange:f,getLayoutForFile:P}=yn({hideStackedFileSidebar:t,stackedDefaultCollapsedAll:s,pinSelectedFileHeaderToTopOnNavigate:e,diffScope:a,branchBase:p,branchHead:u,targetFilePath:b});r.useEffect(()=>{c&&l?.(d)},[d,c,l]);const Q=r.useCallback(()=>{W(ee=>!ee)},[W]),xe=r.useCallback(()=>{y(!S)},[S,y]),ce=r.useCallback(()=>{le(U==="side-by-side"?"unified":"side-by-side")},[U,le]),Z=z.size,be=r.useMemo(()=>({turnCount:B,branchCount:K,expandedCount:Z,totalCount:$.length,loadFullFiles:I,wrapLines:S,layoutMode:U,onExpandOrCollapseAll:ie,onToggleLoadFullFiles:Q,onToggleWrapLines:xe,onToggleLayout:ce}),[B,K,Z,$.length,I,S,U,ie,Q,xe,ce]);r.useEffect(()=>{c&&m?.(be)},[c,be,m]);const H=()=>{if(!k)return null;const ee=L=>w!==null?w:j&&L===A;return n.jsxs("div",{className:te("flex min-w-0 flex-1 min-h-0 h-full",h?"gap-0":"gap-3 px-3 pb-3 pt-2"),children:[oe&&n.jsxs("section",{className:"hidden lg:flex w-72 flex-col rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/40",children:[n.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Files"}),n.jsx("span",{className:"typography-meta text-muted-foreground",children:$.length})]}),n.jsx(en,{changedFiles:$,selectedFile:null,onSelectFile:ge})]}),n.jsx("div",{className:"relative flex-1 min-w-0 min-h-0 h-full",children:n.jsx(et,{ref:se,outerClassName:"min-h-0 h-full",className:"[overflow-anchor:none] pb-16",disableHorizontal:!0,observeMutations:!1,preventOverscroll:!0,"data-diff-virtual-root":!0,children:n.jsx("div",{className:"flex flex-col [overflow-anchor:none]","data-diff-virtual-content":!0,children:$.map(L=>n.jsx(ln,{directory:k,file:L,layout:P(L),wrapLines:S,isSelected:!1,isExpanded:z.has(L.path),isMounted:N.has(L.path)||L.path===E,onSelect:he,onExpandedChange:ve,registerSectionRef:me,showOpenInEditorAction:i&&d!=="turn"&&d!=="branch",isOpeningInEditor:V===L.path,onOpenInEditor:(Ee,Ae)=>{f(Ee,Ae)},staged:ee(L.path),showFileActions:d!=="turn"&&d!=="branch",loadFullFiles:I,initialDiffData:d==="turn"?fe.get(L.path)??null:d==="branch"?T.get(L.path)??null:null},`${L.path}:${ne.get(L.path)??0}`))})})})]})},O=()=>k?d!=="turn"&&g&&!C?n.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[n.jsx(q,{name:"loader-4",className:"size-4 animate-spin"}),"Loading repository status..."]}):d!=="turn"&&d!=="branch"&&x===!1?n.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."}):d==="branch"&&X?n.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[n.jsx(q,{name:"loader-4",className:"size-4 animate-spin"}),"Loading branch changes..."]}):d==="branch"&&R?n.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: ${R}`}):$.length===0?n.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d==="turn"?"No last turn changes to display":"Working tree clean, no changes to display"}):H():n.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Select a session directory to view diffs"}),De=n.jsxs("div",{className:F?"flex min-w-0 flex-1 items-center gap-1.5":"@container/diff-toolbar flex min-w-0 items-center gap-2 px-3 py-2 bg-background",children:[(x!==!1||d==="turn")&&(d==="all"||d==="working"||d==="staged"||d==="turn"||d==="branch")?n.jsx(Gt,{scope:d,isGitRepo:x,branchAvailable:!!(p&&u),allCount:ae,workingCount:G,stagedCount:pe,turnCount:B,branchCount:K,onScopeChange:ee=>{_(ee),l?.(ee)}}):n.jsx("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:n.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:g&&!C?"Loading changes...":$.length===1?`${$.length} file changed`:`${$.length} files changed`})}),$.length>0&&n.jsxs(Le,{variant:"ghost",size:"sm",onClick:ie,className:te("diff-toolbar__expand-button h-7 flex-shrink-0 gap-1 px-1.5 text-muted-foreground hover:text-foreground","ml-auto"),title:z.size>0?"Collapse all":"Expand all",children:[n.jsx(q,{name:"expand-up-down",className:"size-4"}),n.jsx("span",{className:"diff-toolbar__expand-label typography-ui-label",children:z.size>0?"Collapse all":"Expand all"})]}),$.length>0&&d!=="turn"&&d!=="branch"&&n.jsxs(_t,{children:[n.jsx(Wt,{asChild:!0,children:n.jsx(Le,{variant:"ghost",size:"sm",onClick:()=>W(ee=>!ee),"aria-pressed":I,"aria-label":I?"Unload full files":"Load full files",className:te("h-7 w-7 flex-shrink-0 p-0 text-muted-foreground hover:text-foreground",I&&"bg-interactive-selection text-interactive-selection-foreground"),children:n.jsx(q,{name:"file-download",className:"size-4"})})}),n.jsx(Bt,{children:n.jsx("p",{children:I?"Unload full files":"Load full files"})})]}),$.length>0&&n.jsx(Le,{variant:"ghost",size:"sm",onClick:()=>y(!S),className:te("h-5 w-5 p-0 transition-opacity",S?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:S?"Disable line wrap":"Enable line wrap",children:n.jsx(q,{name:"text-wrap",className:"size-4"})}),U&&n.jsx(it,{mode:U==="side-by-side"?"side-by-side":"unified",onModeChange:le})]});return n.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[F?St.createPortal(De,F):c?null:De,O()]})};export{Di as DiffView};
@@ -0,0 +1,6 @@
1
+ import{j as t,R as o,b as As,r as C}from"./vendor-react-B5Z1Mdn3.js";import{m as H,C as Os,e as Ps,bK as Ls,A as Is,bL as Bs,u as ve,G as we,a as $s,w as Vs,H as Ws,bM as it,D as _s,F as qs,V as nn,bN as Ks,ao as an,r as sn,B as rr,aG as Us}from"./index-jrfQYSvP.js";import{c4 as Gs,I as S,ac as dt,c5 as Hs,$ as ct,ae as _n,af as qn,ag as Kn,ah as Un,ai as Gn,aj as Hn,B as G,a0 as mr,a3 as pr,a5 as hr,a6 as Lt,t as ie,a7 as It,a8 as Js,c6 as Bt,ad as Jn,E as on,aX as Ys,c7 as Yn,c8 as Xn,c9 as Qn,ca as Zn,cb as dr,cc as Xs,a1 as Ae,a2 as Oe,a4 as Pe,a9 as Qs,ak as Zs,Y as eo,aa as to,ab as ro,cd as cn,al as ln,aE as no,ce as ao,cf as so,cg as un}from"./useAppFontEffects-BP07Vl6M.js";import{E as ce,D as Wt,V as ea,s as oo,d as io,e as co,f as dn,k as nr,W as lo}from"./vendor-codemirror-view-Ct4T37Ue.js";import{H as fn,x as At,y as uo,i as fo,z as mo}from"./vendor-codemirror-language-BByA_dGF.js";import{a as c,c as po}from"./vendor-lezer-highlight-CDMHUZ74.js";import{i as ta,S as ho,k as gr,E as go,o as We,a as xo}from"./vendor-codemirror-state-CNWM3Q8V.js";import{ensurePierreThemeRegistered as mn,getResolvedShikiTheme as vo}from"./appThemeRegistry-gegrE2dq.js";import{D as bo}from"./DiagramEditor-BPDkGHsj.js";import{q as wo,t as yo,v as ko,w as jo,x as No,J as Ot}from"./runtimeEndpointReset-CUiPe6dQ.js";import{j as ra,h as fr,i as na}from"./SessionUnreadDot-BdSDgvhC.js";import{g as $t,c as aa,d as sa,e as xr,n as Co,f as So,M as lt,h as ae,j as Ro,s as Fo,i as Eo,a as zo,t as Pt,k as ar,b as Mo,l as To,u as Do,m as pn,o as Ao,p as hn}from"./useFilesViewSearch-oxIKk-ea.js";import{J as Oo,F as Po}from"./JsonTreeView-C1Kzaybf.js";import{h as Lo,k as Io,l as Bo,j as $o}from"./vendor-codemirror-commands-CNlncqrr.js";import{a as gn,g as Vt,b as xn,c as vn,o as Vo,d as Wo}from"./vendor-codemirror-search-BV44140v.js";import{v as _o,g as qo}from"./vendor-replit-codemirror-vim-DaSwPsXt.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-CdaWtC7e.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-vilE4xyj.js";import"./vendor-dnd-kit-core-C9qcAm_1.js";import"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-dnd-kit-sortable-D8ozj8M-.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-BJrrV83E.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"./vendor-xterm-xterm-CrXqRur4.js";import"./permissionStore-iKN1K2_x.js";import"./web-components-B5sMa_kC.js";import"./computeVirtualFileMetrics-Cr3jh0d6.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-C4yk5BOo.js";function bn(e,r){const n=e.metadata.variant==="dark",i=e.config?.fonts?.mono||"monospace",s=e.colors.syntax.highlights||{},l=e.colors.syntax.tokens||{},f=r?.fontSize?`${r.fontSize}px`:"var(--text-code)",m=ce.theme({"&":{backgroundColor:"var(--background)",color:e.colors.syntax.base.foreground,fontSize:f,lineHeight:"1.5",position:"relative"},".cm-scroller":{fontFamily:i,backgroundColor:"var(--background)"},".cm-comment":{color:e.colors.syntax.base.comment},".cm-keyword":{color:e.colors.syntax.base.keyword},".cm-string":{color:e.colors.syntax.base.string},".cm-string-2":{color:l.stringEscape||e.colors.syntax.base.string},".cm-number":{color:e.colors.syntax.base.number},".cm-operator":{color:e.colors.syntax.base.operator},".cm-punctuation":{color:l.punctuation||e.colors.syntax.base.comment},".cm-atom":{color:l.boolean||e.colors.syntax.base.number},".cm-builtin":{color:l.functionCall||e.colors.syntax.base.function},".cm-def":{color:l.variableGlobal||e.colors.syntax.base.variable},".cm-attribute":{color:l.variableOther||l.variableProperty||e.colors.syntax.base.operator},".cm-meta":{color:e.colors.syntax.base.comment},".cm-property":{color:l.variableProperty||e.colors.syntax.base.keyword},".cm-variable":{color:e.colors.syntax.base.variable},".cm-variable-2":{color:l.variableOther||e.colors.syntax.base.function},".cm-variable-3":{color:l.variableGlobal||e.colors.syntax.base.type},".cm-tag":{color:l.tag||e.colors.syntax.base.keyword},".cm-link":{color:l.url||e.colors.syntax.base.keyword,textDecoration:"underline"},".cm-content":{caretColor:e.colors.interactive.cursor},".cm-cursor, .cm-dropCursor":{borderLeftColor:e.colors.interactive.cursor},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:e.colors.interactive.selection},".cm-gutters":{backgroundColor:"var(--background)",color:s.lineNumber||e.colors.syntax.base.comment,borderRight:`1px solid ${e.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:s.lineNumberActive||e.colors.syntax.base.foreground},".cm-activeLine":{backgroundColor:e.colors.surface.overlay},".cm-panels":{backgroundColor:"transparent",color:e.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 ${e.colors.interactive.border}`,backgroundColor:e.colors.surface.elevated,color:e.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, ${e.colors.surface.elevated} 85%, transparent)`,border:`1px solid ${e.colors.interactive.border}`,borderRadius:"10px",boxShadow:`0 2px 8px color-mix(in srgb, ${e.colors.surface.background} 60%, transparent)`,width:"auto",minWidth:"360px",maxWidth:"480px"},".cm-search":{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"0",width:"100%",color:e.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 ${e.colors.interactive.border}`,backgroundColor:e.colors.surface.background,color:e.colors.surface.foreground,fontFamily:"inherit",fontSize:"12px",lineHeight:"1",outline:"none",transition:"border-color 150ms ease"},".cm-search .cm-textfield::placeholder":{color:e.colors.surface.mutedForeground,opacity:1},".cm-search .cm-textfield:focus":{borderColor:e.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:e.colors.interactive.hover},'.cm-search label:has(input[type="checkbox"]:checked)':{backgroundColor:e.colors.interactive.hover,borderColor:e.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:e.colors.surface.mutedForeground,pointerEvents:"none"},".cm-search label:hover::after":{color:e.colors.surface.foreground},'.cm-search label:has(input[type="checkbox"]:checked)::after':{color:e.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:e.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:e.colors.surface.mutedForeground,pointerEvents:"none"},".cm-search .cm-button:hover":{backgroundColor:e.colors.interactive.hover},".cm-search .cm-button:hover::after":{color:e.colors.surface.foreground},".cm-search .cm-button:active":{backgroundColor:e.colors.interactive.active},".cm-search .cm-button:focus-visible":{outline:"none",boxShadow:`0 0 0 1px ${e.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:e.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:e.colors.interactive.hover,color:e.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:e.colors.status.infoBackground,boxShadow:`inset 0 0 0 1px ${e.colors.status.infoBorder}`,borderRadius:"2px"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:e.colors.interactive.selection,color:e.colors.interactive.selectionForeground,boxShadow:`inset 0 0 0 1px ${e.colors.interactive.borderFocus}`},"&.cm-focused":{outline:"none"}},{dark:n}),h=fn.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"}]),w=fn.define([{tag:[c.comment,c.docComment,c.meta,c.documentMeta],color:e.colors.syntax.base.comment},{tag:[c.keyword,c.controlKeyword,c.moduleKeyword,c.definitionKeyword,c.modifier],color:e.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:e.colors.syntax.base.operator},{tag:[c.string,c.regexp,c.attributeValue,c.special(c.string),c.monospace],color:e.colors.syntax.base.string},{tag:c.escape,color:l.stringEscape||e.colors.syntax.base.string},{tag:[c.number,c.bool,c.atom,c.null,c.self],color:e.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:e.colors.syntax.base.function},{tag:c.definition(c.variableName),color:l.variableGlobal||e.colors.syntax.base.variable},{tag:[c.variableName,c.local(c.variableName),c.constant(c.variableName),c.literal],color:e.colors.syntax.base.variable},{tag:c.propertyName,color:l.variableProperty||e.colors.syntax.base.variable},{tag:c.attributeName,color:l.variableOther||e.colors.syntax.base.variable},{tag:[c.className,c.typeName,c.namespace],color:e.colors.syntax.base.type},{tag:[c.tagName,c.labelName,c.annotation,c.macroName],color:l.tag||e.colors.syntax.base.keyword},{tag:c.link,color:l.url||e.colors.syntax.base.function,textDecoration:"underline"},{tag:[c.punctuation,c.separator,c.bracket,c.paren,c.brace,c.squareBracket,c.angleBracket],color:l.punctuation||e.colors.syntax.base.comment}]);return r?.syntaxColors===!1?[m]:[m,At(uo,{fallback:!0}),At(po),At(h),At(w)]}const Ko=180,oa=ho.define(),Uo=1,Go=2,Ho=4,wn=new Map,Jo=(e,r)=>{const n=`${e}|${r}`,i=wn.get(n);if(i)return i;let s="";e&&(s+=`color:${e};`),r&Uo&&(s+="font-style:italic;"),r&Go&&(s+="font-weight:bold;"),r&Ho&&(s+="text-decoration:underline;");const l=Wt.mark({attributes:{style:s}});return wn.set(n,l),l},Yo=(e,r)=>{const n=new gr,i=e.state.doc,s=Math.min(r.length,i.lines);for(let l=0;l<s;l+=1){const f=r[l];if(!f||f.length===0)continue;const m=i.line(l+1);let h=m.from;for(const[w,j,x]of f){if(w<=0)continue;const v=h,N=Math.min(h+w,m.to);h+=w,!(N<=v)&&(!j&&!x||n.add(v,N,Jo(j,x)))}}return n.finish()},Xo=ta.define({create(){return Wt.none},update(e,r){let n=e.map(r.changes);for(const i of r.effects)i.is(oa)&&(n=i.value);return n},provide:e=>ce.decorations.from(e)}),Qo=e=>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)},Ko)}async tokenize(r){const n=++this.generation,i=r.state.doc.toString(),s=await Gs(i,e.language,e.themeName,e.theme);s&&n===this.generation&&r.state.doc.length===i.length&&r.dispatch({effects:oa.of(Yo(r,s))})}destroy(){this.timer&&clearTimeout(this.timer)}}),Zo=e=>[Xo,Qo(e)],Fe=e=>(e||"").replace(/\\/g,"/").replace(/\/+$/g,""),Qe=e=>{const r=Fe(e);return!r||r==="/"?r||"/":r.split("/").filter(Boolean).at(-1)??r},ia=e=>{const r=Fe(e);if(!r||r==="/")return null;const n=r.lastIndexOf("/");if(n<0)return null;if(n===0)return"/";const i=r.slice(0,n);return/^[A-Za-z]:$/.test(i)?`${i}/`:i},yn=(e,r)=>{const n=Fe(e),i=Fe(r);return!n||!i?!1:n===i||n.startsWith(`${i}/`)},kn=(e,r)=>{const n=Fe(e);if(!n)return Fe(r);if(n.startsWith("/")||/^[A-Za-z]:(\/|$)/.test(n))return n;const i=Fe(r);return i?`${i}/${n}`:n},ei=(e,r)=>{const n=Fe(e),i=Fe(r);if(!n||n===i)return!1;const s=ia(n);return s?i&&yn(n,i)?yn(s,i):!0:!1},ti=e=>{if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;const r=["KB","MB","GB"];let n=e/1024;for(const i of r){if(n<1024||i===r[r.length-1])return`${n.toFixed(n>=10?0:1)} ${i}`;n/=1024}return""},ri=(e,r)=>!r||e===r?Qe(e):e.startsWith(`${r}/`)?e.slice(r.length+1):e,ni=({root:e,directory:r,entries:n,query:i,searchResults:s,isSearching:l,directoryError:f,refreshing:m,editorPath:h,editor:w,onClose:j,onQueryChange:x,onOpenDirectory:v,onOpenFile:N,onBackFromEditor:y,onRefresh:b})=>{if(!e)return t.jsx(ut,{message:"Select a project to browse files."});if(h)return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-transparent text-foreground",children:[t.jsxs("header",{className:"flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-1 px-2 text-foreground",children:[t.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:y,style:{touchAction:"manipulation"},children:t.jsx(S,{name:"arrow-left",className:"size-5"})}),t.jsx("div",{className:"min-w-0 flex-1",children:t.jsx("h2",{className:"truncate typography-ui-label text-foreground",children:Qe(h)})})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:w})]});const T=r===e?"Project files":Qe(r),M=ei(r,e)?ia(r):null,u=!!M&&!i.trim(),P=M===e?"Project files":Qe(M??"");return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-transparent text-foreground",children:[t.jsxs("header",{className:"flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-1 px-2 text-foreground",children:[j?t.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:j,style:{touchAction:"manipulation"},children:t.jsx(S,{name:"close",className:"size-5"})}):null,u&&M?t.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 ${Qe(M)}`,onClick:()=>v(M),style:{touchAction:"manipulation"},children:t.jsx(S,{name:"arrow-left",className:"size-5"})}):null,t.jsx("div",{className:"min-w-0 flex-1 px-1",children:t.jsx("h2",{className:"truncate typography-ui-label text-foreground",children:T})}),t.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:b,style:{touchAction:"manipulation"},children:t.jsx(S,{name:"refresh",className:H("size-5",m&&"animate-spin")})})]}),t.jsx("div",{className:"shrink-0 px-3 pb-2 pt-1",children:t.jsxs("div",{className:"relative",children:[t.jsx(S,{name:"search",className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"}),t.jsx(dt,{value:i,onChange:_=>x(_.target.value),placeholder:"Search files",className:"h-11 pl-9"})]})}),t.jsx(Hs,{className:"min-h-0 w-full flex-1 overflow-y-auto pb-3",children:f?t.jsx(ut,{message:f}):i.trim()?t.jsx(ai,{root:e,results:s,isSearching:l,onOpenFile:N}):n===void 0?t.jsx(ut,{loading:!0,message:"Loading..."}):t.jsxs("div",{className:"flex w-full min-w-0 flex-col",children:[u&&M?t.jsxs("button",{type:"button",className:ra,"aria-label":`Up one level to ${P}`,onClick:()=>v(M),style:{touchAction:"manipulation"},children:[t.jsx(S,{name:"arrow-left",className:H(fr(!0),"text-muted-foreground")}),t.jsx("span",{className:H(na(!0),"flex-1 text-muted-foreground"),children:"Up one level"})]}):null,n.length===0?t.jsx("div",{className:"px-3 py-8 text-center typography-ui-label text-muted-foreground",children:"This directory is empty."}):null,n.map(_=>t.jsx(ca,{name:_.name,path:_.path,directory:_.type==="directory",meta:_.type==="directory"?void 0:ti(_.size),onClick:()=>_.type==="directory"?v(kn(_.path,r||e)):N(kn(_.path,r||e))},_.path))]})})]})},ca=({name:e,path:r,directory:n,meta:i,onClick:s})=>t.jsxs("button",{type:"button",className:ra,onClick:s,style:{touchAction:"manipulation"},children:[n?t.jsx(S,{name:"folder-3-fill",className:H(fr(!0),"text-primary/80")}):t.jsx(ct,{filePath:r,className:fr(!0)}),t.jsx("span",{className:H(na(!0),"flex-1 text-foreground"),children:e}),i?t.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground",children:i}):null,n?t.jsx(S,{name:"arrow-right-s",className:"size-4 shrink-0 text-muted-foreground/60"}):null]}),ai=({root:e,results:r,isSearching:n,onOpenFile:i})=>n?t.jsx(ut,{loading:!0,message:"Loading..."}):r.length===0?t.jsx(ut,{message:"No files found."}):t.jsx("div",{className:"flex w-full min-w-0 flex-col",children:r.map(s=>t.jsx(ca,{name:Qe(s.path),path:s.path,directory:!1,meta:s.relativePath??ri(s.path,e),onClick:()=>i(s.path)},s.path))}),ut=({message:e,loading:r=!1})=>t.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center",children:t.jsxs("div",{className:"flex max-w-sm flex-col items-center gap-2",children:[r?t.jsx(S,{name:"loader-4",className:"size-5 animate-spin text-muted-foreground"}):t.jsx(S,{name:"folder-open-fill",className:"size-6 text-muted-foreground"}),t.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e})]})}),si=({activeDialog:e,dialogData:r,dialogInputValue:n,onDialogInputChange:i,isDialogSubmitting:s,onDialogSubmit:l,onClose:f,inputRef:m})=>t.jsx(_n,{open:!!e,onOpenChange:h=>!h&&f(),children:t.jsxs(qn,{initialFocus:m,children:[t.jsxs(Kn,{children:[t.jsxs(Un,{children:[e==="createFile"&&"Create File",e==="createFolder"&&"Create Folder",e==="rename"&&"Rename",e==="delete"&&"Delete"]}),t.jsxs(Gn,{children:[e==="createFile"&&`Create a new file in ${r?.path??"root"}`,e==="createFolder"&&`Create a new folder in ${r?.path??"root"}`,e==="rename"&&`Rename ${r?.name??""}`,e==="delete"&&`Are you sure you want to delete ${r?.name??""}? This action cannot be undone.`]})]}),e!=="delete"&&t.jsx("div",{className:"py-4",children:t.jsx(dt,{value:n,onChange:h=>i(h.target.value),placeholder:e==="rename"?"New name":"Name",onKeyDown:h=>{h.key==="Enter"&&l()},ref:m})}),t.jsxs(Hn,{children:[t.jsx(G,{variant:"outline",onClick:f,disabled:s,children:"Cancel"}),t.jsx(G,{variant:e==="delete"?"destructive":"default",onClick:()=>{l()},disabled:s||e!=="delete"&&!n.trim(),children:s?t.jsx(S,{name:"loader-4",className:"size-4 animate-spin"}):e==="delete"?"Delete":"Confirm"})]})]})}),oi=({label:e,iconDataUrl:r})=>{const[n,i]=o.useState(!1),s=e.trim().slice(0,1).toUpperCase()||"?";return r&&!n?t.jsx("img",{src:r,alt:"",className:"size-4 rounded-sm",onError:()=>i(!0)}):t.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:s})},la=({filePath:e,extension:r})=>t.jsx(ct,{filePath:e,extension:r}),ii=({status:e})=>{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)"}[e];return t.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:r}})},jn=({name:e})=>{const r=o.useRef(null),n=o.useRef(null),[i,s]=o.useState(!1);return o.useLayoutEffect(()=>{const l=r.current,f=n.current;if(!l||!f)return;const m=()=>{s(f.scrollWidth>l.clientWidth+1)};m();const h=new ResizeObserver(m);return h.observe(l),h.observe(f),()=>{h.disconnect()}},[e]),t.jsxs("span",{ref:r,className:"relative block min-w-0 flex-1 overflow-hidden whitespace-nowrap",children:[t.jsx("span",{ref:n,"aria-hidden":"true",className:"invisible absolute whitespace-nowrap",children:e}),i?t.jsxs("span",{className:"open-file-name-marquee-track",children:[t.jsx("span",{className:"open-file-name-marquee-item",children:e}),t.jsx("span",{className:"open-file-name-marquee-item","aria-hidden":"true",children:e})]}):t.jsx("span",{className:"block min-w-0 truncate",children:e})]})},ci=({node:e,root:r,isExpanded:n,isActive:i,isMobile:s,isBrowserClient:l,alwaysShowActions:f,status:m,badge:h,permissions:w,downloadFile:j,contextMenuPath:x,setContextMenuPath:v,rightClickMenuPath:N,setRightClickMenuPath:y,onSelect:b,onToggle:T,onRevealPath:M,onOpenDialog:u})=>{const P=e.type==="directory",{canRename:_,canCreateFile:$,canCreateFolder:K,canDelete:U,canReveal:q}=w,J=!P&&!!j,D=q&&!l,A=_||$||K||U||J||D,k=o.useCallback(d=>{A&&(d?.preventDefault(),y(e.path))},[A,e.path,y]),I=o.useCallback(()=>{P?T(e.path):b(e)},[P,e,b,T]),R=o.useCallback(d=>{d.stopPropagation(),y(null),v(e.path)},[e.path,v,y]),F=({Item:d,Separator:B})=>t.jsxs(t.Fragment,{children:[_&&t.jsxs(d,{onClick:z=>{z.stopPropagation(),u("rename",e)},children:[t.jsx(S,{name:"edit",className:"mr-2 size-4"})," ","Rename"]}),t.jsxs(d,{onClick:z=>{z.stopPropagation(),Lt(e.path).then(O=>{if(O.ok){ie.success("Path copied");return}ie.error("Copy failed")})},children:[t.jsx(S,{name:"file-copy",className:"mr-2 size-4"})," ","Copy Path"]}),t.jsxs(d,{onClick:z=>{z.stopPropagation();const O=$t(r,e.path)||e.path;Lt(O).then(Y=>{if(Y.ok){ie.success("Relative path copied");return}ie.error("Copy failed")})},children:[t.jsx(S,{name:"file-copy-2",className:"mr-2 size-4"})," ","Copy Relative Path"]}),!P&&j&&t.jsxs(d,{onClick:z=>{z.stopPropagation(),j(e.path).catch(O=>{console.error("Download failed:",O),ie.error("Operation failed")})},children:[t.jsx(S,{name:"download",className:"mr-2 size-4"})," ",l?"Download":"Save"]}),D&&t.jsxs(d,{onClick:z=>{z.stopPropagation(),M(e.path)},children:[t.jsx(S,{name:"folder-received",className:"mr-2 size-4"})," ",Os()]}),P&&($||K)&&t.jsxs(t.Fragment,{children:[t.jsx(B,{}),$&&t.jsxs(d,{onClick:z=>{z.stopPropagation(),u("createFile",e)},children:[t.jsx(S,{name:"file-add",className:"mr-2 size-4"})," ","New File"]}),K&&t.jsxs(d,{onClick:z=>{z.stopPropagation(),u("createFolder",e)},children:[t.jsx(S,{name:"folder-add",className:"mr-2 size-4"})," ","New Folder"]})]}),U&&t.jsxs(t.Fragment,{children:[t.jsx(B,{}),t.jsxs(d,{onClick:z=>{z.stopPropagation(),u("delete",e)},className:"text-destructive focus:text-destructive",children:[t.jsx(S,{name:"delete-bin",className:"mr-2 size-4"})," ","Delete"]})]})]});return t.jsxs(wo,{open:N===e.path,onOpenChange:d=>y(d?e.path:null),children:[t.jsxs(yo,{render:t.jsx("div",{className:"group relative flex items-center",onContextMenu:s?void 0:k}),children:[t.jsxs("button",{type:"button",onClick:I,onContextMenu:s?void 0:k,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",i?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[P?n?t.jsx(S,{name:"folder-open",className:"size-4 flex-shrink-0 text-muted-foreground"}):t.jsx(S,{name:"folder-3",className:"size-4 flex-shrink-0 text-muted-foreground"}):t.jsx(la,{filePath:e.path,extension:e.extension}),t.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:e.path,children:e.name}),!P&&m&&t.jsx(ii,{status:m}),P&&h&&t.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[h.modified>0&&t.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",h.modified]}),h.added>0&&t.jsxs("span",{className:"text-[var(--status-success)]",children:["+",h.added]})]})]}),A&&t.jsx("div",{className:H("absolute right-1 top-1/2 -translate-y-1/2",f?"opacity-100":"opacity-0 focus-within:opacity-100 group-hover:opacity-100"),children:t.jsxs(mr,{open:x===e.path,onOpenChange:d=>v(d?e.path:null),children:[t.jsx(pr,{asChild:!0,children:t.jsx(G,{variant:"ghost",size:"icon",className:"size-6",onClick:R,children:t.jsx(S,{name:"more-2-fill",className:"size-4"})})}),t.jsx(hr,{align:"end",side:"bottom",onCloseAutoFocus:()=>v(null),children:F({Item:It,Separator:Js})})]})})]}),t.jsx(ko,{className:"min-w-[180px]",children:F({Item:jo,Separator:No})})]})},sr=(e,r,n)=>{const[i,s]=o.useState(""),[l,f]=o.useState(0);return o.useEffect(()=>{if(!e){s("");return}let m=!1;s("");const h=Ps(),w=Ls(h);Is(h).then(x=>{m||!x||(s(e),r(null))}).catch(x=>{m||(r(x instanceof Error?x.message:n),s(e))});const j=Bs(()=>{m||(s(e),f(x=>x+1),r(null))});return()=>{m=!0,w(),j()}},[e,r,n]),{readyKey:i,nonce:l}},li=e=>e!==null&&typeof e=="object"&&"updateStatus"in e&&typeof e.updateStatus=="function",ui=e=>{const r=document.createElement("div");r.className="cm-vim-panel";const n=qo(e);if(!n)return{top:!1,dom:r};n.state.statusbar=r;const i=n.state.vimPlugin;return li(i)&&i.updateStatus(),{top:!1,dom:r,destroy(){n.state.statusbar===r&&(n.state.statusbar=null)}}};function Nn(e){return e?[_o(),oo.of(ui),io()]:[]}const di={next:"Next match",prev:"Previous match",select:"Select all matches",replace:"Replace",replaceAll:"Replace all",close:"Close"},fi={case:"Match case",re:"Regular expression",word:"Match whole word"};function mi(e){const r=e.querySelector(".cm-search");if(r){for(const[n,i]of Object.entries(di)){const s=r.querySelector(`button[name="${n}"]`);s&&!s.title&&(s.title=i)}for(const[n,i]of Object.entries(fi)){const l=r.querySelector(`input[name="${n}"]`)?.parentElement;l&&!l.title&&(l.title=i)}}}const or=new WeakMap;function pi(e,r){const n=Vt(e.state);if(!n.valid)return or.delete(e),0;const i=or.get(e);if(!r&&i?.doc===e.state.doc&&i.query.eq(n))return i.total;const s=n.getCursor(e.state);let l=0;for(let f=s.next();!f.done;f=s.next())l+=1;return or.set(e,{query:n,doc:e.state.doc,total:l}),l}function hi(e){const r=Vt(e.state);if(!r.valid)return 0;const n=e.state.selection.main,i=r.getCursor(e.state);let s=0,l=0;for(let f=i.next();!f.done;f=i.next()){const m=f.value;if(s+=1,l===0&&(l=s),n.from===m.from&&n.to===m.to||n.from<m.to&&n.to>m.from||m.from>=n.head)return s}return l}function Cn(e,r,n=!1){const i=e.querySelector(".cm-search");if(!i)return;let s=i.querySelector(".cm-search-message");if(!s){s=document.createElement("span"),s.className="cm-search-message",s.setAttribute("aria-live","polite");const m=i.querySelector('button[name="next"]'),h=m?.parentNode===i?m:i.firstChild;i.insertBefore(s,h)}const l=pi(r,n),f=l===0?0:hi(r);s.textContent=l===0?"":`${f}/${l}`}const Sn=new We,Rn=new We,Fn=new We,En=new We,zn=new We,Mn=new We,Tn=new We,Dn=e=>e,ir=mo,gi=Vo,xi=Wo;class vi extends lo{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 An=(e,r)=>!e||e.length===0?[]:ta.define({create(n){const i=new gr,s=[...e].sort((l,f)=>l.afterLine-f.afterLine);for(const l of s){const f=n.doc.lines;if(l.afterLine>f)continue;const m=n.doc.line(l.afterLine);i.add(m.to,m.to,Wt.widget({widget:new vi(l.id,r),block:!0,side:1}))}return i.finish()},update(n,i){return n.map(i.changes)},provide:n=>ce.decorations.from(n)}),On=e=>{if(!e)return[];const r=Math.max(1,e.start),n=Math.max(r,e.end);return ea.fromClass(class{decorations;constructor(i){this.decorations=this.build(i)}update(i){(i.docChanged||i.viewportChanged)&&(this.decorations=this.build(i.view))}build(i){const s=new gr;for(let l=r;l<=n&&l<=i.state.doc.lines;l+=1){const f=i.state.doc.line(l);s.add(f.from,f.from,Wt.line({class:"oc-cm-selected-line"}))}return s.finish()}},{decorations:i=>i.decorations})};function bi({value:e,onChange:r,extensions:n,className:i,readOnly:s,lineNumbersConfig:l,highlightLines:f,onViewReady:m,onViewDestroy:h,blockWidgets:w,enableSearch:j,searchOpen:x,onSearchOpenChange:v,vimMode:N}){const y=o.useRef(null),b=o.useRef(null),T=o.useRef(e),M=o.useRef(r),u=o.useRef(m),P=o.useRef(h),_=o.useRef(v),$=o.useRef(w),K=o.useRef(N),U=o.useRef(new Map),[q,J]=o.useState([]),D=o.useCallback(k=>{const I=(k??[]).map(R=>{const F=U.current.get(R.id);return F?{id:R.id,content:R.content,container:F}:null}).filter(R=>R!==null);J(R=>R.length===I.length&&R.every((F,d)=>{const B=I[d];return F.id===B.id&&F.content===B.content&&F.container===B.container})?R:I)},[]),A=o.useCallback(k=>{const I=y.current,R=k??b.current;if(!I||!R)return;const F=R.dom.querySelector(".cm-gutters"),d=F instanceof HTMLElement?F.getBoundingClientRect().width:0;I.style.setProperty("--oc-editor-gutter-width",`${d}px`)},[]);return o.useEffect(()=>{T.current=e},[e]),o.useEffect(()=>{M.current=r},[r]),o.useEffect(()=>{u.current=m,P.current=h},[m,h]),o.useEffect(()=>{_.current=v},[v]),o.useEffect(()=>{$.current=w,D(w)},[w,D]),o.useEffect(()=>{if(!y.current)return;const k=(()=>{if(typeof document>"u")return null;const R=document.querySelector('meta[name="csp-nonce"]')?.getAttribute("content");if(R)return R;const F=window.__PICHAMBER_CSP_NONCE__;return typeof F=="string"&&F.length>0?F:null})(),I=go.create({doc:T.current,extensions:[...k?[ce.cspNonce.of(k)]:[],co({fixed:!0}),Sn.of(dn(l)),Lo(),fo.of(" "),Tn.of(Nn(N)),nr.of([Io,...Bo,...$o]),ce.updateListener.of(R=>{A(R.view),(R.viewportChanged||R.geometryChanged)&&D($.current);const F=gn(R.startState),d=gn(R.state);F!==d&&_.current?.(d);const B=!Vt(R.startState).eq(Vt(R.state));if(d&&(F!==d||B||R.docChanged||R.selectionSet)&&Cn(R.view.dom,R.view,F!==d||B||R.docChanged),!R.docChanged)return;const z=R.state.doc.toString();T.current=z,M.current(z),D($.current)}),Rn.of(ce.editable.of(!s)),Fn.of(n??[]),En.of(On(f)),zn.of(An(w,U.current)),Mn.of(j?[xn({top:!0}),nr.of(Dn(vn))]:[])]});return b.current=new ce({state:I,parent:y.current}),ir(b.current,b.current.state.doc.length,200),b.current.requestMeasure(),requestAnimationFrame(()=>{A(b.current),D($.current)}),b.current&&u.current?.(b.current),()=>{P.current?.(),b.current?.destroy(),b.current=null,J([])}},[$,A,D]),o.useEffect(()=>{const k=b.current;k&&(k.dispatch({effects:[Sn.reconfigure(dn(l)),Rn.reconfigure(ce.editable.of(!s)),Fn.reconfigure(n??[]),En.reconfigure(On(f)),zn.reconfigure(An(w,U.current)),Mn.reconfigure(j?[xn({top:!0}),nr.of(Dn(vn))]:[])]}),ir(k,k.state.doc.length,200),k.requestMeasure(),requestAnimationFrame(()=>{A(k),D($.current)}))},[n,f,l,s,w,j,A,D]),o.useEffect(()=>{const k=b.current;if(!k){K.current=N;return}K.current!==N&&(K.current=N,k.dispatch({effects:Tn.reconfigure(Nn(N))}))},[N]),o.useEffect(()=>{const k=b.current;!k||j===!1||(x?(gi(k),requestAnimationFrame(()=>{mi(k.dom),Cn(k.dom,k,!0)})):xi(k))},[x,j]),o.useEffect(()=>{const k=b.current;if(!k)return;const I=k.state.doc.toString();I!==e&&(k.dispatch({changes:{from:0,to:I.length,insert:e}}),ir(k,k.state.doc.length,300),k.requestMeasure(),requestAnimationFrame(()=>A(k)))},[e,A]),t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:y,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)]",i)}),q.map(k=>As.createPortal(k.content,k.container,k.id))]})}const Pn=({variant:e,selectedFile:r,loading:n,suppressLoadingIndicator:i,fileError:s,isSelectedImage:l,imageSrc:f,imagePreviewNonce:m,isSelectedPdf:h,pdfSrc:w,pdfPreviewNonce:j,isUnsupportedBinary:x,onDownload:v,enableRichPreviews:N,drawioViewMode:y,drawioRemountNonce:b,diagramEditorRef:T,diagramEditorXml:M,onDiagramChange:u,jsonViewMode:P,markdownViewMode:_,htmlViewMode:$,htmlLoading:K,htmlPreviewNonce:U,htmlPreviewSrc:q,fileContent:J,canUseShikiFileView:D,textViewMode:A,draftContent:k,onDraftChange:I,canEdit:R,vimMode:F,editorExtensions:d,editorWrapperRef:B,shouldMaskEditorForPendingNavigation:z,onEditorViewReady:O,onEditorViewDestroy:Y,enableSearch:ee=!1,searchOpen:ne,onSearchOpenChange:te,pierreTheme:V,shikiThemeType:Z,wrapLines:Le})=>{const ye=e==="fullscreen",oe=ye?"p-4":"p-3",W=!!(r?.path&&Bt(r.path)),Q=!!(r?.path&&aa(r.path)),X=!!(r?.path&&sa(r.path)),le=!!(r?.path&&xr(r.path)),_e=()=>r?t.jsx("div",{className:"h-full",children:t.jsx(Po,{file:{name:r.name,contents:k,lang:Yn(r.path)||void 0},options:{disableFileHeader:!0,overflow:Le?"wrap":"scroll",theme:V,themeType:Z},className:"block h-full w-full",style:{height:"100%"}})}):null;return t.jsx(Jn,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:r?n?i?t.jsx("div",{className:oe}):t.jsxs("div",{className:`${oe} flex items-center gap-2 typography-ui text-muted-foreground`,children:[t.jsx(S,{name:"loader-4",className:"size-4 animate-spin"}),ye?"Loading…":"Loading..."]}):s?t.jsx("div",{className:`${oe} typography-ui text-[color:var(--status-error)]`,children:s}):l?t.jsx("div",{className:H("flex h-full items-center justify-center",oe),children:t.jsx("img",{src:f,alt:r.name||"Image",className:H("max-w-full object-contain rounded-md border border-border/30 bg-primary/10",ye?"max-h-full":"max-h-[70vh]")},m)}):h?t.jsx("div",{className:"h-full overflow-hidden bg-[var(--surface-background)]",children:t.jsx("iframe",{src:w,className:"h-full w-full border-0",title:r.name},j)}):x?t.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[t.jsx("div",{className:"typography-ui-header text-foreground",children:"Cannot preview binary file"}),t.jsx("div",{className:"max-w-md typography-ui text-muted-foreground",children:"This file is binary and cannot be edited in PiChamber. Download it to open with another app."}),v?t.jsxs(G,{type:"button",variant:"outline",size:"sm",onClick:v,children:[t.jsx(S,{name:"download",className:"mr-2 size-4"}),"Save file"]}):null]}):N&&W&&y==="preview"?t.jsx("div",{className:"h-full overflow-hidden",style:{minHeight:"400px"},children:t.jsx(bo,{ref:T,xml:M,onChange:u},`${r.path}:${b}`)}):N&&Q&&P==="tree"?t.jsx(on,{fallback:t.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[t.jsx("div",{className:"mb-1 font-medium text-destructive",children:"JSON viewer unavailable"}),t.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to text mode to view raw content."})]}),children:t.jsx("div",{className:"h-full overflow-auto",children:t.jsx(Oo,{jsonString:J,maxHeight:"100%",initiallyExpandedDepth:2})})}):X&&_==="preview"?t.jsxs("div",{className:H("h-full overflow-auto",oe),children:[J.length>500*1024?t.jsx("div",{className:"mb-3 rounded-md border border-status-warning/20 bg-status-warning/10 px-3 py-2 text-sm text-status-warning",children:`This file is large (${Math.round(J.length/1024)}KB). Preview may be limited.`}):null,t.jsx(on,{fallback:t.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[t.jsx("div",{className:"mb-1 font-medium text-destructive",children:"Preview unavailable"}),t.jsx("div",{className:"text-sm text-muted-foreground",children:"Switch to edit mode to fix the issue."})]}),children:t.jsx(Ys,{content:J,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):N&&le&&$==="preview"?K?t.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground typography-ui-label",children:"Loading..."}):t.jsx("div",{className:"h-full overflow-hidden",children:t.jsx("iframe",{src:q,className:"w-full h-full border-none",sandbox:"allow-scripts allow-same-origin allow-forms",title:"HTML Preview"},U)}):D&&A==="view"?_e():t.jsxs("div",{className:H("relative h-full",z&&"overflow-hidden"),ref:B,children:[t.jsx("div",{className:H("h-full",z&&"invisible"),children:t.jsx(bi,{value:k,onChange:I,readOnly:!R,vimMode:F,extensions:d,className:"h-full",onViewReady:O,onViewDestroy:Y,...ee?{enableSearch:!0,searchOpen:ne,onSearchOpenChange:te}:{}})}),z?t.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-background",children:t.jsxs("div",{className:"flex items-center gap-2 typography-ui text-muted-foreground",children:[t.jsx(S,{name:"loader-4",className:"size-4 animate-spin"}),"Opening file at change..."]})}):null]}):t.jsx("div",{className:`${oe} typography-ui text-muted-foreground`,children:"Pick a file from the tree."})})};async function wi(e,r,n){if(Xn(e)&&!Qn(e))return{kind:r?"desktop-image":"asset-image"};if(Zn(e))return{kind:"pdf"};if(dr(e))return{kind:"binary",detectedFromContent:!1};const s=await n(e);if(Xs(s))return{kind:"binary",detectedFromContent:!0};const l=Co(s);return{kind:"text",content:l,draft:l.length>lt?`${l.slice(0,lt)}
2
+
3
+ … truncated …`:l,lineEnding:So(s)}}function yi({isDirty:e,saveDraft:r}){const n=ve(v=>v.setMainTabGuard),[i,s]=C.useState(!1),l=C.useRef(null),f=C.useRef(!1),m=C.useCallback(v=>f.current?(f.current=!1,!1):e?(l.current=v,s(!0),!0):!1,[e]);C.useEffect(()=>{if(!e){n(null);return}const v=N=>!m({kind:"tab",tab:N});return n(v),()=>{ve.getState().mainTabGuard===v&&n(null)}},[e,m,n]);const h=C.useCallback(()=>{const v=l.current;return l.current=null,f.current=!0,s(!1),v?.kind==="tab"&&n(null),v},[n]),w=C.useCallback(()=>h(),[h]),j=C.useCallback(async()=>await r()?h():(f.current=!1,null),[r,h]),x=C.useCallback(v=>{v||s(!0)},[]);return{confirmOpen:i,discardAndTakeIntent:w,keepModalOpen:x,requestNavigation:m,saveAndTakeIntent:j}}function ki(e,r){if(e.state.doc.length!==r.length)return!1;if(r.length===0)return!0;const n=Math.min(128,r.length);if(e.state.sliceDoc(0,n)!==r.slice(0,n))return!1;const i=Math.max(0,r.length-n);return e.state.sliceDoc(i,r.length)===r.slice(i)}function ji({root:e,selectedPath:r,loadedPath:n,fileLoading:i,fileError:s,isImage:l,isPdf:f,isUnsupportedBinary:m,canEdit:h,textViewMode:w,setTextViewMode:j,draftContent:x,confirmDiscardOpen:v,selectFilePath:N}){const y=ve(D=>D.pendingFileNavigation),b=ve(D=>D.setPendingFileNavigation),T=ve(D=>D.pendingFileFocusPath),M=ve(D=>D.setPendingFileFocusPath),u=C.useRef(null),[P,_]=C.useState(0),$=C.useRef(null),K=C.useRef({key:"",attempts:0}),U=C.useCallback(()=>{_(D=>D+1)},[]);C.useEffect(()=>()=>{$.current!==null&&window.cancelAnimationFrame($.current)},[]),C.useEffect(()=>{if(!y||!e)return;const D=()=>{$.current===null&&($.current=window.requestAnimationFrame(()=>{$.current=null,U()}))},A=()=>{b(null),K.current={key:"",attempts:0}},k=ae(y.path);if(!k){A();return}const I=`${k}:${y.line}:${y.column??1}`;if(K.current.key!==I&&(K.current={key:I,attempts:0}),r!==k){v||N(k);return}if(i||n!==k)return;if(s||l||f||m){A();return}if(!h)return;if(w!=="edit"){j("edit");return}const R=u.current;if(!R||!ki(R,x)){D();return}const F=Math.max(1,Math.min(y.line,R.state.doc.lines)),d=R.state.doc.line(F),B=Math.max(1,y.column||1),z=d.from+Math.min(Math.max(0,d.to-d.from),B-1);if(!(R.state.selection.main.head===z)||K.current.attempts===0){K.current.attempts+=1,R.dispatch({selection:{anchor:z},effects:ce.scrollIntoView(z,{y:"center"})}),R.focus(),D();return}window.requestAnimationFrame(()=>{const Y=u.current;Y&&(Y.dispatch({selection:{anchor:z},effects:ce.scrollIntoView(z,{y:"center"})}),Y.focus())}),A()},[h,v,x,P,s,i,l,f,m,n,U,y,e,r,N,b,j,w]),C.useEffect(()=>{if(!T||!e)return;const D=ae(T);if(!D){M(null);return}r!==D||i||n!==D||(!s&&!l&&!f&&!m&&h&&w==="edit"&&u.current?.focus(),M(null))},[h,s,i,l,f,m,n,T,e,r,M,w]);const q=ae(y?.path??"");return{editorViewRef:u,notifyEditorViewChanged:U,shouldMaskEditor:!!(y&&q&&r===q&&!i&&!s&&!l&&!f&&!m)}}function Ni(e){return!(!e.autoSaveEnabled||!e.isDirty||!e.canWrite||e.isSaving||e.fileLoading||e.isNonEditableBinary||!e.selectedFilePath||e.loadedFilePath!==e.selectedFilePath)}function Ci(e){return e.selectedFilePath?e.isDirty?!(e.fileLoading||e.loadedFilePath!==e.selectedFilePath||e.isNonEditableBinary||e.draftContent===""&&e.fileContent!==""&&e.loadedFilePath!==e.selectedFilePath):!0:!1}const Si=1500,Ri=2e3;function Fi({autoSaveEnabled:e,selectedPath:r,loadedPath:n,fileLoading:i,isDirty:s,draftContent:l,fileContent:f,lineEnding:m,isNonEditableBinary:h,writeFile:w,onSaved:j}){const[x,v]=C.useState(!1),[N,y]=C.useState("idle"),b=C.useRef(null),T=C.useRef(null),M=C.useCallback(()=>{b.current&&(clearTimeout(b.current),b.current=null)},[]),u=C.useCallback(()=>{y("saved"),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{T.current=null,y("idle")},Ri)},[]),P=C.useCallback(async()=>{if(!r||!w)return ie.error("Saving not supported"),!1;if(!Ci({selectedFilePath:r,loadedFilePath:n,fileLoading:i,isDirty:s,draftContent:l,fileContent:f,isNonEditableBinary:h}))return h?console.warn(`[saveDraft] refusing to save binary file "${r}".`):l===""&&f!==""&&n!==r&&console.warn(`[saveDraft] refusing to save empty draft for "${r}" (${f.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(!s)return!0;v(!0);try{const $=Ro(l,m);return(await w(r,$))?.success?(j(r,l),!0):(ie.error("Failed to write file"),!1)}catch($){return ie.error($ instanceof Error?$.message:"Save failed"),!1}finally{v(!1)}},[l,f,i,s,h,m,n,j,r,w]),_=C.useCallback(async()=>{if(M(),x)return!1;const $=await P();return $&&u(),$},[M,x,P,u]);return C.useEffect(()=>{e||(y("idle"),M())},[e,M]),C.useEffect(()=>{if(Ni({autoSaveEnabled:e,isDirty:s,canWrite:!!(r&&w),isSaving:x,fileLoading:i,selectedFilePath:r,loadedFilePath:n,isNonEditableBinary:h}))return b.current=setTimeout(()=>{b.current=null,P().then($=>{$&&u()})},Si),M},[e,M,l,i,s,h,x,n,P,r,u,w]),C.useEffect(()=>{y("idle"),v(!1)},[r]),C.useEffect(()=>()=>{M(),T.current&&clearTimeout(T.current)},[M]),{autoSaveStatus:N,cancelPendingAutosave:M,isSaving:x,saveDraft:P,saveNow:_}}function Ei(e,r){return r.mtimeMs!==void 0&&e.mtimeMs!==void 0&&r.mtimeMs!==e.mtimeMs||r.size!==e.size}function zi({selectedPath:e,loadedPath:r,isDirty:n,readStat:i,onExternalChange:s,pollIntervalMs:l=2e3}){const f=C.useRef(null),m=C.useRef(n);m.current=n;const h=C.useCallback(w=>{f.current=w},[]);return C.useEffect(()=>{if(!e||r!==e)return;let w=!1;const j=window.setInterval(()=>{document.hidden||i(e).then(x=>{if(w||!x)return;const v=f.current;if(!v||v.path!==e){f.current=x;return}!Ei(v,x)||m.current||(f.current=x,s())}).catch(()=>{})},l);return()=>{w=!0,window.clearInterval(j)}},[r,s,l,i,e]),{recordStat:h}}const Ln="pichamber:files:md-viewer-mode",In="pichamber:files:html-viewer-mode",Bn="pichamber:files:json-viewer-mode",Mi=1500,Ti=1500;function cr(e,r,n){try{const i=localStorage.getItem(e);if(i&&r.includes(i))return i}catch{}return n}function lr(e,r){try{localStorage.setItem(e,r)}catch{}}function Di({root:e,selectedPath:r,fileContent:n,draftContent:i,setDraftContent:s,autoSaveEnabled:l,writeFile:f,readStat:m,recordStat:h}){const[w,j]=C.useState("edit"),[x,v]=C.useState("edit"),[N,y]=C.useState("text"),[b,T]=C.useState("edit"),[M,u]=C.useState("edit"),[P,_]=C.useState(0),[$,K]=C.useState(!1),U=C.useRef({}),q=C.useRef({}),J=C.useRef({}),D=C.useRef({}),A=C.useRef(""),k=C.useRef(""),I=C.useRef(null),R=C.useRef(null),F=C.useRef(null),d=C.useCallback(()=>{I.current&&(clearTimeout(I.current),I.current=null),F.current!==null&&(cancelAnimationFrame(F.current),F.current=null)},[]),B=C.useCallback(W=>{A.current=W,k.current=W},[]),z=C.useCallback(()=>B(""),[B]);C.useEffect(()=>{r&&(j(U.current[r]??"edit"),v(q.current[r]??cr(Ln,["preview","edit"],"edit")),T(J.current[r]??cr(In,["preview","edit"],"edit")),u(D.current[r]??"edit"),y(cr(Bn,["tree","text"],"text")))},[r]);const O=C.useCallback(W=>{r&&(U.current[r]=W),j(W)},[r]),Y=C.useCallback(W=>{r&&(q.current[r]=W),v(W),lr(Ln,W)},[r]),ee=C.useCallback(W=>{r&&(J.current[r]=W),T(W),lr(In,W)},[r]),ne=C.useCallback(W=>{y(W),lr(Bn,W)},[]),te=C.useCallback(W=>{if(r&&(D.current[r]=W),d(),W==="edit"){s(A.current||n),u(W);return}A.current=i;const Q=r;u("edit"),F.current=requestAnimationFrame(()=>{F.current=requestAnimationFrame(()=>{F.current=null,!(e&&Q&&we.getState().byRoot[e]?.selectedPath!==Q)&&(_(X=>X+1),u("preview"))})})},[d,i,n,e,r,s]),V=C.useCallback(async(W,Q)=>{if(!f||Q===k.current)return!1;if(!(await f(W,Q))?.success)return ie.error("Failed to write file"),!1;B(Q),s(Q);const le=await m(W).catch(()=>null);return le&&h(le),!0},[m,B,h,s,f]),Z=C.useCallback(()=>{K(!0),R.current&&clearTimeout(R.current),R.current=setTimeout(()=>K(!1),Ti)},[]),Le=C.useCallback(async(W,Q)=>{I.current&&(clearTimeout(I.current),I.current=null);const X=await V(W,Q);return X&&Z(),X},[V,Z]),ye=C.useCallback(W=>{A.current=W,!(!l||!r||M!=="preview"||!f)&&(I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{I.current=null,V(r,W).then(Q=>{Q&&Z()}).catch(Q=>{ie.error(Q instanceof Error?Q.message:"Save failed")})},Mi))},[l,M,V,r,Z,f]);C.useEffect(()=>d,[d,M,r]),C.useEffect(()=>()=>{R.current&&clearTimeout(R.current)},[]);const oe=Bt(r??"")&&(A.current||i)||n;return{clearDiagramContent:z,diagramEditorXml:oe,diagramSaved:$,drawioRemountNonce:P,drawioViewMode:M,handleDiagramChange:ye,htmlViewMode:b,jsonViewMode:N,mdViewMode:x,recordDiagramContent:B,saveDiagramNow:Le,saveDiagramXml:V,saveDrawioViewMode:te,saveHtmlViewMode:ee,saveJsonViewMode:ne,saveMdViewMode:Y,saveTextViewMode:O,setTextViewMode:j,textViewMode:w}}function Ai(e,r){return e==="mobile"?!0:r==="full"}function Oi(e,r){if(e===r)return!0;if(e.length!==r.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],s=r[n];if(i.name!==s.name||i.path!==s.path||i.type!==s.type||i.extension!==s.extension||i.relativePath!==s.relativePath||i.size!==s.size)return!1}return!0}function Pi({files:e,root:r,activeDirectory:n,expandedPaths:i,chrome:s,showGitignored:l,removeExpandedPathsByPrefix:f,enabled:m=!0,visible:h=!0}){const[w,j]=o.useState({}),[x,v]=o.useState({}),N=o.useRef(new Set),y=o.useRef(new Set),b=o.useRef(new Map),T=o.useRef(new Map),M=o.useRef(0),u=o.useRef(!1),[P,_]=o.useState(()=>$s());o.useEffect(()=>Vs(F=>{_(F.runtimeKey)}),[]),o.useEffect(()=>(u.current=!1,()=>{u.current=!0,T.current=new Map,y.current=new Set,b.current=new Map}),[]);const $=o.useCallback((F,d)=>{const B=[];for(const z of d){if(!z?.name||s==="desktop"&&!l&&Fo(z.name))continue;const O=ae(z.path||""),Y=O?Eo(O)?O:ae(`${F}/${O}`):ae(`${F}/${z.name}`),ee=z.isDirectory?"directory":"file";B.push({name:z.name,path:Y,type:ee,extension:ee==="file"&&z.name.includes(".")?z.name.split(".").pop()?.toLowerCase():void 0,size:z.size})}return zo(B)},[s,l]),K=`${P}|${r}|g${l?"1":"0"}|${s}`,U=o.useRef(K);U.current=K;const q=o.useCallback(async F=>{if(!m)return;const d=ae(F.trim());if(!d||N.current.has(d))return;const B=b.current.get(d);if(B){await B;return}const z=U.current,O=M.current+1;M.current=O,T.current=new Map(T.current).set(d,O),y.current=new Set(y.current).add(d);const Y=()=>!u.current&&U.current===z&&T.current.get(d)===O,ee=(async()=>{try{const ne=e.listDirectory?(await e.listDirectory(d)).entries.map(V=>({name:V.name,path:V.path,isDirectory:V.isDirectory,size:V.size})):(await Ws(d)).map(V=>({name:V.name,path:V.path,isDirectory:V.isDirectory}));if(!Y())return;N.current=new Set(N.current).add(d),v(V=>{if(!V[d])return V;const Z={...V};return delete Z[d],Z});const te=$(d,ne);j(V=>{const Z=V[d];return Z&&Oi(Z,te)?V:{...V,[d]:te}})}catch(ne){if(!Y())return;const te=ne instanceof Error?ne.message:String(ne??"");te==="Directory not found"&&r&&d!==r?(f(r,d),v(V=>{if(!V[d])return V;const Z={...V};return delete Z[d],Z})):(console.error("Failed to load files directory:",ne),v(V=>({...V,[d]:te})))}finally{T.current.get(d)===O&&(T.current=new Map(T.current),T.current.delete(d))}})();b.current.set(d,ee);try{await ee}finally{b.current.get(d)===ee&&(b.current.delete(d),y.current=new Set(y.current),y.current.delete(d))}},[m,e,$,f,r]),J=o.useCallback(()=>{N.current=new Set,y.current=new Set,b.current=new Map,T.current=new Map,v({}),j(F=>Object.keys(F).length===0?F:{})},[]),D=o.useCallback(async()=>{!m||!r||(J(),await q(r))},[m,q,J,r]),A=o.useCallback(async F=>{if(!m)return;if(!F){await D();return}const d=ae(F);N.current=new Set(N.current),N.current.delete(d),y.current=new Set(y.current),y.current.delete(d),b.current.delete(d),T.current=new Map(T.current),T.current.delete(d),await q(d)},[m,q,D]),k=o.useRef("");o.useEffect(()=>{k.current!==K&&(k.current=K,J())},[J,K]),o.useEffect(()=>{!m||!h||!r||N.current.has(ae(r))||q(r)},[m,q,r,K,h]),o.useEffect(()=>{!m||!h||!n||q(n)},[n,m,q,h]),o.useEffect(()=>{if(!m||!h||!e.listDirectory)return;const F=O=>{const Y=ae(O);return b.current.has(Y)||y.current.has(Y)},d=()=>{if(!(typeof document<"u"&&document.hidden))for(const O of i)F(O)||A(O)},B=()=>{typeof document<"u"&&document.hidden||d()};typeof document<"u"&&document.addEventListener("visibilitychange",B);const z=i.length>0?window.setInterval(d,8e3):null;return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",B),z!==null&&window.clearInterval(z)}},[m,i,e.listDirectory,A,h]);const I=o.useRef(m&&h);o.useEffect(()=>{const F=m&&h,d=I.current;if(I.current=F,!(!F||d)){if(!e.listDirectory){r&&!N.current.has(ae(r))&&q(r);return}if(i.length===0){r&&!N.current.has(ae(r))&&q(r);return}for(const B of i){const z=ae(B);b.current.has(z)||y.current.has(z)||A(B)}}},[m,i,e.listDirectory,q,A,r,h]);const R=o.useCallback(F=>N.current.has(ae(F)),[]);return{childrenByDir:w,loadErrorsByDir:x,isLoaded:R,loadDirectory:q,refreshDirectory:A,refreshRoot:D}}const Li=({showEditorTabsRow:e,isMobile:r,showMobilePageContent:n,onBackMobile:i,selectedFile:s,openFiles:l,root:f,alwaysShowActions:m,editorTabsOverflow:h,editorTabsScrollRef:w,onSelectFile:j,onCloseFile:x})=>e?t.jsxs("div",{className:"flex min-w-0 items-center px-3 py-1.5",children:[r&&n&&t.jsx("button",{type:"button",onClick:i,"aria-label":"Back",className:"inline-flex size-7 flex-shrink-0 items-center justify-center mr-1 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:t.jsx(S,{name:"arrow-left-s",className:"size-5"})}),r?s?t.jsxs(mr,{children:[t.jsx(pr,{asChild:!0,children:t.jsxs("button",{type:"button",className:"inline-flex min-w-0 max-w-full items-center gap-1 text-left typography-ui-label font-medium","aria-label":"Open files",children:[t.jsx(ct,{filePath:s.path,extension:s.extension,className:"size-3.5 flex-shrink-0"}),t.jsx(jn,{name:s.name}),t.jsx(S,{name:"arrow-down-s",className:"size-4 flex-shrink-0 text-muted-foreground"})]})}),t.jsx(hr,{align:"start",className:"w-[min(24rem,calc(100vw-2rem))] max-w-[calc(100vw-2rem)]",children:l.map(v=>{const N=s?.path===v.path;return t.jsxs(It,{onSelect:y=>{if(y.target.closest("[data-close-open-file]")){y.preventDefault();return}N||j(v)},className:H("flex min-w-0 items-center justify-between gap-2 overflow-hidden",N&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-hidden",children:[t.jsx(ct,{filePath:v.path,extension:v.extension,className:"size-3.5 flex-shrink-0"}),t.jsx(jn,{name:v.name})]}),t.jsx("button",{type:"button","data-close-open-file":!0,onPointerDown:y=>{y.preventDefault(),y.stopPropagation()},onClick:y=>{y.preventDefault(),y.stopPropagation(),x(v.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 ${v.name}`,children:t.jsx(S,{name:"close",className:"size-3.5"})})]},v.path)})})]}):t.jsx("div",{className:"typography-ui-label font-medium truncate",children:"Select a file"}):l.length>0?t.jsxs("div",{className:"relative min-w-0 flex-1",children:[h.left&&t.jsx("div",{className:"pointer-events-none absolute left-0 top-0 bottom-0 w-6 z-10 bg-gradient-to-r from-background to-transparent"}),h.right&&t.jsx("div",{className:"pointer-events-none absolute right-0 top-0 bottom-0 w-6 z-10 bg-gradient-to-l from-background to-transparent"}),t.jsx("div",{ref:w,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:l.map(v=>{const N=s?.path===v.path;return t.jsxs("div",{title:$t(f,v.path),className:H("group inline-flex items-center gap-1 rounded-md border px-2 py-1 typography-ui-label transition-colors whitespace-nowrap",N?"bg-[var(--interactive-selection)] border-[var(--primary-muted)] text-[var(--interactive-selection-foreground)]":"bg-transparent border-[var(--interactive-border)] text-[var(--surface-muted-foreground)] hover:bg-[var(--interactive-hover)] hover:text-[var(--surface-foreground)]"),children:[t.jsx(ct,{filePath:v.path,extension:v.extension,className:"size-3.5 flex-shrink-0"}),t.jsx("button",{type:"button",onClick:()=>{N||j(v)},className:"max-w-[12rem] truncate text-left",children:v.name}),t.jsx("button",{type:"button",onClick:y=>{y.stopPropagation(),x(v.path)},className:H("rounded-sm p-0.5 text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]",!N&&!m&&"opacity-0 group-hover:opacity-100"),"aria-label":`Close ${v.name}`,children:t.jsx(S,{name:"close",className:"size-3.5"})})]},v.path)})})]}):t.jsx("div",{className:"typography-ui-label font-medium truncate",children:"Select a file"})]}):null,Ii=(e,r)=>{if(!r)return null;const n=Number.parseInt(e.trim(),10);return!Number.isFinite(n)||n<1?null:Math.min(n,r.state.doc.lines)},$n=(e,r)=>{const n=e.state.doc.lineAt(r.main.head);return{lineNumber:n.number,character:r.main.head-n.from+1,selection:r}},Vn=(e,r,n)=>{const i=e.state.doc.line(r),s=Math.max(1,Math.min(n,i.length+1)),l=i.from+s-1;e.dispatch({selection:xo.cursor(l),effects:ce.scrollIntoView(l,{y:"center"})})};function Bi({open:e,onOpenChange:r,view:n,variant:i="overlay"}){const[s,l]=o.useState(""),f=o.useRef(null),m=o.useRef(!1),h=o.useRef(null),w=o.useRef(null),j=o.useMemo(()=>Ii(s,n),[s,n]);o.useEffect(()=>{!e||!n||(m.current=!1,f.current=$n(n,n.state.selection),l(""))},[e,n]),o.useEffect(()=>{e&&window.requestAnimationFrame(()=>{w.current?.focus(),w.current?.select()})},[e]),o.useEffect(()=>{if(!(!e||!n||!f.current)){if(j===null){const{selection:b}=f.current;n.dispatch({selection:b,effects:ce.scrollIntoView(b.main.from,{y:"center"})});return}Vn(n,j,f.current.character)}},[j,e,n]);const x=o.useCallback(()=>{if(!n||m.current||!f.current)return;const{selection:b}=f.current;n.dispatch({selection:b,effects:ce.scrollIntoView(b.main.from,{y:"center"})})},[n]),v=o.useCallback(b=>{b||x(),r(b)},[r,x]),N=o.useCallback(()=>{!n||j===null||!f.current||(m.current=!0,Vn(n,j,f.current.character),r(!1),n.focus())},[j,r,n]);o.useEffect(()=>{if(!e)return;const b=M=>{const u=h.current,P=M.target;!u||!(P instanceof Node)||u.contains(P)||v(!1)},T=M=>{M.key==="Escape"&&(M.preventDefault(),v(!1))};return document.addEventListener("pointerdown",b,!0),document.addEventListener("keydown",T,!0),()=>{document.removeEventListener("pointerdown",b,!0),document.removeEventListener("keydown",T,!0)}},[v,e,i]);const y=o.useMemo(()=>n?j===null?`Current Line: ${(f.current??$n(n,n.state.selection)).lineNumber}. Type a line number between 1 and ${n.state.doc.lines} to navigate to.`:`Go to line ${j}`:"Editor unavailable.",[j,n]);return i==="inline"?e?t.jsxs("div",{ref:h,className:"ml-1 flex h-6 items-center gap-1",children:[t.jsx(dt,{ref:w,type:"number",min:1,step:1,inputMode:"numeric",value:s,onChange:b=>l(b.target.value),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),N())},placeholder:"Line",className:"h-6 w-20 rounded-md border-border/70 bg-transparent px-2 typography-meta"}),t.jsx(G,{variant:"outline",size:"xs",onClick:N,disabled:!n||j===null,className:"h-6 px-2",children:"Go"})]}):null:t.jsx("div",{ref:h,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",e?"pointer-events-auto translate-y-0 opacity-100":"pointer-events-none -translate-y-1 opacity-0"),children:t.jsxs("div",{className:"min-w-0",children:[t.jsx(dt,{ref:w,type:"number",min:1,step:1,inputMode:"numeric",value:s,onChange:b=>l(b.target.value),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),N())},placeholder:"Line number",className:"h-8 w-full rounded-md border-border/70 bg-background/60 typography-ui-label"}),t.jsx("div",{className:"mt-2 rounded-md bg-primary/15 px-3 py-1.5 typography-ui-label text-foreground/95",children:y})]})})}const ur=({currentMode:e,onToggle:r})=>{const n=e==="preview",i=n?"Switch to edit mode":"Switch to preview mode",s=n?"Edit":"Preview";return t.jsxs(Ae,{children:[t.jsx(Oe,{asChild:!0,children:t.jsx(G,{variant:"ghost",size:"sm",onClick:r,"aria-label":i,className:"h-5 w-5 p-0",children:n?t.jsx(S,{name:"eye",className:"size-4","aria-hidden":"true"}):t.jsx(S,{name:"eye-off",className:"size-4","aria-hidden":"true"})})}),t.jsx(Pe,{sideOffset:8,children:s})]})},$i=({selectedFile:e,displaySelectedPath:r,layout:n="floating",exitFullscreenOnly:i=!1,canEdit:s,isEditingFile:l,isSaving:f,autoSaveEnabled:m,autoSaveStatus:h,isDirty:w,onSaveDraft:j,onToggleAutoSave:x,openInApps:v,openInCacheStale:N,onOpenInApp:y,onRefreshOpenInApps:b,onToolbarDropdownOpenChange:T,isSelectedImage:M,isSelectedPdf:u,isUnsupportedBinary:P,wrapLines:_,onToggleWrapLines:$,textViewMode:K,onToggleSearch:U,isGoToLineOpen:q,onOpenGoToLineChange:J,editorView:D,canUseShikiFileView:A,isJson:k,isHtml:I,onToggleTextViewMode:R,isMarkdown:F,mdViewMode:d,onToggleMdViewMode:B,isDrawio:z,drawioViewMode:O,onToggleDrawioViewMode:Y,diagramSaved:ee,onSaveDiagram:ne,jsonViewMode:te,onToggleJsonViewMode:V,canCopy:Z,copiedContent:Le,onCopyContent:ye,canCopyPath:oe,copiedPath:W,onCopyPath:Q,onDownloadFile:X,isMobile:le,mode:_e,isFullscreen:Ie,onToggleFullscreen:Ee,onExitFullscreen:_t})=>{if(!e)return null;const ft=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",se=(ue,mt)=>t.jsxs(Ae,{children:[t.jsx(Oe,{asChild:!0,children:t.jsx("span",{className:"inline-flex",children:mt})}),t.jsx(Pe,{side:"bottom",sideOffset:6,children:ue})]});return t.jsxs("div",{className:ft,children:[s&&l&&t.jsxs(t.Fragment,{children:[f?t.jsxs("span",{className:"flex items-center gap-1 px-1 text-muted-foreground typography-meta",children:[t.jsx(S,{name:"loader-4",className:"size-3.5 animate-spin"}),"Saving..."]}):m&&h==="saved"&&!w?t.jsxs("span",{className:"flex items-center gap-1 px-1 text-[color:var(--status-success)] typography-meta",children:[t.jsx(S,{name:"check",className:"size-3.5"}),"Saved"]}):w?se(m?`Save now (${it()}+S) - auto-saves after 1.5s`:`Save now (${it()}+S)`,t.jsx(G,{variant:"ghost",size:"sm",onClick:()=>{j()},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:m?`Save now (${it()}+S) - auto-saves after 1.5s`:`Save now (${it()}+S)`,"aria-label":`Save (${it()}+S)`,children:t.jsx(S,{name:"save-3",className:"size-4"})})):null,se(m?"Auto-save on":"Manual save",t.jsx(G,{variant:"ghost",size:"sm",onClick:x,className:H("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",m?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:m?"Auto-save on":"Manual save","aria-label":m?"Auto-save on":"Manual save",children:m?t.jsx(S,{name:"file-check-fill",className:"size-4"}):t.jsx(S,{name:"file-check",className:"size-4"})}))]}),t.jsxs(mr,{onOpenChange:T,children:[t.jsxs(Ae,{children:[t.jsx(Oe,{asChild:!0,children:t.jsx("span",{className:"inline-flex",children:t.jsx(pr,{asChild:!0,children:t.jsx(G,{variant:"ghost",size:"sm",className:"size-6 p-0 text-foreground opacity-100 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Open in desktop app","aria-label":"Open in desktop app",children:t.jsx(S,{name:"file-transfer",className:"size-4"})})})})}),t.jsx(Pe,{side:"bottom",sideOffset:6,children:"Open in desktop app"})]}),t.jsxs(hr,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[v.map(ue=>t.jsxs(It,{className:"flex items-center gap-2",onClick:()=>{y(ue)},children:[t.jsx(oi,{label:ue.label,iconDataUrl:ue.iconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:ue.label})]},ue.id)),N?t.jsxs(It,{className:"flex items-center gap-2",onClick:()=>{b()},children:[t.jsx(S,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]}),!M&&!u&&!P&&t.jsxs(t.Fragment,{children:[se(_?"Disable line wrap":"Enable line wrap",t.jsx(G,{variant:"ghost",size:"sm",onClick:$,className:H("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",_?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:_?"Disable line wrap":"Enable line wrap",children:t.jsx(S,{name:"text-wrap",className:"size-4"})})),K==="edit"&&t.jsxs(t.Fragment,{children:[se("Find in file",t.jsx(G,{variant:"ghost",size:"sm",onClick:ue=>{U(),ue.currentTarget.blur()},className:"size-6 p-0 text-foreground opacity-100 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Find in file",children:t.jsx(S,{name:"search",className:"size-4"})})),se("Go to line",t.jsx(G,{variant:"ghost",size:"sm",onClick:ue=>{J(!q),ue.currentTarget.blur()},className:"size-6 p-0 text-foreground opacity-100 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Go to line",children:t.jsx(S,{name:"menu-fold-2",className:"size-4"})})),t.jsx(Bi,{open:q,onOpenChange:J,view:D,variant:"inline"})]})]}),A&&s&&!k&&!I&&t.jsx(ur,{currentMode:K==="view"?"preview":"edit",onToggle:R}),F&&se(d==="preview"?"Switch to edit mode":"Switch to preview mode",t.jsx(G,{variant:"ghost",size:"sm",onClick:B,className:H("size-6 p-0 transition-colors hover:bg-[var(--interactive-hover)] focus-visible:bg-[var(--interactive-hover)] active:bg-[var(--interactive-hover)]",d==="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:d==="preview"?"Switch to edit mode":"Switch to preview mode","aria-label":d==="preview"?"Switch to edit mode":"Switch to preview mode",children:t.jsx(S,{name:d==="preview"?"eye":"eye-off",className:"size-4"})})),xr(e?.path??"")&&t.jsx(ur,{currentMode:I?"preview":"edit",onToggle:R}),z&&t.jsxs(t.Fragment,{children:[t.jsx(ur,{currentMode:O,onToggle:Y}),O==="preview"&&t.jsx(G,{variant:"ghost",size:"sm",onClick:()=>{ne()},className:"size-6 p-0 text-foreground hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Save diagram",children:ee?t.jsx(S,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):t.jsx(S,{name:"save-3",className:"size-4"})})]}),k&&se(te==="tree"?"Switch to Text View":"Switch to Tree View",t.jsx(G,{variant:"ghost",size:"sm",onClick:V,className:"size-6 p-0 text-muted-foreground opacity-65 hover:bg-transparent hover:opacity-100 focus-visible:bg-transparent active:bg-transparent",title:te==="tree"?"Switch to Text View":"Switch to Tree View",children:te==="tree"?t.jsx(S,{name:"code-sslash",className:"size-4"}):t.jsx(S,{name:"node-tree",className:"size-4"})})),Z&&se("Copy file contents",t.jsx(G,{variant:"ghost",size:"sm",onClick:()=>{ye()},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:Le?t.jsx(S,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):t.jsx(S,{name:"clipboard",className:"size-4"})})),oe&&se(`Copy file path (${r})`,t.jsx(G,{variant:"ghost",size:"sm",onClick:()=>{Q()},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:W?t.jsx(S,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):t.jsx(S,{name:"file-copy-2",className:"size-4"})})),X&&se("Save file",t.jsx(G,{variant:"ghost",size:"sm",onClick:X,className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Save file","aria-label":"Save file",children:t.jsx(S,{name:"download",className:"size-4"})})),i?se("Exit fullscreen",t.jsx(G,{variant:"ghost",size:"sm",onClick:_t,className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:"Exit fullscreen","aria-label":"Exit fullscreen",children:t.jsx(S,{name:"fullscreen-exit",className:"size-4"})})):!le&&_e==="full"&&se(Ie?"Exit fullscreen":"Fullscreen",t.jsx(G,{variant:"ghost",size:"sm",onClick:Ee,className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:Ie?"Exit fullscreen":"Fullscreen","aria-label":Ie?"Exit fullscreen":"Fullscreen",children:Ie?t.jsx(S,{name:"fullscreen-exit",className:"size-4"}):t.jsx(S,{name:"fullscreen",className:"size-4"})}))]})},Vi=({open:e,onOpenChange:r,isSaving:n,onSaveAndContinue:i,onDiscardAndContinue:s})=>t.jsx(_n,{open:e,onOpenChange:r,children:t.jsxs(qn,{showCloseButton:!1,className:"max-w-md",children:[t.jsxs(Kn,{children:[t.jsx(Un,{children:"Unsaved changes"}),t.jsx(Gn,{children:"Save your edits before continuing?"})]}),t.jsxs(Hn,{children:[t.jsx(G,{variant:"outline",onClick:i,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"}),t.jsx(G,{variant:"destructive",onClick:s,children:"Discard"})]})]})}),Wn=(e,r)=>e.startsWith(`${r}/`)?e.slice(r.length+1):e,Wi=e=>e.index==="A"||e.working_dir==="?"?"git-added":e.index==="D"?"git-deleted":e.index==="M"||e.working_dir==="M"?"git-modified":null,_i=({root:e,openPaths:r,gitFiles:n})=>{const i=new Set(r),s=new Map,l=new Map,f={modified:0,added:0};for(const w of n??[]){s.has(w.path)||s.set(w.path,w);const j=+(w.index==="M"||w.working_dir==="M"),x=+(w.index==="A"||w.working_dir==="?");if(j===0&&x===0)continue;f.modified+=j,f.added+=x;const v=w.path.split("/");for(let N=1;N<v.length;N+=1){const y=v.slice(0,N).join("/");if(!y)continue;let b=l.get(y);b||(b={modified:0,added:0},l.set(y,b)),b.modified+=j,b.added+=x}}return{getFileStatus:w=>{if(i.has(w))return"open";if(s.size===0)return null;const j=Wn(w,e),x=s.get(j);return x?Wi(x):null},getFolderBadge:w=>{if(!n)return null;const j=Wn(w,e);if(!j)return f.modified+f.added>0?{...f}:null;const x=l.get(j);return x?{...x}:null}}},qi=e=>new Set(e),Ki=({root:e,isMobile:r,searchQuery:n,onSearchQueryChange:i,searchInputRef:s,searching:l,searchResults:f,selectedFile:m,onSelectFile:h,onOpenDialog:w,currentDirectory:j,refreshRoot:x,childrenByDir:v,loadErrorsByDir:N,expandedPaths:y,isBrowserClient:b,alwaysShowActions:T,getFileStatus:M,getFolderBadge:u,fileRowPermissions:P,downloadFile:_,contextMenuPath:$,setContextMenuPath:K,rightClickMenuPath:U,setRightClickMenuPath:q,toggleDirectory:J,handleRevealPath:D,refreshDirectory:A})=>{const k=!!(e&&v[e]),I=e?N[e]:null,R=o.useMemo(()=>qi(y),[y]);function F(d,B){const z=v[d]??[];return z.map((O,Y)=>{const ee=O.type==="directory",ne=ee&&R.has(O.path),te=m?.path===O.path,V=Y===z.length-1;return t.jsxs("li",{className:"relative",children:[B>0&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),V&&t.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-background"})]}),t.jsx(ci,{node:O,root:e,isExpanded:ne,isActive:te,isMobile:r,isBrowserClient:b,alwaysShowActions:T,status:ee?void 0:M(O.path),badge:ee?u(O.path):void 0,permissions:P,downloadFile:_,contextMenuPath:$,setContextMenuPath:K,rightClickMenuPath:U,setRightClickMenuPath:q,onSelect:h,onToggle:J,onRevealPath:D,onOpenDialog:w}),ee&&ne&&t.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[N[O.path]?t.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[t.jsx("span",{className:"min-w-0 flex-1 truncate text-[var(--status-error)]",title:N[O.path],children:N[O.path]}),t.jsxs(G,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{A(O.path)},children:[t.jsx(S,{name:"refresh",className:"size-3.5"}),"Refresh"]})]}):null,F(O.path,B+1)]})]},O.path)})}return t.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:[t.jsx("div",{className:H("flex flex-col gap-2 py-2",r?"px-3":"px-2"),children:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("div",{className:"relative flex-1 min-w-0",children:[t.jsx(S,{name:"search",className:"pointer-events-none absolute left-2 top-2 size-4 text-muted-foreground"}),t.jsx(dt,{ref:s,value:n,onChange:d=>i(d.target.value),placeholder:"Search files...",className:"h-8 pl-8 pr-8 typography-meta"}),n.trim().length>0&&t.jsx("button",{type:"button","aria-label":"Clear search",className:"absolute right-2 top-2 inline-flex size-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{i(""),s.current?.focus()},children:t.jsx(S,{name:"close",className:"size-4"})})]}),t.jsxs(Ae,{children:[t.jsx(Oe,{asChild:!0,children:t.jsx("span",{className:"inline-flex flex-shrink-0",children:t.jsx(G,{variant:"ghost",size:"sm",onClick:()=>w("createFile",{path:j,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:"New File","aria-label":"New File",children:t.jsx(S,{name:"file-add",className:"size-4"})})})}),t.jsx(Pe,{side:"bottom",sideOffset:6,children:"New File"})]}),t.jsxs(Ae,{children:[t.jsx(Oe,{asChild:!0,children:t.jsx("span",{className:"inline-flex flex-shrink-0",children:t.jsx(G,{variant:"ghost",size:"sm",onClick:()=>w("createFolder",{path:j,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:"New Folder","aria-label":"New Folder",children:t.jsx(S,{name:"folder-add",className:"size-4"})})})}),t.jsx(Pe,{side:"bottom",sideOffset:6,children:"New Folder"})]}),t.jsxs(Ae,{children:[t.jsx(Oe,{asChild:!0,children:t.jsx("span",{className:"inline-flex flex-shrink-0",children:t.jsx(G,{variant:"ghost",size:"sm",onClick:()=>{x()},className:"size-8 p-0 flex-shrink-0",title:"Refresh","aria-label":"Refresh",children:t.jsx(S,{name:"refresh",className:"size-4"})})})}),t.jsx(Pe,{side:"bottom",sideOffset:6,children:"Refresh"})]})]})}),t.jsx(Jn,{outerClassName:"flex-1 min-h-0",className:H("py-2",r?"px-3":"px-2"),children:t.jsx("ul",{className:"flex flex-col",children:l?t.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[t.jsx(S,{name:"loader-4",className:"size-4 animate-spin"}),"Searching..."]}):f.length>0?f.map(d=>{const B=m?.path===d.path;return t.jsx("li",{children:t.jsxs("button",{type:"button",onClick:()=>{h(d)},className:H("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",B?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[t.jsx(la,{filePath:d.path,extension:d.extension}),t.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:d.path,children:d.relativePath??d.path})]})},d.path)}):I?t.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[t.jsx("span",{className:"text-[var(--status-error)]",children:I}),t.jsxs(G,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{x()},children:[t.jsx(S,{name:"refresh",className:"size-3.5"}),"Refresh"]})]}):k?F(e,0):t.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading..."})})})]})},nu=({mode:e="full",chrome:r="desktop",onClose:n,isVisible:i=!0})=>{const{files:s,runtime:l}=Qs(),f=r==="mobile",{currentTheme:m,availableThemes:h,lightThemeId:w,darkThemeId:j}=Zs(),{isMobile:x,isTablet:v,screenWidth:N}=eo(),y=_s(l.platform),b=x||v,T=qs(),M=to()??"",u=ae(M.trim()),P=Ai(r,e),_=e!=="editor-only",$=e==="editor-only"&&!x,K=ro(M),[U,q]=o.useState(""),J=o.useRef(null),[D,A]=o.useState(!1),[k,I]=o.useState(u),[R,F]=o.useState(!1),[d,B]=o.useState(!0),[z,O]=o.useState(!1),[Y,ee]=o.useState(!1),[ne,te]=o.useState(!1),V=o.useRef(null);o.useEffect(()=>{f&&(I(u),q(""),A(!1))},[f,u]);const Z=o.useRef(0),Le=o.useCallback(a=>{Z.current=Math.max(0,Z.current+(a?1:-1))},[]),ye=o.useCallback(a=>a instanceof Element?a.closest('[data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-item"]')!==null:!1,[]);o.useEffect(()=>{if(!ne)return;const a=p=>{Z.current>0||ye(p.target)||V.current&&!V.current.contains(p.target)&&te(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[ye,ne]);const oe=o.useMemo(()=>h.find(a=>a.metadata.id===w)??nn(!1),[h,w]),W=o.useMemo(()=>h.find(a=>a.metadata.id===j)??nn(!0),[h,j]);o.useEffect(()=>{mn(oe),mn(W)},[oe,W]);const Q=o.useMemo(()=>[],[]),X=we(a=>u?a.byRoot[u]?.openPaths??Q:Q),le=we(a=>u?a.byRoot[u]?.selectedPath??null:null),_e=we(a=>u?a.byRoot[u]?.expandedPaths??Q:Q),Ie=we(a=>a.removeOpenPath),Ee=we(a=>a.removeOpenPathsByPrefix),_t=we(a=>a.removeExpandedPathsByPrefix),Ne=we(a=>a.setSelectedPath),ft=we(a=>a.toggleExpandedPath),se=we(a=>a.expandPaths),{childrenByDir:ue,loadErrorsByDir:mt,isLoaded:qe,loadDirectory:Ke,refreshDirectory:pt,refreshRoot:ua}=Pi({files:s,root:u,activeDirectory:f?k:void 0,expandedPaths:_e,chrome:r,showGitignored:T,removeExpandedPathsByPrefix:_t,enabled:P,visible:i}),ze=o.useCallback(a=>{const p=ae(a),E=p.split("/"),L=E[E.length-1]||p,fe=L.includes(".")?L.split(".").pop()?.toLowerCase():void 0;return{name:L,path:p,type:"file",extension:fe}},[]),ht=o.useMemo(()=>X.map(ze),[X,ze]),qt=o.useMemo(()=>{if(le){const a=Pt(le);if(X.some(p=>Pt(p)===a))return le}return X[0]??null},[X,le]),g=o.useMemo(()=>qt?ze(qt):null,[qt,ze]),Ce=g?.path??"";o.useEffect(()=>{if(!u||!le)return;const a=Pt(le);X.some(E=>Pt(E)===a)||Ne(u,X[0]??null)},[X,u,le,Ne]);const gt=!!(u&&Ce&&!ar(Ce,u)),vr=gt?cn(Ce):void 0,de=o.useMemo(()=>({allowOutsideWorkspace:e==="editor-only"&&gt,outsideFileGrant:vr,directory:u||void 0}),[e,gt,vr,u]),Kt=o.useRef(null),[da,fa]=o.useState({left:!1,right:!1}),br=o.useCallback(()=>{const a=Kt.current;a&&fa({left:a.scrollLeft>2,right:a.scrollLeft+a.clientWidth<a.scrollWidth-2})},[]),wr=o.useRef(br);wr.current=br,o.useEffect(()=>{const a=Kt.current;if(!a)return;const p=()=>wr.current();p(),a.addEventListener("scroll",p,{passive:!0});const E=new ResizeObserver(p);return E.observe(a),()=>{a.removeEventListener("scroll",p),E.disconnect()}},[ht.length]);const[he,Se]=o.useState(""),[Ut,Ze]=o.useState(!1),[yr,ge]=o.useState(null),[ma,Be]=o.useState(""),me=o.useRef(""),[et,ke]=o.useState(null),[tt,je]=o.useState(""),[pa,ha]=o.useState(`
4
+ `),kr=o.useRef(null),xt=o.useRef(0),rt=o.useRef(null),[jr,Nr]=o.useState(!1),vt=ve(a=>a.autoSaveEnabled),ga=ve(a=>a.setAutoSaveEnabled),xa=o.useRef(null),[va,ba]=o.useState(null),[wa,ya]=o.useState(null),{value:ka,show:ja}=ln(!1,1200),{value:Na,show:Ca}=ln(!1,1200),[Sa,Ra]=o.useState(!1),Gt=o.useCallback(()=>{u&&Ne(u,null),Se(""),ge(null),Be(""),ke(null),x&&A(!1)},[x,u,Ne]),{operation:Fa,target:Ea,inputValue:za,setInputValue:Ma,submitting:Ta,inputRef:Da,open:Aa,close:Oa,submit:Pa,capabilities:{canCreateFile:Cr,canCreateFolder:Sr,canRename:Rr,canDelete:Fr}}=Mo({files:s,root:u,selectedPath:g?.path??"",refreshDirectory:pt,removeOpenPathsByPrefix:Ee,clearSelectedPath:Gt}),Er=!!s.revealPath,La=Ot(a=>a.availableApps),Ia=Ot(a=>a.isCacheStale),zr=Ot(a=>a.initialize),Ba=Ot(a=>a.loadInstalledApps);o.useEffect(()=>{zr()},[zr]);const $a=o.useCallback(a=>{s.revealPath&&s.revealPath(a).catch(()=>{ie.error("Failed to reveal path")})},[s]),Va=o.useCallback(async a=>{if(!g?.path||await Ks(g.path,a.id,a.appName)||await an(g.path,a.appName))return;const L=To(g.path)||u;L&&await an(L,a.appName)||ie.error(`Failed to open in ${a.appName}`)},[u,g?.path]),Wa=ve(a=>a.fileEditorKeymap),Mr=ve(a=>a.expandedEditorToolbar);o.useEffect(()=>{je("")},[g?.path]);const Tr=o.useRef("");o.useEffect(()=>{!u||Tr.current===u||(Tr.current=u,Se(""),ge(null),Be(""),ke(null),A(!1))},[u]);const _a=f?k:M,{results:Dr,searching:Ar}=Do({directory:_a,query:U,chrome:r,showGitignored:T}),Or=o.useCallback(async(a,p)=>{if(s.readFile)return(await s.readFile(a,{...p??{},directory:u||void 0})).content??"";const E=new URLSearchParams({path:a});p?.allowOutsideWorkspace&&E.set("allowOutsideWorkspace","true"),p?.outsideFileGrant&&E.set("outsideFileGrant",p.outsideFileGrant),p?.optional&&E.set("optional","true"),u&&E.set("directory",u);const L=await sn(`/api/fs/read?${E.toString()}`,{cache:p?.optional?"no-store":"default"});if(!L.ok){const fe=await L.json().catch(()=>({error:L.statusText}));throw new Error(fe.error||"Failed to read file")}return L.text()},[s,u]),Ue=o.useCallback(async(a,p)=>{if(s.statFile){const E=await s.statFile(a,{...p??{},directory:u||void 0});return{path:E.path,size:E.size,mtimeMs:E.mtimeMs}}return null},[s,u]);o.useEffect(()=>{if(!u||!s.statFile||X.length===0)return;let a=!1;const p=[...X];return Promise.all(p.map(async E=>{try{const L=await s.statFile?.(E,{directory:u||void 0});!a&&L&&!L.isFile&&Ee(u,E)}catch(L){!a&&pn(L)&&Ee(u,E)}})),()=>{a=!0}},[s,X,Ee,u]);const Ht=o.useMemo(()=>he.length>lt?`${he.slice(0,lt)}
5
+
6
+ … truncated …`:he,[he]),bt=tt!==Ht,Pr=o.useCallback(a=>Ue(a,de),[Ue,de]),qa=o.useCallback(()=>{ke(null)},[]),{recordStat:Me}=zi({selectedPath:g?.path??null,loadedPath:et,isDirty:bt,readStat:Pr,onExternalChange:qa}),{clearDiagramContent:Lr,diagramEditorXml:Ka,diagramSaved:Ua,drawioRemountNonce:Ga,drawioViewMode:Jt,handleDiagramChange:Ha,htmlViewMode:wt,jsonViewMode:yt,mdViewMode:kt,recordDiagramContent:jt,saveDiagramNow:Ja,saveDrawioViewMode:Ya,saveJsonViewMode:Xa,saveMdViewMode:Ir,saveTextViewMode:Qa,setTextViewMode:Yt,textViewMode:$e}=Di({root:u,selectedPath:g?.path??null,fileContent:he,draftContent:tt,setDraftContent:je,autoSaveEnabled:vt,writeFile:s.writeFile,readStat:Pr,recordStat:Me}),Te=o.useCallback(()=>kt,[kt]),Za=o.useCallback((a,p)=>{if(Se(p),u&&ar(a,u)){const E=$t(u,a);E&&no.requestGitRefresh({directory:u,paths:[E]})}Bt(a)&&jt(p),Ue(a).then(E=>{E&&Me(E)}).catch(()=>{})},[Ue,jt,Me,u]),{autoSaveStatus:es,isSaving:Br,saveDraft:$r,saveNow:Vr}=Fi({autoSaveEnabled:vt,selectedPath:g?.path??null,loadedPath:et,fileLoading:Ut,isDirty:bt,draftContent:tt,fileContent:he,lineEnding:pa,isNonEditableBinary:!!(g?.path&&(dr(g.path)||jr)),writeFile:s.writeFile,onSaved:Za}),{confirmOpen:Wr,discardAndTakeIntent:_r,keepModalOpen:ts,requestNavigation:Nt,saveAndTakeIntent:qr}=yi({isDirty:bt,saveDraft:$r});o.useEffect(()=>{const a=p=>{Us(p)&&(p.key.toLowerCase()==="s"?(p.preventDefault(),Vr()):p.key.toLowerCase()==="f"&&(p.preventDefault(),ee(!0)))};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[Vr]);const Kr=o.useCallback(async a=>{const p=xt.current+1;xt.current=p;const E=()=>{if(!u)return!1;const re=we.getState().byRoot[u],Ye=re?.selectedPath??re?.openPaths[0]??null;return xt.current===p&&Ye===a.path};ge(null),Be(""),ke(null),Nr(!1),x&&A(!0);const L=cn(a.path),fe={allowOutsideWorkspace:e==="editor-only"&&!!u&&!ar(a.path,u),outsideFileGrant:L};let xe=!1;Ze(!0),await wi(a.path,l.isDesktop,re=>Or(re,fe)).then(re=>{if(E()){if(re.kind!=="text"){if(Se(""),je(""),re.kind==="desktop-image"){xe=!0;return}re.kind==="binary"&&Nr(re.detectedFromContent),ke(a.path);return}ha(re.lineEnding),Se(re.content),jt(re.content),je(re.draft),ke(a.path),Ue(a.path,fe).then(Ye=>{Ye&&E()&&Me(Ye)}).catch(()=>{})}}).catch(re=>{if(E()){if(Ao(re)){if(Ze(!1),u&&Ne(u,null),ge(null),Se(""),je(""),ke(null),Me(null),U.trim().length>0&&q(""),x&&A(!1),u){const Xe=[...hn(a.path,u),a.path];Xe.length>0&&se(u,Xe);for(const rn of Xe)qe(rn)||Ke(rn)}return}if(pn(re)){u&&Ee(u,a.path),Se(""),je(""),ge(null),Me(null),x&&A(!1);return}Se(""),je(""),ge(re instanceof Error?re.message:"Failed to read file"),Me(null)}}).finally(()=>{E()&&!xe&&Ze(!1)})},[se,qe,x,Ke,e,Or,Ue,jt,Me,Ee,u,l.isDesktop,U,Ne]),Ct=o.useCallback(async(a,p)=>{if(!u||!P)return;const E=hn(a,u),L=p?[...E,a]:E;L.length>0&&se(u,L);const fe=L.map(xe=>{if(!qe(xe))return Ke(xe)}).filter(Boolean);await Promise.all(fe)},[se,qe,Ke,P,u]),Ur=o.useCallback((a,p)=>{const E=p.findIndex(L=>L.path===a);return E===-1||p.length<=1?null:p[E+1]??p[E-1]??null},[]),Re=o.useCallback(async a=>{Nt({kind:"select",file:a})||(u&&(Ne(u,a.path),Ct(a.path,!1)),ge(null),Be(""),Se(""),Lr(),je(""),ke(null),x&&A(!0))},[Lr,Ct,x,Nt,u,Ne]),rs=o.useCallback(a=>{Re(ze(a))},[Re,ze]),ns=o.useCallback(a=>{const p=ae(a);p&&(q(""),I(p),A(!1))},[]),as=o.useCallback(a=>{const p=ae(a);p&&(A(!0),Re(ze(p)))},[Re,ze]),ss=o.useCallback(async()=>{if(!(!k||R)){F(!0);try{await pt(k)}finally{F(!1)}}},[k,R,pt]);o.useEffect(()=>{!g?.path||!P||!i||Ct(g.path,!1)},[Ct,i,P,g?.path]),o.useEffect(()=>{if(!g){xt.current+=1,rt.current=null,Ze(!1);return}if(et===g.path||rt.current===g.path)return;const a=g.path;rt.current=a,Kr(g).finally(()=>{rt.current===a&&(rt.current=null)})},[Kr,et,g]);const Ge=o.useCallback(async a=>{if(a.kind==="select"){await Re(a.file);return}if(a.kind==="tab"){ve.getState().setActiveMainTab(a.tab);return}u&&Ie(u,a.path),g?.path===a.path&&(a.nextFile?await Re(a.nextFile):Gt())},[Gt,Re,Ie,u,g?.path]),os=o.useCallback(()=>{const a=_r();je(Ht),a&&Ge(a)},[Ge,_r,Ht]),is=o.useCallback(async()=>{const a=await qr();a&&await Ge(a)},[Ge,qr]),cs=o.useCallback(a=>{const p=g?.path===a,E={kind:"close",path:a,nextFile:Ur(a,ht)};p&&Nt(E)||Ge(E)},[Ge,Ur,ht,Nt,g?.path]),St=o.useMemo(()=>_i({root:u,openPaths:X,gitFiles:K?.files}),[u,X,K]),ls=o.useCallback(a=>St.getFileStatus(a),[St]),us=o.useCallback(a=>St.getFolderBadge(a),[St]),ds=o.useCallback(async a=>{const p=ae(a);!u||!P||(ft(u,p),qe(p)||await Ke(p))},[qe,Ke,P,u,ft]),fs=o.useMemo(()=>({canRename:Rr,canCreateFile:Cr,canCreateFolder:Sr,canDelete:Fr,canReveal:Er}),[Rr,Cr,Sr,Fr,Er]),be=!!(g?.path&&Xn(g.path)),He=!!(g?.path&&Qn(g.path)),Ve=!!(g?.path&&Zn(g.path)),Xt=!!(g?.path&&(dr(g.path)||jr)),Rt=Xt&&!be&&!Ve,Je=o.useMemo(()=>$t(u,Ce),[Ce,u]),ms=!!(g&&(!be||He)&&!Ve&&!Rt&&he.length>0),ps=!!(g&&Je.length>0),nt=!!(g&&!gt&&!Xt&&!be&&s.writeFile&&he.length<=lt),at=!!(g?.path&&sa(g.path)),Qt=!!(g?.path&&aa(g.path)),st=!!(g?.path&&xr(g.path)),Gr=!!(g?.path&&Bt(g.path)),hs=!!(g&&!Xt&&!be),{editorViewRef:pe,notifyEditorViewChanged:Ft,shouldMaskEditor:gs}=ji({root:u,selectedPath:Ce||null,loadedPath:et,fileLoading:Ut,fileError:yr,isImage:be,isPdf:Ve,isUnsupportedBinary:Rt,canEdit:nt,textViewMode:$e,setTextViewMode:Yt,draftContent:tt,confirmDiscardOpen:Wr,selectFilePath:rs}),Hr=hs&&!at&&!Gr&&!(st&&wt==="preview"),xs=at&&kt==="edit"||st&&wt==="edit"||Qt&&yt==="text"||!at&&!st&&!Qt&&$e==="edit",Et=o.useMemo(()=>Ce?ao(Ce):null,[Ce]),[Jr,Zt]=o.useState(null);o.useEffect(()=>{let a=!1;const p=g?.path;if(!p||Et){Zt(null);return}return Zt(null),so(p).then(E=>{a||Zt(E)}),()=>{a=!0}},[g?.path,Et]),o.useEffect(()=>{!nt&&$e==="edit"&&Yt("view")},[nt,Yt,$e]);const De=o.useCallback(a=>{if(!x||!a||!a.hasFocus||typeof window>"u")return;const p=window.visualViewport;if(!p)return;const E=document.documentElement.clientHeight||window.innerHeight;if(Math.max(0,E-(p.offsetTop+p.height))<=0)return;const fe=a.state.selection.main.head,xe=a.coordsAtPos(fe);if(!xe)return;const re=Math.round(p.offsetTop+p.height),Xe=xe.bottom+20-re;Xe<=0||(a.scrollDOM.scrollTop+=Xe)},[x]);o.useEffect(()=>{if(!x||typeof window>"u")return;const a=()=>{window.requestAnimationFrame(()=>{De(pe.current)})},p=window.visualViewport;return p?.addEventListener("resize",a),p?.addEventListener("scroll",a,{passive:!0}),document.addEventListener("selectionchange",a),()=>{p?.removeEventListener("resize",a),p?.removeEventListener("scroll",a),document.removeEventListener("selectionchange",a)}},[pe,x,De]);const zt=ve(a=>a.editorFontSize),vs=o.useMemo(()=>{if(!g?.path)return[bn(m,{fontSize:zt})];const a=Yn(g.path),p=[bn(m,a?{syntaxColors:!1,fontSize:zt}:{fontSize:zt})],E=Et??Jr;return E&&p.push(E),a&&p.push(Zo({language:a,themeName:m.metadata.id,theme:vo(m)})),d&&p.push(ce.lineWrapping),x&&p.push(ce.updateListener.of(L=>{L.view.hasFocus&&(L.selectionSet||L.focusChanged||L.viewportChanged||L.geometryChanged)&&window.requestAnimationFrame(()=>{De(L.view)})})),p},[m,g?.path,Et,Jr,d,x,De,zt]),bs=o.useMemo(()=>({light:oe.metadata.id,dark:W.metadata.id}),[oe.metadata.id,W.metadata.id]),Mt=g?.path&&be&&!l.isDesktop&&!He?`${g.path}|${de.allowOutsideWorkspace?"outside":"workspace"}|${de.outsideFileGrant??""}`:"",Tt=g?.path&&Ve?`${g.path}|${de.allowOutsideWorkspace?"outside":"workspace"}|${de.outsideFileGrant??""}`:"",ot=g?.path&&st&&wt==="preview"?g.path:"",er="Failed to read file",{readyKey:Yr,nonce:ws}=sr(Mt,ge,er),{readyKey:Xr,nonce:ys}=sr(ot,ge,er),{readyKey:Qr,nonce:ks}=sr(Tt,ge,er),js=!!(Mt&&Yr!==Mt),Ns=!!(ot&&Xr!==ot),Cs=!!(Tt&&Qr!==Tt),Ss=g?.path&&be?l.isDesktop?He?`data:${un(g.path)};utf8,${encodeURIComponent(he)}`:ma:He?`data:${un(g.path)};utf8,${encodeURIComponent(he)}`:Yr===Mt?rr().authenticatedAsset("/api/fs/raw",{path:g.path,allowOutsideWorkspace:de.allowOutsideWorkspace?"true":void 0,outsideFileGrant:de.outsideFileGrant,directory:u||void 0}):"":"",Rs=g?.path&&Ve&&Qr===Tt?rr().authenticatedAsset("/api/fs/raw",{path:g.path,allowOutsideWorkspace:de.allowOutsideWorkspace?"true":void 0,outsideFileGrant:de.outsideFileGrant,directory:u||void 0}):"",Fs=ot&&Xr===ot&&g?.path?(()=>{const a=g.path.split("/").map(p=>encodeURIComponent(p)).join("/");return rr().authenticatedAsset(`/api/fs/serve${a.startsWith("/")?a:`/${a}`}`)})():void 0;o.useEffect(()=>{let a=!1;return(async()=>{if(!l.isDesktop||!g?.path||!be||He){me.current&&(URL.revokeObjectURL(me.current),me.current=""),Be("");return}ge(null),me.current&&(URL.revokeObjectURL(me.current),me.current=""),await(s.readFileBinary?s.readFileBinary(g.path,de).then(L=>L.dataUrl):(async()=>{const L=await sn("/api/fs/raw",{query:{path:g.path,allowOutsideWorkspace:de.allowOutsideWorkspace?"true":void 0,outsideFileGrant:de.outsideFileGrant,directory:u||void 0}});if(!L.ok)throw new Error("Failed to read file");const fe=await L.blob(),xe=URL.createObjectURL(fe);return a?(URL.revokeObjectURL(xe),""):(me.current=xe,xe)})()).then(L=>{a||(Be(L),ke(g.path))}).catch(L=>{me.current&&(URL.revokeObjectURL(me.current),me.current=""),a||(Be(""),ge(L instanceof Error?L.message:"Failed to read file"),ke(null))}).finally(()=>{a||Ze(!1)})})(),()=>{a=!0}},[s,be,He,u,l.isDesktop,g?.path,de]),o.useEffect(()=>()=>{me.current&&(URL.revokeObjectURL(me.current),me.current="")},[]);const Zr=o.useCallback(()=>{const a=s.downloadFile,p=g?.path;!a||!p||a(p).catch(E=>{console.error("Download failed:",E),ie.error("Operation failed")})},[s.downloadFile,g?.path]),tr=({exitFullscreenOnly:a=!1,layout:p="floating"}={})=>t.jsx($i,{selectedFile:g,displaySelectedPath:Je,layout:p,exitFullscreenOnly:a,canEdit:nt,isEditingFile:xs,isSaving:Br,autoSaveEnabled:vt,autoSaveStatus:es,isDirty:bt,onSaveDraft:$r,onToggleAutoSave:()=>ga(!vt),openInApps:La,openInCacheStale:Ia,onOpenInApp:Va,onRefreshOpenInApps:()=>Ba(!0),onToolbarDropdownOpenChange:Le,isSelectedImage:be,isSelectedPdf:Ve,isUnsupportedBinary:Rt,wrapLines:d,onToggleWrapLines:()=>B(!d),textViewMode:$e,onToggleSearch:()=>ee(!Y),isGoToLineOpen:Sa,onOpenGoToLineChange:Ra,editorView:pe.current,canUseShikiFileView:Hr,isJson:Qt,isHtml:st,onToggleTextViewMode:()=>{Qa($e==="view"?"edit":"view")},isMarkdown:at,mdViewMode:Te(),onToggleMdViewMode:()=>Ir(Te()==="preview"?"edit":"preview"),isDrawio:Gr,drawioViewMode:Jt,onToggleDrawioViewMode:()=>Ya(Jt==="preview"?"edit":"preview"),diagramSaved:Ua,onSaveDiagram:async()=>{const E=kr.current?.getXml();g?.path&&E&&await Ja(g.path,E)},jsonViewMode:yt,onToggleJsonViewMode:()=>Xa(yt==="tree"?"text":"tree"),canCopy:ms,copiedContent:ka,onCopyContent:async()=>{(await Lt(he)).ok?ja(!0):ie.error("Copy failed")},canCopyPath:ps,copiedPath:Na,onCopyPath:async()=>{(await Lt(Je)).ok?Ca(!0):ie.error("Copy failed")},onDownloadFile:s.downloadFile&&g?Zr:void 0,isMobile:x,mode:e,isFullscreen:z,onToggleFullscreen:()=>O(!z),onExitFullscreen:()=>O(!1)}),Es=o.useCallback(a=>{pe.current=a,Ft(),window.requestAnimationFrame(()=>{De(a)})},[pe,Ft,De]),zs=o.useCallback(()=>{pe.current&&(pe.current=null),Ft()},[pe,Ft]),Ms=o.useCallback(a=>{pe.current=a,window.requestAnimationFrame(()=>{De(a)})},[pe,De]),Ts=o.useCallback(()=>{pe.current&&(pe.current=null)},[pe]),en={selectedFile:g,loading:Ut||js||Cs,suppressLoadingIndicator:$,fileError:yr,isSelectedImage:be,imageSrc:Ss,imagePreviewNonce:ws,isSelectedPdf:Ve,pdfSrc:Rs,pdfPreviewNonce:ks,isUnsupportedBinary:Rt,onDownload:s.downloadFile&&g?Zr:void 0,drawioViewMode:Jt,drawioRemountNonce:Ga,diagramEditorRef:kr,diagramEditorXml:Ka,onDiagramChange:Ha,jsonViewMode:yt,markdownViewMode:kt,htmlViewMode:wt,htmlLoading:Ns,htmlPreviewNonce:ys,htmlPreviewSrc:Fs,fileContent:he,canUseShikiFileView:Hr,textViewMode:$e,draftContent:tt,onDraftChange:je,canEdit:nt,vimMode:Wa==="vim",editorExtensions:vs,shouldMaskEditorForPendingNavigation:gs,pierreTheme:bs,shikiThemeType:m.metadata.variant==="dark"?"dark":"light",wrapLines:d},Dt=t.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[t.jsx(Vi,{open:Wr,onOpenChange:ts,isSaving:Br,onSaveAndContinue:()=>{is()},onDiscardAndContinue:os}),t.jsxs("div",{className:H("flex flex-col flex-shrink-0",_&&"border-b border-border/40"),children:[t.jsx(Li,{showEditorTabsRow:_,isMobile:x,showMobilePageContent:D,onBackMobile:()=>A(!1),selectedFile:g,openFiles:ht,root:u,alwaysShowActions:b,editorTabsOverflow:da,editorTabsScrollRef:Kt,onSelectFile:Re,onCloseFile:cs}),(Mr||x)&&g?t.jsxs("div",{className:"flex min-w-0 items-center gap-3 border-t border-border/40 bg-[var(--surface-subtle)] px-3 py-1",children:[Je&&!x?t.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta text-muted-foreground",title:Je,children:Je}):null,t.jsx("div",{className:"ml-auto min-w-0 shrink-0 overflow-x-auto",children:tr({layout:"docked"})})]}):null]}),t.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[g&&!Y&&!(Mr||x)&&t.jsx("div",{ref:V,className:"absolute right-3 top-3 z-30",onMouseLeave:()=>{Z.current>0||te(!1)},children:ne?tr():t.jsxs("div",{className:"flex items-center gap-1",children:[at?t.jsxs(Ae,{children:[t.jsx(Oe,{asChild:!0,children:t.jsx("span",{className:"inline-flex",children:t.jsx(G,{variant:"ghost",size:"sm",onClick:()=>Ir(Te()==="preview"?"edit":"preview"),className:H("size-8 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-0 shadow-sm transition-colors",Te()==="preview"?"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)] hover:bg-[var(--interactive-selection)]":"text-muted-foreground hover:text-foreground"),"aria-label":Te()==="preview"?"Switch to edit mode":"Switch to preview mode",title:Te()==="preview"?"Switch to edit mode":"Switch to preview mode",children:t.jsx(S,{name:Te()==="preview"?"eye":"eye-off",className:"size-4"})})})}),t.jsx(Pe,{side:"bottom",sideOffset:6,children:Te()==="preview"?"Switch to edit mode":"Switch to preview mode"})]}):null,t.jsxs(Ae,{children:[t.jsx(Oe,{asChild:!0,children:t.jsx("span",{className:"inline-flex",onMouseEnter:()=>te(!0),children:t.jsx(G,{variant:"ghost",size:"sm",onClick:()=>te(!0),className:"size-8 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-0 text-muted-foreground shadow-sm hover:text-foreground","aria-label":"Show editor controls",title:"Editor controls",children:t.jsx(S,{name:"more-2-fill",className:"size-4"})})})}),t.jsx(Pe,{side:"bottom",sideOffset:6,children:"Editor controls"})]})]})}),t.jsx(Pn,{variant:"embedded",...en,enableRichPreviews:!0,editorWrapperRef:xa,onEditorViewReady:Es,onEditorViewDestroy:zs,enableSearch:!0,searchOpen:Y,onSearchOpenChange:ee})]})]}),tn=t.jsx(Ki,{root:u,isMobile:x,searchQuery:U,onSearchQueryChange:q,searchInputRef:J,searching:Ar,searchResults:Dr,selectedFile:g,onSelectFile:Re,onOpenDialog:Aa,currentDirectory:M,refreshRoot:ua,childrenByDir:ue,loadErrorsByDir:mt,expandedPaths:_e,isBrowserClient:y,alwaysShowActions:b,getFileStatus:ls,getFolderBadge:us,fileRowPermissions:fs,downloadFile:s.downloadFile,contextMenuPath:va,setContextMenuPath:ba,rightClickMenuPath:wa,setRightClickMenuPath:ya,toggleDirectory:ds,handleRevealPath:$a,refreshDirectory:pt}),Ds=e==="full"&&z&&g&&t.jsx("div",{className:"absolute inset-0 z-50 flex flex-col bg-background",children:t.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[t.jsx("div",{className:"absolute right-4 top-4 z-30",children:tr({exitFullscreenOnly:!0})}),t.jsx(Pn,{variant:"fullscreen",...en,enableRichPreviews:!1,onEditorViewReady:Ms,onEditorViewDestroy:Ts})]})});return f?t.jsx(ni,{root:u,directory:k||u,entries:k||u?ue[k||u]:void 0,query:U,searchResults:Dr,isSearching:Ar,directoryError:k||u?mt[k||u]??null:null,refreshing:R,editorPath:D?g?.path??null:null,editor:Dt,onClose:n,onQueryChange:q,onOpenDirectory:ns,onOpenFile:as,onBackFromEditor:()=>A(!1),onRefresh:()=>{ss()}}):t.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden bg-background relative",children:[t.jsx(si,{activeDialog:Fa,dialogData:Ea,dialogInputValue:za,onDialogInputChange:Ma,isDialogSubmitting:Ta,onDialogSubmit:Pa,onClose:Oa,inputRef:Da}),Ds,x?D?Dt:tn:e==="editor-only"?t.jsx("div",{className:"flex flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden bg-background",children:Dt})}):t.jsxs("div",{className:"flex flex-1 min-h-0 min-w-0 gap-3 px-3 pb-3 pt-2",children:[N>=700&&t.jsx("div",{className:"w-72 flex-shrink-0 min-h-0 overflow-hidden",children:tn}),t.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:Dt})]})]})};export{nu as FilesView};