summaryrefslogtreecommitdiffhomepage
path: root/packages/app/src/context/file.tsx
blob: 050262ae6292e7bfca29e25784d0a1fba9b661e5 (plain)
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
import { createEffect, createMemo, onCleanup } from "solid-js"
import { createStore, produce } from "solid-js/store"
import { createSimpleContext } from "@opencode-ai/ui/context"
import type { FileContent } from "@opencode-ai/sdk/v2"
import { showToast } from "@opencode-ai/ui/toast"
import { useParams } from "@solidjs/router"
import { getFilename } from "@opencode-ai/util/path"
import { useSDK } from "./sdk"
import { useSync } from "./sync"
import { Persist, persisted } from "@/utils/persist"

export type FileSelection = {
  startLine: number
  startChar: number
  endLine: number
  endChar: number
}

export type SelectedLineRange = {
  start: number
  end: number
  side?: "additions" | "deletions"
  endSide?: "additions" | "deletions"
}

export type FileViewState = {
  scrollTop?: number
  scrollLeft?: number
  selectedLines?: SelectedLineRange | null
}

export type FileState = {
  path: string
  name: string
  loaded?: boolean
  loading?: boolean
  error?: string
  content?: FileContent
}

function stripFileProtocol(input: string) {
  if (!input.startsWith("file://")) return input
  return input.slice("file://".length)
}

function stripQueryAndHash(input: string) {
  const hashIndex = input.indexOf("#")
  const queryIndex = input.indexOf("?")

  if (hashIndex !== -1 && queryIndex !== -1) {
    return input.slice(0, Math.min(hashIndex, queryIndex))
  }

  if (hashIndex !== -1) return input.slice(0, hashIndex)
  if (queryIndex !== -1) return input.slice(0, queryIndex)
  return input
}

export function selectionFromLines(range: SelectedLineRange): FileSelection {
  const startLine = Math.min(range.start, range.end)
  const endLine = Math.max(range.start, range.end)
  return {
    startLine,
    endLine,
    startChar: 0,
    endChar: 0,
  }
}

function normalizeSelectedLines(range: SelectedLineRange): SelectedLineRange {
  if (range.start <= range.end) return range

  const startSide = range.side
  const endSide = range.endSide ?? startSide

  return {
    ...range,
    start: range.end,
    end: range.start,
    side: endSide,
    endSide: startSide !== endSide ? startSide : undefined,
  }
}

