aboutsummaryrefslogtreecommitdiff
path: root/src/stores/useFilesStore.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/stores/useFilesStore.ts')
-rw-r--r--src/stores/useFilesStore.ts84
1 files changed, 84 insertions, 0 deletions
diff --git a/src/stores/useFilesStore.ts b/src/stores/useFilesStore.ts
new file mode 100644
index 0000000..200fb68
--- /dev/null
+++ b/src/stores/useFilesStore.ts
@@ -0,0 +1,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
+ },
+}))