summaryrefslogtreecommitdiffhomepage
path: root/packages/app/src/context/file.tsx
blob: d7630509a1ba3a305db09e4d014980f8ed2ba65a (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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import { createEffect, createMemo, createRoot, 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 { useLanguage } from "@/context/language"
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,
  }
}

const WORKSPACE_KEY = "__workspace__"
const MAX_FILE_VIEW_SESSIONS = 20
const MAX_VIEW_FILES = 500

type ViewSession = ReturnType<typeof createViewSession>

type ViewCacheEntry = {
  value: ViewSession
  dispose: VoidFunction
}

function createViewSession(dir: string, id: string | undefined) {
  const legacyViewKey = `${dir}/file${id ? "/" + id : ""}.v1`

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

  const meta = { 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 (meta.pruned) return
    meta.pruned = true
    pruneView()
  })

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

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

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

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

  return {
    ready,
    scrollTop,
    scrollLeft,
    selectedLines,
    setScrollTop,
    setScrollLeft,
    setSelectedLines,
  }
}

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

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

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

      let path = input

      // Only strip protocol and decode if it's a file URI
      if (path.startsWith("file://")) {
        const raw = stripQueryAndHash(stripFileProtocol(path))
        try {
          // Attempt to treat as a standard URI
          path = decodeURIComponent(raw)
        } catch {
          // Fallback for legacy paths that might contain invalid URI sequences (e.g. "100%")
          // In this case, we treat the path as raw, but still strip the protocol
          path = raw
        }
      }

      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)
      const encoded = path.split("/").map(encodeURIComponent).join("/")
      return `file://${encoded}`
    }

    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 viewCache = new Map<string, ViewCacheEntry>()

    const disposeViews = () => {
      for (const entry of viewCache.values()) {
        entry.dispose()
      }
      viewCache.clear()
    }

    const pruneViews = () => {
      while (viewCache.size > MAX_FILE_VIEW_SESSIONS) {
        const first = viewCache.keys().next().value
        if (!first) return
        const entry = viewCache.get(first)
        entry?.dispose()
        viewCache.delete(first)
      }
    }

    const loadView = (dir: string, id: string | undefined) => {
      const key = `${dir}:${id ?? WORKSPACE_KEY}`
      const existing = viewCache.get(key)
      if (existing) {
        viewCache.delete(key)
        viewCache.set(key, existing)
        return existing.value
      }

      const entry = createRoot((dispose) => ({
        value: createViewSession(dir, id),
        dispose,
      }))

      viewCache.set(key, entry)
      pruneViews()
      return entry.value
    }

    const view = createMemo(() => loadView(params.dir!, params.id))

    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: language.t("toast.file.loadFailed.title"),
            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().scrollTop(normalize(input))
    const scrollLeft = (input: string) => view().scrollLeft(normalize(input))
    const selectedLines = (input: string) => view().selectedLines(normalize(input))

    const setScrollTop = (input: string, top: number) => {
      const path = normalize(input)
      view().setScrollTop(path, top)
    }

    const setScrollLeft = (input: string, left: number) => {
      const path = normalize(input)
      view().setScrollLeft(path, left)
    }

    const setSelectedLines = (input: string, range: SelectedLineRange | null) => {
      const path = normalize(input)
      view().setSelectedLines(path, range)
    }

    onCleanup(() => {
      stop()
      disposeViews()
    })

    return {
      ready: () => view().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)),
    }
  },
})