file.tsx 7.9 KB

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