Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

9.2 KB
Raw Blame
import PeelCore
import SwiftUI

struct ProjectList: View {
    @Environment(ProjectLibrary.self) private var projects
    @State private var isRescanning = false
    @State private var searchText = ""

    private var isShowingRefusal: Binding<Bool> {
        Binding(
            get: { !projects.refused.isEmpty },
            set: { if !$0 { projects.clearRefusals() } }
        )
    }

    private var listed: [ProjectGroup] {
        let all = projects.groups ?? []
        guard !searchText.isEmpty else { return all }
        return all.filter { group in
            SearchText.matches(group.name, searchText)
                || group.artifacts.contains { $0.matches(searchText) }
        }
    }

    var body: some View {
        @Bindable var projects = projects
        let filtered = listed

        List(selection: $projects.selection) {
            if projects.needsFullDiskAccess || !projects.unreadable.isEmpty, !filtered.isEmpty {
                UnreadableFoldersNotice(folders: projects.unreadable, needsFullDiskAccess: projects.needsFullDiskAccess)
            }
            if !projects.unsearchable.isEmpty, !filtered.isEmpty {
                Notice(
                    title: Text("Some folders couldn’t be searched"),
                    detail: Text(verbatim: Self.reasons(projects.unsearchable)),
                    kind: .note
                ) {}
                .padding(.vertical, 6)
                .listRowSeparator(.hidden)
            }
            ForEach(filtered) { group in
                ProjectRow(group: group)
            }
        }
        .accessibilityLabel(Text(Tool.projects.title))
        .columnSearch(text: $searchText, prompt: "Search Build Artifacts", when: projects.groups?.isEmpty == false)
        .scanState(phase(filtered), isRescanning: isRescanning, scan: projects.scanRun) {
            if projects.folders.isEmpty {
                NoProjectFolders(suggested: projects.suggestedFolders) {
                    Task { await projects.addFolder() }
                } add: { folder in
                    Task { await projects.add([folder]) }
                }
            } else if !searchText.isEmpty, projects.groups?.isEmpty == false, filtered.isEmpty {
                ContentUnavailableView.search(text: searchText)
            } else if projects.groups?.isEmpty == true, projects.needsFullDiskAccess || !projects.unreadable.isEmpty {
                ContentUnavailableView {
                    Label("Not Everything Could Be Read", systemImage: "exclamationmark.triangle")
                } description: {
                    UnreadableFoldersDetail(
                        folders: projects.unreadable, needsFullDiskAccess: projects.needsFullDiskAccess
                    )
                    unsearchableReasons
                } actions: {
                    EmptyStateActions {
                        UnreadableFoldersActions(
                            folders: projects.unreadable,
                            needsFullDiskAccess: projects.needsFullDiskAccess
                        )
                    }
                }
            } else if projects.groups?.isEmpty == true, !projects.unsearchable.isEmpty {
                ContentUnavailableView {
                    Label("Not Everything Could Be Searched", systemImage: "exclamationmark.triangle")
                } description: {
                    unsearchableReasons
                }
            } else if projects.groups?.isEmpty == true {
                ContentUnavailableView(
                    "Nothing Built Here",
                    systemImage: "checkmark.seal",
                    description: Text("No build output was found in the folders you chose.")
                )
            }
        }
        .edgeBar(.bottom) {
            Group {
                if projects.wasCutShort {
                    Text("There were more folders than Peel looks at in one go, so this list isn’t all of them.")
                        .font(.caption)
                        .foregroundStyle(.secondary)
                        .padding(.horizontal, 12)
                        .padding(.bottom, 8)
                        .transition(.opacity)
                }
            }
            .motion(.settle, .movement, value: projects.wasCutShort)
        }
        .alert(projects.refused.count == 1 ? "That folder can’t be searched." : "These folders can’t be searched.", isPresented: isShowingRefusal) {
            Button("OK", role: .cancel) {}
        } message: {
            Text(verbatim: Self.reasons(projects.refused))
        }
        .fadesInColumn(whenRowsChange: projects.groups?.map(\.id))
        .navigationTitle(Text(Tool.projects.title))
        .announcesScan(
            projects.isScanning,
            found: projects.summary,
            couldNotLook: projects.folders.isEmpty ? "No Folders Yet"
                : !projects.unreadable.isEmpty ? "Not Everything Could Be Read"
                : !projects.unsearchable.isEmpty ? "Not Everything Could Be Searched" : nil,
            wasStopped: projects.scanRun.wasStopped
        )
        .toolbar {
            ToolbarItem {
                Menu {
                    // The title says what the item does. A bare path would read as a list of folders, and in macOS 27
                    // and later AppKit typically hides menu item images (`NSMenuItem.h`), so the symbol may not show.
                    ForEach(projects.folders, id: \.self) { folder in
                        Button("Stop Looking in \(folder.abbreviatedPath)", systemImage: "minus.circle") {
                            Task { await projects.removeFolder(folder) }
                        }
                    }
                    if !projects.folders.isEmpty {
                        Divider()
                    }
                    Button("Add Folder…", systemImage: "plus") {
                        Task { await projects.addFolder() }
                    }
                } label: {
                    ToolbarMenuLabel(title: "Folders", systemImage: "folder")
                }
                .help(Text("The folders Peel looks through"))
            }
            ToolbarItem {
                SelectOnEveryPage(
                    pages: SelectablePages(filtered.map { ($0.page, $0.artifacts.selectableRows) }),
                    selection: projects
                ) { page in
                    guard projects.selection == nil, let group = filtered.first(where: { $0.page == page }) else {
                        return
                    }
                    projects.selection = group.id
                }
            }
            ToolbarItem {
                RescanButton(
                    isRunning: $isRescanning,
                    isDisabled: projects.folders.isEmpty || projects.isRemoving,
                    scan: projects.scanRun
                ) {
                    await projects.refresh()
                }
            }
        }
        .task {
            await projects.readSuggestions()
            await projects.refreshUnlessScanned(within: ProjectLibrary.scanAgainAfter)
        }
        .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
            Task {
                await projects.readSuggestions()
                await projects.refreshUnlessScanned(within: ProjectLibrary.scanAgainAfter)
            }
        }
        .rescanOnExclusionChange("ProjectList") { await projects.refresh() }
        .rescanAfterPutBack(.projects) { await projects.refresh() }
    }

    @ViewBuilder private var unsearchableReasons: some View {
        if !projects.unsearchable.isEmpty {
            Text(verbatim: Self.reasons(projects.unsearchable))
        }
    }

    static func reasons(_ folders: [(url: URL, reason: ProjectArtifacts.Refusal)]) -> String {
        RemovalFailureAlert.firstItems(folders.map { "\($0.url.abbreviatedPath)\n\($0.reason.explanation)" })
            .joined(separator: "\n\n")
    }

    private func phase(_ filtered: [ProjectGroup]) -> ScanPhase {
        if projects.folders.isEmpty { return .message }
        if !searchText.isEmpty, projects.groups?.isEmpty == false, filtered.isEmpty { return .message }
        if projects.groups == nil { return projects.scanRun.wasStopped ? .stopped : .scanning(.walk) }
        if projects.groups?.isEmpty == true { return .message }
        return .content
    }
}

private struct ProjectRow: View {
    let group: ProjectGroup

    var body: some View {
        ToolRow(systemImage: "folder") {
            Text(verbatim: group.name)
                .lineLimit(1)
        } details: {
            switch group.lastChange {
            case .recently:
                StatusLabel(title: Text("Changed in the last 7 days"), systemImage: "hand.raised", tint: .accentColor)
            case .at(let last):
                Text("Last changed \(last, format: .relative(presentation: .named))")
                    .lineLimit(1)
            case .notKnown:
                Text("Too large to tell when it last changed")
            case .notReadInTime:
                Text("Took too long to tell when it last changed")
            case .none:
                EmptyView()
            }
        } trailing: {
            Text(group.total.text)
                .rowFigure()
        }
    }
}