aboutsummaryrefslogtreecommitdiff
path: root/src/stores/useFilesStore.ts
blob: 200fb68ea8c5b1b4f0c45fb8add7abece105adc1 (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
import { create } from 'zustand'
import type { FileEntry } from '@/types'
import { openDir, pickDirectory, writeFile, createDir } from '@/lib/tauri'

interface FilesState {
  fileTree: FileEntry[]
  rootPath: string | null
  loading: boolean
  openFolder: () => Promise<void>
  loadFolder: (path: string) => Promise<void>
  createFile: (parentPath?: string) => Promise<string | null>
  createFolder: (parentPath?: string) => Promise<string | null>
}

function generateName(base: string, existing: string[]): string {
  const used = new Set(existing)
  let name = base
  let counter = 1
  while (used.has(name)) {
    name = `${base} ${counter++}`
  }
  return name
}

function collectNames(entries: FileEntry[]): string[] {
  const names: string[] = []
  for (const e of entries) {
    names.push(e.name)
  }
  return names
}

export const useFilesStore = create<FilesState>((set, get) => ({
  fileTree: [],
  rootPath: null,
  loading: false,

  openFolder: async () => {
    const path = await pickDirectory()
    if (!path) return
    set({ rootPath: path, loading: true })
    localStorage.setItem('yace_last_folder', path)
    try {
      const entries = await openDir(path)
      set({ fileTree: entries, loading: false })
    } catch {
      set({ loading: false })
    }
  },

  loadFolder: async (path: string) => {
    set({ loading: true })
    try {
      const entries = await openDir(path)
      set({ fileTree: entries, rootPath: path, loading: false })
    } catch {
      set({ loading: false })
    }
  },

  createFile: async (parentPath?: string): Promise<string | null> => {
    const { rootPath, fileTree } = get()
    if (!rootPath) return null
    const targetDir = parentPath ?? rootPath
    const name = generateName('Untitled-1', collectNames(fileTree))
    const filePath = `${targetDir}\\${name}`
    await writeFile(filePath, '')
    const entries = await openDir(rootPath)
    set({ fileTree: entries })
    return filePath
  },

  createFolder: async (parentPath?: string): Promise<string | null> => {
    const { rootPath, fileTree } = get()
    if (!rootPath) return null
    const targetDir = parentPath ?? rootPath
    const name = generateName('New Folder', collectNames(fileTree))
    const dirPath = `${targetDir}\\${name}`
    await createDir(dirPath)
    const entries = await openDir(rootPath)
    set({ fileTree: entries })
    return dirPath
  },
}))