dialog-select-directory.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. import { useDialog } from "@opencode-ai/ui/context/dialog"
  2. import { Dialog } from "@opencode-ai/ui/dialog"
  3. import { FileIcon } from "@opencode-ai/ui/file-icon"
  4. import { List } from "@opencode-ai/ui/list"
  5. import { getDirectory, getFilename } from "@opencode-ai/util/path"
  6. import fuzzysort from "fuzzysort"
  7. import { createMemo, createResource, createSignal } from "solid-js"
  8. import { useGlobalSDK } from "@/context/global-sdk"
  9. import { useGlobalSync } from "@/context/global-sync"
  10. import { useLanguage } from "@/context/language"
  11. import type { ListRef } from "@opencode-ai/ui/list"
  12. interface DialogSelectDirectoryProps {
  13. title?: string
  14. multiple?: boolean
  15. onSelect: (result: string | string[] | null) => void
  16. }
  17. type Row = {
  18. absolute: string
  19. search: string
  20. }
  21. export function DialogSelectDirectory(props: DialogSelectDirectoryProps) {
  22. const sync = useGlobalSync()
  23. const sdk = useGlobalSDK()
  24. const dialog = useDialog()
  25. const language = useLanguage()
  26. const [filter, setFilter] = createSignal("")
  27. let list: ListRef | undefined
  28. const missingBase = createMemo(() => !(sync.data.path.home || sync.data.path.directory))
  29. const [fallbackPath] = createResource(
  30. () => (missingBase() ? true : undefined),
  31. async () => {
  32. return sdk.client.path
  33. .get()
  34. .then((x) => x.data)
  35. .catch(() => undefined)
  36. },
  37. { initialValue: undefined },
  38. )
  39. const home = createMemo(() => sync.data.path.home || fallbackPath()?.home || "")
  40. const start = createMemo(
  41. () => sync.data.path.home || sync.data.path.directory || fallbackPath()?.home || fallbackPath()?.directory,
  42. )
  43. const cache = new Map<string, Promise<Array<{ name: string; absolute: string }>>>()
  44. const clean = (value: string) => {
  45. const first = (value ?? "").split(/\r?\n/)[0] ?? ""
  46. return first.replace(/[\u0000-\u001F\u007F]/g, "").trim()
  47. }
  48. function normalize(input: string) {
  49. const v = input.replaceAll("\\", "/")
  50. if (v.startsWith("//") && !v.startsWith("///")) return "//" + v.slice(2).replace(/\/+/g, "/")
  51. return v.replace(/\/+/g, "/")
  52. }
  53. function normalizeDriveRoot(input: string) {
  54. const v = normalize(input)
  55. if (/^[A-Za-z]:$/.test(v)) return v + "/"
  56. return v
  57. }
  58. function trimTrailing(input: string) {
  59. const v = normalizeDriveRoot(input)
  60. if (v === "/") return v
  61. if (v === "//") return v
  62. if (/^[A-Za-z]:\/$/.test(v)) return v
  63. return v.replace(/\/+$/, "")
  64. }
  65. function join(base: string | undefined, rel: string) {
  66. const b = trimTrailing(base ?? "")
  67. const r = trimTrailing(rel).replace(/^\/+/, "")
  68. if (!b) return r
  69. if (!r) return b
  70. if (b.endsWith("/")) return b + r
  71. return b + "/" + r
  72. }
  73. function rootOf(input: string) {
  74. const v = normalizeDriveRoot(input)
  75. if (v.startsWith("//")) return "//"
  76. if (v.startsWith("/")) return "/"
  77. if (/^[A-Za-z]:\//.test(v)) return v.slice(0, 3)
  78. return ""
  79. }
  80. function parentOf(input: string) {
  81. const v = trimTrailing(input)
  82. if (v === "/") return v
  83. if (v === "//") return v
  84. if (/^[A-Za-z]:\/$/.test(v)) return v
  85. const i = v.lastIndexOf("/")
  86. if (i <= 0) return "/"
  87. if (i === 2 && /^[A-Za-z]:/.test(v)) return v.slice(0, 3)
  88. return v.slice(0, i)
  89. }
  90. function modeOf(input: string) {
  91. const raw = normalizeDriveRoot(input.trim())
  92. if (!raw) return "relative" as const
  93. if (raw.startsWith("~")) return "tilde" as const
  94. if (rootOf(raw)) return "absolute" as const
  95. return "relative" as const
  96. }
  97. function display(path: string, input: string) {
  98. const full = trimTrailing(path)
  99. if (modeOf(input) === "absolute") return full
  100. return tildeOf(full) || full
  101. }
  102. function tildeOf(absolute: string) {
  103. const full = trimTrailing(absolute)
  104. const h = home()
  105. if (!h) return ""
  106. const hn = trimTrailing(h)
  107. const lc = full.toLowerCase()
  108. const hc = hn.toLowerCase()
  109. if (lc === hc) return "~"
  110. if (lc.startsWith(hc + "/")) return "~" + full.slice(hn.length)
  111. return ""
  112. }
  113. function row(absolute: string): Row {
  114. const full = trimTrailing(absolute)
  115. const tilde = tildeOf(full)
  116. const withSlash = (value: string) => {
  117. if (!value) return ""
  118. if (value.endsWith("/")) return value
  119. return value + "/"
  120. }
  121. const search = Array.from(
  122. new Set([full, withSlash(full), tilde, withSlash(tilde), getFilename(full)].filter(Boolean)),
  123. ).join("\n")
  124. return { absolute: full, search }
  125. }
  126. function scoped(value: string) {
  127. const base = start()
  128. if (!base) return
  129. const raw = normalizeDriveRoot(value)
  130. if (!raw) return { directory: trimTrailing(base), path: "" }
  131. const h = home()
  132. if (raw === "~") return { directory: trimTrailing(h ?? base), path: "" }
  133. if (raw.startsWith("~/")) return { directory: trimTrailing(h ?? base), path: raw.slice(2) }
  134. const root = rootOf(raw)
  135. if (root) return { directory: trimTrailing(root), path: raw.slice(root.length) }
  136. return { directory: trimTrailing(base), path: raw }
  137. }
  138. async function dirs(dir: string) {
  139. const key = trimTrailing(dir)
  140. const existing = cache.get(key)
  141. if (existing) return existing
  142. const request = sdk.client.file
  143. .list({ directory: key, path: "" })
  144. .then((x) => x.data ?? [])
  145. .catch(() => [])
  146. .then((nodes) =>
  147. nodes
  148. .filter((n) => n.type === "directory")
  149. .map((n) => ({
  150. name: n.name,
  151. absolute: trimTrailing(normalizeDriveRoot(n.absolute)),
  152. })),
  153. )
  154. cache.set(key, request)
  155. return request
  156. }
  157. async function match(dir: string, query: string, limit: number) {
  158. const items = await dirs(dir)
  159. if (!query) return items.slice(0, limit).map((x) => x.absolute)
  160. return fuzzysort.go(query, items, { key: "name", limit }).map((x) => x.obj.absolute)
  161. }
  162. const directories = async (filter: string) => {
  163. const value = clean(filter)
  164. const scopedInput = scoped(value)
  165. if (!scopedInput) return [] as string[]
  166. const raw = normalizeDriveRoot(value)
  167. const isPath = raw.startsWith("~") || !!rootOf(raw) || raw.includes("/")
  168. const query = normalizeDriveRoot(scopedInput.path)
  169. const find = () =>
  170. sdk.client.find
  171. .files({ directory: scopedInput.directory, query, type: "directory", limit: 50 })
  172. .then((x) => x.data ?? [])
  173. .catch(() => [])
  174. if (!isPath) {
  175. const results = await find()
  176. return results.map((rel) => join(scopedInput.directory, rel)).slice(0, 50)
  177. }
  178. const segments = query.replace(/^\/+/, "").split("/")
  179. const head = segments.slice(0, segments.length - 1).filter((x) => x && x !== ".")
  180. const tail = segments[segments.length - 1] ?? ""
  181. const cap = 12
  182. const branch = 4
  183. let paths = [scopedInput.directory]
  184. for (const part of head) {
  185. if (part === "..") {
  186. paths = paths.map(parentOf)
  187. continue
  188. }
  189. const next = (await Promise.all(paths.map((p) => match(p, part, branch)))).flat()
  190. paths = Array.from(new Set(next)).slice(0, cap)
  191. if (paths.length === 0) return [] as string[]
  192. }
  193. const out = (await Promise.all(paths.map((p) => match(p, tail, 50)))).flat()
  194. const deduped = Array.from(new Set(out))
  195. const base = raw.startsWith("~") ? trimTrailing(scopedInput.directory) : ""
  196. const expand = !raw.endsWith("/")
  197. if (!expand || !tail) {
  198. const items = base ? Array.from(new Set([base, ...deduped])) : deduped
  199. return items.slice(0, 50)
  200. }
  201. const needle = tail.toLowerCase()
  202. const exact = deduped.filter((p) => getFilename(p).toLowerCase() === needle)
  203. const target = exact[0]
  204. if (!target) return deduped.slice(0, 50)
  205. const children = await match(target, "", 30)
  206. const items = Array.from(new Set([...deduped, ...children]))
  207. return (base ? Array.from(new Set([base, ...items])) : items).slice(0, 50)
  208. }
  209. const items = async (value: string) => {
  210. const results = await directories(value)
  211. return results.map(row)
  212. }
  213. function resolve(absolute: string) {
  214. props.onSelect(props.multiple ? [absolute] : absolute)
  215. dialog.close()
  216. }
  217. return (
  218. <Dialog title={props.title ?? language.t("command.project.open")}>
  219. <List
  220. search={{ placeholder: language.t("dialog.directory.search.placeholder"), autofocus: true }}
  221. emptyMessage={language.t("dialog.directory.empty")}
  222. loadingMessage={language.t("common.loading")}
  223. items={items}
  224. key={(x) => x.absolute}
  225. filterKeys={["search"]}
  226. ref={(r) => (list = r)}
  227. onFilter={(value) => setFilter(clean(value))}
  228. onKeyEvent={(e, item) => {
  229. if (e.key !== "Tab") return
  230. if (e.shiftKey) return
  231. if (!item) return
  232. e.preventDefault()
  233. e.stopPropagation()
  234. const value = display(item.absolute, filter())
  235. list?.setFilter(value.endsWith("/") ? value : value + "/")
  236. }}
  237. onSelect={(path) => {
  238. if (!path) return
  239. resolve(path.absolute)
  240. }}
  241. >
  242. {(item) => {
  243. const path = display(item.absolute, filter())
  244. if (path === "~") {
  245. return (
  246. <div class="w-full flex items-center justify-between rounded-md">
  247. <div class="flex items-center gap-x-3 grow min-w-0">
  248. <FileIcon node={{ path: item.absolute, type: "directory" }} class="shrink-0 size-4" />
  249. <div class="flex items-center text-14-regular min-w-0">
  250. <span class="text-text-strong whitespace-nowrap">~</span>
  251. <span class="text-text-weak whitespace-nowrap">/</span>
  252. </div>
  253. </div>
  254. </div>
  255. )
  256. }
  257. return (
  258. <div class="w-full flex items-center justify-between rounded-md">
  259. <div class="flex items-center gap-x-3 grow min-w-0">
  260. <FileIcon node={{ path: item.absolute, type: "directory" }} class="shrink-0 size-4" />
  261. <div class="flex items-center text-14-regular min-w-0">
  262. <span class="text-text-weak whitespace-nowrap overflow-hidden overflow-ellipsis truncate min-w-0">
  263. {getDirectory(path)}
  264. </span>
  265. <span class="text-text-strong whitespace-nowrap">{getFilename(path)}</span>
  266. <span class="text-text-weak whitespace-nowrap">/</span>
  267. </div>
  268. </div>
  269. </div>
  270. )
  271. }}
  272. </List>
  273. </Dialog>
  274. )
  275. }