file-tree.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. import { useFile } from "@/context/file"
  2. import { encodeFilePath } from "@/context/file/path"
  3. import { Collapsible } from "@opencode-ai/ui/collapsible"
  4. import { FileIcon } from "@opencode-ai/ui/file-icon"
  5. import { Icon } from "@opencode-ai/ui/icon"
  6. import {
  7. createEffect,
  8. createMemo,
  9. For,
  10. Match,
  11. on,
  12. Show,
  13. splitProps,
  14. Switch,
  15. untrack,
  16. type ComponentProps,
  17. type ParentProps,
  18. } from "solid-js"
  19. import { Dynamic } from "solid-js/web"
  20. import type { FileNode } from "@opencode-ai/sdk/v2"
  21. const MAX_DEPTH = 128
  22. function pathToFileUrl(filepath: string): string {
  23. return `file://${encodeFilePath(filepath)}`
  24. }
  25. type Kind = "add" | "del" | "mix"
  26. type Filter = {
  27. files: Set<string>
  28. dirs: Set<string>
  29. }
  30. export function shouldListRoot(input: { level: number; dir?: { loaded?: boolean; loading?: boolean } }) {
  31. if (input.level !== 0) return false
  32. if (input.dir?.loaded) return false
  33. if (input.dir?.loading) return false
  34. return true
  35. }
  36. export function shouldListExpanded(input: {
  37. level: number
  38. dir?: { expanded?: boolean; loaded?: boolean; loading?: boolean }
  39. }) {
  40. if (input.level === 0) return false
  41. if (!input.dir?.expanded) return false
  42. if (input.dir.loaded) return false
  43. if (input.dir.loading) return false
  44. return true
  45. }
  46. export function dirsToExpand(input: {
  47. level: number
  48. filter?: { dirs: Set<string> }
  49. expanded: (dir: string) => boolean
  50. }) {
  51. if (input.level !== 0) return []
  52. if (!input.filter) return []
  53. return [...input.filter.dirs].filter((dir) => !input.expanded(dir))
  54. }
  55. const kindLabel = (kind: Kind) => {
  56. if (kind === "add") return "A"
  57. if (kind === "del") return "D"
  58. return "M"
  59. }
  60. const kindTextColor = (kind: Kind) => {
  61. if (kind === "add") return "color: var(--icon-diff-add-base)"
  62. if (kind === "del") return "color: var(--icon-diff-delete-base)"
  63. return "color: var(--icon-diff-modified-base)"
  64. }
  65. const kindDotColor = (kind: Kind) => {
  66. if (kind === "add") return "background-color: var(--icon-diff-add-base)"
  67. if (kind === "del") return "background-color: var(--icon-diff-delete-base)"
  68. return "background-color: var(--icon-diff-modified-base)"
  69. }
  70. const visibleKind = (node: FileNode, kinds?: ReadonlyMap<string, Kind>, marks?: Set<string>) => {
  71. const kind = kinds?.get(node.path)
  72. if (!kind) return
  73. if (!marks?.has(node.path)) return
  74. return kind
  75. }
  76. const buildDragImage = (target: HTMLElement) => {
  77. const icon = target.querySelector('[data-component="file-icon"]') ?? target.querySelector("svg")
  78. const text = target.querySelector("span")
  79. if (!icon || !text) return
  80. const image = document.createElement("div")
  81. image.className =
  82. "flex items-center gap-x-2 px-2 py-1 bg-surface-raised-base rounded-md border border-border-base text-12-regular text-text-strong"
  83. image.style.position = "absolute"
  84. image.style.top = "-1000px"
  85. image.innerHTML = (icon as SVGElement).outerHTML + (text as HTMLSpanElement).outerHTML
  86. return image
  87. }
  88. const withFileDragImage = (event: DragEvent) => {
  89. const image = buildDragImage(event.currentTarget as HTMLElement)
  90. if (!image) return
  91. document.body.appendChild(image)
  92. event.dataTransfer?.setDragImage(image, 0, 12)
  93. setTimeout(() => document.body.removeChild(image), 0)
  94. }
  95. const FileTreeNode = (
  96. p: ParentProps &
  97. ComponentProps<"div"> &
  98. ComponentProps<"button"> & {
  99. node: FileNode
  100. level: number
  101. active?: string
  102. nodeClass?: string
  103. draggable: boolean
  104. kinds?: ReadonlyMap<string, Kind>
  105. marks?: Set<string>
  106. as?: "div" | "button"
  107. },
  108. ) => {
  109. const [local, rest] = splitProps(p, [
  110. "node",
  111. "level",
  112. "active",
  113. "nodeClass",
  114. "draggable",
  115. "kinds",
  116. "marks",
  117. "as",
  118. "children",
  119. "class",
  120. "classList",
  121. ])
  122. const kind = () => visibleKind(local.node, local.kinds, local.marks)
  123. const active = () => !!kind() && !local.node.ignored
  124. const color = () => {
  125. const value = kind()
  126. if (!value) return
  127. return kindTextColor(value)
  128. }
  129. return (
  130. <Dynamic
  131. component={local.as ?? "div"}
  132. classList={{
  133. "w-full min-w-0 h-6 flex items-center justify-start gap-x-1.5 rounded-md px-1.5 py-0 text-left hover:bg-surface-raised-base-hover active:bg-surface-base-active transition-colors cursor-pointer": true,
  134. "bg-surface-base-active": local.node.path === local.active,
  135. ...local.classList,
  136. [local.class ?? ""]: !!local.class,
  137. [local.nodeClass ?? ""]: !!local.nodeClass,
  138. }}
  139. style={`padding-left: ${Math.max(0, 8 + local.level * 12 - (local.node.type === "file" ? 24 : 4))}px`}
  140. draggable={local.draggable}
  141. onDragStart={(event: DragEvent) => {
  142. if (!local.draggable) return
  143. event.dataTransfer?.setData("text/plain", `file:${local.node.path}`)
  144. event.dataTransfer?.setData("text/uri-list", pathToFileUrl(local.node.path))
  145. if (event.dataTransfer) event.dataTransfer.effectAllowed = "copy"
  146. withFileDragImage(event)
  147. }}
  148. {...rest}
  149. >
  150. {local.children}
  151. <span
  152. classList={{
  153. "flex-1 min-w-0 text-12-medium whitespace-nowrap truncate": true,
  154. "text-text-weaker": local.node.ignored,
  155. "text-text-weak": !local.node.ignored && !active(),
  156. }}
  157. style={active() ? color() : undefined}
  158. >
  159. {local.node.name}
  160. </span>
  161. {(() => {
  162. const value = kind()
  163. if (!value) return null
  164. if (local.node.type === "file") {
  165. return (
  166. <span class="shrink-0 w-4 text-center text-12-medium" style={kindTextColor(value)}>
  167. {kindLabel(value)}
  168. </span>
  169. )
  170. }
  171. return <div class="shrink-0 size-1.5 mr-1.5 rounded-full" style={kindDotColor(value)} />
  172. })()}
  173. </Dynamic>
  174. )
  175. }
  176. export default function FileTree(props: {
  177. path: string
  178. class?: string
  179. nodeClass?: string
  180. active?: string
  181. level?: number
  182. allowed?: readonly string[]
  183. modified?: readonly string[]
  184. kinds?: ReadonlyMap<string, Kind>
  185. draggable?: boolean
  186. onFileClick?: (file: FileNode) => void
  187. _filter?: Filter
  188. _marks?: Set<string>
  189. _deeps?: Map<string, number>
  190. _kinds?: ReadonlyMap<string, Kind>
  191. _chain?: readonly string[]
  192. }) {
  193. const file = useFile()
  194. const level = props.level ?? 0
  195. const draggable = () => props.draggable ?? true
  196. const key = (p: string) =>
  197. file
  198. .normalize(p)
  199. .replace(/[\\/]+$/, "")
  200. .replaceAll("\\", "/")
  201. const chain = props._chain ? [...props._chain, key(props.path)] : [key(props.path)]
  202. const filter = createMemo(() => {
  203. if (props._filter) return props._filter
  204. const allowed = props.allowed
  205. if (!allowed) return
  206. const files = new Set(allowed)
  207. const dirs = new Set<string>()
  208. for (const item of allowed) {
  209. const parts = item.split("/")
  210. const parents = parts.slice(0, -1)
  211. for (const [idx] of parents.entries()) {
  212. const dir = parents.slice(0, idx + 1).join("/")
  213. if (dir) dirs.add(dir)
  214. }
  215. }
  216. return { files, dirs }
  217. })
  218. const marks = createMemo(() => {
  219. if (props._marks) return props._marks
  220. const out = new Set<string>()
  221. for (const item of props.modified ?? []) out.add(item)
  222. for (const item of props.kinds?.keys() ?? []) out.add(item)
  223. if (out.size === 0) return
  224. return out
  225. })
  226. const kinds = createMemo(() => {
  227. if (props._kinds) return props._kinds
  228. return props.kinds
  229. })
  230. const deeps = createMemo(() => {
  231. if (props._deeps) return props._deeps
  232. const out = new Map<string, number>()
  233. const root = props.path
  234. if (!(file.tree.state(root)?.expanded ?? false)) return out
  235. const seen = new Set<string>()
  236. const stack: { dir: string; lvl: number; i: number; kids: string[]; max: number }[] = []
  237. const push = (dir: string, lvl: number) => {
  238. const id = key(dir)
  239. if (seen.has(id)) return
  240. seen.add(id)
  241. const kids = file.tree
  242. .children(dir)
  243. .filter((node) => node.type === "directory" && (file.tree.state(node.path)?.expanded ?? false))
  244. .map((node) => node.path)
  245. stack.push({ dir, lvl, i: 0, kids, max: lvl })
  246. }
  247. push(root, level - 1)
  248. while (stack.length > 0) {
  249. const top = stack[stack.length - 1]!
  250. if (top.i < top.kids.length) {
  251. const next = top.kids[top.i]!
  252. top.i++
  253. push(next, top.lvl + 1)
  254. continue
  255. }
  256. out.set(top.dir, top.max)
  257. stack.pop()
  258. const parent = stack[stack.length - 1]
  259. if (!parent) continue
  260. parent.max = Math.max(parent.max, top.max)
  261. }
  262. return out
  263. })
  264. createEffect(() => {
  265. const current = filter()
  266. const dirs = dirsToExpand({
  267. level,
  268. filter: current,
  269. expanded: (dir) => untrack(() => file.tree.state(dir)?.expanded) ?? false,
  270. })
  271. for (const dir of dirs) file.tree.expand(dir)
  272. })
  273. createEffect(
  274. on(
  275. () => props.path,
  276. (path) => {
  277. const dir = untrack(() => file.tree.state(path))
  278. if (!shouldListRoot({ level, dir })) return
  279. void file.tree.list(path)
  280. },
  281. { defer: false },
  282. ),
  283. )
  284. const nodes = createMemo(() => {
  285. const nodes = file.tree.children(props.path)
  286. const current = filter()
  287. if (!current) return nodes
  288. const parent = (path: string) => {
  289. const idx = path.lastIndexOf("/")
  290. if (idx === -1) return ""
  291. return path.slice(0, idx)
  292. }
  293. const leaf = (path: string) => {
  294. const idx = path.lastIndexOf("/")
  295. return idx === -1 ? path : path.slice(idx + 1)
  296. }
  297. const out = nodes.filter((node) => {
  298. if (node.type === "file") return current.files.has(node.path)
  299. return current.dirs.has(node.path)
  300. })
  301. const seen = new Set(out.map((node) => node.path))
  302. for (const dir of current.dirs) {
  303. if (parent(dir) !== props.path) continue
  304. if (seen.has(dir)) continue
  305. out.push({
  306. name: leaf(dir),
  307. path: dir,
  308. absolute: dir,
  309. type: "directory",
  310. ignored: false,
  311. })
  312. seen.add(dir)
  313. }
  314. for (const item of current.files) {
  315. if (parent(item) !== props.path) continue
  316. if (seen.has(item)) continue
  317. out.push({
  318. name: leaf(item),
  319. path: item,
  320. absolute: item,
  321. type: "file",
  322. ignored: false,
  323. })
  324. seen.add(item)
  325. }
  326. out.sort((a, b) => {
  327. if (a.type !== b.type) {
  328. return a.type === "directory" ? -1 : 1
  329. }
  330. return a.name.localeCompare(b.name)
  331. })
  332. return out
  333. })
  334. return (
  335. <div data-component="filetree" class={`flex flex-col gap-0.5 ${props.class ?? ""}`}>
  336. <For each={nodes()}>
  337. {(node) => {
  338. const expanded = () => file.tree.state(node.path)?.expanded ?? false
  339. const deep = () => deeps().get(node.path) ?? -1
  340. const kind = () => visibleKind(node, kinds(), marks())
  341. const active = () => !!kind() && !node.ignored
  342. return (
  343. <Switch>
  344. <Match when={node.type === "directory"}>
  345. <Collapsible
  346. variant="ghost"
  347. class="w-full"
  348. data-scope="filetree"
  349. forceMount={false}
  350. open={expanded()}
  351. onOpenChange={(open) => (open ? file.tree.expand(node.path) : file.tree.collapse(node.path))}
  352. >
  353. <Collapsible.Trigger>
  354. <FileTreeNode
  355. node={node}
  356. level={level}
  357. active={props.active}
  358. nodeClass={props.nodeClass}
  359. draggable={draggable()}
  360. kinds={kinds()}
  361. marks={marks()}
  362. >
  363. <div class="size-4 flex items-center justify-center text-icon-weak">
  364. <Icon name={expanded() ? "chevron-down" : "chevron-right"} size="small" />
  365. </div>
  366. </FileTreeNode>
  367. </Collapsible.Trigger>
  368. <Collapsible.Content class="relative pt-0.5">
  369. <div
  370. classList={{
  371. "absolute top-0 bottom-0 w-px pointer-events-none bg-border-weak-base opacity-0 transition-opacity duration-150 ease-out motion-reduce:transition-none": true,
  372. "group-hover/filetree:opacity-100": expanded() && deep() === level,
  373. "group-hover/filetree:opacity-50": !(expanded() && deep() === level),
  374. }}
  375. style={`left: ${Math.max(0, 8 + level * 12 - 4) + 8}px`}
  376. />
  377. <Show
  378. when={level < MAX_DEPTH && !chain.includes(key(node.path))}
  379. fallback={<div class="px-2 py-1 text-12-regular text-text-weak">...</div>}
  380. >
  381. <FileTree
  382. path={node.path}
  383. level={level + 1}
  384. allowed={props.allowed}
  385. modified={props.modified}
  386. kinds={props.kinds}
  387. active={props.active}
  388. draggable={props.draggable}
  389. onFileClick={props.onFileClick}
  390. _filter={filter()}
  391. _marks={marks()}
  392. _deeps={deeps()}
  393. _kinds={kinds()}
  394. _chain={chain}
  395. />
  396. </Show>
  397. </Collapsible.Content>
  398. </Collapsible>
  399. </Match>
  400. <Match when={node.type === "file"}>
  401. <FileTreeNode
  402. node={node}
  403. level={level}
  404. active={props.active}
  405. nodeClass={props.nodeClass}
  406. draggable={draggable()}
  407. kinds={kinds()}
  408. marks={marks()}
  409. as="button"
  410. type="button"
  411. onClick={() => props.onFileClick?.(node)}
  412. >
  413. <div class="w-4 shrink-0" />
  414. <Switch>
  415. <Match when={node.ignored}>
  416. <FileIcon
  417. node={node}
  418. class="size-4 filetree-icon filetree-icon--mono"
  419. style="color: var(--icon-weak-base)"
  420. mono
  421. />
  422. </Match>
  423. <Match when={active()}>
  424. <FileIcon
  425. node={node}
  426. class="size-4 filetree-icon filetree-icon--mono"
  427. style={kindTextColor(kind()!)}
  428. mono
  429. />
  430. </Match>
  431. <Match when={!node.ignored}>
  432. <span class="filetree-iconpair size-4">
  433. <FileIcon
  434. node={node}
  435. class="size-4 filetree-icon filetree-icon--color opacity-0 group-hover/filetree:opacity-100"
  436. />
  437. <FileIcon
  438. node={node}
  439. class="size-4 filetree-icon filetree-icon--mono group-hover/filetree:opacity-0"
  440. mono
  441. />
  442. </span>
  443. </Match>
  444. </Switch>
  445. </FileTreeNode>
  446. </Match>
  447. </Switch>
  448. )
  449. }}
  450. </For>
  451. </div>
  452. )
  453. }