export const { use: useFile, provider: FileProvider } = createSimpleContext({
  name: "File",
  init: () => {
    const sdk = useSDK()
    const sync = useSync()
    const params = useParams()

    const directory = createMemo(() => sync.data.path.directory)

    function normalize(input: string) {
      const root = directory()
      const prefix = root.endsWith("/") ? root : root + "/"

      let path = stripQueryAndHash(stripFileProtocol(input))

      if (path.startsWith(prefix)) {
        path = path.slice(prefix.length)
      }

      if (path.startsWith(root)) {
        path = path.slice(root.length)
      }

      if (path.startsWith("./")) {
        path = path.slice(2)
      }

      if (path.startsWith("/")) {
        path = path.slice(1)
      }

      return path
    }

    function tab(input: string) {
      const path = normalize(input)
      return `file://${path}`
    }

    function pathFromTab(tabValue: string) {
      if (!tabValue.startsWith("file://")) return
      return normalize(tabValue)
    }

    const inflight = new Map<string, Promise<void>>()

    const [store, setStore] = createStore<{
      file: Record<string, FileState>
    }>({
      file: {},
    })

    const legacyViewKey = createMemo(() => `${params.dir}/file${params.id ? "/" + params.id : ""}.v1`)

    const [view, setView, _, ready] = persisted(
      Persist.scoped(params.dir!, params.id, "file-view", [legacyViewKey()]),
      createStore<{
        file: Record<string, FileViewState>
      }>({
        file: {},
      }),
    )

    const MAX_VIEW_FILES = 500
    const viewMeta = { pruned: false }

    const pruneView = (keep?: string) => {
      const keys = Object.keys(view.file)
      if (keys.length <= MAX_VIEW_FILES) return

      const drop = keys.filter((key) => key !== keep).slice(0, keys.length - MAX_VIEW_FILES)
      if (drop.length === 0) return

      setView(
        produce((draft) => {
          for (const key of drop) {
            delete draft.file[key]
          }
        }),
      )
    }

    createEffect(() => {
      if (!ready()) return
      if (viewMeta.pruned) return
      viewMeta.pruned = true
      pruneView()
    })

    function ensure(path: string) {
      if (!path) return
      if (store.file[path]) return
      setStore("file", path, { path, name: getFilename(path) })
    }

    function load(input: string, options?: { force?: boolean }) {
      const path = normalize(input)
      if (!path) return Promise.resolve()

      ensure(path)

      const current = store.file[path]
      if (!options?.force && current?.loaded) return Promise.resolve()

      const pending = inflight.get(path)
      if (pending) return pending

      setStore(
        "file",
        path,
        produce((draft) => {
          draft.loading = true
          draft.error = undefined
        }),
      )

      const promise = sdk.client.file
        .read({ path })
        .then((x) => {
          setStore(
            "file",
            path,
            produce((draft) => {
              draft.loaded = true
              draft.loading = false
              draft.content = x.data
            }),
          )
        })
        .catch((e) => {
          setStore(
            "file",
            path,
            produce((draft) => {
              draft.loading = false
              draft.error = e.message
            }),
          )
          showToast({
            variant: "error",
            title: "Failed to load file",
            description: e.message,
          })
        })
        .finally(() => {
          inflight.delete(path)
        })

      inflight.set(path, promise)
      return promise
    }

    const stop = sdk.event.listen((e) => {
      const event = e.details
      if (event.type !== "file.watcher.updated") return
      const path = normalize(event.properties.file)
      if (!path) return
      if (path.startsWith(".git/")) return
      if (!store.file[path]) return
      load(path, { force: true })
    })

    const get = (input: string) => store.file[normalize(input)]

    const scrollTop = (input: string) => view.file[normalize(input)]?.scrollTop
    const scrollLeft = (input: string) => view.file[normalize(input)]?.scrollLeft
    const selectedLines = (input: string) => view.file[normalize(input)]?.selectedLines

    const setScrollTop = (input: string, top: number) => {
      const path = normalize(input)
      setView("file", path, (current) => {
        if (current?.scrollTop === top) return current
        return {
          ...(current ?? {}),
          scrollTop: top,
        }
      })
      pruneView(path)
    }

    const setScrollLeft = (input: string, left: number) => {
      const path = normalize(input)
      setView("file", path, (current) => {
        if (current?.scrollLeft === left) return current
        return {
          ...(current ?? {}),
          scrollLeft: left,
        }
      })
      pruneView(path)
    }

    const setSelectedLines = (input: string, range: SelectedLineRange | null) => {
      const path = normalize(input)
      const next = range ? normalizeSelectedLines(range) : null
      setView("file", path, (current) => {
        if (current?.selectedLines === next) return current
        return {
          ...(current ?? {}),
          selectedLines: next,
        }
      })
      pruneView(path)
    }

    onCleanup(() => stop())

    return {
      ready,
      normalize,
      tab,
      pathFromTab,
      get,
      load,
      scrollTop,
      scrollLeft,
      setScrollTop,
      setScrollLeft,
      selectedLines,
      setSelectedLines,
      searchFiles: (query: string) =>
        sdk.client.find.files({ query, dirs: "false" }).then((x) => (x.data ?? []).map(normalize)),
      searchFilesAndDirectories: (query: string) =>
        sdk.client.find.files({ query, dirs: "true" }).then((x) => (x.data ?? []).map(normalize)),
    }
  },
})