file.tsx 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import { batch, createEffect, createMemo, onCleanup } from "solid-js"
  2. import { createStore, produce, reconcile } from "solid-js/store"
  3. import { createSimpleContext } from "@opencode-ai/ui/context"
  4. import { showToast } from "@/utils/toast"
  5. import { useParams } from "@solidjs/router"
  6. import { base64Encode } from "@opencode-ai/core/util/encode"
  7. import { getFilename } from "@opencode-ai/core/util/path"
  8. import { useSDK } from "./sdk"
  9. import { useSync } from "./sync"
  10. import { useLanguage } from "@/context/language"
  11. import { useLayout } from "@/context/layout"
  12. import { createPathHelpers } from "./file/path"
  13. import {
  14. approxBytes,
  15. evictContentLru,
  16. getFileContentBytesTotal,
  17. getFileContentEntryCount,
  18. hasFileContent,
  19. removeFileContentBytes,
  20. resetFileContentLru,
  21. setFileContentBytes,
  22. touchFileContent,
  23. } from "./file/content-cache"
  24. import { createFileViewCache } from "./file/view-cache"
  25. import { useServerSDK } from "./server-sdk"
  26. import { SessionRouteKey, SessionStateKey } from "@/utils/server-scope"
  27. import { createFileTreeStore } from "./file/tree-store"
  28. import { invalidateFromWatcher } from "./file/watcher"
  29. import {
  30. selectionFromLines,
  31. type FileState,
  32. type FileSelection,
  33. type FileViewState,
  34. type SelectedLineRange,
  35. } from "./file/types"
  36. export type { FileSelection, SelectedLineRange, FileViewState, FileState }
  37. export { selectionFromLines }
  38. export {
  39. evictContentLru,
  40. getFileContentBytesTotal,
  41. getFileContentEntryCount,
  42. removeFileContentBytes,
  43. resetFileContentLru,
  44. setFileContentBytes,
  45. touchFileContent,
  46. }
  47. function errorMessage(error: unknown, fallback: string) {
  48. if (error instanceof Error && error.message) return error.message
  49. if (typeof error === "string" && error) return error
  50. return fallback
  51. }
  52. export const { use: useFile, provider: FileProvider } = createSimpleContext({
  53. name: "File",
  54. gate: false,
  55. init: () => {
  56. const sdk = useSDK()
  57. useSync()
  58. const params = useParams()
  59. const serverSDK = useServerSDK()
  60. const language = useLanguage()
  61. const layout = useLayout()
  62. const scope = createMemo(() => sdk().directory)
  63. const path = createPathHelpers(scope)
  64. const tabs = layout.tabs(() =>
  65. SessionStateKey.from(serverSDK().scope, SessionRouteKey.fromRoute(base64Encode(sdk().directory), params.id)),
  66. )
  67. const inflight = new Map<string, Promise<void>>()
  68. const [store, setStore] = createStore<{
  69. file: Record<string, FileState>
  70. }>({
  71. file: {},
  72. })
  73. const tree = createFileTreeStore({
  74. scope,
  75. normalizeDir: path.normalizeDir,
  76. list: (dir) =>
  77. sdk()
  78. .client.file.list({ path: dir })
  79. .then((x) => x.data ?? []),
  80. onError: (message) => {
  81. showToast({
  82. variant: "error",
  83. title: language.t("toast.file.listFailed.title"),
  84. description: message,
  85. })
  86. },
  87. })
  88. const evictContent = (keep?: Set<string>) => {
  89. evictContentLru(keep, (target) => {
  90. if (!store.file[target]) return
  91. setStore(
  92. "file",
  93. target,
  94. produce((draft) => {
  95. draft.content = undefined
  96. draft.loaded = false
  97. }),
  98. )
  99. })
  100. }
  101. createEffect(() => {
  102. scope()
  103. inflight.clear()
  104. resetFileContentLru()
  105. batch(() => {
  106. setStore("file", reconcile({}))
  107. tree.reset()
  108. })
  109. })
  110. const viewCache = createFileViewCache(serverSDK().scope)
  111. const view = createMemo(() => viewCache.load(scope(), params.id))
  112. const ensure = (file: string) => {
  113. if (!file) return
  114. if (store.file[file]) return
  115. setStore("file", file, { path: file, name: getFilename(file) })
  116. }
  117. const setLoading = (file: string) => {
  118. setStore(
  119. "file",
  120. file,
  121. produce((draft) => {
  122. draft.loading = true
  123. draft.error = undefined
  124. }),
  125. )
  126. }
  127. const setLoaded = (file: string, content: FileState["content"]) => {
  128. setStore(
  129. "file",
  130. file,
  131. produce((draft) => {
  132. draft.loaded = true
  133. draft.loading = false
  134. draft.content = content
  135. }),
  136. )
  137. }
  138. const setLoadError = (file: string, message: string) => {
  139. setStore(
  140. "file",
  141. file,
  142. produce((draft) => {
  143. draft.loading = false
  144. draft.error = message
  145. }),
  146. )
  147. showToast({
  148. variant: "error",
  149. title: language.t("toast.file.loadFailed.title"),
  150. description: message,
  151. })
  152. }
  153. const load = (input: string, options?: { force?: boolean }) => {
  154. const file = path.normalize(input)
  155. if (!file) return Promise.resolve()
  156. const directory = scope()
  157. const key = `${directory}\n${file}`
  158. ensure(file)
  159. const current = store.file[file]
  160. if (!options?.force && current?.loaded) return Promise.resolve()
  161. const pending = inflight.get(key)
  162. if (pending) return pending
  163. setLoading(file)
  164. const promise = sdk()
  165. .client.file.read({ path: file })
  166. .then((x) => {
  167. if (scope() !== directory) return
  168. const content = x.data
  169. setLoaded(file, content)
  170. if (!content) return
  171. touchFileContent(file, approxBytes(content))
  172. evictContent(new Set([file]))
  173. })
  174. .catch((e) => {
  175. if (scope() !== directory) return
  176. setLoadError(file, errorMessage(e, language.t("error.chain.unknown")))
  177. })
  178. .finally(() => {
  179. inflight.delete(key)
  180. })
  181. inflight.set(key, promise)
  182. return promise
  183. }
  184. const search = (query: string, dirs: "true" | "false", options?: { limit?: number; signal?: AbortSignal }) =>
  185. serverSDK()
  186. .api.file.find(
  187. {
  188. location: { directory: sdk().directory },
  189. query,
  190. type: dirs === "true" ? "directory" : "file",
  191. limit: options?.limit,
  192. },
  193. { signal: options?.signal },
  194. )
  195. .then(
  196. (x) => x.data.map((entry) => path.normalize(entry.path)),
  197. (error) => {
  198. if (options?.signal?.aborted) throw error
  199. return []
  200. },
  201. )
  202. const stop = sdk().event.listen((e) => {
  203. invalidateFromWatcher(e.details, {
  204. normalize: path.normalize,
  205. hasFile: (file) => Boolean(store.file[file]),
  206. isOpen: (file) => tabs.all().some((tab) => path.pathFromTab(tab) === file),
  207. loadFile: (file) => {
  208. void load(file, { force: true })
  209. },
  210. node: tree.node,
  211. isDirLoaded: tree.isLoaded,
  212. refreshDir: (dir) => {
  213. void tree.listDir(dir, { force: true })
  214. },
  215. })
  216. })
  217. const get = (input: string) => {
  218. const file = path.normalize(input)
  219. const state = store.file[file]
  220. const content = state?.content
  221. if (!content) return state
  222. if (hasFileContent(file)) {
  223. touchFileContent(file)
  224. return state
  225. }
  226. touchFileContent(file, approxBytes(content))
  227. return state
  228. }
  229. function withPath(input: string, action: (file: string) => unknown) {
  230. return action(path.normalize(input))
  231. }
  232. const scrollTop = (input: string) => withPath(input, (file) => view().scrollTop(file))
  233. const scrollLeft = (input: string) => withPath(input, (file) => view().scrollLeft(file))
  234. const selectedLines = (input: string) => withPath(input, (file) => view().selectedLines(file))
  235. const setScrollTop = (input: string, top: number) => withPath(input, (file) => view().setScrollTop(file, top))
  236. const setScrollLeft = (input: string, left: number) => withPath(input, (file) => view().setScrollLeft(file, left))
  237. const setSelectedLines = (input: string, range: SelectedLineRange | null) =>
  238. withPath(input, (file) => view().setSelectedLines(file, range))
  239. onCleanup(() => {
  240. stop()
  241. viewCache.clear()
  242. })
  243. return {
  244. ready: () => view().ready(),
  245. normalize: path.normalize,
  246. tab: path.tab,
  247. pathFromTab: path.pathFromTab,
  248. tree: {
  249. list: tree.listDir,
  250. refresh: (input: string) => tree.listDir(input, { force: true }),
  251. state: tree.dirState,
  252. children: tree.children,
  253. expand: tree.expandDir,
  254. collapse: tree.collapseDir,
  255. toggle(input: string) {
  256. if (tree.dirState(input)?.expanded) {
  257. tree.collapseDir(input)
  258. return
  259. }
  260. tree.expandDir(input)
  261. },
  262. },
  263. get,
  264. load,
  265. scrollTop,
  266. scrollLeft,
  267. setScrollTop,
  268. setScrollLeft,
  269. selectedLines,
  270. setSelectedLines,
  271. searchFiles: (query: string, options?: { limit?: number; signal?: AbortSignal }) =>
  272. search(query, "false", options),
  273. searchFilesAndDirectories: (query: string) => search(query, "true"),
  274. }
  275. },
  276. })