From 979fb654f5ffa0716a966d41691d165b35bac266 Mon Sep 17 00:00:00 2001 From: Rudenko Dmitry Date: Fri, 23 Oct 2026 14:24:06 +0300 Subject: [PATCH] refactor: extract InspectorModel from AppModel - Move inspector target, Quick Look, metadata and file actions into InspectorModel - Forward objectWillChange and attach tree/current/selection providers - Migrate UI to model.inspector and keep compatibility wrappers - Add InspectorModelTests for target, Quick Look, metadata and copy paths - AppModel is now 1105 lines; 147 tests green Refs #66 --- .github/workflows/release.yml | 2 +- README.md | 2 +- ROADMAP.md | 2 +- Sources/DiskScope/DiskScopeApp.swift | 4 +- Sources/DiskScopeKit/App/AppModel.swift | 113 ++++------- Sources/DiskScopeKit/App/InspectorModel.swift | 176 ++++++++++++++++++ Sources/DiskScopeKit/UI/ContentView.swift | 2 +- Sources/DiskScopeKit/UI/DuplicatesView.swift | 2 +- Sources/DiskScopeKit/UI/InspectorView.swift | 46 +---- .../DiskScopeKit/UI/LargestFilesView.swift | 8 +- Sources/DiskScopeKit/UI/MapView.swift | 8 +- .../DiskScopeKit/UI/SimilarImagesView.swift | 2 +- Sources/DiskScopeKit/UI/TreemapView.swift | 8 +- Sources/DiskScopeKit/UI/TypesView.swift | 6 +- Sources/DiskScopeKit/UI/WindowChrome.swift | 4 +- .../InspectorModelTests.swift | 143 ++++++++++++++ docs/build.md | 2 +- 17 files changed, 388 insertions(+), 142 deletions(-) create mode 100644 Sources/DiskScopeKit/App/InspectorModel.swift create mode 100644 Tests/DiskScopeKitTests/InspectorModelTests.swift diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7ebf7e1..350aaa3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -270,5 +270,5 @@ jobs: echo "| SHA-256 DMG | \`${DMG_SHA256}\` |" echo "| SHA-256 ZIP | \`${ZIP_SHA256}\` |" echo "| Архитектуры | arm64 + x86_64 |" - echo "| Тесты | 143 XCTest |" + echo "| Тесты | 147 XCTest |" } >> "$GITHUB_STEP_SUMMARY" diff --git a/README.md b/README.md index 23bfa79..b39612f 100644 --- a/README.md +++ b/README.md @@ -371,7 +371,7 @@ Headless-сканер для бенчмарков: ## Тесты -143 теста: сравнение суммы скана с `du`, агрегация мелких файлов, пакеты, +147 тестов: сравнение суммы скана с `du`, агрегация мелких файлов, пакеты, симлинки, Unicode-имена, отказ доступа, отмена, copy-on-write удаление, свойства squarified-раскладки, вложенные ячейки, полный цикл `AppModel` (скан → навигация → фильтры), даты создания и изменения, правила очистки, diff --git a/ROADMAP.md b/ROADMAP.md index 6ef3a93..ee1a431 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -23,7 +23,7 @@ | 2.0 — Платформа | 6/6: локализация, notarization/Sparkle/Homebrew, CLI, App Intents, доступность, меню-бар | | Backlog | 5/5: кэш, параллельный скан, бюджеты, старые файлы, APFS-клоны | -Текущая база: **143 XCTest**, 17,9 тыс. строк исходников, 398 ключей +Текущая база: **147 XCTest**, 17,9 тыс. строк исходников, 398 ключей локализации, `main` зелёный. ## Принципы diff --git a/Sources/DiskScope/DiskScopeApp.swift b/Sources/DiskScope/DiskScopeApp.swift index 3fd1052..b43d1ef 100644 --- a/Sources/DiskScope/DiskScopeApp.swift +++ b/Sources/DiskScope/DiskScopeApp.swift @@ -83,9 +83,9 @@ struct DiskScopeApp: App { Button("Инспектор") { model.showInspector.toggle() } .keyboardShortcut("i", modifiers: [.command, .option]) .disabled(model.tree == nil) - Button("Быстрый просмотр") { model.previewSelection() } + Button("Быстрый просмотр") { model.inspector.previewSelection() } .keyboardShortcut("y", modifiers: .command) - .disabled(!model.canQuickLook) + .disabled(!model.inspector.canQuickLook) Divider() Button("Карта папки") { model.tab = .map } .keyboardShortcut("1", modifiers: .command) diff --git a/Sources/DiskScopeKit/App/AppModel.swift b/Sources/DiskScopeKit/App/AppModel.swift index f4bd3a8..237b2c1 100644 --- a/Sources/DiskScopeKit/App/AppModel.swift +++ b/Sources/DiskScopeKit/App/AppModel.swift @@ -105,8 +105,8 @@ public final class AppModel: ObservableObject { @Published public internal(set) var history: HistoryModel @Published public internal(set) var duplicates = DuplicatesModel() @Published public internal(set) var similar = SimilarModel() + @Published public internal(set) var inspector = InspectorModel() @Published public var showInspector = false - @Published public var quickLookURL: URL? @Published public internal(set) var budget = BudgetModel() @@ -162,6 +162,16 @@ public final class AppModel: ObservableObject { nav.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() }.store(in: &cancellables) + inspector.attach( + treeProvider: { [weak self] in self?.tree }, + currentIndexProvider: { [weak self] in self?.currentIndex ?? 0 }, + selectionProvider: { [weak self] in self?.selection ?? [] }, + toast: { [weak self] text, symbol in self?.showToast(text, symbol: symbol) }, + error: { [weak self] message in self?.errorMessage = message } + ) + inspector.objectWillChange.sink { [weak self] _ in + self?.objectWillChange.send() + }.store(in: &cancellables) trash.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() }.store(in: &cancellables) @@ -246,6 +256,31 @@ public final class AppModel: ObservableObject { set { nav.categoryFilter = newValue } } + // MARK: - Inspector compatibility + + public var inspectorNode: Int32? { inspector.inspectorNode } + public var canQuickLook: Bool { inspector.canQuickLook } + public var quickLookURL: URL? { + get { inspector.quickLookURL } + set { inspector.quickLookURL = newValue } + } + + public func previewSelection() { + inspector.previewSelection() + } + + public func previewNode(_ index: Int32) { + inspector.previewNode(index) + } + + public func copyPaths(_ indices: [Int32]) { + inspector.copyPaths(indices) + } + + public func openInTerminal(_ index: Int32) { + inspector.openInTerminal(index) + } + // MARK: - Derived state public var filteredLargestRows: [ItemRow] { @@ -952,82 +987,6 @@ extension AppModel { } } -extension AppModel { - // MARK: - Inspector and file actions - - public var inspectorNode: Int32? { - if selection.count == 1 { return selection.first } - if selection.isEmpty { return currentIndex } - return nil - } - - public var canQuickLook: Bool { - guard let tree else { return false } - return selection.contains { index in - index > 0 && Int(index) < tree.count - && !tree.isDeleted(index) - && tree.node(index).nodeKind == .file - } - } - - public func previewSelection() { - guard let tree else { return } - let index = selection.sorted().first { candidate in - candidate > 0 && Int(candidate) < tree.count - && !tree.isDeleted(candidate) - && tree.node(candidate).nodeKind == .file - } - guard let index else { - quickLookURL = nil - return - } - previewNode(index) - } - - public func previewNode(_ index: Int32) { - guard let tree, index > 0, Int(index) < tree.count, - !tree.isDeleted(index), - tree.node(index).nodeKind == .file else { return } - quickLookURL = tree.url(of: index) - } - - public func copyPaths(_ indices: [Int32]) { - guard let tree else { return } - let paths = indices.compactMap { index -> String? in - guard index >= 0, Int(index) < tree.count, !tree.isDeleted(index) else { return nil } - return tree.path(of: index) - } - guard !paths.isEmpty else { return } - NSPasteboard.general.clearContents() - NSPasteboard.general.setString(paths.joined(separator: "\n"), forType: .string) - showToast( - paths.count == 1 ? "Путь скопирован" : "Скопировано путей: \(paths.count)", - symbol: "doc.on.doc" - ) - } - - public func openInTerminal(_ index: Int32) { - guard let tree, index >= 0, Int(index) < tree.count, !tree.isDeleted(index) else { return } - let url = tree.url(of: index) - let folder = tree.isDirectory(index) ? url : url.deletingLastPathComponent() - let terminal = URL(fileURLWithPath: "/System/Applications/Utilities/Terminal.app") - guard FileManager.default.fileExists(atPath: terminal.path) else { - errorMessage = "Не удалось найти Terminal.app" - return - } - NSWorkspace.shared.open( - [folder], - withApplicationAt: terminal, - configuration: NSWorkspace.OpenConfiguration() - ) { [weak self] _, error in - guard let error else { return } - DispatchQueue.main.async { - self?.errorMessage = "Не удалось открыть терминал: \(error.localizedDescription)" - } - } - } -} - extension AppModel { public var freeSpaceText: String { guard let volume = internalVolume else { return "—" } diff --git a/Sources/DiskScopeKit/App/InspectorModel.swift b/Sources/DiskScopeKit/App/InspectorModel.swift new file mode 100644 index 0000000..201c67e --- /dev/null +++ b/Sources/DiskScopeKit/App/InspectorModel.swift @@ -0,0 +1,176 @@ +import AppKit +import Combine +import Foundation + +/// File-system metadata shown in the inspector for a single node. +public struct FileMetadata: Equatable, Sendable { + public let logicalSize: Int64? + public let created: Date? + public let modified: Date? + public let isPackage: Bool + + public init(logicalSize: Int64?, created: Date?, modified: Date?, isPackage: Bool) { + self.logicalSize = logicalSize + self.created = created + self.modified = modified + self.isPackage = isPackage + } +} + +/// Owns the inspector target, Quick Look, node metadata and file actions. +@MainActor +public final class InspectorModel: ObservableObject { + @Published public var quickLookURL: URL? + @Published public private(set) var metadata: FileMetadata? + @Published public private(set) var metadataIndex: Int32? + + private var treeProvider: () -> ScanTree? = { nil } + private var currentIndexProvider: () -> Int32 = { 0 } + private var selectionProvider: () -> Set = { [] } + private var toastHandler: (String, String) -> Void = { _, _ in } + private var errorHandler: (String) -> Void = { _ in } + private var metadataTreeID: ObjectIdentifier? + + public init() {} + + func attach( + treeProvider: @escaping () -> ScanTree?, + currentIndexProvider: @escaping () -> Int32, + selectionProvider: @escaping () -> Set, + toast: @escaping (String, String) -> Void, + error: @escaping (String) -> Void + ) { + self.treeProvider = treeProvider + self.currentIndexProvider = currentIndexProvider + self.selectionProvider = selectionProvider + self.toastHandler = toast + self.errorHandler = error + } + + // MARK: - Inspector target + + public var inspectorNode: Int32? { + let selection = selectionProvider() + if selection.count == 1 { return selection.first } + if selection.isEmpty { return currentIndexProvider() } + return nil + } + + public var canQuickLook: Bool { + guard let tree = treeProvider() else { return false } + return selectionProvider().contains { index in + index > 0 && Int(index) < tree.count + && !tree.isDeleted(index) + && tree.node(index).nodeKind == .file + } + } + + // MARK: - Quick Look + + public func previewSelection() { + guard let tree = treeProvider() else { return } + let index = selectionProvider().sorted().first { candidate in + candidate > 0 && Int(candidate) < tree.count + && !tree.isDeleted(candidate) + && tree.node(candidate).nodeKind == .file + } + guard let index else { + quickLookURL = nil + return + } + previewNode(index) + } + + public func previewNode(_ index: Int32) { + guard let tree = treeProvider(), index > 0, Int(index) < tree.count, + !tree.isDeleted(index), + tree.node(index).nodeKind == .file else { return } + quickLookURL = tree.url(of: index) + } + + // MARK: - Metadata + + /// Returns metadata only when it belongs to the current tree and node. + public func metadata(for index: Int32) -> FileMetadata? { + guard metadataIndex == index, + let tree = treeProvider(), + metadataTreeID == ObjectIdentifier(tree) else { return nil } + return metadata + } + + public func loadMetadata(for index: Int32) { + guard let tree = treeProvider(), index > 0, Int(index) < tree.count else { + resetMetadata() + return + } + let node = tree.node(index) + guard node.nodeKind != .aggregate else { + resetMetadata() + return + } + let treeID = ObjectIdentifier(tree) + let url = tree.url(of: index) + metadata = nil + metadataIndex = index + metadataTreeID = treeID + + let values = try? url.resourceValues(forKeys: [ + .fileSizeKey, + .creationDateKey, + .contentModificationDateKey, + .isPackageKey, + ]) + guard metadataIndex == index, metadataTreeID == treeID else { return } + metadata = FileMetadata( + logicalSize: values?.fileSize.map(Int64.init), + created: values?.creationDate, + modified: values?.contentModificationDate, + isPackage: values?.isPackage ?? false + ) + } + + private func resetMetadata() { + metadata = nil + metadataIndex = nil + metadataTreeID = nil + } + + // MARK: - File actions + + public func copyPaths(_ indices: [Int32]) { + guard let tree = treeProvider() else { return } + let paths = indices.compactMap { index -> String? in + guard index >= 0, Int(index) < tree.count, !tree.isDeleted(index) else { return nil } + return tree.path(of: index) + } + guard !paths.isEmpty else { return } + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(paths.joined(separator: "\n"), forType: .string) + toastHandler( + paths.count == 1 ? "Путь скопирован" : "Скопировано путей: \(paths.count)", + "doc.on.doc" + ) + } + + public func openInTerminal(_ index: Int32) { + guard let tree = treeProvider(), index >= 0, Int(index) < tree.count, + !tree.isDeleted(index) else { return } + let url = tree.url(of: index) + let folder = tree.isDirectory(index) ? url : url.deletingLastPathComponent() + let terminal = URL(fileURLWithPath: "/System/Applications/Utilities/Terminal.app") + guard FileManager.default.fileExists(atPath: terminal.path) else { + errorHandler("Не удалось найти Terminal.app") + return + } + NSWorkspace.shared.open( + [folder], + withApplicationAt: terminal, + configuration: NSWorkspace.OpenConfiguration() + ) { [weak self] _, error in + guard let error else { return } + DispatchQueue.main.async { + self?.errorHandler("Не удалось открыть терминал: \(error.localizedDescription)") + } + } + } +} diff --git a/Sources/DiskScopeKit/UI/ContentView.swift b/Sources/DiskScopeKit/UI/ContentView.swift index 94b95ba..e08c314 100644 --- a/Sources/DiskScopeKit/UI/ContentView.swift +++ b/Sources/DiskScopeKit/UI/ContentView.swift @@ -60,7 +60,7 @@ public struct ContentView: View { .environmentObject(model) } .onAppear { model.refreshVolumes() } - .quickLookPreview($model.quickLookURL) + .quickLookPreview($model.inspector.quickLookURL) .preferredColorScheme(AppAppearance(rawValue: appearance)?.colorScheme) .environment(\.locale, AppLanguage(rawValue: language)?.locale ?? Locale.current) } diff --git a/Sources/DiskScopeKit/UI/DuplicatesView.swift b/Sources/DiskScopeKit/UI/DuplicatesView.swift index b2bf16e..213b8b1 100644 --- a/Sources/DiskScopeKit/UI/DuplicatesView.swift +++ b/Sources/DiskScopeKit/UI/DuplicatesView.swift @@ -273,7 +273,7 @@ private struct DuplicateGroupCard: View { model.reveal(indices: [file.index]) } IconActionButton(symbol: "eye", help: "Быстрый просмотр") { - model.previewNode(file.index) + model.inspector.previewNode(file.index) } } .padding(.horizontal, 14) diff --git a/Sources/DiskScopeKit/UI/InspectorView.swift b/Sources/DiskScopeKit/UI/InspectorView.swift index ed75890..dc6904f 100644 --- a/Sources/DiskScopeKit/UI/InspectorView.swift +++ b/Sources/DiskScopeKit/UI/InspectorView.swift @@ -12,7 +12,7 @@ struct InspectorView: View { if selectedCount > 1 { multiSelection - } else if let index = model.inspectorNode { + } else if let index = model.inspector.inspectorNode { InspectorDetails(index: index) .environmentObject(model) } else { @@ -83,7 +83,7 @@ struct InspectorView: View { HStack(spacing: 6) { GhostButton(title: "Копировать пути", symbol: "doc.on.doc") { - model.copyPaths(Array(model.selection)) + model.inspector.copyPaths(Array(model.selection)) } GhostButton(title: "В коллекцию", symbol: "tray.full") { model.addToCollection(Array(model.selection)) @@ -99,21 +99,14 @@ struct InspectorView: View { } } -private struct FileMetadata { - let logicalSize: Int64? - let created: Date? - let modified: Date? - let isPackage: Bool -} - private struct InspectorDetails: View { @EnvironmentObject private var model: AppModel let index: Int32 - @State private var metadata: FileMetadata? @State private var budgetEditing = false @State private var budgetText = "" private var tree: ScanTree? { model.tree } + private var metadata: FileMetadata? { model.inspector.metadata(for: index) } private var node: ScanNode? { guard let tree, index >= 0, Int(index) < tree.count else { return nil } return tree.node(index) @@ -138,7 +131,7 @@ private struct InspectorDetails: View { .padding(12) } .task(id: index) { - await loadMetadata() + model.inspector.loadMetadata(for: index) } } @@ -318,16 +311,16 @@ private struct InspectorDetails: View { } if node?.nodeKind == .file { GhostButton(title: "Пробел", symbol: "eye") { - model.previewNode(index) + model.inspector.previewNode(index) } } } HStack(spacing: 6) { GhostButton(title: "Копировать путь", symbol: "doc.on.doc") { - model.copyPaths([index]) + model.inspector.copyPaths([index]) } GhostButton(title: "Терминал", symbol: "terminal") { - model.openInTerminal(index) + model.inspector.openInTerminal(index) } } GhostButton( @@ -398,29 +391,4 @@ private struct InspectorDetails: View { guard let date else { return "—" } return date.formatted(date: .abbreviated, time: .shortened) } - - private func loadMetadata() async { - guard let tree, index > 0, Int(index) < tree.count else { - metadata = nil - return - } - let node = tree.node(index) - guard node.nodeKind != .aggregate else { - metadata = nil - return - } - let url = tree.url(of: index) - let values = try? url.resourceValues(forKeys: [ - .fileSizeKey, - .creationDateKey, - .contentModificationDateKey, - .isPackageKey, - ]) - metadata = FileMetadata( - logicalSize: values?.fileSize.map(Int64.init), - created: values?.creationDate, - modified: values?.contentModificationDate, - isPackage: values?.isPackage ?? false - ) - } } diff --git a/Sources/DiskScopeKit/UI/LargestFilesView.swift b/Sources/DiskScopeKit/UI/LargestFilesView.swift index be50a76..a2c2571 100644 --- a/Sources/DiskScopeKit/UI/LargestFilesView.swift +++ b/Sources/DiskScopeKit/UI/LargestFilesView.swift @@ -125,7 +125,7 @@ struct LargestFilesView: View { .tableStyle(.inset(alternatesRowBackgrounds: false)) .scrollContentBackground(.hidden) .onKeyPress(.space) { - model.previewSelection() + model.inspector.previewSelection() return .handled } .contextMenu(forSelectionType: Int32.self) { selection in @@ -134,10 +134,10 @@ struct LargestFilesView: View { Button("Открыть") { model.openRow(first) } Button("Показать в Finder") { model.reveal(indices: Array(selection)) } if !isContainer { - Button("Быстрый просмотр") { model.previewNode(first) } + Button("Быстрый просмотр") { model.inspector.previewNode(first) } } - Button("Копировать путь") { model.copyPaths(Array(selection)) } - Button("Открыть в терминале") { model.openInTerminal(first) } + Button("Копировать путь") { model.inspector.copyPaths(Array(selection)) } + Button("Открыть в терминале") { model.inspector.openInTerminal(first) } let allCollected = selection.allSatisfy { model.isInCollection($0) } Button(allCollected ? "Убрать из коллекции" : "В коллекцию") { if allCollected { diff --git a/Sources/DiskScopeKit/UI/MapView.swift b/Sources/DiskScopeKit/UI/MapView.swift index f47311b..21cbdc7 100644 --- a/Sources/DiskScopeKit/UI/MapView.swift +++ b/Sources/DiskScopeKit/UI/MapView.swift @@ -65,7 +65,7 @@ struct ChildrenTable: View { .tableStyle(.inset(alternatesRowBackgrounds: false)) .scrollContentBackground(.hidden) .onKeyPress(.space) { - model.previewSelection() + model.inspector.previewSelection() return .handled } .contextMenu(forSelectionType: Int32.self) { selection in @@ -76,15 +76,15 @@ struct ChildrenTable: View { .disabled(isAggregate) Button("Показать в Finder") { model.reveal(indices: Array(selection)) } if !isContainer { - Button("Быстрый просмотр") { model.previewNode(first) } + Button("Быстрый просмотр") { model.inspector.previewNode(first) } } if isContainer { Button("Сканировать эту папку") { if let path = model.tree?.path(of: first) { model.scan(path: path) } } } - Button("Копировать путь") { model.copyPaths(Array(selection)) } - Button("Открыть в терминале") { model.openInTerminal(first) } + Button("Копировать путь") { model.inspector.copyPaths(Array(selection)) } + Button("Открыть в терминале") { model.inspector.openInTerminal(first) } let allCollected = selection.allSatisfy { model.isInCollection($0) } Button(allCollected ? "Убрать из коллекции" : "В коллекцию") { if allCollected { diff --git a/Sources/DiskScopeKit/UI/SimilarImagesView.swift b/Sources/DiskScopeKit/UI/SimilarImagesView.swift index 820594a..cb1de86 100644 --- a/Sources/DiskScopeKit/UI/SimilarImagesView.swift +++ b/Sources/DiskScopeKit/UI/SimilarImagesView.swift @@ -256,7 +256,7 @@ private struct SimilarGroupCard: View { model.reveal(indices: [image.index]) } IconActionButton(symbol: "eye", help: "Быстрый просмотр") { - model.previewNode(image.index) + model.inspector.previewNode(image.index) } } .padding(.horizontal, 14) diff --git a/Sources/DiskScopeKit/UI/TreemapView.swift b/Sources/DiskScopeKit/UI/TreemapView.swift index 0916d31..26a0999 100644 --- a/Sources/DiskScopeKit/UI/TreemapView.swift +++ b/Sources/DiskScopeKit/UI/TreemapView.swift @@ -86,7 +86,7 @@ struct TreemapView: View { } .onKeyPress(.space) { if let keyboardNode, tree.node(keyboardNode).nodeKind == .file { - model.previewNode(keyboardNode) + model.inspector.previewNode(keyboardNode) } return .handled } @@ -145,9 +145,9 @@ struct TreemapView: View { if let node = previewNode, isValid(node: node) { Button("Открыть") { model.openRow(node) } Button("Показать в Finder") { model.reveal(indices: [node]) } - Button("Быстрый просмотр") { model.previewNode(node) } - Button("Копировать путь") { model.copyPaths([node]) } - Button("Открыть в терминале") { model.openInTerminal(node) } + Button("Быстрый просмотр") { model.inspector.previewNode(node) } + Button("Копировать путь") { model.inspector.copyPaths([node]) } + Button("Открыть в терминале") { model.inspector.openInTerminal(node) } Divider() Button(model.isInCollection(node) ? "Убрать из коллекции" : "В коллекцию") { model.toggleCollection([node]) diff --git a/Sources/DiskScopeKit/UI/TypesView.swift b/Sources/DiskScopeKit/UI/TypesView.swift index 67cbcbb..db2cc23 100644 --- a/Sources/DiskScopeKit/UI/TypesView.swift +++ b/Sources/DiskScopeKit/UI/TypesView.swift @@ -308,10 +308,10 @@ private struct TopItemRow: View { Button("Открыть") { model.openRow(row.id) } Button("Показать в Finder") { model.reveal(indices: [row.id]) } if !row.isContainer { - Button("Быстрый просмотр") { model.previewNode(row.id) } + Button("Быстрый просмотр") { model.inspector.previewNode(row.id) } } - Button("Копировать путь") { model.copyPaths([row.id]) } - Button("Открыть в терминале") { model.openInTerminal(row.id) } + Button("Копировать путь") { model.inspector.copyPaths([row.id]) } + Button("Открыть в терминале") { model.inspector.openInTerminal(row.id) } Divider() Button(model.isInCollection(row.id) ? "Убрать из коллекции" : "В коллекцию") { model.toggleCollection([row.id]) diff --git a/Sources/DiskScopeKit/UI/WindowChrome.swift b/Sources/DiskScopeKit/UI/WindowChrome.swift index f1cc125..36e96a7 100644 --- a/Sources/DiskScopeKit/UI/WindowChrome.swift +++ b/Sources/DiskScopeKit/UI/WindowChrome.swift @@ -507,7 +507,7 @@ struct CommandPaletteView: View { model.showInspector.toggle() } ) - if model.canQuickLook { + if model.inspector.canQuickLook { items.append( PaletteCommand( id: "quick-look", @@ -516,7 +516,7 @@ struct CommandPaletteView: View { symbol: "eye", shortcut: "⌘Y" ) { - model.previewSelection() + model.inspector.previewSelection() } ) } diff --git a/Tests/DiskScopeKitTests/InspectorModelTests.swift b/Tests/DiskScopeKitTests/InspectorModelTests.swift new file mode 100644 index 0000000..28aed49 --- /dev/null +++ b/Tests/DiskScopeKitTests/InspectorModelTests.swift @@ -0,0 +1,143 @@ +import AppKit +import Foundation +import XCTest +@testable import DiskScopeKit + +@MainActor +final class InspectorModelTests: XCTestCase { + private func makeTree() throws -> ScanTree { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("DiskScopeInspector-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory( + at: root.appendingPathComponent("Sub"), + withIntermediateDirectories: true + ) + try Data(repeating: 0x41, count: 5_000) + .write(to: root.appendingPathComponent("video.mov")) + try Data(repeating: 0x42, count: 3_000) + .write(to: root.appendingPathComponent("Sub/notes.txt")) + addTeardownBlock { try? FileManager.default.removeItem(at: root) } + return try DiskScanner(options: .detailed).scan(path: root.path) + } + + private func index(of name: String, in tree: ScanTree) throws -> Int32 { + try XCTUnwrap(tree.children(of: 0).first { tree.name(of: $0) == name }) + } + + func testInspectorTargetFollowsSelectionAndCurrentFolder() throws { + let tree = try makeTree() + let file = try index(of: "video.mov", in: tree) + let folder = try index(of: "Sub", in: tree) + var selection: Set = [] + var currentIndex: Int32 = 0 + let inspector = InspectorModel() + inspector.attach( + treeProvider: { tree }, + currentIndexProvider: { currentIndex }, + selectionProvider: { selection }, + toast: { _, _ in }, + error: { _ in } + ) + + XCTAssertEqual(inspector.inspectorNode, 0) + XCTAssertFalse(inspector.canQuickLook) + + selection = [file] + XCTAssertEqual(inspector.inspectorNode, file) + XCTAssertTrue(inspector.canQuickLook) + + selection = [folder] + XCTAssertEqual(inspector.inspectorNode, folder) + XCTAssertFalse(inspector.canQuickLook) + + selection = [file, folder] + XCTAssertNil(inspector.inspectorNode) + XCTAssertTrue(inspector.canQuickLook) + + selection = [] + currentIndex = folder + XCTAssertEqual(inspector.inspectorNode, folder) + } + + func testQuickLookPrefersSelectedFileAndClearsForFolder() throws { + let tree = try makeTree() + let file = try index(of: "video.mov", in: tree) + let folder = try index(of: "Sub", in: tree) + var selection: Set = [] + let inspector = InspectorModel() + inspector.attach( + treeProvider: { tree }, + currentIndexProvider: { 0 }, + selectionProvider: { selection }, + toast: { _, _ in }, + error: { _ in } + ) + + inspector.previewSelection() + XCTAssertNil(inspector.quickLookURL) + + selection = [file] + inspector.previewSelection() + XCTAssertEqual(inspector.quickLookURL, tree.url(of: file)) + + selection = [folder] + inspector.previewSelection() + XCTAssertNil(inspector.quickLookURL) + + inspector.previewNode(file) + XCTAssertEqual(inspector.quickLookURL, tree.url(of: file)) + } + + func testMetadataLoadsForFileAndResetsForRoot() throws { + let tree = try makeTree() + let file = try index(of: "video.mov", in: tree) + let inspector = InspectorModel() + inspector.attach( + treeProvider: { tree }, + currentIndexProvider: { 0 }, + selectionProvider: { [] }, + toast: { _, _ in }, + error: { _ in } + ) + + inspector.loadMetadata(for: file) + let metadata = try XCTUnwrap(inspector.metadata(for: file)) + XCTAssertEqual(metadata.logicalSize, 5_000) + XCTAssertFalse(metadata.isPackage) + XCTAssertNotNil(metadata.created) + XCTAssertNotNil(metadata.modified) + + inspector.loadMetadata(for: 0) + XCTAssertNil(inspector.metadata) + XCTAssertNil(inspector.metadataIndex) + XCTAssertNil(inspector.metadata(for: file)) + } + + func testCopyPathsWritesPasteboardAndReportsToast() throws { + let tree = try makeTree() + let file = try index(of: "video.mov", in: tree) + let pasteboard = NSPasteboard.general + let previous = pasteboard.string(forType: .string) + addTeardownBlock { + pasteboard.clearContents() + if let previous { pasteboard.setString(previous, forType: .string) } + } + + var toasts: [(text: String, symbol: String)] = [] + let inspector = InspectorModel() + inspector.attach( + treeProvider: { tree }, + currentIndexProvider: { 0 }, + selectionProvider: { [] }, + toast: { toasts.append((text: $0, symbol: $1)) }, + error: { _ in } + ) + + inspector.copyPaths([file]) + + XCTAssertEqual(pasteboard.string(forType: .string), tree.path(of: file)) + XCTAssertEqual(toasts.count, 1) + XCTAssertEqual(toasts.first?.text, "Путь скопирован") + XCTAssertEqual(toasts.first?.symbol, "doc.on.doc") + } +} diff --git a/docs/build.md b/docs/build.md index 17a0b34..9972105 100644 --- a/docs/build.md +++ b/docs/build.md @@ -95,7 +95,7 @@ MKDOCS_SITE_URL=http://localhost:8000/ .venv/bin/mkdocs build --strict ## Тесты -143 XCTest-тестов покрывают: +147 XCTest-тестов покрывают: - сканер и точность суммы против `du`; - агрегацию мелких файлов, пакеты, симлинки, Unicode-имена;