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 loadFolder: (path: string) => Promise createFile: (parentPath?: string) => Promise createFolder: (parentPath?: string) => Promise } 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((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 => { 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 => { 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 }, }))