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.

8.3 KB
Raw Blame
import PeelCore
import SwiftUI

struct ProjectDetailView: View {
    @Environment(ProjectLibrary.self) private var projects
    let group: ProjectGroup

    var body: some View {
        List {
            header
                .listRowSeparator(.hidden)
            RemovalsHeldBanner()

            Section {
                ForEach(Array(group.artifacts.enumerated()), id: \.element.id) { index, artifact in
                    RemovalRow(
                        url: artifact.url,
                        icon: .symbol("shippingbox"),
                        detail: detail(for: artifact),
                        warning: warning(for: artifact),
                        size: artifact.size ?? 0,
                        isMeasured: artifact.size != nil,
                        isFirst: index == 0,
                        selection: projects, isSelected: projects.isSelected(artifact.url)
                    )
                }
                .listRowSeparator(.hidden)
            } header: {
                SectionHeaderLine {
                    heading(
                        "What the Build Left",
                        "What a build makes again, and what it installed. Nothing is selected for you: Select Recommended selects what Peel is sure about, and every other row says why."
                    )
                } actions: {
                    SelectMenu(
                        list: group.artifacts.selectableRows,
                        place: Text(verbatim: group.name),
                        selection: projects
                    )
                }
            }

            Section {
                backupsCheckbox
                    .disabled(!projects.canMarkForBackups(group))
                    .listRowSeparator(.hidden)
                let failures = projects.backupMarkFailures(in: group)
                if !failures.isEmpty {
                    Text(verbatim: Self.whyMarksFailed(failures))
                        .font(.caption)
                        .foregroundStyle(.secondary)
                }
                if group.artifacts.contains(where: { projects.excludedFromAbove.contains($0.url) }) {
                    Text("Time Machine already leaves out some of these, through a folder above them or a rule of its own, so that part isn’t Peel’s to change.")
                        .font(.caption)
                        .foregroundStyle(.secondary)
                }
            } header: {
                Text("Backups")
            }
        }
        .scrollBarBelowSectionHeaders()
        .dimmedWhileBusy(projects.isScanning)
        .edgeBar(.bottom) {
            RemovalBar(
                page: group.page,
                isScanning: projects.isScanning,
                scan: projects.scanRun
            )
        }
        .fadesInColumn(whenRowsChange: group.artifacts.map(\.url))
        .navigationTitle(group.name)
        .toolbar(removing: .title)
    }

    /// A checkbox beside its words rather than a `Toggle` that is the row, as the list's other rows are.
    private var backupsCheckbox: some View {
        let isOn = Binding(
            get: { projects.isExcludedFromBackups(group) },
            set: { isExcluded in Task { await projects.setExcludedFromBackups(isExcluded, in: group) } }
        )
        let explanation = String(localized: "Backups keep the project and skip the folders listed here, node_modules and Pods included. Installed packages such as .venv, and the .terraform folder, stay in backups, as do folders whose name could mean anything and folders Peel doesn’t select because of what is inside. The mark sits on the folder itself: it moves with the folder, and a folder that a build deletes and makes again comes back without it.")
        let others = projects.markedByOthers(in: group).map(\.lastPathComponent)
        let othersNote = others.isEmpty ? nil : String(localized: "Time Machine already leaves out \(others.formatted(.list(type: .and))), which something other than Peel marked.")
        return HStack(alignment: .checkboxTitleLine, spacing: 5) {
            NativeCheckbox(
                isOn: isOn,
                label: String(localized: "Leave these out of Time Machine"),
                hint: [explanation, othersNote].compactMap(\.self).joined(separator: " ")
            )
            VStack(alignment: .leading, spacing: 2) {
                Text("Leave these out of Time Machine")
                    .checkboxTitleLine()
                Text(verbatim: explanation)
                    .font(.caption)
                    .foregroundStyle(.secondary)
                if let othersNote {
                    Text(verbatim: othersNote)
                        .font(.caption)
                        .foregroundStyle(.secondary)
                }
            }
            .checkboxTitle()
            .contentShape(.rect)
            .onTapGesture { isOn.wrappedValue.toggle() }
            // The checkbox's label already reads them.
            .accessibilityHidden(true)
        }
    }

    private var header: some View {
        PageHeader(systemImage: "folder") {
            Text(verbatim: group.name)
                .pageTitle()
                .help(Text(verbatim: group.name))
        } details: {
            Text(group.project.abbreviatedPath)
                .font(.subheadline.monospaced())
                .foregroundStyle(.secondary)
                .lineLimit(1)
                .truncationMode(.middle)
            if group.lastChange == .recently {
                NoteBadge(
                    title: Text("Changed in the last 7 days"), systemImage: "hand.raised",
                    name: String(localized: "Changed in the last 7 days"),
                    detail: Text("Something in this project changed in the last 7 days, so none of it is selected for you.")
                )
            }
        } trailing: {
            // The size of all the folders listed, selected or not. The bar at the bottom shows the selection's size.
            TotalLabel(total: group.total, caption: Text("in here"))
        }
        .contextMenu {
            ItemMenu(url: group.project)
        }
    }

    private func detail(for artifact: ProjectArtifact) -> LocalizedStringResource {
        guard let tool = artifact.tool else { return "Marked as a cache" }
        return "Made by \(tool)"
    }

    private func warning(for artifact: ProjectArtifact) -> String? {
        switch artifact.keptBecause {
        case .heldBack(let heldBack):
            String(localized: heldBack.explanation)
        case .installedPackages:
            artifact.name == ".terraform"
                ? String(localized: "Not selected: it holds your current workspace and the last backend configuration, which `terraform init` doesn’t bring back.")
                : String(localized: "Not selected: these are installed packages, not build output.")
        case .genericName:
            String(localized: "Not selected: \(artifact.name) is a common folder name, so Peel leaves the choice to you.")
        case .changedRecently:
            String(localized: "Not selected: something in this project changed in the last 7 days.")
        case .lastChangeNotKnown:
            String(localized: "Not selected: this project is too large for Peel to tell when it last changed.")
        case .lastChangeNotReadInTime:
            String(localized: "Not selected: Peel couldn’t read this project in time to tell when it last changed.")
        case nil:
            nil
        }
    }
}

extension ProjectDetailView {
    static func whyMarksFailed(_ failures: [TimeMachineExclusion.Refusal]) -> String {
        let owners = failures.compactMap { failure -> String? in
            guard case .ownedByAnotherAccount(let name) = failure else { return nil }
            return name ?? String(localized: "another account")
        }
        let refused = failures.count { $0 == .refused }
        var sentences: [String] = []
        if !owners.isEmpty {
            let accounts = Set(owners).sorted().formatted(.list(type: .and))
            sentences.append(String(inflecting: "^[\(owners.count) folder](inflect: true) belonging to \(accounts) wouldn’t take the mark."))
        }
        if refused > 0 {
            sentences.append(String(inflecting: "macOS refused the mark on ^[\(refused) folder](inflect: true) without saying why."))
        }
        return sentences.joined(separator: " ")
    }
}