@daoninc/opencode-file-explorer 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +74 -2
- package/model.ts +149 -0
- package/package.json +18 -4
- package/preview.ts +8 -0
- package/prompt-focus.ts +35 -0
- package/prompt.ts +24 -0
- package/tui.tsx +337 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Daon Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,75 @@
|
|
|
1
|
-
#
|
|
1
|
+
# File explorer panel
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
## Install
|
|
4
|
+
|
|
5
|
+
Initial npm release is pending. After publication, add to the existing `plugins`
|
|
6
|
+
array in `~/.config/opencode/cli.json`:
|
|
7
|
+
|
|
8
|
+
```json
|
|
9
|
+
{ "plugins": ["@daoninc/opencode-file-explorer@0.1.0"] }
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Requires OpenCode V2. This is a TUI-only package; remove the equivalent local
|
|
13
|
+
entry when switching to npm. MIT licensed; see `LICENSE`.
|
|
14
|
+
|
|
15
|
+
## Features
|
|
16
|
+
|
|
17
|
+
Global OpenCode V2 TUI plugin. Run `/files`, or choose
|
|
18
|
+
**Open file explorer** from Ctrl+P. The panel follows the current session's
|
|
19
|
+
working directory and uses the connected server's filesystem, including for
|
|
20
|
+
remote sessions. It does not write or delete files.
|
|
21
|
+
|
|
22
|
+
The Files sidebar can open this panel directly at a selected file's preview.
|
|
23
|
+
Clicking a sidebar file or pressing Enter previews it; pressing **a** in either
|
|
24
|
+
view inserts its reference into the draft without submitting.
|
|
25
|
+
|
|
26
|
+
| Key | Action |
|
|
27
|
+
| --- | --- |
|
|
28
|
+
| Up/Down, k/j | Move selection; scroll in preview |
|
|
29
|
+
| Enter | Expand/collapse folder or preview file |
|
|
30
|
+
| a | Insert selected/previewed file's `@path` reference into the prompt |
|
|
31
|
+
| / | Focus the search field |
|
|
32
|
+
| Down/Up, Tab, Enter (in search field) | Leave search field and navigate results |
|
|
33
|
+
| Right/l | Expand folder |
|
|
34
|
+
| Left/h, Backspace/b | Collapse folder, select parent, or leave preview |
|
|
35
|
+
| Page Up/Down, Ctrl+B/F | Scroll a page |
|
|
36
|
+
| Home/g, End/Shift+G | First/last entry or start/end of preview |
|
|
37
|
+
| . | Toggle hidden files |
|
|
38
|
+
| r | Refresh expanded folders |
|
|
39
|
+
| f | Toggle fullscreen (when terminal width permits) |
|
|
40
|
+
| Esc | Leave preview, or close panel |
|
|
41
|
+
| q | Close panel |
|
|
42
|
+
|
|
43
|
+
Click a folder to toggle it or a file to preview it. Use Ctrl+X, Right to
|
|
44
|
+
focus the panel and Ctrl+X, Left to return to the conversation. The host
|
|
45
|
+
automatically uses fullscreen on narrow terminals.
|
|
46
|
+
|
|
47
|
+
The search field recursively searches filenames and paths through the connected
|
|
48
|
+
server, not just expanded folders. Click it or press `/` to type. Results are
|
|
49
|
+
ranked by the server, show full relative paths, and are limited to 200 matches.
|
|
50
|
+
Search is debounced and stale requests are cancelled. Use Down or Enter to
|
|
51
|
+
return to navigation; file shortcuts do not intercept typing in the field.
|
|
52
|
+
Esc clears the search and restores the folder tree. The hidden-file toggle
|
|
53
|
+
also applies to results, subject to the server's search exclusions.
|
|
54
|
+
|
|
55
|
+
Select a file (or open its preview), then press **a** or click **Add to prompt**.
|
|
56
|
+
This inserts a textual `@path` reference at the prompt cursor, preserves your
|
|
57
|
+
existing draft, and closes the panel. It does not submit the prompt or create a
|
|
58
|
+
native attachment chip. The current TUI plugin API has no native attachment
|
|
59
|
+
method; use the prompt's `@` picker if you need an explicit file attachment.
|
|
60
|
+
|
|
61
|
+
Folders load on demand, sorted folders-first. Dotfiles are hidden initially;
|
|
62
|
+
ignored files and dependency folders are otherwise included, but not scanned
|
|
63
|
+
until expanded. Expanded folders refresh after relevant filesystem/session
|
|
64
|
+
events and every 10 seconds while mounted. File previews are read on demand,
|
|
65
|
+
display at most 64 KiB, and exclude binary files. The current generated client
|
|
66
|
+
rejects HTTP 206 partial responses, so previews fetch the full file without
|
|
67
|
+
Range; avoid previewing very large files over slow connections.
|
|
68
|
+
They are read-only plain text and do not auto-refresh. Symlink handling follows
|
|
69
|
+
the server filesystem API. Paths outside the session root are not browsed.
|
|
70
|
+
|
|
71
|
+
Run unit tests:
|
|
72
|
+
|
|
73
|
+
```sh
|
|
74
|
+
bun test
|
|
75
|
+
```
|
package/model.ts
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
export type Entry = { path: string; type: "file" | "directory" }
|
|
2
|
+
export type Row = Entry & { name: string; depth: number; parent: string }
|
|
3
|
+
export type TreeState = {
|
|
4
|
+
children: Record<string, Entry[]>
|
|
5
|
+
expanded: Set<string>
|
|
6
|
+
loading: Set<string>
|
|
7
|
+
errors: Record<string, string>
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function nameOf(path: string) {
|
|
11
|
+
return path.replace(/\/$/, "").split("/").at(-1) ?? path
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function sorted(entries: Entry[]) {
|
|
15
|
+
return [...entries].sort((a, b) => {
|
|
16
|
+
if (a.type !== b.type) return a.type === "directory" ? -1 : 1
|
|
17
|
+
return nameOf(a.path).localeCompare(nameOf(b.path), undefined, { numeric: true, sensitivity: "base" })
|
|
18
|
+
})
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function searchRows(entries: Entry[], hidden: boolean): Row[] {
|
|
22
|
+
// Keep the server's relevance ranking and show paths to disambiguate names.
|
|
23
|
+
const seen = new Set<string>()
|
|
24
|
+
return entries.filter((entry) => {
|
|
25
|
+
if (entry.type !== "file" || seen.has(entry.path)) return false
|
|
26
|
+
if (!hidden && entry.path.split("/").some((part) => part.startsWith("."))) return false
|
|
27
|
+
seen.add(entry.path)
|
|
28
|
+
return true
|
|
29
|
+
}).map((entry) => ({ ...entry, name: entry.path, depth: 0, parent: "" }))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function visibleRows(state: TreeState, hidden: boolean): Row[] {
|
|
33
|
+
const rows: Row[] = []
|
|
34
|
+
const visit = (parent: string, depth: number, ancestors: Set<string>) => {
|
|
35
|
+
for (const entry of state.children[parent] ?? []) {
|
|
36
|
+
const name = nameOf(entry.path)
|
|
37
|
+
if (!hidden && name.startsWith(".")) continue
|
|
38
|
+
if (ancestors.has(entry.path)) continue
|
|
39
|
+
rows.push({ ...entry, name, depth, parent })
|
|
40
|
+
if (entry.type === "directory" && state.expanded.has(entry.path)) {
|
|
41
|
+
visit(entry.path, depth + 1, new Set([...ancestors, entry.path]))
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
visit("", 0, new Set([""]))
|
|
46
|
+
return rows
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function previewText(bytes: Uint8Array, limit = 65_536) {
|
|
50
|
+
if (bytes.subarray(0, 8192).includes(0)) return "Binary file — text preview unavailable."
|
|
51
|
+
// Strip terminal control characters while preserving newlines and tabs.
|
|
52
|
+
const text = new TextDecoder().decode(bytes.subarray(0, limit))
|
|
53
|
+
.replace(/\r\n/g, "\n")
|
|
54
|
+
.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, "")
|
|
55
|
+
return (text || "(empty file)") + (bytes.length > limit ? "\n\n… preview truncated at 64 KiB …" : "")
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
type PreviewRead = (
|
|
59
|
+
input: { location: { directory: string }; path: string },
|
|
60
|
+
options: { signal: AbortSignal },
|
|
61
|
+
) => Promise<Uint8Array>
|
|
62
|
+
|
|
63
|
+
export async function readPreview(read: PreviewRead, directory: string, path: string, signal: AbortSignal) {
|
|
64
|
+
// The generated client only accepts HTTP 200 for file.read. A Range header
|
|
65
|
+
// produces HTTP 206 (or 416 for empty files), which it currently rejects.
|
|
66
|
+
// Keep the connected client's authentication and cancellation; cap display,
|
|
67
|
+
// not transfer size, until its transport supports partial responses.
|
|
68
|
+
const bytes = await read({ location: { directory }, path }, { signal })
|
|
69
|
+
return previewText(bytes)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function createTree(
|
|
73
|
+
list: (directory: string, path: string, signal: AbortSignal) => Promise<Entry[]>,
|
|
74
|
+
notify: (state: TreeState) => void,
|
|
75
|
+
) {
|
|
76
|
+
let state: TreeState
|
|
77
|
+
let directory = ""
|
|
78
|
+
let disposed = false
|
|
79
|
+
let generation = 0
|
|
80
|
+
const requests = new Map<string, { controller: AbortController; promise: Promise<void> }>()
|
|
81
|
+
const publish = () => { if (!disposed) notify({ ...state }) }
|
|
82
|
+
const cancel = () => {
|
|
83
|
+
generation++
|
|
84
|
+
for (const request of requests.values()) request.controller.abort()
|
|
85
|
+
requests.clear()
|
|
86
|
+
}
|
|
87
|
+
const reset = () => {
|
|
88
|
+
state = { children: {}, expanded: new Set(), loading: new Set(), errors: {} }
|
|
89
|
+
}
|
|
90
|
+
reset()
|
|
91
|
+
|
|
92
|
+
function load(path: string): Promise<void> {
|
|
93
|
+
if (disposed) return Promise.resolve()
|
|
94
|
+
const pending = requests.get(path)
|
|
95
|
+
if (pending) return pending.promise
|
|
96
|
+
const epoch = generation
|
|
97
|
+
const root = directory
|
|
98
|
+
const controller = new AbortController()
|
|
99
|
+
state.loading.add(path)
|
|
100
|
+
delete state.errors[path]
|
|
101
|
+
publish()
|
|
102
|
+
const promise = Promise.resolve().then(() => list(root, path, controller.signal)).then((entries) => {
|
|
103
|
+
if (disposed || generation !== epoch) return
|
|
104
|
+
state.children[path] = sorted(entries)
|
|
105
|
+
}).catch((error: unknown) => {
|
|
106
|
+
if (disposed || generation !== epoch || controller.signal.aborted) return
|
|
107
|
+
state.errors[path] = error instanceof Error ? error.message : "Unable to read directory"
|
|
108
|
+
}).finally(() => {
|
|
109
|
+
if (disposed || generation !== epoch) return
|
|
110
|
+
state.loading.delete(path)
|
|
111
|
+
requests.delete(path)
|
|
112
|
+
publish()
|
|
113
|
+
})
|
|
114
|
+
requests.set(path, { controller, promise })
|
|
115
|
+
return promise
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return {
|
|
119
|
+
async setDirectory(next: string) {
|
|
120
|
+
if (disposed) return
|
|
121
|
+
cancel()
|
|
122
|
+
directory = next
|
|
123
|
+
reset()
|
|
124
|
+
await load("")
|
|
125
|
+
},
|
|
126
|
+
async toggle(path: string) {
|
|
127
|
+
if (disposed) return
|
|
128
|
+
if (state.expanded.has(path)) {
|
|
129
|
+
state.expanded.delete(path)
|
|
130
|
+
publish()
|
|
131
|
+
return
|
|
132
|
+
}
|
|
133
|
+
state.expanded.add(path)
|
|
134
|
+
publish()
|
|
135
|
+
if (!state.children[path] || state.errors[path]) await load(path)
|
|
136
|
+
},
|
|
137
|
+
async refresh() {
|
|
138
|
+
if (disposed) return
|
|
139
|
+
// Refresh only loaded, expanded folders, with bounded parallelism.
|
|
140
|
+
const paths = ["", ...state.expanded]
|
|
141
|
+
const epoch = generation
|
|
142
|
+
for (let i = 0; i < paths.length; i += 4) {
|
|
143
|
+
if (disposed || generation !== epoch) return
|
|
144
|
+
await Promise.all(paths.slice(i, i + 4).map(load))
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
dispose() { disposed = true; cancel() },
|
|
148
|
+
}
|
|
149
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@daoninc/opencode-file-explorer",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Searchable read-only file explorer and preview panel for OpenCode",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"exports": {
|
|
8
|
+
"./tui": "./tui.tsx",
|
|
9
|
+
"./model": "./model.ts",
|
|
10
|
+
"./prompt": "./prompt.ts",
|
|
11
|
+
"./prompt-focus": "./prompt-focus.ts"
|
|
12
|
+
},
|
|
13
|
+
"files": ["tui.tsx", "model.ts", "preview.ts", "prompt.ts", "prompt-focus.ts", "README.md", "LICENSE"],
|
|
14
|
+
"scripts": { "test": "bun test", "prepublishOnly": "bun run ../../scripts/check-release.ts ." },
|
|
15
|
+
"dependencies": { "@opencode/plugin": "^2.3.1" },
|
|
16
|
+
"peerDependencies": { "@opentui/core": ">=0.8.4 <0.9", "@opentui/solid": ">=0.8.4 <0.9", "solid-js": "^1.9.0" },
|
|
17
|
+
"publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" },
|
|
18
|
+
"keywords": ["opencode", "opencode-plugin", "tui", "file-explorer"],
|
|
19
|
+
"repository": { "type": "git", "url": "git+https://github.com/daon-private/sdk-tools.git", "directory": "AI/opencode/plugins/file-explorer" }
|
|
20
|
+
}
|
package/preview.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type PreviewRequest = { path: string; sessionID: string; directory: string }
|
|
2
|
+
|
|
3
|
+
export function createPreviewRequest(path: string | undefined, sessionID: string, directory: string): PreviewRequest {
|
|
4
|
+
if (!path || /[\x00-\x1f\x7f]/.test(path) || path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path) || path.split(/[\\/]/).includes("..")) {
|
|
5
|
+
throw new Error("Choose a file inside the current session directory.")
|
|
6
|
+
}
|
|
7
|
+
return { path, sessionID, directory }
|
|
8
|
+
}
|
package/prompt-focus.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
type Editor = { readonly isDestroyed: boolean; focus(): void }
|
|
2
|
+
type Renderer = {
|
|
3
|
+
readonly currentFocusedEditor: Editor | null
|
|
4
|
+
on(event: "focused_editor", handler: () => void): unknown
|
|
5
|
+
off(event: "focused_editor", handler: () => void): unknown
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function trackPromptFocus(renderer: Renderer, sessionID: () => string, activeSessionID: () => string | undefined, canRemember: () => boolean = () => true) {
|
|
9
|
+
let last: { sessionID: string; editor: Editor } | undefined
|
|
10
|
+
let disposed = false
|
|
11
|
+
const remember = () => {
|
|
12
|
+
const active = activeSessionID()
|
|
13
|
+
const editor = renderer.currentFocusedEditor
|
|
14
|
+
if (disposed || !canRemember() || active !== sessionID() || !editor || editor.isDestroyed) return
|
|
15
|
+
last = { sessionID: active, editor }
|
|
16
|
+
}
|
|
17
|
+
renderer.on("focused_editor", remember)
|
|
18
|
+
remember()
|
|
19
|
+
return {
|
|
20
|
+
remember,
|
|
21
|
+
focus() {
|
|
22
|
+
remember()
|
|
23
|
+
if (disposed || activeSessionID() !== sessionID() || last?.sessionID !== sessionID() || last.editor.isDestroyed) {
|
|
24
|
+
throw new Error("Click the prompt field once, then select the file again.")
|
|
25
|
+
}
|
|
26
|
+
last.editor.focus()
|
|
27
|
+
if (renderer.currentFocusedEditor !== last.editor) throw new Error("The prompt field is not currently available.")
|
|
28
|
+
},
|
|
29
|
+
dispose() {
|
|
30
|
+
disposed = true
|
|
31
|
+
renderer.off("focused_editor", remember)
|
|
32
|
+
last = undefined
|
|
33
|
+
},
|
|
34
|
+
}
|
|
35
|
+
}
|
package/prompt.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export function fileReference(path: string) {
|
|
2
|
+
if (!path || /[\x00-\x1f\x7f]/.test(path)) throw new Error("This filename cannot be inserted safely into the prompt.")
|
|
3
|
+
return ` @${path} `
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
type PromptTarget = {
|
|
7
|
+
close(): void
|
|
8
|
+
isCurrent(): boolean
|
|
9
|
+
focus(): void
|
|
10
|
+
paste(bytes: Uint8Array): void
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function insertFileReference(path: string, target: PromptTarget) {
|
|
14
|
+
const bytes = new TextEncoder().encode(fileReference(path))
|
|
15
|
+
if (!target.isCurrent()) return
|
|
16
|
+
target.close()
|
|
17
|
+
// Let the host restore its prompt and input mode after closing the panel.
|
|
18
|
+
await new Promise<void>((resolve) => queueMicrotask(resolve))
|
|
19
|
+
if (!target.isCurrent()) return
|
|
20
|
+
target.focus()
|
|
21
|
+
// Use the renderer's public paste input instead of modifying host renderables,
|
|
22
|
+
// replacing draft state, touching the clipboard, or sending a prompt.
|
|
23
|
+
target.paste(bytes)
|
|
24
|
+
}
|
package/tui.tsx
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
/** @jsxImportSource @opentui/solid */
|
|
2
|
+
import { Plugin, usePlugin } from "@opencode/plugin/tui"
|
|
3
|
+
import type { PanelInput } from "@opencode/plugin/tui/context"
|
|
4
|
+
import type { ScrollBoxRenderable } from "@opentui/core"
|
|
5
|
+
import { createEffect, createMemo, createSignal, For, onCleanup, Show, untrack } from "solid-js"
|
|
6
|
+
import { createTree, readPreview, searchRows, visibleRows, type Entry, type Row, type TreeState } from "./model"
|
|
7
|
+
import { insertFileReference } from "./prompt"
|
|
8
|
+
import { trackPromptFocus } from "./prompt-focus"
|
|
9
|
+
import { createPreviewRequest, type PreviewRequest } from "./preview"
|
|
10
|
+
|
|
11
|
+
const PANEL = "local.file-explorer"
|
|
12
|
+
|
|
13
|
+
function Explorer(props: { panel: PanelInput; request?: PreviewRequest; focusPrompt: () => void }) {
|
|
14
|
+
const context = usePlugin()
|
|
15
|
+
const fallback = context.location ?? context.data.location.default()
|
|
16
|
+
const directory = () => context.data.session.get(props.panel.sessionID)?.location.directory ?? fallback.directory
|
|
17
|
+
const [state, setState] = createSignal<TreeState>({ children: {}, expanded: new Set(), loading: new Set(), errors: {} })
|
|
18
|
+
const [hidden, setHidden] = createSignal(false)
|
|
19
|
+
const [selected, setSelected] = createSignal("")
|
|
20
|
+
const [preview, setPreview] = createSignal<string>()
|
|
21
|
+
const [content, setContent] = createSignal("")
|
|
22
|
+
const [reading, setReading] = createSignal(false)
|
|
23
|
+
const [query, setQuery] = createSignal("")
|
|
24
|
+
const [searchFocused, setSearchFocused] = createSignal(true)
|
|
25
|
+
const [matches, setMatches] = createSignal<Entry[]>([])
|
|
26
|
+
const [searching, setSearching] = createSignal(false)
|
|
27
|
+
const [searchError, setSearchError] = createSignal("")
|
|
28
|
+
const isSearch = () => Boolean(query().trim())
|
|
29
|
+
const rows = createMemo(() => isSearch() ? searchRows(matches(), hidden()) : visibleRows(state(), hidden()))
|
|
30
|
+
const current = () => rows().find((row) => row.path === selected())
|
|
31
|
+
const promptFile = () => preview() ?? (current()?.type === "file" ? selected() : undefined)
|
|
32
|
+
let treeScroll: ScrollBoxRenderable | undefined
|
|
33
|
+
let previewScroll: ScrollBoxRenderable | undefined
|
|
34
|
+
let readRequest: AbortController | undefined
|
|
35
|
+
let debounce: ReturnType<typeof setTimeout> | undefined
|
|
36
|
+
let disposed = false
|
|
37
|
+
|
|
38
|
+
const tree = createTree(async (directory, path, signal) => {
|
|
39
|
+
const response = await context.client.file.list({ location: { directory }, path: path || "." }, { signal })
|
|
40
|
+
return response.data
|
|
41
|
+
}, setState)
|
|
42
|
+
|
|
43
|
+
const closePreview = () => {
|
|
44
|
+
readRequest?.abort()
|
|
45
|
+
setPreview(undefined)
|
|
46
|
+
setReading(false)
|
|
47
|
+
}
|
|
48
|
+
async function open(row = current()) {
|
|
49
|
+
if (!row) return
|
|
50
|
+
if (row.type === "directory") { await tree.toggle(row.path); return }
|
|
51
|
+
await previewFile(row.path)
|
|
52
|
+
}
|
|
53
|
+
async function previewFile(path: string) {
|
|
54
|
+
readRequest?.abort()
|
|
55
|
+
const request = new AbortController()
|
|
56
|
+
readRequest = request
|
|
57
|
+
setSearchFocused(false)
|
|
58
|
+
setPreview(path)
|
|
59
|
+
setContent("")
|
|
60
|
+
setReading(true)
|
|
61
|
+
try {
|
|
62
|
+
const text = await readPreview(
|
|
63
|
+
(input, options) => context.client.file.read(input, options),
|
|
64
|
+
directory(), path, request.signal,
|
|
65
|
+
)
|
|
66
|
+
if (!disposed && !request.signal.aborted) setContent(text)
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (!disposed && !request.signal.aborted) setContent(`Cannot preview file: ${error instanceof Error ? error.message : String(error)}`)
|
|
69
|
+
} finally {
|
|
70
|
+
if (!disposed && !request.signal.aborted) setReading(false)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function move(delta: number) {
|
|
75
|
+
if (preview()) { previewScroll?.scrollBy(delta); return }
|
|
76
|
+
const index = rows().findIndex((row) => row.path === selected())
|
|
77
|
+
const row = rows()[Math.max(0, Math.min(rows().length - 1, index + delta))]
|
|
78
|
+
if (row) setSelected(row.path)
|
|
79
|
+
}
|
|
80
|
+
function back() {
|
|
81
|
+
if (preview()) { closePreview(); return }
|
|
82
|
+
const row = current()
|
|
83
|
+
if (!row) return
|
|
84
|
+
if (state().expanded.has(row.path)) { void tree.toggle(row.path); return }
|
|
85
|
+
if (row.parent) setSelected(row.parent)
|
|
86
|
+
}
|
|
87
|
+
const [searchRevision, setSearchRevision] = createSignal(0)
|
|
88
|
+
function refresh() {
|
|
89
|
+
if (isSearch()) setSearchRevision((value) => value + 1)
|
|
90
|
+
else void tree.refresh()
|
|
91
|
+
}
|
|
92
|
+
async function addToPrompt() {
|
|
93
|
+
const path = promptFile()
|
|
94
|
+
if (!path) return
|
|
95
|
+
// Capture before close(), which disposes this component.
|
|
96
|
+
const sessionID = props.panel.sessionID
|
|
97
|
+
const root = directory()
|
|
98
|
+
try {
|
|
99
|
+
await insertFileReference(path, {
|
|
100
|
+
close: () => props.panel.close(),
|
|
101
|
+
isCurrent: () => {
|
|
102
|
+
const route = context.ui.router.current()
|
|
103
|
+
return route.type === "session" && route.sessionID === sessionID &&
|
|
104
|
+
(context.data.session.get(sessionID)?.location.directory ?? fallback.directory) === root
|
|
105
|
+
},
|
|
106
|
+
focus: props.focusPrompt,
|
|
107
|
+
paste: (bytes) => context.renderer.keyInput.processPaste(bytes),
|
|
108
|
+
})
|
|
109
|
+
} catch (error) {
|
|
110
|
+
context.ui.toast.show({ message: error instanceof Error ? error.message : String(error), variant: "error" })
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
createEffect(() => {
|
|
115
|
+
const next = directory()
|
|
116
|
+
untrack(() => {
|
|
117
|
+
closePreview()
|
|
118
|
+
setSelected("")
|
|
119
|
+
setQuery("")
|
|
120
|
+
setSearchFocused(true)
|
|
121
|
+
void tree.setDirectory(next)
|
|
122
|
+
})
|
|
123
|
+
})
|
|
124
|
+
createEffect(() => {
|
|
125
|
+
const request = props.request
|
|
126
|
+
const root = directory()
|
|
127
|
+
if (!request || request.sessionID !== props.panel.sessionID || request.directory !== root) return
|
|
128
|
+
untrack(() => {
|
|
129
|
+
setSelected(request.path)
|
|
130
|
+
void previewFile(request.path)
|
|
131
|
+
})
|
|
132
|
+
})
|
|
133
|
+
createEffect(() => {
|
|
134
|
+
const root = directory()
|
|
135
|
+
const text = query().trim()
|
|
136
|
+
searchRevision()
|
|
137
|
+
setMatches([])
|
|
138
|
+
setSearchError("")
|
|
139
|
+
setSearching(Boolean(text))
|
|
140
|
+
if (!text) return
|
|
141
|
+
let active = true
|
|
142
|
+
const request = new AbortController()
|
|
143
|
+
const timer = setTimeout(async () => {
|
|
144
|
+
try {
|
|
145
|
+
const response = await context.client.file.find(
|
|
146
|
+
{ location: { directory: root }, query: text, type: "file", limit: 200 },
|
|
147
|
+
{ signal: request.signal },
|
|
148
|
+
)
|
|
149
|
+
if (active) setMatches(response.data)
|
|
150
|
+
} catch (error) {
|
|
151
|
+
if (active && !request.signal.aborted) setSearchError(error instanceof Error ? error.message : String(error))
|
|
152
|
+
} finally {
|
|
153
|
+
if (active) setSearching(false)
|
|
154
|
+
}
|
|
155
|
+
}, 150)
|
|
156
|
+
onCleanup(() => { active = false; clearTimeout(timer); request.abort() })
|
|
157
|
+
})
|
|
158
|
+
createEffect(() => {
|
|
159
|
+
const list = rows()
|
|
160
|
+
const path = selected()
|
|
161
|
+
if (!list.some((row) => row.path === path)) {
|
|
162
|
+
// Retain the nearest visible ancestor when collapsing or hiding a folder.
|
|
163
|
+
let parent = path
|
|
164
|
+
while (parent.includes("/")) {
|
|
165
|
+
parent = parent.slice(0, parent.lastIndexOf("/"))
|
|
166
|
+
if (list.some((row) => row.path === parent)) { setSelected(parent); return }
|
|
167
|
+
}
|
|
168
|
+
setSelected(list[0]?.path ?? "")
|
|
169
|
+
}
|
|
170
|
+
})
|
|
171
|
+
createEffect(() => {
|
|
172
|
+
const index = rows().findIndex((row) => row.path === selected())
|
|
173
|
+
if (preview() || !treeScroll || index < 0) return
|
|
174
|
+
const top = treeScroll.scrollTop
|
|
175
|
+
const height = treeScroll.viewport.height
|
|
176
|
+
if (index < top) treeScroll.scrollTo(index)
|
|
177
|
+
else if (index >= top + height) treeScroll.scrollTo(index - height + 1)
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
context.keymap.layer(() => ({
|
|
181
|
+
enabled: () => props.panel.focused && !searchFocused(),
|
|
182
|
+
commands: [
|
|
183
|
+
{ bind: "down,j", run: () => move(1) },
|
|
184
|
+
{ bind: "up,k", run: () => move(-1) },
|
|
185
|
+
{ bind: "pagedown,ctrl+f", run: () => move(Math.max(1, (treeScroll?.viewport.height ?? 12) - 1)) },
|
|
186
|
+
{ bind: "pageup,ctrl+b", run: () => move(-Math.max(1, (treeScroll?.viewport.height ?? 12) - 1)) },
|
|
187
|
+
{ bind: "home,g", run: () => { if (preview()) previewScroll?.scrollTo(0); else setSelected(rows()[0]?.path ?? "") } },
|
|
188
|
+
{ bind: "end,shift+g", run: () => { if (preview()) previewScroll?.scrollTo(previewScroll.scrollHeight); else setSelected(rows().at(-1)?.path ?? "") } },
|
|
189
|
+
{ bind: "return", run: async () => { if (!preview()) await open() } },
|
|
190
|
+
{ bind: "right,l", run: async () => { const row = current(); if (!preview() && row?.type === "directory" && !state().expanded.has(row.path)) await open(row) } },
|
|
191
|
+
{ bind: "left,h,backspace,b", run: back },
|
|
192
|
+
{ bind: ".", run: () => { setHidden((value) => !value) } },
|
|
193
|
+
{ bind: "r", run: refresh },
|
|
194
|
+
{ bind: "/", enabled: () => !preview(), run: () => { setSearchFocused(true) } },
|
|
195
|
+
{ id: "local.file-explorer.add-to-prompt", title: "Add file reference to prompt", bind: "a", enabled: () => Boolean(promptFile()), run: addToPrompt },
|
|
196
|
+
{ bind: "f", run: () => props.panel.toggleFullscreen() },
|
|
197
|
+
{ bind: "escape", run: () => { if (preview()) closePreview(); else if (isSearch()) setQuery(""); else props.panel.close() } },
|
|
198
|
+
{ bind: "q", run: () => props.panel.close() },
|
|
199
|
+
],
|
|
200
|
+
}))
|
|
201
|
+
context.keymap.layer(() => ({
|
|
202
|
+
enabled: () => props.panel.focused && searchFocused() && !preview(),
|
|
203
|
+
priority: 2,
|
|
204
|
+
commands: [
|
|
205
|
+
{ bind: "escape", run: () => { setQuery(""); setSearchFocused(false) } },
|
|
206
|
+
{ bind: "down,up,tab,return", run: () => { setSearchFocused(false) } },
|
|
207
|
+
],
|
|
208
|
+
}))
|
|
209
|
+
|
|
210
|
+
const stop = context.data.listen(({ details }) => {
|
|
211
|
+
if (details.location && details.location.directory !== directory()) return
|
|
212
|
+
if (!["filesystem.changed", "session.execution.succeeded", "session.shell.ended", "shell.exited"].includes(details.type)) return
|
|
213
|
+
clearTimeout(debounce)
|
|
214
|
+
debounce = setTimeout(refresh, 300)
|
|
215
|
+
})
|
|
216
|
+
const poll = setInterval(refresh, 10_000)
|
|
217
|
+
onCleanup(() => {
|
|
218
|
+
disposed = true
|
|
219
|
+
tree.dispose()
|
|
220
|
+
readRequest?.abort()
|
|
221
|
+
stop()
|
|
222
|
+
clearTimeout(debounce)
|
|
223
|
+
clearInterval(poll)
|
|
224
|
+
})
|
|
225
|
+
|
|
226
|
+
return <box flexDirection="column" flexGrow={1} minHeight={0} paddingLeft={1} paddingRight={1}
|
|
227
|
+
onMouseDown={() => props.panel.focus()}>
|
|
228
|
+
<box flexDirection="row" justifyContent="space-between" flexShrink={0}>
|
|
229
|
+
<text fg={context.theme.text.base}><b>{preview() ? "File preview" : "Files"}</b></text>
|
|
230
|
+
<text fg={context.theme.text.muted}>{isSearch() ? searching() ? "Searching…" : `${rows().length}${matches().length === 200 ? "+" : ""} results` : state().loading.size ? "Loading…" : hidden() ? "incl. hidden" : ""}</text>
|
|
231
|
+
</box>
|
|
232
|
+
<text fg={context.theme.text.muted} flexShrink={0} wrapMode="char">{context.ui.format.path(directory())}</text>
|
|
233
|
+
<Show when={!preview()}>
|
|
234
|
+
<box flexDirection="row" flexShrink={0} marginTop={1} gap={1}>
|
|
235
|
+
<input id="file-explorer-search" flexGrow={1} value={query()} placeholder="/ to search files…"
|
|
236
|
+
focused={props.panel.focused && searchFocused()}
|
|
237
|
+
textColor={context.theme.text.base}
|
|
238
|
+
focusedTextColor={context.theme.text.base}
|
|
239
|
+
backgroundColor={context.theme.background.action.primary.hovered}
|
|
240
|
+
focusedBackgroundColor={context.theme.background.action.primary.hovered}
|
|
241
|
+
onInput={setQuery}
|
|
242
|
+
onMouseDown={() => { props.panel.focus(); setSearchFocused(true) }}
|
|
243
|
+
/>
|
|
244
|
+
</box>
|
|
245
|
+
</Show>
|
|
246
|
+
<Show when={preview()} fallback={
|
|
247
|
+
<scrollbox ref={treeScroll} flexGrow={1} minHeight={0} marginTop={1}>
|
|
248
|
+
<Show when={isSearch() ? searchError() : state().errors[""]}><text fg={context.theme.text.muted}>{isSearch() ? `Search failed: ${searchError()}` : `Cannot list folder: ${state().errors[""]}`} (r to retry)</text></Show>
|
|
249
|
+
<Show when={rows().length === 0 && (isSearch() ? !searching() && !searchError() : !state().loading.has("") && !state().errors[""])}>
|
|
250
|
+
<text fg={context.theme.text.muted}>{isSearch() ? "No matching files." : "No visible files. Press . to show hidden files."}</text>
|
|
251
|
+
</Show>
|
|
252
|
+
<For each={rows()}>{(row) => <box height={1} flexShrink={0}
|
|
253
|
+
backgroundColor={selected() === row.path ? context.theme.background.action.primary.selected : undefined}
|
|
254
|
+
onMouseUp={(event) => {
|
|
255
|
+
if (event.button !== 0 || context.renderer.getSelection()?.getSelectedText()) return
|
|
256
|
+
event.stopPropagation()
|
|
257
|
+
props.panel.focus()
|
|
258
|
+
setSearchFocused(false)
|
|
259
|
+
setSelected(row.path)
|
|
260
|
+
void open(row)
|
|
261
|
+
}}>
|
|
262
|
+
<text fg={selected() === row.path ? context.theme.text.action.primary.selected : context.theme.text.base} wrapMode="none">
|
|
263
|
+
{" ".repeat(row.depth)}<span style={{ fg: context.theme.text.muted }}>{row.type === "directory" ? state().loading.has(row.path) ? "◌ " : state().expanded.has(row.path) ? "▾ " : "▸ " : " "}</span>
|
|
264
|
+
<Show when={selected() === row.path} fallback={row.name}><b>{row.name}</b></Show>{row.type === "directory" ? "/" : ""}{state().errors[row.path] ? " [unreadable; collapse/reopen to retry]" : ""}
|
|
265
|
+
</text>
|
|
266
|
+
</box>}</For>
|
|
267
|
+
</scrollbox>
|
|
268
|
+
}>
|
|
269
|
+
<text fg={context.theme.text.muted} flexShrink={0} wrapMode="char">{preview()}</text>
|
|
270
|
+
<scrollbox ref={previewScroll} flexGrow={1} minHeight={0} marginTop={1}>
|
|
271
|
+
<text fg={context.theme.text.base} wrapMode="word">{reading() ? "Reading…" : content()}</text>
|
|
272
|
+
</scrollbox>
|
|
273
|
+
</Show>
|
|
274
|
+
<Show when={promptFile()}>
|
|
275
|
+
<box flexShrink={0} marginTop={1} backgroundColor={context.theme.background.action.primary.hovered}
|
|
276
|
+
onMouseUp={(event) => {
|
|
277
|
+
if (event.button !== 0 || context.renderer.getSelection()?.getSelectedText()) return
|
|
278
|
+
event.stopPropagation()
|
|
279
|
+
void addToPrompt()
|
|
280
|
+
}}>
|
|
281
|
+
<text fg={context.theme.text.base}>[a] Add to prompt</text>
|
|
282
|
+
</box>
|
|
283
|
+
</Show>
|
|
284
|
+
<text fg={context.theme.text.muted} flexShrink={0} marginTop={1} wrapMode="word">
|
|
285
|
+
{preview() ? "↑↓ scroll · a add to prompt · b back · f fullscreen · q close" : searchFocused() ? "↓ results · Esc clear search" : "/ search · ← collapse · . hidden · f fullscreen · q close"}
|
|
286
|
+
</text>
|
|
287
|
+
</box>
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export default Plugin.define({
|
|
291
|
+
id: "local.file-explorer",
|
|
292
|
+
setup(context) {
|
|
293
|
+
const [request, setRequest] = createSignal<PreviewRequest>()
|
|
294
|
+
const activeSessionID = () => {
|
|
295
|
+
const route = context.ui.router.current()
|
|
296
|
+
return route.type === "session" ? route.sessionID : undefined
|
|
297
|
+
}
|
|
298
|
+
// Remember the real draft editor, not this panel's search input.
|
|
299
|
+
const promptFocus = trackPromptFocus(context.renderer, () => activeSessionID() ?? "", activeSessionID, () => !context.ui.panel.current())
|
|
300
|
+
const unregister = context.ui.slot({
|
|
301
|
+
append: "session.panel",
|
|
302
|
+
render: (panel) => <Show when={panel.name === PANEL}><Explorer panel={panel} request={request()} focusPrompt={() => promptFocus.focus()} /></Show>,
|
|
303
|
+
})
|
|
304
|
+
context.keymap.layer(() => ({
|
|
305
|
+
mode: "global",
|
|
306
|
+
commands: [{
|
|
307
|
+
id: "local.file-explorer.open",
|
|
308
|
+
title: "Open file explorer",
|
|
309
|
+
group: "Files",
|
|
310
|
+
palette: true,
|
|
311
|
+
slash: { name: "files" },
|
|
312
|
+
run: () => {
|
|
313
|
+
setRequest(undefined)
|
|
314
|
+
if (!context.ui.panel.open(PANEL)) context.ui.toast.show({ message: "Open a session first to browse its files.", variant: "info" })
|
|
315
|
+
},
|
|
316
|
+
}, {
|
|
317
|
+
id: "local.file-explorer.preview",
|
|
318
|
+
title: "Preview a file from the sidebar",
|
|
319
|
+
run: (path) => {
|
|
320
|
+
const sessionID = activeSessionID()
|
|
321
|
+
if (!sessionID) return
|
|
322
|
+
const directory = (context.data.session.get(sessionID)?.location ?? context.location ?? context.data.location.default()).directory
|
|
323
|
+
try {
|
|
324
|
+
setRequest(createPreviewRequest(path, sessionID, directory))
|
|
325
|
+
if (!context.ui.panel.open(PANEL)) {
|
|
326
|
+
setRequest(undefined)
|
|
327
|
+
context.ui.toast.show({ message: "Open a session first to preview its files.", variant: "info" })
|
|
328
|
+
}
|
|
329
|
+
} catch (error) {
|
|
330
|
+
context.ui.toast.show({ message: error instanceof Error ? error.message : String(error), variant: "error" })
|
|
331
|
+
}
|
|
332
|
+
},
|
|
333
|
+
}],
|
|
334
|
+
}))
|
|
335
|
+
return () => { unregister(); promptFocus.dispose() }
|
|
336
|
+
},
|
|
337
|
+
})
|