Repository navigation
Expand file tree
/
Copy pathrenderer.tsx
More file actions
713 lines (571 loc) · 22.5 KB
/
Copy pathrenderer.tsx
File metadata and controls
713 lines (571 loc) · 22.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
import {
batch,
createMemo,
createSignal,
lazy,
on,
onCleanup,
Show,
Suspense,
type ParentProps,
type Signal,
} from "solid-js"
import { createStore, produce } from "solid-js/store"
import { Icon } from "@opencode/ui/icon"
import { encodeFilePath, getFilename } from "@opencode/util/path"
import {
Command,
createKeyed,
bindPlugin,
LinkHandler,
MenuItem,
Slot,
Style,
usePanel,
type Files,
type LineRange,
type Link,
type OpenOptions,
type MountedSession,
type SessionScreen,
type ServerRef,
type Plugin,
} from "@opencode/plugin/gui"
import { artifactKind } from "@opencode/util/artifact"
import { resolveArtifactPath } from "./artifact"
import { FileContext, type FileShared } from "./context"
import type { OpenApp } from "./apps"
import {
FileTree,
OpenInApp,
type FileListProps,
type FileTreeProps,
type OpenInAppProps,
} from "@opencode/plugin/gui/file"
import type File from "./index"
import { FileVisual } from "./label"
import { fileTabId, fileTabPath, isFileTab, workspaceFileUrl } from "./path"
import tabStyles from "./tabs.css?inline"
import { onIdle, BuiltinPanel, type BuiltinPanelTab } from "@opencode/plugin/gui/builtin"
import { Browser } from "@opencode/plugin/gui/browser"
import { Changes } from "@opencode/plugin/gui/review"
const OPEN = "open"
const isLauncher = (id: string) => id === OPEN || id.startsWith(`${OPEN}:`)
const GROUP = "browser"
const TABPANEL = "session-side-panel-file-browser-tabpanel"
const HANDOFF_SESSIONS = 40
const FILTER_SESSIONS = 40
const DEFAULT_LINE_HEIGHT = 24
type Handoff = { sessions: Record<string, Record<string, LineRange | null>> }
type StyleLoad = { loaded?: Promise<void> }
type LinkCheck = { result: boolean | Promise<boolean>; expires: number; known?: true }
const setup: Plugin.Setup<typeof File> = (ctx) => {
const sessions = ctx.sessions
const layout = ctx.layout
const storage = ctx.storage
const desktop = ctx.desktop
const [handoff, setHandoff] = storage.memory<Handoff>("handoff", { initial: { sessions: {} } })
const preference = desktop ? ctx.stores.app : undefined
const [request, setRequest] = createStore<{ app?: OpenApp }>({})
const [filters, setFilters] = createStore<Record<string, { text: string; browsing: boolean } | undefined>>({})
const revealListeners = new Map<string, Set<() => void>>()
let clickController: AbortController | undefined
// Tab objects per session screen, which stays while it routes another session, reused so neither strip updates nor a
// session switch rebuild a trigger. `close` prunes them.
const tabs = new WeakMap<SessionScreen, Map<string, BuiltinPanelTab>>()
const tabsOf = (screen: SessionScreen) => {
const existing = tabs.get(screen)
if (existing) return existing
const created = new Map<string, BuiltinPanelTab>()
tabs.set(screen, created)
return created
}
// The file tab each session screen last selected, for reloads the side panel does not see.
const focused = new WeakMap<SessionScreen, string>()
const key = (files: Files, path: string) => `file:${fileTabId(files, path)}`
const active = (session: MountedSession, id: string) => {
const state = layout.state(`file:${id}`, session)
return state === "active" || state === "visible"
}
const updateFilter = (session: string, patch: { text?: string; browsing?: boolean }) => {
setFilters(
produce((draft) => {
const current = draft[session]
const text = patch.text ?? current?.text ?? ""
const browsing = patch.browsing ?? current?.browsing ?? false
delete draft[session]
if (!text && !browsing) return
draft[session] = { text, browsing }
const keys = Object.keys(draft)
keys.slice(0, Math.max(0, keys.length - FILTER_SESSIONS)).forEach((item) => delete draft[item])
}),
)
}
// Opens on the session screen, whose file model serves the routed session `session` is.
const open = (session: MountedSession, path: string, options?: OpenOptions) => {
const screen = ctx.screen.current()
if (!screen) return
// Not batched: the mobile tab strip must register the new tab before it leaves the browser, or Kobalte falls back
// to the first tab and reselects it.
layout.open(key(screen.file, path), session, options)
updateFilter(session.key, { browsing: false })
void screen.file.sync(path)
}
const applySelection = (session: MountedSession, files: Files, path: string, selection: LineRange | undefined) => {
if (!selection || artifactKind(path) !== "text") return
const tabKey = key(files, path)
const existing = layout.scroll.get(session, tabKey)
files.selection.set(path, selection)
layout.scroll.set(session, tabKey, {
x: existing?.x ?? 0,
y: Math.max(0, (selection.start - 4) * DEFAULT_LINE_HEIGHT),
})
shared.reveal.run(session.key, path)
}
// Reuses the selected launcher; otherwise wide screens add another one beside the open tabs, so several can stay
// open. Narrow screens never store a launcher, so they keep the one.
const openPicker = (session: MountedSession, query: string, options?: OpenOptions & { another?: boolean }) => {
const selected = options?.another
? undefined
: layout.stored(session).find((id) => isLauncher(id) && active(session, id))
batch(() => {
updateFilter(session.key, { text: query, browsing: true })
if (selected || layout.narrow())
layout.open(`file:${selected ?? OPEN}`, session, { tab: "preview", background: options?.background })
else layout.open(`file:${OPEN}:${crypto.randomUUID()}`, session, { tab: "select" })
if (!options?.background && layout.narrow() && !layout.side.opened(session)) layout.side.toggle(session)
})
if (options?.background) return
queueMicrotask(() => {
const element = shared.filter.element
if (element?.isConnected) return element.focus()
shared.filter.pending = true
})
}
const shared: FileShared = {
changes: ctx.use(Changes),
browser: ctx.use(Browser),
filter: {
get: (session) => filters[session]?.text ?? "",
set: (session, value) => updateFilter(session, { text: value }),
browsing: (session) => filters[session]?.browsing ?? false,
setBrowsing: (session, value) => updateFilter(session, { browsing: value }),
},
installed: new Map(),
app: preference && {
current: () => preference.value.app,
set: (app) =>
preference.update((draft) => {
draft.app = app
}),
},
request: {
app: () => request.app,
set: (app) => setRequest("app", app),
},
handoff: {
get: (session, path) => handoff.sessions[session]?.[path],
set: (session, files) =>
setHandoff((draft) => {
delete draft.sessions[session]
draft.sessions[session] = files
const keys = Object.keys(draft.sessions)
keys.slice(0, Math.max(0, keys.length - HANDOFF_SESSIONS)).forEach((item) => delete draft.sessions[item])
}),
},
reveal: {
register(session, path, run) {
const targetKey = `${session}\n${path}`
const set = revealListeners.get(targetKey) ?? new Set()
set.add(run)
revealListeners.set(targetKey, set)
return () => {
set.delete(run)
if (set.size === 0) revealListeners.delete(targetKey)
}
},
run(session, path) {
revealListeners.get(`${session}\n${path}`)?.forEach((fn) => fn())
},
},
active,
open,
}
const FileProvider = (props: ParentProps) => (
<FileContext.Provider value={shared}>{props.children}</FileContext.Provider>
)
// Tab trigger styles render with the strip, before any panel chunk loads.
ctx.add(Style, tabStyles)
const style: StyleLoad = {}
const styled = <T,>(module: Promise<T>) => {
style.loaded ??= import("./styles").then((css) => void ctx.add(Style, css.default))
return Promise.all([module, style.loaded]).then(([value]) => value)
}
const FileBrowser = lazy(() => styled(import("./browser")))
const MobileFiles = lazy(() => styled(import("./mobile")))
const Tree = lazy(() => styled(import("./pierre-tree")))
const List = lazy(() => styled(import("./list")))
onCleanup(
onIdle(() => {
void import("./pierre-tree")
void FileBrowser.preload()
void Tree.preload()
void List.preload()
void import("./resolve-link")
if (layout.narrow()) void MobileFiles.preload()
}),
)
const launcher = (id: string): BuiltinPanelTab => ({
id,
get title() {
return ctx.t("command.open")
},
label: () => (
<div class="flex items-center gap-1.5">
<Icon name="file-tree" size="small" />
<span>{ctx.t("command.open")}</span>
</div>
),
draggable: false,
transient: true,
group: GROUP,
dom: { panel: TABPANEL },
})
const fileTab = (files: Files, id: string): BuiltinPanelTab => {
const path = () => fileTabPath(files, id)
const missing = () => files.missing(path())
return {
id,
get title() {
const name = getFilename(path())
return missing() ? ctx.t("tab.notFound", { name }) : name
},
label: (state) => <FileVisual path={path()} temporary={state.preview} notFound={missing()} />,
get missing() {
return missing()
},
get file() {
return path()
},
group: GROUP,
// A gone selection falls back to the first file tab.
fallback: true,
dom: { panel: TABPANEL },
}
}
ctx.add(BuiltinPanel, {
id: "main",
region: "side",
legacy: { "open-file": OPEN },
// Older builds stored some files as absolute paths; one file is one tab once the workspace root is known.
// Resolves the stored URL once and encodes the result, so an encoded name such as a%23b.txt stays one file.
normalize: (input) =>
isFileTab(input.id) && input.screen.file.ready()
? `//${encodeFilePath(fileTabPath(input.screen.file, input.id))}`
: input.id,
mobile: {
get title() {
return ctx.t("mobile.title")
},
order: 20,
kind: "menu",
icon: "folder",
},
list(input) {
return input.open.flatMap((id) => {
if (!isLauncher(id) && !isFileTab(id)) return []
const cache = tabsOf(input.screen)
const existing = cache.get(id)
if (existing) return [existing]
const created = isLauncher(id) ? launcher(id) : fileTab(input.screen.file, id)
cache.set(id, created)
return [created]
})
},
close(input) {
tabs.get(input.screen)?.delete(input.tab.id)
if (isFileTab(input.tab.id)) input.screen.file.unwatch(fileTabPath(input.screen.file, input.tab.id))
},
render: (props) => {
const panel = usePanel()
return (
<FileProvider>
<Suspense>
<Show
when={panel.placement() === "mobile"}
fallback={<FileBrowser tab={() => props.tab} session={props.session} screen={props.screen} />}
>
<MobileFiles session={props.session} screen={props.screen} />
</Show>
</Suspense>
</FileProvider>
)
},
focus(input) {
if (!isFileTab(input.tab.id)) return
focused.set(input.screen, input.tab.id)
void input.screen.file.sync(fileTabPath(input.screen.file, input.tab.id), { silent: true })
},
})
const browse = () => {
const session = sessions.current()
if (session) openPicker(session, shared.filter.get(session.key))
}
const mac = /(Mac|iPhone|iPad)/.test(navigator.platform)
ctx.add(
Command,
(): Command => ({
id: "browse",
title: ctx.t("command.open"),
group: ctx.t("command.category.view"),
bind: mac ? "ctrl+meta+p" : "ctrl+alt+p",
editable: true,
enabled: !!sessions.current(),
run: browse,
}),
)
// A new tab always offers another launcher, however many are open.
ctx.add(
MenuItem,
(): MenuItem => ({
menu: "session.panel",
id: "open",
title: ctx.t("command.open"),
icon: "file-tree",
keybind: "file.browse",
order: 30,
run: () => {
const session = sessions.current()
if (session) openPicker(session, "", { another: true })
},
}),
)
const OpenInAppButton = lazy(() => import("./open-in-app"))
// How many "Open in" buttons each screen's panel headers show; the tab strip shows its own only while none do.
const headers = new WeakMap<SessionScreen, Signal<number>>()
const headerButtons = (screen: SessionScreen) => {
const existing = headers.get(screen)
if (existing) return existing
const created = createSignal(0)
headers.set(screen, created)
return created
}
if (desktop) {
onCleanup(onIdle(() => void OpenInAppButton.preload()))
ctx.add(Slot, {
at: "session.panel.end",
render: (input) => (
<Show when={headerButtons(input.screen)[0]() === 0}>
<FileProvider>
<Suspense>
<OpenInAppButton session={input.session} screen={input.screen} />
</Suspense>
</FileProvider>
</Show>
),
})
}
ctx.provide(OpenInApp, {
Button: bindPlugin((props: OpenInAppProps) => {
const count = headerButtons(props.screen)
count[1]((value) => value + 1)
onCleanup(() => count[1]((value) => value - 1))
return (
<Show when={desktop}>
<FileProvider>
<Suspense>
<OpenInAppButton session={props.session} screen={props.screen} />
</Suspense>
</FileProvider>
</Show>
)
}),
})
// The review panel lists its changed files with the browser's tree; it renders under this plugin, on the
// session screen's file model.
ctx.provide(FileTree, {
Tree: bindPlugin((props: FileTreeProps) => (
<FileProvider>
<Suspense>
<Tree
session={props.session}
screen={props.screen}
allowed={props.allowed}
kinds={props.kinds}
labels={props.labels}
draggable={false}
active={props.active}
onFileClick={(node) => props.onFileClick(node.path)}
/>
</Suspense>
</FileProvider>
)),
List: bindPlugin((props: FileListProps) => (
<FileProvider>
<Suspense>
<List
session={props.session}
screen={props.screen}
files={props.files}
kinds={props.kinds}
active={props.active}
highlighted={props.highlighted}
onFileClick={(path) => props.onFileClick(path)}
/>
</Suspense>
</FileProvider>
)),
})
/**
* Turn a link into a path the file model can load: workspace-relative when it is under the root,
* otherwise absolute. Relative links resolve against `base`; ones that climb past the root
* become absolute too, so a `../../shared/report.pdf` still opens.
*/
const resolve = (files: Files, value: string, base?: string) => {
const root = files.root.replaceAll("\\", "/").replace(/\/+$/, "")
if (/^[a-z]:\//i.test(value) || value.startsWith("/")) return files.resolve(value)
const relative = resolveArtifactPath(base ?? "", value)
if (relative !== undefined) return files.resolve(relative)
// Climbing past the workspace root: resolve from the referencing folder's absolute location.
const dir = base ? `${root}/${base.replace(/\/+$/, "")}` : root
return files.resolve(resolveArtifactPath(dir, value) ?? value)
}
// Screens survive tab switches, unlike Markdown and MountedSession objects. Weak client keys also drop results
// from an old server connection without retaining its controller.
const linkChecks = new WeakMap<SessionScreen, WeakMap<ServerRef["client"], Map<string, LinkCheck>>>()
// Messages style a path as a link only when this says the file exists.
const linkExists = (link: Link): boolean | Promise<boolean> => {
const session = sessions.current()
const screen = ctx.screen.current()
const files = screen?.file
if (!session || !screen || !files || (link.session && link.session.key !== session.key)) return false
const clients = linkChecks.get(screen) ?? new WeakMap<ServerRef["client"], Map<string, LinkCheck>>()
linkChecks.set(screen, clients)
const client = session.server.client
const checks = clients.get(client) ?? new Map<string, LinkCheck>()
clients.set(client, checks)
const root = files.root
const key = JSON.stringify([session.key, root, link.base ?? null, link.href])
const cached = checks.get(key)
if (cached && cached.expires > Date.now()) return cached.known ?? cached.result
const current = () =>
!ctx.signal.aborted &&
sessions.current()?.key === session.key &&
files.root === root &&
session.server.client === client
const pending = import("./resolve-link")
.then(async ({ checkFileLinkExists, parseFileLink }) => {
if (!current()) return false
// A link in a previewed document opens relative to it, so only that path counts.
const path = parseFileLink(link.href).path
const direct =
link.base === undefined || path.startsWith("//") || path.startsWith("~")
? undefined
: resolve(files, path, link.base)
const exists = await (link.base === undefined
? checkFileLinkExists({ files, href: link.href, signal: ctx.signal })
: direct
? files.exists(direct)
: false)
if (!current()) return false
if (checks.get(key)?.result === pending)
checks.set(key, { result: exists, expires: Date.now() + (exists ? 60_000 : 5_000) })
return exists
})
.catch(() => false)
.finally(() => {
// Aborted, failed or no-longer-current checks are retryable, not cached negatives.
if (checks.get(key)?.result === pending) checks.delete(key)
})
// Revalidate known paths without bringing back their plain-code flash. Expired negatives await a fresh check.
const known = cached?.result === true ? true : undefined
checks.delete(key)
checks.set(key, { result: pending, expires: Infinity, known })
while (checks.size > 512) checks.delete(checks.keys().next().value!)
return known ?? pending
}
// Opens files the agent references as side panel tabs, inside or outside the workspace, or as
// a browser tab for HTML when the desktop can load the file directly.
ctx.add(LinkHandler, {
match: () => true,
exists: linkExists,
open(link) {
const session = sessions.current()
const screen = ctx.screen.current()
const files = screen?.file
if (!session || !screen || !files || (link.session && link.session.key !== session.key)) return
clickController?.abort()
// A known workspace file (the palette, a file comment) opens at once with every file listed.
if (link.exact || link.origin === "file") {
const path = files.resolve(link.href)
if (!path) return
open(session, path, { background: link.background })
return
}
const controller = new AbortController()
clickController = controller
const signal = AbortSignal.any([ctx.signal, controller.signal])
const sessionKey = session.key
const stillCurrent = () => {
const current = sessions.current()
return !signal.aborted && current?.key === sessionKey && ctx.screen.current() === screen ? current : undefined
}
const openResolvedFile = (targetPath: string, selection?: LineRange) => {
const routed = stillCurrent()
if (!routed) return Promise.resolve()
// The browser pane shows HTML it can load. While it is pending or off, the file opens as a tab instead.
const pane = ctx.use(Browser)()
if (artifactKind(targetPath) === "html" && pane.status === "active" && pane.value.canOpen(routed, targetPath)) {
pane.value.open(routed, workspaceFileUrl(files.root, targetPath))
return Promise.resolve()
}
// Confirm the file exists before a tab appears for it; a file deleted since its link rendered shows the load
// error. Always reread: a cached copy can be stale.
return files.sync(targetPath, { force: true }).then(() => {
const latest = stillCurrent()
if (!latest || !files.get(targetPath)?.loaded) return
batch(() => {
applySelection(latest, files, targetPath, selection)
layout.open(key(files, targetPath), latest, { background: link.background })
// A tapped link switches the narrow-screen view; the side region still opens for when the window is wide.
if (layout.narrow() && !layout.side.opened(latest)) layout.side.toggle(latest)
})
// After the batch, as in `open`: the mobile tab strip registers the tab before it leaves the browser.
updateFilter(latest.key, { browsing: false })
})
}
void (async () => {
const { findFileLink, isAbsoluteLink, parseFileLink } = await import("./resolve-link")
if (!stillCurrent()) return
const parsed = parseFileLink(link.href)
const direct = resolve(files, parsed.path, link.base)
if (!direct) return
// Absolute paths, links written relative to a document, and agent previews name one exact file.
if (isAbsoluteLink(parsed.path) || link.base !== undefined || link.background) {
await openResolvedFile(direct, parsed.selection)
return
}
const target = await findFileLink({ files, path: parsed.path, signal })
const latest = stillCurrent()
if (!latest) return
if (target?.kind === "picker") {
openPicker(latest, target.query)
return
}
// With no match, the literal path still covers files the search index skips, such as an ignored `.env`.
await openResolvedFile(target?.path ?? direct, parsed.selection)
})()
},
})
// A new workspace directory drops loaded files; reload the selected file tab.
const root = createMemo<string | undefined>((previous) => ctx.screen.current()?.file.root ?? previous)
const moved = createMemo(on(root, () => ({}), { defer: true }))
createKeyed(moved, () => {
const session = sessions.current()
const screen = ctx.screen.current()
if (!session || !screen) return
const id = focused.get(screen)
if (id && active(session, id)) void screen.file.sync(fileTabPath(screen.file, id), { force: true, silent: true })
})
}
export default setup