import Foundation import HelderCore import HelderServices import Observation @Observable @MainActor public final class ExplorerStore { public private(set) var tree: FileNode? /// Expanded folders; a newly opened project starts fully collapsed. public private(set) var expanded: Set = [] /// The keyboard cursor, by path. public var selectedPath: String? /// Receives a toast title and its mono detail line; `WorkspaceModel` wires it to `ToastStore`. @ObservationIgnored public var notify: (_ title: String, _ detail: String?) -> Void = { _, _ in } @ObservationIgnored private let files: FileServicing @ObservationIgnored private let system: SystemActing @ObservationIgnored private var reloadGeneration = 0 public init(files: FileServicing, system: SystemActing) { self.files = files self.system = system } public func rows(showHidden: Bool) -> [TreeRow] { tree.map { FileTree.visibleRows($0, expanded: expanded, showHidden: showHidden) } ?? [] } /// Expands or collapses a folder and re-reads its children, so files the agent added show up. @discardableResult public func toggle(_ directory: String) -> Task { if expanded.contains(directory) { expanded.remove(directory) } else { expanded.insert(directory) } return Task { await refreshChildren(of: directory) } } /// Expands every ancestor of a path so its row is visible. public func reveal(_ path: String) { expanded.formUnion(PathUtils.ancestors(path)) } /// Reveals a path and puts the cursor on it: what opening a file does to the tree. public func select(_ path: String) { reveal(path) selectedPath = path } public func moveSelection(by step: Int, showHidden: Bool) { let list = rows(showHidden: showHidden) guard !list.isEmpty else { return } guard let index = list.firstIndex(where: { $0.path == selectedPath }) else { selectedPath = list[0].path return } selectedPath = list[min(max(index + step, 0), list.count - 1)].path } /// Carries expanded folders and the cursor over a rename. public func remap(from old: String, to new: String, isDirectory: Bool) { expanded = Set(expanded.map { PathUtils.remap($0, from: old, to: new, isDirectory: isDirectory) }) selectedPath = selectedPath.map { PathUtils.remap($0, from: old, to: new, isDirectory: isDirectory) } } // MARK: Loading /// Reloads the whole tree, keeping the expansion. public func reload() async { reloadGeneration += 1 let generation = reloadGeneration let fresh = await files.tree() guard generation == reloadGeneration else { return } tree = fresh } /// Loads once for a column that appears before `WorkspaceModel` loaded the tree. public func loadIfNeeded() async { if tree == nil { await reload() } } public func refreshChildren(of directory: String) async { let generation = reloadGeneration let children = await files.children(of: directory) // A full reload that started meanwhile already carries these children. guard generation == reloadGeneration, let tree else { return } self.tree = FileTree.replacingChildren(of: directory, with: children, in: tree) } // MARK: Disk changes /// Creates an empty file and returns its path; expands the parent folder. public func createFile(in directory: String, name: String) async throws -> String { let path = try newEntryPath(in: directory, name: name) try await files.createFile(path) reveal(path) await reload() return path } /// Creates a folder and returns its path; expands the parent and the new folder. public func createFolder(in directory: String, name: String) async throws -> String { let path = try newEntryPath(in: directory, name: name) try await files.createDirectory(path) reveal(path) expanded.insert(path) await reload() return path } /// Renames on disk and returns the new path; callers must also remap the editor. public func rename(_ path: String, to name: String, isDirectory: Bool) async throws -> String { guard let clean = PathUtils.validatedName(name) else { throw FileServiceError.invalidName(name) } let next = try await files.rename(path, to: clean) guard next != path else { return path } remap(from: path, to: next, isDirectory: isDirectory) await reload() return next } public func delete(_ path: String) async throws { let isDirectory = tree.flatMap { FileTree.find(path, in: $0) }?.isDirectory ?? false try await files.delete(path) expanded = expanded.filter { !PathUtils.isInside($0, path, isDirectory: true) } if let selected = selectedPath, PathUtils.isInside(selected, path, isDirectory: isDirectory) { selectedPath = nil } await reload() } // MARK: Prompt and menu flows /// Finishes the name prompt: creates or renames, toasts, and returns the resulting path (nil on failure or no-op). public func submitName(_ name: String, for purpose: NamePromptRequest.Purpose) async -> String? { do { switch purpose { case let .newFile(directory): let path = try await createFile(in: directory, name: name) notify("Created file", path) return path case let .newFolder(directory): let path = try await createFolder(in: directory, name: name) notify("Created folder", path) return path case let .rename(path, isDirectory): let next = try await rename(path, to: name, isDirectory: isDirectory) guard next != path else { return nil } notify(isDirectory ? "Renamed folder" : "Renamed file", next) return next } } catch { Log.error("fs", "\(purpose) failed: \(error)") switch purpose { case .rename: notify("Rename failed", name) case let .newFile(directory), let .newFolder(directory): notify("Create failed", PathUtils.newEntryPath(inDirectory: directory, name: name.trimmingCharacters(in: .whitespaces))) } return nil } } /// The prompt's preview line: the path a submit would create or rename to, or nil while the name is unusable. nonisolated public static func promptTarget(for purpose: NamePromptRequest.Purpose, name: String) -> String? { let trimmed = name.trimmingCharacters(in: .whitespaces) guard !trimmed.isEmpty else { return nil } switch purpose { case let .newFile(directory): return PathUtils.newEntryPath(inDirectory: directory, name: trimmed) case let .newFolder(directory): return PathUtils.newEntryPath(inDirectory: directory, name: trimmed) + "/" case let .rename(path, isDirectory): guard let clean = PathUtils.validatedName(trimmed), clean != PathUtils.basename(path) else { return nil } return PathUtils.reference(PathUtils.join(PathUtils.dirname(path), clean), isDirectory: isDirectory) } } /// Deletes after the confirm dialog, toasts, and returns whether it worked; callers must also drop editor state. public func deleteEntry(_ path: String, isDirectory: Bool) async -> Bool { do { try await delete(path) } catch { Log.error("fs", "delete failed: \(error)") notify("Delete failed", path) return false } notify(isDirectory ? "Deleted folder" : "Deleted file", path) return true } /// Delete always asks first; nothing else in the Explorer menu does. public func confirmation(for action: ContextAction) -> ConfirmRequest? { guard case let .delete(path, isDirectory) = action else { return nil } return ConfirmRequest( title: isDirectory ? "Delete folder?" : "Delete file?", body: isDirectory ? "\(path)/ and everything inside it will be permanently deleted." : "\(path) will be permanently deleted.", confirmLabel: "Delete", action: action) } /// Runs the actions that need no prompt: copy, Show in Finder, and an already confirmed delete. /// False for actions this store does not own (pass on, new, rename, git). @discardableResult public func perform(_ action: ContextAction) async -> Bool { switch action { case let .copyReference(text): system.copy(text) notify("Copied reference", text) case let .copyFileName(name): system.copy(name) notify("Copied", name) case let .revealInFinder(path): guard let url = files.absoluteURL(for: path) else { return true } system.revealInFinder(url) case let .delete(path, isDirectory): _ = await deleteEntry(path, isDirectory: isDirectory) default: return false } return true } /// The menu target for a visible row. public static func target(for row: TreeRow) -> ContextTarget { row.kind == .directory ? .directory(path: row.path) : .file(path: row.path) } private func newEntryPath(in directory: String, name: String) throws -> String { let trimmed = name.trimmingCharacters(in: .whitespaces) let path = PathUtils.newEntryPath(inDirectory: directory, name: trimmed) guard !trimmed.isEmpty, path != directory else { throw FileServiceError.invalidName(name) } return path } }