diff --git a/Mac/CloudKitStats/CleanUp/CloudKitStatsCleanUpContentView.swift b/Mac/CloudKitStats/CleanUp/CloudKitStatsCleanUpContentView.swift new file mode 100644 index 000000000..7ee49d792 --- /dev/null +++ b/Mac/CloudKitStats/CleanUp/CloudKitStatsCleanUpContentView.swift @@ -0,0 +1,156 @@ +// +// CloudKitStatsCleanUpContentView.swift +// NetNewsWire +// +// Created by Brent Simmons on 3/24/26. +// + +import AppKit + +final class CloudKitStatsCleanUpContentView: NSView { + + let staleStatusDeletedLabel = NSTextField(labelWithString: "0") + let readContentDeletedLabel = NSTextField(labelWithString: "0") + let unreadContentDeletedLabel = NSTextField(labelWithString: "0") + let orphanedContentDeletedLabel = NSTextField(labelWithString: "0") + + let staleStatusDeletedRow: NSView + let readContentDeletedRow: NSView + let unreadContentDeletedRow: NSView + let orphanedContentDeletedRow: NSView + + let errorTextField = NSTextField(wrappingLabelWithString: "") + let refreshButton = NSButton() + + let navigationButtonGroup = NSView() + let returnToPreviousResultsButton = NSButton() + let refreshScanButton = NSButton() + + private let statsStackView = NSStackView() + + init() { + staleStatusDeletedRow = Self.makeStatRow(NSLocalizedString("Stale Status Deleted", comment: "Cleanup stat row label"), valueLabel: staleStatusDeletedLabel) + readContentDeletedRow = Self.makeStatRow(NSLocalizedString("Read Content Deleted", comment: "Cleanup stat row label"), valueLabel: readContentDeletedLabel) + unreadContentDeletedRow = Self.makeStatRow(NSLocalizedString("Unread Content Deleted", comment: "Cleanup stat row label"), valueLabel: unreadContentDeletedLabel) + orphanedContentDeletedRow = Self.makeStatRow(NSLocalizedString("Orphaned Content Deleted", comment: "Cleanup stat row label"), valueLabel: orphanedContentDeletedLabel) + + super.init(frame: .zero) + translatesAutoresizingMaskIntoConstraints = false + + configureStatsStack() + configureErrorViews() + configureNavigationButtons() + + addSubview(statsStackView) + addSubview(navigationButtonGroup) + + let availableSpace = NSLayoutGuide() + addLayoutGuide(availableSpace) + + NSLayoutConstraint.activate([ + statsStackView.topAnchor.constraint(equalTo: topAnchor), + statsStackView.leadingAnchor.constraint(equalTo: leadingAnchor), + statsStackView.trailingAnchor.constraint(equalTo: trailingAnchor), + + availableSpace.topAnchor.constraint(equalTo: statsStackView.bottomAnchor), + availableSpace.bottomAnchor.constraint(equalTo: bottomAnchor), + + navigationButtonGroup.centerYAnchor.constraint(equalTo: availableSpace.centerYAnchor), + navigationButtonGroup.centerXAnchor.constraint(equalTo: centerXAnchor) + ]) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +// MARK: - Private + +private extension CloudKitStatsCleanUpContentView { + + func configureStatsStack() { + statsStackView.translatesAutoresizingMaskIntoConstraints = false + statsStackView.orientation = .vertical + statsStackView.alignment = .leading + statsStackView.spacing = CloudKitStatsLayout.rowSpacing + + statsStackView.addArrangedSubview(staleStatusDeletedRow) + statsStackView.addArrangedSubview(readContentDeletedRow) + statsStackView.addArrangedSubview(unreadContentDeletedRow) + statsStackView.addArrangedSubview(orphanedContentDeletedRow) + statsStackView.addArrangedSubview(errorTextField) + statsStackView.addArrangedSubview(refreshButton) + + NSLayoutConstraint.activate([ + staleStatusDeletedRow.widthAnchor.constraint(equalTo: statsStackView.widthAnchor), + readContentDeletedRow.widthAnchor.constraint(equalTo: statsStackView.widthAnchor), + unreadContentDeletedRow.widthAnchor.constraint(equalTo: statsStackView.widthAnchor), + orphanedContentDeletedRow.widthAnchor.constraint(equalTo: statsStackView.widthAnchor), + errorTextField.widthAnchor.constraint(equalTo: statsStackView.widthAnchor) + ]) + } + + func configureErrorViews() { + errorTextField.textColor = .secondaryLabelColor + errorTextField.font = .systemFont(ofSize: NSFont.systemFontSize) + errorTextField.isHidden = true + + refreshButton.bezelStyle = .rounded + refreshButton.title = NSLocalizedString("Refresh", comment: "Refresh button") + refreshButton.translatesAutoresizingMaskIntoConstraints = false + refreshButton.isHidden = true + } + + func configureNavigationButtons() { + returnToPreviousResultsButton.bezelStyle = .rounded + returnToPreviousResultsButton.title = NSLocalizedString("Return to Previous Scan Results", comment: "Return to previous scan results button") + returnToPreviousResultsButton.translatesAutoresizingMaskIntoConstraints = false + + refreshScanButton.bezelStyle = .rounded + refreshScanButton.title = NSLocalizedString("Refresh Scan", comment: "Refresh scan button") + refreshScanButton.translatesAutoresizingMaskIntoConstraints = false + + navigationButtonGroup.translatesAutoresizingMaskIntoConstraints = false + navigationButtonGroup.isHidden = true + navigationButtonGroup.addSubview(returnToPreviousResultsButton) + navigationButtonGroup.addSubview(refreshScanButton) + + NSLayoutConstraint.activate([ + returnToPreviousResultsButton.topAnchor.constraint(equalTo: navigationButtonGroup.topAnchor), + returnToPreviousResultsButton.leadingAnchor.constraint(equalTo: navigationButtonGroup.leadingAnchor), + returnToPreviousResultsButton.trailingAnchor.constraint(equalTo: navigationButtonGroup.trailingAnchor), + + refreshScanButton.topAnchor.constraint(equalTo: returnToPreviousResultsButton.bottomAnchor, constant: CloudKitStatsLayout.rowSpacing), + refreshScanButton.leadingAnchor.constraint(equalTo: navigationButtonGroup.leadingAnchor), + refreshScanButton.trailingAnchor.constraint(equalTo: navigationButtonGroup.trailingAnchor), + refreshScanButton.bottomAnchor.constraint(equalTo: navigationButtonGroup.bottomAnchor) + ]) + } + + static func makeStatRow(_ title: String, valueLabel: NSTextField) -> NSView { + let container = NSView() + container.translatesAutoresizingMaskIntoConstraints = false + + let titleLabel = NSTextField(labelWithString: title) + titleLabel.translatesAutoresizingMaskIntoConstraints = false + + valueLabel.translatesAutoresizingMaskIntoConstraints = false + CloudKitStatsLayout.configureValueLabel(valueLabel) + + container.addSubview(titleLabel) + container.addSubview(valueLabel) + + NSLayoutConstraint.activate([ + titleLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor), + titleLabel.topAnchor.constraint(equalTo: container.topAnchor), + titleLabel.bottomAnchor.constraint(equalTo: container.bottomAnchor), + + valueLabel.trailingAnchor.constraint(equalTo: container.trailingAnchor), + valueLabel.lastBaselineAnchor.constraint(equalTo: titleLabel.lastBaselineAnchor) + ]) + + return container + } +} diff --git a/Mac/CloudKitStats/CleanUp/CloudKitStatsCleanUpStatusView.swift b/Mac/CloudKitStats/CleanUp/CloudKitStatsCleanUpStatusView.swift new file mode 100644 index 000000000..fe3767316 --- /dev/null +++ b/Mac/CloudKitStats/CleanUp/CloudKitStatsCleanUpStatusView.swift @@ -0,0 +1,59 @@ +// +// CloudKitStatsCleanUpStatusView.swift +// NetNewsWire +// +// Created by Brent Simmons on 3/24/26. +// + +import AppKit + +final class CloudKitStatsCleanUpStatusView: NSView { + + let progressBar = NSProgressIndicator() + let cancelButton = NSButton() + let phaseTextField = NSTextField(labelWithString: "") + + init() { + super.init(frame: .zero) + translatesAutoresizingMaskIntoConstraints = false + + progressBar.style = .bar + progressBar.isIndeterminate = false + progressBar.minValue = 0 + progressBar.maxValue = 1.0 + progressBar.doubleValue = 0 + progressBar.translatesAutoresizingMaskIntoConstraints = false + progressBar.setAccessibilityLabel(NSLocalizedString("Cleanup progress", comment: "Progress bar accessibility label")) + + cancelButton.bezelStyle = .rounded + cancelButton.title = NSLocalizedString("Cancel", comment: "Cancel button") + cancelButton.translatesAutoresizingMaskIntoConstraints = false + cancelButton.widthAnchor.constraint(equalToConstant: CloudKitStatsLayout.buttonWidth).isActive = true + + phaseTextField.textColor = .secondaryLabelColor + phaseTextField.font = .systemFont(ofSize: NSFont.systemFontSize) + phaseTextField.translatesAutoresizingMaskIntoConstraints = false + + addSubview(progressBar) + addSubview(cancelButton) + addSubview(phaseTextField) + + NSLayoutConstraint.activate([ + progressBar.leadingAnchor.constraint(equalTo: leadingAnchor), + progressBar.centerYAnchor.constraint(equalTo: cancelButton.centerYAnchor), + cancelButton.leadingAnchor.constraint(equalTo: progressBar.trailingAnchor, constant: CloudKitStatsLayout.buttonTextGap), + cancelButton.trailingAnchor.constraint(equalTo: trailingAnchor), + cancelButton.topAnchor.constraint(equalTo: topAnchor), + + phaseTextField.topAnchor.constraint(equalTo: cancelButton.bottomAnchor, constant: CloudKitStatsLayout.rowSpacing), + phaseTextField.leadingAnchor.constraint(equalTo: leadingAnchor), + phaseTextField.trailingAnchor.constraint(equalTo: trailingAnchor), + phaseTextField.bottomAnchor.constraint(equalTo: bottomAnchor) + ]) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} diff --git a/Mac/CloudKitStats/CleanUp/CloudKitStatsCleanUpViewController.swift b/Mac/CloudKitStats/CleanUp/CloudKitStatsCleanUpViewController.swift new file mode 100644 index 000000000..fffabc85c --- /dev/null +++ b/Mac/CloudKitStats/CleanUp/CloudKitStatsCleanUpViewController.swift @@ -0,0 +1,153 @@ +// +// CloudKitStatsCleanUpViewController.swift +// NetNewsWire +// +// Created by Brent Simmons on 3/24/26. +// + +import AppKit +import Account + +final class CloudKitStatsCleanUpViewController: NSViewController { + + private let model: CloudKitStatsViewModel + private let statusView = CloudKitStatsCleanUpStatusView() + private let contentView = CloudKitStatsCleanUpContentView() + + init(model: CloudKitStatsViewModel) { + self.model = model + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) is not supported") + } + + override func loadView() { + let containerView = NSView() + containerView.translatesAutoresizingMaskIntoConstraints = false + + statusView.cancelButton.target = nil + statusView.cancelButton.action = #selector(CloudKitStatsViewController.cancelCleanUp(_:)) + + contentView.refreshButton.target = nil + contentView.refreshButton.action = #selector(CloudKitStatsViewController.refreshScan(_:)) + contentView.refreshScanButton.target = nil + contentView.refreshScanButton.action = #selector(CloudKitStatsViewController.refreshScan(_:)) + contentView.returnToPreviousResultsButton.target = nil + contentView.returnToPreviousResultsButton.action = #selector(CloudKitStatsViewController.returnToPreviousScanResults(_:)) + + containerView.addSubview(statusView) + containerView.addSubview(contentView) + + NSLayoutConstraint.activate([ + statusView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: CloudKitStatsLayout.sectionSpacing), + statusView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), + statusView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), + + contentView.topAnchor.constraint(equalTo: statusView.bottomAnchor, constant: CloudKitStatsLayout.sectionSpacing), + contentView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), + contentView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), + contentView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor) + ]) + + self.view = containerView + } + + // MARK: - API + + func updateUI() { + updateCleanUpView() + } +} + +// MARK: - Private + +private extension CloudKitStatsCleanUpViewController { + + // MARK: - UI Update + + func updateCleanUpView() { + if model.cleanUpStatus.cleanUpError != nil { + updateCleanUpViewForError() + return + } + + let isCanceled = model.cleanUpStatus.isCanceled + + guard let progress = model.cleanUpStatus.progress else { + return + } + + contentView.errorTextField.isHidden = true + contentView.refreshButton.isHidden = true + statusView.isHidden = false + + let plan = model.cleanUpPlan + + // Progress bar: visible during cleaning, hidden when canceled, visible at 100% when completed + if isCanceled { + statusView.progressBar.isHidden = true + statusView.cancelButton.isHidden = true + statusView.phaseTextField.isHidden = false + statusView.phaseTextField.stringValue = NSLocalizedString("Canceled.", comment: "Cleanup status text when canceled") + } else if model.cleanUpStatus.isCompleted { + statusView.progressBar.isHidden = false + statusView.progressBar.doubleValue = 1.0 + statusView.cancelButton.isEnabled = false + statusView.phaseTextField.isHidden = false + statusView.phaseTextField.stringValue = cleanUpPhaseText(progress.phase) + } else { + statusView.progressBar.isHidden = false + statusView.cancelButton.isHidden = false + statusView.cancelButton.isEnabled = true + statusView.phaseTextField.isHidden = false + statusView.phaseTextField.stringValue = cleanUpPhaseText(progress.phase) + if plan.totalCount > 0 { + statusView.progressBar.doubleValue = Double(progress.totalDeleted) / Double(plan.totalCount) + } else { + statusView.progressBar.doubleValue = 0 + } + } + + updateStatRow(contentView.staleStatusDeletedRow, label: contentView.staleStatusDeletedLabel, value: progress.staleStatusDeleted, planned: plan.staleStatusCount) + updateStatRow(contentView.readContentDeletedRow, label: contentView.readContentDeletedLabel, value: progress.readContentDeleted, planned: plan.readContentCount) + updateStatRow(contentView.unreadContentDeletedRow, label: contentView.unreadContentDeletedLabel, value: progress.unreadContentDeleted, planned: plan.unreadContentCount) + updateStatRow(contentView.orphanedContentDeletedRow, label: contentView.orphanedContentDeletedLabel, value: progress.orphanedContentDeleted, planned: plan.orphanedContentCount) + + contentView.navigationButtonGroup.isHidden = !(isCanceled || model.cleanUpStatus.isCompleted) + } + + func updateCleanUpViewForError() { + statusView.isHidden = true + contentView.staleStatusDeletedRow.isHidden = true + contentView.readContentDeletedRow.isHidden = true + contentView.unreadContentDeletedRow.isHidden = true + contentView.orphanedContentDeletedRow.isHidden = true + contentView.navigationButtonGroup.isHidden = true + contentView.errorTextField.isHidden = false + contentView.refreshButton.isHidden = false + contentView.errorTextField.stringValue = NSLocalizedString("Cleanup failed to complete, but you may be able to clean up more if you wait a few minutes and try again.\n\nClick Refresh to see your updated stats.", comment: "Cleanup error message") + } + + func updateStatRow(_ row: NSView, label: NSTextField, value: Int, planned: Int) { + row.isHidden = planned == 0 + label.stringValue = CloudKitStatsLayout.formattedNumber(value) + } + + func cleanUpPhaseText(_ phase: CloudKitCleanUpPhase) -> String { + switch phase { + case .deletingStaleStatus: + return NSLocalizedString("Deleting stale status records…", comment: "Cleanup phase text") + case .deletingReadContent: + return NSLocalizedString("Deleting read content records…", comment: "Cleanup phase text") + case .deletingUnreadContent: + return NSLocalizedString("Deleting unread content records…", comment: "Cleanup phase text") + case .deletingOrphanedContent: + return NSLocalizedString("Deleting orphaned content records…", comment: "Cleanup phase text") + case .completed: + return NSLocalizedString("iCloud storage cleanup completed.", comment: "Cleanup phase text when completed") + } + } +} diff --git a/Mac/CloudKitStats/CloudKitStatsLayout.swift b/Mac/CloudKitStats/CloudKitStatsLayout.swift new file mode 100644 index 000000000..87931f15f --- /dev/null +++ b/Mac/CloudKitStats/CloudKitStatsLayout.swift @@ -0,0 +1,77 @@ +// +// CloudKitStatsLayout.swift +// NetNewsWire +// +// Created by Brent Simmons on 3/24/26. +// + +import AppKit + +enum CloudKitStatsLayout { + + static let containerWidth: CGFloat = 400 + static let windowHeight: CGFloat = 450 + static let buttonWidth: CGFloat = 80 + static let sectionSpacing: CGFloat = 14 + static let horizontalPadding: CGFloat = 20 + static let rowSpacing: CGFloat = 6 + static let iconSize: CGFloat = 12 + static let iconLabelGap: CGFloat = 4 + static let spinnerTextGap: CGFloat = 6 + static let buttonTextGap: CGFloat = 8 + static let fetchingAlpha: CGFloat = 0.4 + static let animationDuration: CGFloat = 0.25 + static let starColor = Assets.Colors.star + + @MainActor static func makeDivider() -> NSView { + let divider = NSBox() + divider.boxType = .separator + divider.translatesAutoresizingMaskIntoConstraints = false + return divider + } + + @MainActor static func makeLabelWithIcon(_ text: String, symbolName: String, color: NSColor, iconOffset: CGFloat = 0) -> NSView { + let container = NSView() + container.translatesAutoresizingMaskIntoConstraints = false + + let icon = NSImageView() + icon.translatesAutoresizingMaskIntoConstraints = false + icon.image = NSImage(systemSymbolName: symbolName, accessibilityDescription: text) + icon.contentTintColor = color + icon.setContentHuggingPriority(.required, for: .horizontal) + + let label = NSTextField(labelWithString: text) + label.translatesAutoresizingMaskIntoConstraints = false + + container.addSubview(icon) + container.addSubview(label) + + NSLayoutConstraint.activate([ + label.leadingAnchor.constraint(equalTo: container.leadingAnchor), + label.topAnchor.constraint(equalTo: container.topAnchor), + label.bottomAnchor.constraint(equalTo: container.bottomAnchor), + + icon.leadingAnchor.constraint(equalTo: label.trailingAnchor, constant: iconLabelGap), + icon.centerYAnchor.constraint(equalTo: label.centerYAnchor, constant: iconOffset), + icon.widthAnchor.constraint(equalToConstant: iconSize), + icon.heightAnchor.constraint(equalToConstant: iconSize), + icon.trailingAnchor.constraint(equalTo: container.trailingAnchor) + ]) + + return container + } + + @MainActor static func configureValueLabel(_ label: NSTextField) { + label.font = NSFont.monospacedDigitSystemFont(ofSize: NSFont.systemFontSize, weight: .regular) + label.alignment = .right + } + + static func formattedNumber(_ value: Int) -> String { + NumberFormatter.localizedString(from: NSNumber(value: value), number: .decimal) + } + + static func formattedCount(_ count: Int, singular: String, plural: String) -> String { + let label = count == 1 ? singular : plural + return "\(formattedNumber(count)) \(label)" + } +} diff --git a/Mac/CloudKitStats/CloudKitStatsToolbarView.swift b/Mac/CloudKitStats/CloudKitStatsToolbarView.swift new file mode 100644 index 000000000..bfa7277b8 --- /dev/null +++ b/Mac/CloudKitStats/CloudKitStatsToolbarView.swift @@ -0,0 +1,82 @@ +// +// CloudKitStatsToolbarView.swift +// NetNewsWire +// +// Created by Brent Simmons on 3/24/26. +// + +import AppKit + +final class CloudKitStatsToolbarView: NSView { + + let helpButton: NSButton + let shareButton: NSButton + let cleanUpButton: NSButton + + init() { + helpButton = NSButton() + helpButton.bezelStyle = .helpButton + helpButton.title = "" + helpButton.translatesAutoresizingMaskIntoConstraints = false + helpButton.setAccessibilityLabel(NSLocalizedString("Help — opens in browser", comment: "Help button accessibility label")) + helpButton.target = nil + helpButton.action = #selector(CloudKitStatsViewController.showHelp(_:)) + + shareButton = NSButton() + shareButton.bezelStyle = .rounded + shareButton.image = NSImage(systemSymbolName: "square.and.arrow.up", accessibilityDescription: NSLocalizedString("Share", comment: "Share button accessibility description")) + shareButton.translatesAutoresizingMaskIntoConstraints = false + shareButton.target = nil + shareButton.action = #selector(CloudKitStatsViewController.shareStats(_:)) + + cleanUpButton = NSButton() + cleanUpButton.bezelStyle = .rounded + cleanUpButton.title = NSLocalizedString("Clean Up", comment: "Clean Up button title") + cleanUpButton.translatesAutoresizingMaskIntoConstraints = false + cleanUpButton.target = nil + cleanUpButton.action = #selector(CloudKitStatsViewController.cleanUp(_:)) + + super.init(frame: .zero) + translatesAutoresizingMaskIntoConstraints = false + + let divider = CloudKitStatsLayout.makeDivider() + + let background = NSVisualEffectView() + background.translatesAutoresizingMaskIntoConstraints = false + background.blendingMode = .withinWindow + background.material = .titlebar + + addSubview(divider) + addSubview(background) + addSubview(helpButton) + addSubview(shareButton) + addSubview(cleanUpButton) + + NSLayoutConstraint.activate([ + divider.topAnchor.constraint(equalTo: topAnchor), + divider.leadingAnchor.constraint(equalTo: leadingAnchor), + divider.trailingAnchor.constraint(equalTo: trailingAnchor), + + background.topAnchor.constraint(equalTo: divider.bottomAnchor), + background.leadingAnchor.constraint(equalTo: leadingAnchor), + background.trailingAnchor.constraint(equalTo: trailingAnchor), + background.bottomAnchor.constraint(equalTo: bottomAnchor), + + helpButton.topAnchor.constraint(equalTo: divider.bottomAnchor, constant: CloudKitStatsLayout.sectionSpacing), + helpButton.leadingAnchor.constraint(equalTo: leadingAnchor, constant: CloudKitStatsLayout.horizontalPadding), + helpButton.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -CloudKitStatsLayout.sectionSpacing), + + shareButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -CloudKitStatsLayout.horizontalPadding), + shareButton.centerYAnchor.constraint(equalTo: helpButton.centerYAnchor), + + cleanUpButton.centerXAnchor.constraint(equalTo: centerXAnchor), + cleanUpButton.centerYAnchor.constraint(equalTo: helpButton.centerYAnchor), + cleanUpButton.widthAnchor.constraint(equalToConstant: CloudKitStatsLayout.buttonWidth) + ]) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} diff --git a/Mac/CloudKitStats/CloudKitStatsViewController.swift b/Mac/CloudKitStats/CloudKitStatsViewController.swift index 28cab72c6..529f7d2d3 100644 --- a/Mac/CloudKitStats/CloudKitStatsViewController.swift +++ b/Mac/CloudKitStats/CloudKitStatsViewController.swift @@ -6,916 +6,82 @@ // import AppKit -import CloudKit import Account -import CloudKitSync import RSWeb -@MainActor final class CloudKitStatsViewController: NSViewController { +final class CloudKitStatsViewController: NSViewController { private let model = CloudKitStatsViewModel() - - private static let escapeKeyCode: UInt16 = 53 - private static let containerWidth: CGFloat = 400 - private static let buttonWidth: CGFloat = 80 - private static let sectionSpacing: CGFloat = 14 - private static let horizontalPadding: CGFloat = 20 - private static let rowSpacing: CGFloat = 6 - private static let iconSize: CGFloat = 12 - private static let iconLabelGap: CGFloat = 4 - private static let spinnerTextGap: CGFloat = 6 - private static let buttonTextGap: CGFloat = 8 - private static let fetchingAlpha: CGFloat = 0.4 - private static let animationDuration: CGFloat = 0.25 - private static let starColor = NSColor(red: 0.976, green: 0.776, blue: 0.204, alpha: 1.0) - - // MARK: - Status bar views - - private let spinner = NSProgressIndicator() - private let statusIcon = NSImageView() - private let statusTextField = NSTextField(labelWithString: "") - private let actionButton = NSButton() - private var statusTextLeadingToSpinner: NSLayoutConstraint! - private var statusTextLeadingToContainer: NSLayoutConstraint! - - // MARK: - Stats value labels - - private let statusRecordCountLabel = NSTextField(labelWithString: "0") - private let starredCountLabel = NSTextField(labelWithString: "0") - private let unreadCountLabel = NSTextField(labelWithString: "0") - private let readCountLabel = NSTextField(labelWithString: "0") - private let staleCountLabel = NSTextField(labelWithString: "0") - private let totalContentCountLabel = NSTextField(labelWithString: "0") - private let starredContentCountLabel = NSTextField(labelWithString: "0") - private let unreadContentCountLabel = NSTextField(labelWithString: "0") - private let readContentCountLabel = NSTextField(labelWithString: "0") - private let orphanedContentCountLabel = NSTextField(labelWithString: "0") - - // MARK: - Cleanup views - - private let cleanUpContainerView = NSView() - private let cleanUpProgressBar = NSProgressIndicator() - private let cleanUpCancelButton = NSButton() - private let cleanUpPhaseTextField = NSTextField(labelWithString: "") - private let cleanUpErrorTextField = NSTextField(wrappingLabelWithString: "") - private let cleanUpRefreshButton = NSButton() - private let returnToPreviousResultsButton = NSButton() - private let refreshScanButton = NSButton() - private var cleanUpButtonGroup: NSView! - - private let staleStatusDeletedLabel = NSTextField(labelWithString: "0") - private let readContentDeletedLabel = NSTextField(labelWithString: "0") - private let unreadContentDeletedLabel = NSTextField(labelWithString: "0") - private let orphanedContentDeletedLabel = NSTextField(labelWithString: "0") - - private var staleStatusDeletedRow: NSView! - private var readContentDeletedRow: NSView! - private var unreadContentDeletedRow: NSView! - private var orphanedContentDeletedRow: NSView! - - // MARK: - Bottom bar views - - private let helpButton = NSButton() - private let shareButton = NSButton() - private let cleanUpButton = NSButton() - - // MARK: - Stats containers - - private let statsContainerView = NSView() - private let statusSectionView = NSView() - private let articleSectionView = NSView() + private let toolbarView = CloudKitStatsToolbarView() + private let contentAreaView = NSView() + private var currentChild: NSViewController? private var hasAppeared = false - private var hasShownErrorAlert = false - private var keyMonitor: Any? - - // MARK: - Layout switching - - private var statusBarView: NSView! - private var topDividerView: NSView! - private var normalLayoutConstraints = [NSLayoutConstraint]() - private var cleanUpLayoutConstraints = [NSLayoutConstraint]() - private var isShowingCleanUp = false - - // MARK: - NSViewController override func loadView() { - let containerView = NSView(frame: NSRect(origin: .zero, size: NSSize(width: Self.containerWidth, height: Self.containerWidth))) + let containerView = NSView(frame: .zero) - statusBarView = makeStatusBar() - topDividerView = makeDivider() - let statsSection = makeStatsSection() - makeCleanUpSection() - let bottomDivider = makeDivider() - let bottomBarBackground = makeBarBackground() - let bottomBar = makeBottomBar() + contentAreaView.translatesAutoresizingMaskIntoConstraints = false - containerView.addSubview(statusBarView) - containerView.addSubview(topDividerView) - containerView.addSubview(statsSection) - containerView.addSubview(cleanUpContainerView) - containerView.addSubview(bottomDivider) - containerView.addSubview(bottomBarBackground) - containerView.addSubview(bottomBar) - - cleanUpContainerView.isHidden = true - - normalLayoutConstraints = [ - statusBarView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: Self.sectionSpacing), - topDividerView.topAnchor.constraint(equalTo: statusBarView.bottomAnchor, constant: Self.sectionSpacing), - statsSection.topAnchor.constraint(equalTo: topDividerView.bottomAnchor, constant: Self.sectionSpacing), - bottomDivider.topAnchor.constraint(equalTo: statsSection.bottomAnchor, constant: Self.sectionSpacing) - ] - - cleanUpLayoutConstraints = [ - cleanUpContainerView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: Self.sectionSpacing), - bottomDivider.topAnchor.constraint(equalTo: cleanUpContainerView.bottomAnchor, constant: Self.sectionSpacing) - ] + containerView.addSubview(contentAreaView) + containerView.addSubview(toolbarView) NSLayoutConstraint.activate([ - statusBarView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: Self.horizontalPadding), - statusBarView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -Self.horizontalPadding), + contentAreaView.topAnchor.constraint(equalTo: containerView.topAnchor), + contentAreaView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: CloudKitStatsLayout.horizontalPadding), + contentAreaView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -CloudKitStatsLayout.horizontalPadding), + contentAreaView.bottomAnchor.constraint(equalTo: toolbarView.topAnchor), - topDividerView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), - topDividerView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), - - statsSection.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: Self.horizontalPadding), - statsSection.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -Self.horizontalPadding), - - cleanUpContainerView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: Self.horizontalPadding), - cleanUpContainerView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -Self.horizontalPadding), - - bottomDivider.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), - bottomDivider.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), - - bottomBarBackground.topAnchor.constraint(equalTo: bottomDivider.bottomAnchor), - bottomBarBackground.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), - bottomBarBackground.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), - bottomBarBackground.bottomAnchor.constraint(equalTo: containerView.bottomAnchor), - - bottomBar.topAnchor.constraint(equalTo: bottomDivider.bottomAnchor, constant: Self.sectionSpacing), - bottomBar.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: Self.horizontalPadding), - bottomBar.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -Self.horizontalPadding), - bottomBar.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -Self.sectionSpacing) + toolbarView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), + toolbarView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), + toolbarView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor) ]) - NSLayoutConstraint.activate(normalLayoutConstraints) - self.view = containerView } override func viewDidAppear() { super.viewDidAppear() - model.onChange = { [weak self] in - self?.updateUI() - } - if !hasAppeared { hasAppeared = true + model.onChange = { [weak self] in + self?.updateUI() + } + switchToScan() model.fetch() } updateUI() - - keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in - guard let self, self.view.window?.isKeyWindow == true else { - return event - } - let isEscape = event.keyCode == Self.escapeKeyCode - let isCmdPeriod = event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command && event.charactersIgnoringModifiers == "." - if (isEscape || isCmdPeriod) && self.model.fetchStatus.isFetching { - self.model.cancelFetch() - return nil - } - return event - } - } - - override func viewDidDisappear() { - super.viewDidDisappear() - if let keyMonitor { - NSEvent.removeMonitor(keyMonitor) - } - keyMonitor = nil } } -// MARK: - Private +// MARK: - Actions -private extension CloudKitStatsViewController { +extension CloudKitStatsViewController { - // MARK: - View Construction - - func makeStatusBar() -> NSView { - let container = NSView() - container.translatesAutoresizingMaskIntoConstraints = false - - spinner.style = .spinning - spinner.controlSize = .small - spinner.translatesAutoresizingMaskIntoConstraints = false - spinner.startAnimation(nil) - - statusIcon.translatesAutoresizingMaskIntoConstraints = false - statusIcon.image = NSImage(systemSymbolName: "checkmark.circle.fill", accessibilityDescription: "Completed") - statusIcon.contentTintColor = .systemGreen - statusIcon.isHidden = true - - statusTextField.translatesAutoresizingMaskIntoConstraints = false - statusTextField.textColor = .secondaryLabelColor - statusTextField.font = .systemFont(ofSize: NSFont.systemFontSize) - statusTextField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) - - actionButton.translatesAutoresizingMaskIntoConstraints = false - actionButton.bezelStyle = .rounded - actionButton.title = "Cancel" - actionButton.target = self - actionButton.action = #selector(actionButtonPressed(_:)) - - container.addSubview(spinner) - container.addSubview(statusIcon) - container.addSubview(statusTextField) - container.addSubview(actionButton) - - statusTextLeadingToSpinner = statusTextField.leadingAnchor.constraint(equalTo: spinner.trailingAnchor, constant: Self.spinnerTextGap) - statusTextLeadingToContainer = statusTextField.leadingAnchor.constraint(equalTo: container.leadingAnchor) - - NSLayoutConstraint.activate([ - spinner.leadingAnchor.constraint(equalTo: container.leadingAnchor), - spinner.centerYAnchor.constraint(equalTo: statusTextField.centerYAnchor), - - statusIcon.leadingAnchor.constraint(equalTo: container.leadingAnchor), - statusIcon.centerYAnchor.constraint(equalTo: statusTextField.centerYAnchor), - - statusTextLeadingToSpinner, - - actionButton.topAnchor.constraint(equalTo: container.topAnchor), - actionButton.bottomAnchor.constraint(equalTo: container.bottomAnchor), - statusTextField.bottomAnchor.constraint(lessThanOrEqualTo: container.bottomAnchor), - - actionButton.leadingAnchor.constraint(greaterThanOrEqualTo: statusTextField.trailingAnchor, constant: Self.buttonTextGap), - actionButton.trailingAnchor.constraint(equalTo: container.trailingAnchor), - actionButton.lastBaselineAnchor.constraint(equalTo: statusTextField.lastBaselineAnchor), - actionButton.widthAnchor.constraint(equalToConstant: Self.buttonWidth) - ]) - - return container + @objc func refreshScan(_ sender: Any?) { + model.fetch() } - func makeBarBackground() -> NSVisualEffectView { - let background = NSVisualEffectView() - background.translatesAutoresizingMaskIntoConstraints = false - background.blendingMode = .withinWindow - background.material = .titlebar - return background + @objc func cancelScan(_ sender: Any?) { + model.cancelFetch() } - func makeDivider() -> NSView { - let divider = NSBox() - divider.boxType = .separator - divider.translatesAutoresizingMaskIntoConstraints = false - return divider + @objc func cancelCleanUp(_ sender: Any?) { + model.cancelCleanUp() } - func makeLabelWithIcon(_ text: String, symbolName: String, color: NSColor, iconOffset: CGFloat = 0) -> NSView { - let container = NSView() - container.translatesAutoresizingMaskIntoConstraints = false - - let icon = NSImageView() - icon.translatesAutoresizingMaskIntoConstraints = false - icon.image = NSImage(systemSymbolName: symbolName, accessibilityDescription: text) - icon.contentTintColor = color - icon.setContentHuggingPriority(.required, for: .horizontal) - - let label = NSTextField(labelWithString: text) - label.translatesAutoresizingMaskIntoConstraints = false - - container.addSubview(icon) - container.addSubview(label) - - NSLayoutConstraint.activate([ - label.leadingAnchor.constraint(equalTo: container.leadingAnchor), - label.topAnchor.constraint(equalTo: container.topAnchor), - label.bottomAnchor.constraint(equalTo: container.bottomAnchor), - - icon.leadingAnchor.constraint(equalTo: label.trailingAnchor, constant: Self.iconLabelGap), - icon.centerYAnchor.constraint(equalTo: label.centerYAnchor, constant: iconOffset), - icon.widthAnchor.constraint(equalToConstant: Self.iconSize), - icon.heightAnchor.constraint(equalToConstant: Self.iconSize), - icon.trailingAnchor.constraint(equalTo: container.trailingAnchor) - ]) - - return container + @objc func returnToPreviousScanResults(_ sender: Any?) { + model.cleanUpStatus = .idle + updateUI() } - func makeStatsSection() -> NSView { - statsContainerView.translatesAutoresizingMaskIntoConstraints = false - - statusSectionView.translatesAutoresizingMaskIntoConstraints = false - articleSectionView.translatesAutoresizingMaskIntoConstraints = false - - buildSectionRows(statusSectionView, rows: [ - ("Status Records", nil), - ("Total", statusRecordCountLabel), - (makeLabelWithIcon("Starred", symbolName: "star.fill", color: Self.starColor), starredCountLabel), - (makeLabelWithIcon("Unread", symbolName: "circle.fill", color: .controlAccentColor, iconOffset: 0.5), unreadCountLabel), - ("Read", readCountLabel), - ("Stale", staleCountLabel) - ]) - - buildSectionRows(articleSectionView, rows: [ - ("Article Content Records", nil), - ("Total", totalContentCountLabel), - (makeLabelWithIcon("Starred", symbolName: "star.fill", color: Self.starColor), starredContentCountLabel), - (makeLabelWithIcon("Unread", symbolName: "circle.fill", color: .controlAccentColor, iconOffset: 0.5), unreadContentCountLabel), - ("Read", readContentCountLabel), - ("Orphaned", orphanedContentCountLabel) - ]) - - let divider = makeDivider() - - statsContainerView.addSubview(statusSectionView) - statsContainerView.addSubview(divider) - statsContainerView.addSubview(articleSectionView) - - NSLayoutConstraint.activate([ - statusSectionView.topAnchor.constraint(equalTo: statsContainerView.topAnchor), - statusSectionView.leadingAnchor.constraint(equalTo: statsContainerView.leadingAnchor), - statusSectionView.trailingAnchor.constraint(equalTo: statsContainerView.trailingAnchor), - - divider.topAnchor.constraint(equalTo: statusSectionView.bottomAnchor, constant: Self.sectionSpacing), - divider.leadingAnchor.constraint(equalTo: statsContainerView.leadingAnchor), - divider.trailingAnchor.constraint(equalTo: statsContainerView.trailingAnchor), - - articleSectionView.topAnchor.constraint(equalTo: divider.bottomAnchor, constant: Self.sectionSpacing), - articleSectionView.leadingAnchor.constraint(equalTo: statsContainerView.leadingAnchor), - articleSectionView.trailingAnchor.constraint(equalTo: statsContainerView.trailingAnchor), - articleSectionView.bottomAnchor.constraint(equalTo: statsContainerView.bottomAnchor) - ]) - - return statsContainerView - } - - func buildSectionRows(_ container: NSView, rows: [(Any, NSTextField?)]) { - var constraints = [NSLayoutConstraint]() - var previousAnchor = container.topAnchor - var previousSpacing: CGFloat = 0 - var dataRowViews = [NSView]() - - for (label, valueLabel) in rows { - if let valueLabel { - // Data row - let labelView: NSView - if let string = label as? String { - labelView = NSTextField(labelWithString: string) - } else { - labelView = label as! NSView - } - labelView.translatesAutoresizingMaskIntoConstraints = false - valueLabel.translatesAutoresizingMaskIntoConstraints = false - configureValueLabel(valueLabel) - - container.addSubview(labelView) - container.addSubview(valueLabel) - - // For icon rows, the labelView is a container — find the - // text field inside it so baseline alignment is correct. - let baselineView: NSView - if let textField = labelView as? NSTextField { - baselineView = textField - } else if let textField = labelView.subviews.compactMap({ $0 as? NSTextField }).first { - baselineView = textField - } else { - baselineView = labelView - } - - constraints.append(contentsOf: [ - labelView.topAnchor.constraint(equalTo: previousAnchor, constant: previousSpacing), - labelView.leadingAnchor.constraint(equalTo: container.leadingAnchor), - valueLabel.trailingAnchor.constraint(equalTo: container.trailingAnchor), - valueLabel.lastBaselineAnchor.constraint(equalTo: baselineView.lastBaselineAnchor) - ]) - - dataRowViews.append(labelView) - previousAnchor = labelView.bottomAnchor - previousSpacing = Self.rowSpacing - } else { - // Header row - let title = label as! String - let headerLabel = NSTextField(labelWithString: title) - headerLabel.font = .boldSystemFont(ofSize: NSFont.systemFontSize) - headerLabel.translatesAutoresizingMaskIntoConstraints = false - - container.addSubview(headerLabel) - - constraints.append(contentsOf: [ - headerLabel.topAnchor.constraint(equalTo: previousAnchor, constant: previousSpacing), - headerLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor) - ]) - - previousAnchor = headerLabel.bottomAnchor - previousSpacing = Self.rowSpacing - } - } - - // Make all data rows the same height (tallest wins). - if let firstRow = dataRowViews.first { - for row in dataRowViews.dropFirst() { - constraints.append(row.heightAnchor.constraint(equalTo: firstRow.heightAnchor)) - } - } - - constraints.append(previousAnchor.constraint(equalTo: container.bottomAnchor)) - NSLayoutConstraint.activate(constraints) - } - - func configureValueLabel(_ label: NSTextField) { - label.font = NSFont.monospacedDigitSystemFont(ofSize: NSFont.systemFontSize, weight: .regular) - label.alignment = .right - } - - func makeCleanUpSection() { - cleanUpContainerView.translatesAutoresizingMaskIntoConstraints = false - - let stackView = NSStackView() - stackView.translatesAutoresizingMaskIntoConstraints = false - stackView.orientation = .vertical - stackView.alignment = .leading - stackView.spacing = Self.rowSpacing - - // Progress bar + Cancel button in a horizontal row - let progressRow = NSView() - progressRow.translatesAutoresizingMaskIntoConstraints = false - - cleanUpProgressBar.style = .bar - cleanUpProgressBar.isIndeterminate = false - cleanUpProgressBar.minValue = 0 - cleanUpProgressBar.maxValue = 1.0 - cleanUpProgressBar.doubleValue = 0 - cleanUpProgressBar.translatesAutoresizingMaskIntoConstraints = false - - cleanUpCancelButton.bezelStyle = .rounded - cleanUpCancelButton.title = "Cancel" - cleanUpCancelButton.translatesAutoresizingMaskIntoConstraints = false - cleanUpCancelButton.target = self - cleanUpCancelButton.action = #selector(cleanUpCancelButtonPressed(_:)) - cleanUpCancelButton.widthAnchor.constraint(equalToConstant: Self.buttonWidth).isActive = true - - progressRow.addSubview(cleanUpProgressBar) - progressRow.addSubview(cleanUpCancelButton) - - NSLayoutConstraint.activate([ - cleanUpProgressBar.leadingAnchor.constraint(equalTo: progressRow.leadingAnchor), - cleanUpProgressBar.centerYAnchor.constraint(equalTo: cleanUpCancelButton.centerYAnchor), - cleanUpCancelButton.leadingAnchor.constraint(equalTo: cleanUpProgressBar.trailingAnchor, constant: Self.buttonTextGap), - cleanUpCancelButton.trailingAnchor.constraint(equalTo: progressRow.trailingAnchor), - cleanUpCancelButton.topAnchor.constraint(equalTo: progressRow.topAnchor), - cleanUpCancelButton.bottomAnchor.constraint(equalTo: progressRow.bottomAnchor) - ]) - - cleanUpPhaseTextField.textColor = .secondaryLabelColor - cleanUpPhaseTextField.font = .systemFont(ofSize: NSFont.systemFontSize) - - staleStatusDeletedRow = makeCleanUpStatRow("Stale Status Deleted", valueLabel: staleStatusDeletedLabel) - readContentDeletedRow = makeCleanUpStatRow("Read Content Deleted", valueLabel: readContentDeletedLabel) - unreadContentDeletedRow = makeCleanUpStatRow("Unread Content Deleted", valueLabel: unreadContentDeletedLabel) - orphanedContentDeletedRow = makeCleanUpStatRow("Orphaned Content Deleted", valueLabel: orphanedContentDeletedLabel) - - cleanUpErrorTextField.textColor = .secondaryLabelColor - cleanUpErrorTextField.font = .systemFont(ofSize: NSFont.systemFontSize) - cleanUpErrorTextField.isHidden = true - - cleanUpRefreshButton.bezelStyle = .rounded - cleanUpRefreshButton.title = "Refresh" - cleanUpRefreshButton.target = self - cleanUpRefreshButton.action = #selector(refreshButtonPressed(_:)) - cleanUpRefreshButton.translatesAutoresizingMaskIntoConstraints = false - cleanUpRefreshButton.isHidden = true - - stackView.addArrangedSubview(progressRow) - stackView.addArrangedSubview(cleanUpPhaseTextField) - stackView.addArrangedSubview(staleStatusDeletedRow) - stackView.addArrangedSubview(readContentDeletedRow) - stackView.addArrangedSubview(unreadContentDeletedRow) - stackView.addArrangedSubview(orphanedContentDeletedRow) - stackView.addArrangedSubview(cleanUpErrorTextField) - stackView.addArrangedSubview(cleanUpRefreshButton) - - stackView.setCustomSpacing(Self.sectionSpacing, after: cleanUpPhaseTextField) - - // Navigation buttons pinned to the bottom, outside the stack view - refreshScanButton.bezelStyle = .rounded - refreshScanButton.title = "Refresh Scan" - refreshScanButton.translatesAutoresizingMaskIntoConstraints = false - refreshScanButton.target = self - refreshScanButton.action = #selector(refreshButtonPressed(_:)) - returnToPreviousResultsButton.bezelStyle = .rounded - returnToPreviousResultsButton.title = "Return to Previous Scan Results" - returnToPreviousResultsButton.translatesAutoresizingMaskIntoConstraints = false - returnToPreviousResultsButton.target = self - returnToPreviousResultsButton.action = #selector(returnToPreviousResultsButtonPressed(_:)) - - // Button group container for vertical centering - cleanUpButtonGroup = NSView() - cleanUpButtonGroup.translatesAutoresizingMaskIntoConstraints = false - cleanUpButtonGroup.isHidden = true - cleanUpButtonGroup.addSubview(returnToPreviousResultsButton) - cleanUpButtonGroup.addSubview(refreshScanButton) - - NSLayoutConstraint.activate([ - returnToPreviousResultsButton.topAnchor.constraint(equalTo: cleanUpButtonGroup.topAnchor), - returnToPreviousResultsButton.leadingAnchor.constraint(equalTo: cleanUpButtonGroup.leadingAnchor), - returnToPreviousResultsButton.trailingAnchor.constraint(equalTo: cleanUpButtonGroup.trailingAnchor), - - refreshScanButton.topAnchor.constraint(equalTo: returnToPreviousResultsButton.bottomAnchor, constant: 8), - refreshScanButton.leadingAnchor.constraint(equalTo: cleanUpButtonGroup.leadingAnchor), - refreshScanButton.trailingAnchor.constraint(equalTo: cleanUpButtonGroup.trailingAnchor), - refreshScanButton.bottomAnchor.constraint(equalTo: cleanUpButtonGroup.bottomAnchor) - ]) - - cleanUpContainerView.addSubview(stackView) - cleanUpContainerView.addSubview(cleanUpButtonGroup) - - // Layout guide for the space between the stack and the bottom edge - let availableSpace = NSLayoutGuide() - cleanUpContainerView.addLayoutGuide(availableSpace) - - NSLayoutConstraint.activate([ - stackView.topAnchor.constraint(equalTo: cleanUpContainerView.topAnchor), - stackView.leadingAnchor.constraint(equalTo: cleanUpContainerView.leadingAnchor), - stackView.trailingAnchor.constraint(equalTo: cleanUpContainerView.trailingAnchor), - - progressRow.widthAnchor.constraint(equalTo: stackView.widthAnchor), - - staleStatusDeletedRow.widthAnchor.constraint(equalTo: stackView.widthAnchor), - readContentDeletedRow.widthAnchor.constraint(equalTo: stackView.widthAnchor), - unreadContentDeletedRow.widthAnchor.constraint(equalTo: stackView.widthAnchor), - orphanedContentDeletedRow.widthAnchor.constraint(equalTo: stackView.widthAnchor), - - cleanUpErrorTextField.widthAnchor.constraint(equalTo: stackView.widthAnchor), - - availableSpace.topAnchor.constraint(equalTo: stackView.bottomAnchor), - availableSpace.bottomAnchor.constraint(equalTo: cleanUpContainerView.bottomAnchor), - - cleanUpButtonGroup.centerYAnchor.constraint(equalTo: availableSpace.centerYAnchor), - cleanUpButtonGroup.centerXAnchor.constraint(equalTo: cleanUpContainerView.centerXAnchor) - ]) - } - - func makeCleanUpStatRow(_ title: String, valueLabel: NSTextField) -> NSView { - let container = NSView() - container.translatesAutoresizingMaskIntoConstraints = false - - let titleLabel = NSTextField(labelWithString: title) - titleLabel.translatesAutoresizingMaskIntoConstraints = false - - valueLabel.translatesAutoresizingMaskIntoConstraints = false - configureValueLabel(valueLabel) - - container.addSubview(titleLabel) - container.addSubview(valueLabel) - - NSLayoutConstraint.activate([ - titleLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor), - titleLabel.topAnchor.constraint(equalTo: container.topAnchor), - titleLabel.bottomAnchor.constraint(equalTo: container.bottomAnchor), - - valueLabel.trailingAnchor.constraint(equalTo: container.trailingAnchor), - valueLabel.lastBaselineAnchor.constraint(equalTo: titleLabel.lastBaselineAnchor) - ]) - - return container - } - - func makeBottomBar() -> NSView { - let container = NSView() - container.translatesAutoresizingMaskIntoConstraints = false - - helpButton.bezelStyle = .helpButton - helpButton.title = "" - helpButton.translatesAutoresizingMaskIntoConstraints = false - helpButton.target = self - helpButton.action = #selector(helpButtonPressed(_:)) - - shareButton.bezelStyle = .rounded - shareButton.image = NSImage(systemSymbolName: "square.and.arrow.up", accessibilityDescription: "Share") - shareButton.translatesAutoresizingMaskIntoConstraints = false - shareButton.target = self - shareButton.action = #selector(shareButtonPressed(_:)) - - cleanUpButton.bezelStyle = .rounded - cleanUpButton.title = "Clean Up" - cleanUpButton.translatesAutoresizingMaskIntoConstraints = false - cleanUpButton.target = self - cleanUpButton.action = #selector(cleanUpButtonPressed(_:)) - - container.addSubview(helpButton) - container.addSubview(shareButton) - container.addSubview(cleanUpButton) - - NSLayoutConstraint.activate([ - helpButton.leadingAnchor.constraint(equalTo: container.leadingAnchor), - helpButton.centerYAnchor.constraint(equalTo: container.centerYAnchor), - - shareButton.trailingAnchor.constraint(equalTo: container.trailingAnchor), - shareButton.centerYAnchor.constraint(equalTo: container.centerYAnchor), - - cleanUpButton.centerXAnchor.constraint(equalTo: container.centerXAnchor), - cleanUpButton.centerYAnchor.constraint(equalTo: container.centerYAnchor), - cleanUpButton.widthAnchor.constraint(equalToConstant: Self.buttonWidth), - - container.heightAnchor.constraint(equalTo: cleanUpButton.heightAnchor) - ]) - - return container - } - - // MARK: - UI Update - - func updateUI() { - let isCleanUpActive = model.cleanUpStatus.isActive - let needsTransition = isCleanUpActive != isShowingCleanUp - - if needsTransition { - animateLayoutTransition(toCleanUp: isCleanUpActive) - } else { - NSAnimationContext.runAnimationGroup { context in - context.duration = Self.animationDuration - context.allowsImplicitAnimation = true - - if isCleanUpActive { - updateCleanUpView() - } else { - updateStatusBar() - updateStatsValues() - } - updateBottomBar() - } - } - } - - func animateLayoutTransition(toCleanUp: Bool) { - // Prepare incoming views: unhide at alpha 0 so they can fade in. - if toCleanUp { - cleanUpContainerView.alphaValue = 0 - cleanUpContainerView.isHidden = false - } else { - statusBarView.alphaValue = 0 - topDividerView.alphaValue = 0 - statsContainerView.alphaValue = 0 - statusBarView.isHidden = false - topDividerView.isHidden = false - statsContainerView.isHidden = false - } - - NSAnimationContext.runAnimationGroup { context in - context.duration = Self.animationDuration - context.allowsImplicitAnimation = true - - if toCleanUp { - isShowingCleanUp = true - NSLayoutConstraint.deactivate(normalLayoutConstraints) - NSLayoutConstraint.activate(cleanUpLayoutConstraints) - statusBarView.animator().alphaValue = 0 - topDividerView.animator().alphaValue = 0 - statsContainerView.animator().alphaValue = 0 - cleanUpContainerView.animator().alphaValue = 1 - updateCleanUpView() - } else { - isShowingCleanUp = false - NSLayoutConstraint.deactivate(cleanUpLayoutConstraints) - NSLayoutConstraint.activate(normalLayoutConstraints) - cleanUpContainerView.animator().alphaValue = 0 - statusBarView.animator().alphaValue = 1 - topDividerView.animator().alphaValue = 1 - statsContainerView.animator().alphaValue = 1 - updateStatusBar() - updateStatsValues() - } - updateBottomBar() - } completionHandler: { [weak self] in - // Clean up: hide the faded-out views, reset their alpha for next transition. - Task { @MainActor in - guard let self else { - return - } - if toCleanUp { - self.statusBarView.isHidden = true - self.topDividerView.isHidden = true - self.statsContainerView.isHidden = true - self.statusBarView.alphaValue = 1 - self.topDividerView.alphaValue = 1 - self.statsContainerView.alphaValue = 1 - } else { - self.cleanUpContainerView.isHidden = true - self.cleanUpContainerView.alphaValue = 1 - self.cleanUpProgressBar.doubleValue = 0 - } - } - } - } - - func updateStatusBar() { - switch model.fetchStatus { - case .idle: - break - case .fetching: - hasShownErrorAlert = false - spinner.isHidden = false - spinner.isIndeterminate = true - spinner.style = .spinning - spinner.startAnimation(nil) - statusIcon.isHidden = true - statusTextField.stringValue = "Scanning iCloud storage" - actionButton.title = "Cancel" - statusTextLeadingToSpinner.isActive = true - statusTextLeadingToContainer.isActive = false - case .completed: - spinner.isHidden = true - spinner.stopAnimation(nil) - statusIcon.isHidden = false - statusTextField.stringValue = "Scan completed." - actionButton.title = "Refresh" - statusTextLeadingToSpinner.isActive = true - statusTextLeadingToContainer.isActive = false - case .error: - spinner.isHidden = true - spinner.stopAnimation(nil) - statusIcon.isHidden = true - statusTextField.stringValue = "Scan failed. Numbers are incomplete." - actionButton.title = "Refresh" - statusTextLeadingToSpinner.isActive = false - statusTextLeadingToContainer.isActive = true - showErrorAlertIfNeeded() - case .canceled: - spinner.isHidden = true - spinner.stopAnimation(nil) - statusIcon.isHidden = true - statusTextField.stringValue = "Canceled." - actionButton.title = "Refresh" - statusTextLeadingToSpinner.isActive = false - statusTextLeadingToContainer.isActive = true - } - } - - func updateCleanUpView() { - if model.cleanUpStatus.cleanUpError != nil { - updateCleanUpViewForError() - return - } - - let isCanceled = model.cleanUpStatus.isCanceled - - guard let progress = model.cleanUpStatus.progress else { - return - } - - cleanUpErrorTextField.isHidden = true - cleanUpRefreshButton.isHidden = true - - let plan = model.cleanUpPlan - - // Progress bar: visible during cleaning, hidden when canceled, visible at 100% when completed - if isCanceled { - cleanUpProgressBar.isHidden = true - cleanUpCancelButton.isHidden = true - cleanUpPhaseTextField.isHidden = false - cleanUpPhaseTextField.stringValue = "Canceled." - } else if model.cleanUpStatus.isCompleted { - cleanUpProgressBar.isHidden = false - cleanUpProgressBar.doubleValue = 1.0 - cleanUpCancelButton.isEnabled = false - cleanUpPhaseTextField.isHidden = false - cleanUpPhaseTextField.stringValue = cleanUpPhaseText(progress.phase) - } else { - cleanUpProgressBar.isHidden = false - cleanUpCancelButton.isHidden = false - cleanUpCancelButton.isEnabled = true - cleanUpPhaseTextField.isHidden = false - cleanUpPhaseTextField.stringValue = cleanUpPhaseText(progress.phase) - if plan.totalCount > 0 { - cleanUpProgressBar.doubleValue = Double(progress.totalDeleted) / Double(plan.totalCount) - } else { - cleanUpProgressBar.doubleValue = 0 - } - } - - updateCleanUpStatRow(staleStatusDeletedRow, label: staleStatusDeletedLabel, value: progress.staleStatusDeleted, planned: plan.staleStatusCount) - updateCleanUpStatRow(readContentDeletedRow, label: readContentDeletedLabel, value: progress.readContentDeleted, planned: plan.readContentCount) - updateCleanUpStatRow(unreadContentDeletedRow, label: unreadContentDeletedLabel, value: progress.unreadContentDeleted, planned: plan.unreadContentCount) - updateCleanUpStatRow(orphanedContentDeletedRow, label: orphanedContentDeletedLabel, value: progress.orphanedContentDeleted, planned: plan.orphanedContentCount) - - cleanUpButtonGroup.isHidden = !(isCanceled || model.cleanUpStatus.isCompleted) - } - - func updateCleanUpViewForError() { - cleanUpProgressBar.isHidden = true - cleanUpCancelButton.isHidden = true - cleanUpPhaseTextField.isHidden = true - staleStatusDeletedRow.isHidden = true - readContentDeletedRow.isHidden = true - unreadContentDeletedRow.isHidden = true - orphanedContentDeletedRow.isHidden = true - cleanUpButtonGroup.isHidden = true - cleanUpErrorTextField.isHidden = false - cleanUpRefreshButton.isHidden = false - cleanUpErrorTextField.stringValue = "Clean up failed to complete, but you may be able to clean up more if you wait a few minutes and try again.\n\nClick Refresh to see your updated stats." - } - - func updateCleanUpStatRow(_ row: NSView, label: NSTextField, value: Int, planned: Int) { - row.isHidden = planned == 0 - label.stringValue = formattedNumber(value) - } - - func cleanUpPhaseText(_ phase: CloudKitCleanUpPhase) -> String { - switch phase { - case .deletingStaleStatus: - return "Deleting stale status records…" - case .deletingReadContent: - return "Deleting read content records…" - case .deletingUnreadContent: - return "Deleting unread content records…" - case .deletingOrphanedContent: - return "Deleting orphaned content records…" - case .completed: - return "iCloud storage cleanup completed." - } - } - - func updateStatsValues() { - let stats = model.stats - statusRecordCountLabel.stringValue = formattedNumber(stats.statusCount) - starredCountLabel.stringValue = formattedNumber(stats.starredStatusCount) - unreadCountLabel.stringValue = formattedNumber(stats.unreadStatusCount) - readCountLabel.stringValue = formattedNumber(stats.readStatusCount) - staleCountLabel.stringValue = formattedNumber(stats.staleStatusCount) - totalContentCountLabel.stringValue = formattedNumber(stats.articleCount) - starredContentCountLabel.stringValue = formattedNumber(stats.starredArticleCount) - unreadContentCountLabel.stringValue = formattedNumber(stats.unreadArticleCount) - readContentCountLabel.stringValue = formattedNumber(stats.readArticleCount) - orphanedContentCountLabel.stringValue = formattedNumber(stats.orphanedArticleCount) - - let isFetching = model.fetchStatus.isFetching - let statusSectionDone = !isFetching || stats.articleCount > 0 - statusSectionView.animator().alphaValue = statusSectionDone ? 1.0 : Self.fetchingAlpha - articleSectionView.animator().alphaValue = isFetching ? Self.fetchingAlpha : 1.0 - } - - func updateBottomBar() { - let isCleaning = model.cleanUpStatus.isCleaning - let isCleanUpDone = model.cleanUpStatus.isCompleted || model.cleanUpStatus.isCanceled || model.cleanUpStatus.cleanUpError != nil - - if isCleaning { - cleanUpButton.isEnabled = false - shareButton.isEnabled = true - } else if isCleanUpDone { - cleanUpButton.isEnabled = true - shareButton.isEnabled = true - } else { - let enableShare = model.fetchStatus.isCompleted || model.fetchStatus.fetchError != nil - shareButton.isEnabled = enableShare - cleanUpButton.isEnabled = model.canCleanUp - } - actionButton.isEnabled = !isCleaning - } - - func showErrorAlertIfNeeded() { - guard let fetchError = model.fetchStatus.fetchError, !hasShownErrorAlert else { - return - } - - hasShownErrorAlert = true - let displayError: Error - if fetchError is CKError { - displayError = CloudKitError(fetchError) - } else { - displayError = fetchError - } - DispatchQueue.main.async { - let alert = NSAlert() - alert.alertStyle = .warning - alert.messageText = "Couldn't complete the iCloud scan because of an error:" - alert.informativeText = displayError.localizedDescription - alert.addButton(withTitle: "OK") - alert.runModal() - } - } - - // MARK: - Actions - - @objc func actionButtonPressed(_ sender: Any?) { - if model.fetchStatus.isFetching { - model.cancelFetch() - } else { - model.fetch() - } - } - - @objc func helpButtonPressed(_ sender: Any?) { + @objc func showHelp(_ sender: Any?) { if let url = URL(string: "https://netnewswire.com/help/icloud.html") { MacWebBrowser.openURL(url) } } - @objc func shareButtonPressed(_ sender: Any?) { + @objc func shareStats(_ sender: Any?) { guard let button = sender as? NSButton else { return } @@ -924,7 +90,7 @@ private extension CloudKitStatsViewController { picker.show(relativeTo: button.bounds, of: button, preferredEdge: .minY) } - @objc func cleanUpButtonPressed(_ sender: Any?) { + @objc func cleanUp(_ sender: Any?) { let plan = model.cleanUpPlan guard !plan.isEmpty else { return @@ -932,10 +98,10 @@ private extension CloudKitStatsViewController { let alert = NSAlert() alert.alertStyle = .warning - alert.messageText = "Clean Up iCloud Records" + alert.messageText = NSLocalizedString("Clean Up iCloud Records", comment: "Clean up alert title") alert.informativeText = cleanUpConfirmationText(plan) - alert.addButton(withTitle: "Clean Up") - alert.addButton(withTitle: "Cancel") + alert.addButton(withTitle: NSLocalizedString("Clean Up", comment: "Clean up alert button")) + alert.addButton(withTitle: NSLocalizedString("Cancel", comment: "Cancel button")) guard let window = view.window else { return @@ -948,44 +114,108 @@ private extension CloudKitStatsViewController { self?.model.cleanUp() } } +} - @objc func cleanUpCancelButtonPressed(_ sender: Any?) { - model.cancelCleanUp() +// MARK: - Private + +private extension CloudKitStatsViewController { + + // MARK: - Child View Controller Management + + func switchToCleanUp() { + let incoming = CloudKitStatsCleanUpViewController(model: model) + switchToChild(incoming) + incoming.updateUI() } - @objc func refreshButtonPressed(_ sender: Any?) { - model.fetch() + func switchToScan() { + let incoming = CloudKitStatsScanViewController(model: model) + switchToChild(incoming) + incoming.updateUI() } - @objc func returnToPreviousResultsButtonPressed(_ sender: Any?) { - model.cleanUpStatus = .idle - updateUI() + func switchToChild(_ incoming: NSViewController) { + addChild(incoming) + incoming.view.translatesAutoresizingMaskIntoConstraints = false + + let constraints = [ + incoming.view.topAnchor.constraint(equalTo: contentAreaView.topAnchor), + incoming.view.leadingAnchor.constraint(equalTo: contentAreaView.leadingAnchor), + incoming.view.trailingAnchor.constraint(equalTo: contentAreaView.trailingAnchor), + incoming.view.bottomAnchor.constraint(equalTo: contentAreaView.bottomAnchor) + ] + + if let outgoing = currentChild { + NSLayoutConstraint.activate(constraints) + NSAnimationContext.runAnimationGroup { context in + context.duration = CloudKitStatsLayout.animationDuration + context.allowsImplicitAnimation = true + transition(from: outgoing, to: incoming, options: .crossfade) { + Task { @MainActor in + outgoing.removeFromParent() + } + } + } + } else { + contentAreaView.addSubview(incoming.view) + NSLayoutConstraint.activate(constraints) + } + + currentChild = incoming + } + + // MARK: - UI Update + + func updateUI() { + let shouldShowCleanUp = model.cleanUpStatus.isActive + let isShowingCleanUp = currentChild is CloudKitStatsCleanUpViewController + + if shouldShowCleanUp != isShowingCleanUp { + if shouldShowCleanUp { + switchToCleanUp() + } else { + switchToScan() + } + } else if let child = currentChild as? CloudKitStatsScanViewController { + child.updateUI() + } else if let child = currentChild as? CloudKitStatsCleanUpViewController { + child.updateUI() + } + updateToolbar() + } + + func updateToolbar() { + let isCleaning = model.cleanUpStatus.isCleaning + let isCleanUpDone = model.cleanUpStatus.isCompleted || model.cleanUpStatus.isCanceled || model.cleanUpStatus.cleanUpError != nil + + if isCleaning { + toolbarView.cleanUpButton.isEnabled = false + toolbarView.shareButton.isEnabled = true + } else if isCleanUpDone { + toolbarView.cleanUpButton.isEnabled = true + toolbarView.shareButton.isEnabled = true + } else { + let enableShare = model.fetchStatus.isCompleted || model.fetchStatus.fetchError != nil + toolbarView.shareButton.isEnabled = enableShare + toolbarView.cleanUpButton.isEnabled = model.canCleanUp + } } func cleanUpConfirmationText(_ plan: CloudKitCleanUpPlan) -> String { var lines = [String]() if plan.staleStatusCount > 0 { - lines.append(formattedCount(plan.staleStatusCount, singular: "stale status record", plural: "stale status records")) + lines.append(CloudKitStatsLayout.formattedCount(plan.staleStatusCount, singular: NSLocalizedString("stale status record", comment: "Singular label for stale status records"), plural: NSLocalizedString("stale status records", comment: "Plural label for stale status records"))) } if plan.readContentCount > 0 { - lines.append(formattedCount(plan.readContentCount, singular: "read content record", plural: "read content records")) + lines.append(CloudKitStatsLayout.formattedCount(plan.readContentCount, singular: NSLocalizedString("read content record", comment: "Singular label for read content records"), plural: NSLocalizedString("read content records", comment: "Plural label for read content records"))) } if plan.unreadContentCount > 0 { - lines.append(formattedCount(plan.unreadContentCount, singular: "unread content record", plural: "unread content records")) + lines.append(CloudKitStatsLayout.formattedCount(plan.unreadContentCount, singular: NSLocalizedString("unread content record", comment: "Singular label for unread content records"), plural: NSLocalizedString("unread content records", comment: "Plural label for unread content records"))) } if plan.orphanedContentCount > 0 { - lines.append(formattedCount(plan.orphanedContentCount, singular: "orphaned content record", plural: "orphaned content records")) + lines.append(CloudKitStatsLayout.formattedCount(plan.orphanedContentCount, singular: NSLocalizedString("orphaned content record", comment: "Singular label for orphaned content records"), plural: NSLocalizedString("orphaned content records", comment: "Plural label for orphaned content records"))) } let listText = lines.map { "• " + $0 }.joined(separator: "\n") - return "This will delete:\n" + listText + "\n\nThis may take many minutes." - } - - func formattedNumber(_ value: Int) -> String { - NumberFormatter.localizedString(from: NSNumber(value: value), number: .decimal) - } - - func formattedCount(_ count: Int, singular: String, plural: String) -> String { - let label = count == 1 ? singular : plural - return "\(formattedNumber(count)) \(label)" + return NSLocalizedString("This will delete:", comment: "Clean up confirmation prefix") + "\n" + listText + "\n\n" + NSLocalizedString("This may take many minutes.", comment: "Clean up confirmation suffix") } } diff --git a/Mac/CloudKitStats/CloudKitStatsWindowController.swift b/Mac/CloudKitStats/CloudKitStatsWindowController.swift index 713c0a27f..214a7cebe 100644 --- a/Mac/CloudKitStats/CloudKitStatsWindowController.swift +++ b/Mac/CloudKitStats/CloudKitStatsWindowController.swift @@ -5,22 +5,22 @@ // Created by Brent Simmons on 3/20/26. // -@preconcurrency import AppKit +import AppKit -@MainActor final class CloudKitStatsWindowController: NSWindowController { +final class CloudKitStatsWindowController: NSWindowController { - private static let windowSize = NSSize(width: 400, height: 450) + private static let windowSize = NSSize(width: CloudKitStatsLayout.containerWidth, height: CloudKitStatsLayout.windowHeight) private static let frameAutosaveName = "CloudKitStats" private var hasBeenShown = false init() { let window = NSWindow(contentRect: NSRect(origin: .zero, size: Self.windowSize), styleMask: [.titled, .closable], backing: .buffered, defer: true) - window.title = "iCloud Storage Stats" + window.title = NSLocalizedString("iCloud Storage Stats", comment: "iCloud Storage Stats window title") window.isReleasedWhenClosed = false window.contentViewController = CloudKitStatsViewController() - window.representedURL = URL(string: "https://icloud.com") + window.representedURL = URL(string: "https://icloud.com/") if let iconButton = window.standardWindowButton(.documentIconButton) { iconButton.image = NSImage(systemSymbolName: "icloud", accessibilityDescription: "iCloud") } diff --git a/Mac/CloudKitStats/Scan/CloudKitStatsScanContentView.swift b/Mac/CloudKitStats/Scan/CloudKitStatsScanContentView.swift new file mode 100644 index 000000000..7c9cf0199 --- /dev/null +++ b/Mac/CloudKitStats/Scan/CloudKitStatsScanContentView.swift @@ -0,0 +1,160 @@ +// +// CloudKitStatsScanContentView.swift +// NetNewsWire +// +// Created by Brent Simmons on 3/24/26. +// + +import AppKit + +final class CloudKitStatsScanContentView: NSView { + + // MARK: - Status Records + + let statusRecordCountLabel = NSTextField(labelWithString: "0") + let starredCountLabel = NSTextField(labelWithString: "0") + let unreadCountLabel = NSTextField(labelWithString: "0") + let readCountLabel = NSTextField(labelWithString: "0") + let staleCountLabel = NSTextField(labelWithString: "0") + + // MARK: - Article Content Records + + let totalContentCountLabel = NSTextField(labelWithString: "0") + let starredContentCountLabel = NSTextField(labelWithString: "0") + let unreadContentCountLabel = NSTextField(labelWithString: "0") + let readContentCountLabel = NSTextField(labelWithString: "0") + let orphanedContentCountLabel = NSTextField(labelWithString: "0") + + // MARK: - Section containers (for alpha animation) + + let statusSectionView = NSView() + let articleSectionView = NSView() + + init() { + super.init(frame: .zero) + translatesAutoresizingMaskIntoConstraints = false + + statusSectionView.translatesAutoresizingMaskIntoConstraints = false + articleSectionView.translatesAutoresizingMaskIntoConstraints = false + + buildSectionRows(statusSectionView, rows: [ + .header(NSLocalizedString("Status Records", comment: "Status records section header")), + .data(labelView: NSTextField(labelWithString: NSLocalizedString("Total", comment: "Total row label")), valueLabel: statusRecordCountLabel), + .data(labelView: CloudKitStatsLayout.makeLabelWithIcon(NSLocalizedString("Starred", comment: "Starred row label"), symbolName: "star.fill", color: CloudKitStatsLayout.starColor), valueLabel: starredCountLabel), + .data(labelView: CloudKitStatsLayout.makeLabelWithIcon(NSLocalizedString("Unread", comment: "Unread row label"), symbolName: "circle.fill", color: .controlAccentColor, iconOffset: 0.5), valueLabel: unreadCountLabel), + .data(labelView: NSTextField(labelWithString: NSLocalizedString("Read", comment: "Read row label")), valueLabel: readCountLabel), + .data(labelView: NSTextField(labelWithString: NSLocalizedString("Stale", comment: "Stale row label")), valueLabel: staleCountLabel) + ]) + + buildSectionRows(articleSectionView, rows: [ + .header(NSLocalizedString("Article Content Records", comment: "Article content records section header")), + .data(labelView: NSTextField(labelWithString: NSLocalizedString("Total", comment: "Total row label")), valueLabel: totalContentCountLabel), + .data(labelView: CloudKitStatsLayout.makeLabelWithIcon(NSLocalizedString("Starred", comment: "Starred row label"), symbolName: "star.fill", color: CloudKitStatsLayout.starColor), valueLabel: starredContentCountLabel), + .data(labelView: CloudKitStatsLayout.makeLabelWithIcon(NSLocalizedString("Unread", comment: "Unread row label"), symbolName: "circle.fill", color: .controlAccentColor, iconOffset: 0.5), valueLabel: unreadContentCountLabel), + .data(labelView: NSTextField(labelWithString: NSLocalizedString("Read", comment: "Read row label")), valueLabel: readContentCountLabel), + .data(labelView: NSTextField(labelWithString: NSLocalizedString("Orphaned", comment: "Orphaned row label")), valueLabel: orphanedContentCountLabel) + ]) + + let divider = CloudKitStatsLayout.makeDivider() + + addSubview(statusSectionView) + addSubview(divider) + addSubview(articleSectionView) + + NSLayoutConstraint.activate([ + statusSectionView.topAnchor.constraint(equalTo: topAnchor), + statusSectionView.leadingAnchor.constraint(equalTo: leadingAnchor), + statusSectionView.trailingAnchor.constraint(equalTo: trailingAnchor), + + divider.topAnchor.constraint(equalTo: statusSectionView.bottomAnchor, constant: CloudKitStatsLayout.sectionSpacing), + divider.leadingAnchor.constraint(equalTo: leadingAnchor), + divider.trailingAnchor.constraint(equalTo: trailingAnchor), + + articleSectionView.topAnchor.constraint(equalTo: divider.bottomAnchor, constant: CloudKitStatsLayout.sectionSpacing), + articleSectionView.leadingAnchor.constraint(equalTo: leadingAnchor), + articleSectionView.trailingAnchor.constraint(equalTo: trailingAnchor), + articleSectionView.bottomAnchor.constraint(equalTo: bottomAnchor) + ]) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +// MARK: - Private + +private extension CloudKitStatsScanContentView { + + enum SectionRow { + case header(String) + case data(labelView: NSView, valueLabel: NSTextField) + } + + func buildSectionRows(_ container: NSView, rows: [SectionRow]) { + var constraints = [NSLayoutConstraint]() + var previousAnchor = container.topAnchor + var previousSpacing: CGFloat = 0 + var dataRowViews = [NSView]() + + for row in rows { + switch row { + case .header(let title): + let headerLabel = NSTextField(labelWithString: title) + headerLabel.font = .boldSystemFont(ofSize: NSFont.systemFontSize) + headerLabel.translatesAutoresizingMaskIntoConstraints = false + + container.addSubview(headerLabel) + + constraints.append(contentsOf: [ + headerLabel.topAnchor.constraint(equalTo: previousAnchor, constant: previousSpacing), + headerLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor) + ]) + + previousAnchor = headerLabel.bottomAnchor + previousSpacing = CloudKitStatsLayout.rowSpacing + + case .data(let labelView, let valueLabel): + labelView.translatesAutoresizingMaskIntoConstraints = false + valueLabel.translatesAutoresizingMaskIntoConstraints = false + CloudKitStatsLayout.configureValueLabel(valueLabel) + + container.addSubview(labelView) + container.addSubview(valueLabel) + + // For icon rows, the labelView is a container — find the + // text field inside it so baseline alignment is correct. + let baselineView: NSView + if let textField = labelView as? NSTextField { + baselineView = textField + } else if let textField = labelView.subviews.compactMap({ $0 as? NSTextField }).first { + baselineView = textField + } else { + baselineView = labelView + } + + constraints.append(contentsOf: [ + labelView.topAnchor.constraint(equalTo: previousAnchor, constant: previousSpacing), + labelView.leadingAnchor.constraint(equalTo: container.leadingAnchor), + valueLabel.trailingAnchor.constraint(equalTo: container.trailingAnchor), + valueLabel.lastBaselineAnchor.constraint(equalTo: baselineView.lastBaselineAnchor) + ]) + + dataRowViews.append(labelView) + previousAnchor = labelView.bottomAnchor + previousSpacing = CloudKitStatsLayout.rowSpacing + } + } + + // Make all data rows the same height (tallest wins). + if let firstRow = dataRowViews.first { + for row in dataRowViews.dropFirst() { + constraints.append(row.heightAnchor.constraint(equalTo: firstRow.heightAnchor)) + } + } + + constraints.append(previousAnchor.constraint(equalTo: container.bottomAnchor)) + NSLayoutConstraint.activate(constraints) + } +} diff --git a/Mac/CloudKitStats/Scan/CloudKitStatsScanStatusView.swift b/Mac/CloudKitStats/Scan/CloudKitStatsScanStatusView.swift new file mode 100644 index 000000000..203ee0d22 --- /dev/null +++ b/Mac/CloudKitStats/Scan/CloudKitStatsScanStatusView.swift @@ -0,0 +1,76 @@ +// +// CloudKitStatsScanStatusView.swift +// NetNewsWire +// +// Created by Brent Simmons on 3/24/26. +// + +import AppKit + +final class CloudKitStatsScanStatusView: NSView { + + let spinner = NSProgressIndicator() + let statusIcon = NSImageView() + let statusTextField = NSTextField(labelWithString: "") + let actionButton = NSButton() + + private(set) var statusTextLeadingToSpinner: NSLayoutConstraint! + private(set) var statusTextLeadingToContainer: NSLayoutConstraint! + + init() { + super.init(frame: .zero) + translatesAutoresizingMaskIntoConstraints = false + + spinner.style = .spinning + spinner.controlSize = .small + spinner.translatesAutoresizingMaskIntoConstraints = false + spinner.setAccessibilityLabel(NSLocalizedString("Scanning", comment: "Spinner accessibility label")) + spinner.startAnimation(nil) + + statusIcon.translatesAutoresizingMaskIntoConstraints = false + statusIcon.image = NSImage(systemSymbolName: "checkmark.circle.fill", accessibilityDescription: NSLocalizedString("Completed", comment: "Status icon accessibility description")) + statusIcon.contentTintColor = .systemGreen + statusIcon.isHidden = true + + statusTextField.translatesAutoresizingMaskIntoConstraints = false + statusTextField.textColor = .secondaryLabelColor + statusTextField.font = .systemFont(ofSize: NSFont.systemFontSize) + statusTextField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + + actionButton.translatesAutoresizingMaskIntoConstraints = false + actionButton.bezelStyle = .rounded + actionButton.title = NSLocalizedString("Cancel", comment: "Cancel button") + actionButton.widthAnchor.constraint(equalToConstant: CloudKitStatsLayout.buttonWidth).isActive = true + + addSubview(spinner) + addSubview(statusIcon) + addSubview(statusTextField) + addSubview(actionButton) + + statusTextLeadingToSpinner = statusTextField.leadingAnchor.constraint(equalTo: spinner.trailingAnchor, constant: CloudKitStatsLayout.spinnerTextGap) + statusTextLeadingToContainer = statusTextField.leadingAnchor.constraint(equalTo: leadingAnchor) + + NSLayoutConstraint.activate([ + spinner.leadingAnchor.constraint(equalTo: leadingAnchor), + spinner.centerYAnchor.constraint(equalTo: statusTextField.centerYAnchor), + + statusIcon.leadingAnchor.constraint(equalTo: leadingAnchor), + statusIcon.centerYAnchor.constraint(equalTo: statusTextField.centerYAnchor), + + statusTextLeadingToSpinner, + + actionButton.topAnchor.constraint(equalTo: topAnchor), + actionButton.bottomAnchor.constraint(equalTo: bottomAnchor), + statusTextField.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor), + + actionButton.leadingAnchor.constraint(greaterThanOrEqualTo: statusTextField.trailingAnchor, constant: CloudKitStatsLayout.buttonTextGap), + actionButton.trailingAnchor.constraint(equalTo: trailingAnchor), + actionButton.lastBaselineAnchor.constraint(equalTo: statusTextField.lastBaselineAnchor) + ]) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} diff --git a/Mac/CloudKitStats/Scan/CloudKitStatsScanViewController.swift b/Mac/CloudKitStats/Scan/CloudKitStatsScanViewController.swift new file mode 100644 index 000000000..568119519 --- /dev/null +++ b/Mac/CloudKitStats/Scan/CloudKitStatsScanViewController.swift @@ -0,0 +1,171 @@ +// +// CloudKitStatsScanViewController.swift +// NetNewsWire +// +// Created by Brent Simmons on 3/24/26. +// + +import AppKit +import CloudKit +import Account +import CloudKitSync + +final class CloudKitStatsScanViewController: NSViewController { + + private let model: CloudKitStatsViewModel + + private let statusView = CloudKitStatsScanStatusView() + private let contentView = CloudKitStatsScanContentView() + + private var hasShownErrorAlert = false + + // MARK: - Init + + init(model: CloudKitStatsViewModel) { + self.model = model + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) is not supported") + } + + // MARK: - NSViewController + + override func loadView() { + let containerView = NSView() + containerView.translatesAutoresizingMaskIntoConstraints = false + + let topDivider = CloudKitStatsLayout.makeDivider() + + containerView.addSubview(statusView) + containerView.addSubview(topDivider) + containerView.addSubview(contentView) + + NSLayoutConstraint.activate([ + statusView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: CloudKitStatsLayout.sectionSpacing), + statusView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), + statusView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), + + topDivider.topAnchor.constraint(equalTo: statusView.bottomAnchor, constant: CloudKitStatsLayout.sectionSpacing), + topDivider.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: -CloudKitStatsLayout.horizontalPadding), + topDivider.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: CloudKitStatsLayout.horizontalPadding), + + contentView.topAnchor.constraint(equalTo: topDivider.bottomAnchor, constant: CloudKitStatsLayout.sectionSpacing), + contentView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), + contentView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), + contentView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor) + ]) + + self.view = containerView + } + + // MARK: - API + + func updateUI() { + NSAnimationContext.runAnimationGroup { context in + context.duration = CloudKitStatsLayout.animationDuration + context.allowsImplicitAnimation = true + updateStatusBar() + updateStatsValues() + } + } +} + +// MARK: - Private + +private extension CloudKitStatsScanViewController { + + // MARK: - UI Update + + func updateStatusBar() { + switch model.fetchStatus { + case .idle: + break + case .fetching: + hasShownErrorAlert = false + statusView.spinner.isHidden = false + statusView.spinner.isIndeterminate = true + statusView.spinner.style = .spinning + statusView.spinner.startAnimation(nil) + statusView.statusIcon.isHidden = true + statusView.statusTextField.stringValue = NSLocalizedString("Scanning iCloud storage", comment: "Scan status text while fetching") + statusView.actionButton.title = NSLocalizedString("Cancel", comment: "Cancel button") + statusView.actionButton.keyEquivalent = "\u{1b}" + statusView.actionButton.action = #selector(CloudKitStatsViewController.cancelScan(_:)) + statusView.statusTextLeadingToSpinner.isActive = true + statusView.statusTextLeadingToContainer.isActive = false + case .completed: + statusView.spinner.isHidden = true + statusView.spinner.stopAnimation(nil) + statusView.statusIcon.isHidden = false + statusView.statusTextField.stringValue = NSLocalizedString("Scan completed.", comment: "Scan status text when completed") + statusView.actionButton.title = NSLocalizedString("Refresh", comment: "Refresh button") + statusView.actionButton.keyEquivalent = "" + statusView.actionButton.action = #selector(CloudKitStatsViewController.refreshScan(_:)) + statusView.statusTextLeadingToSpinner.isActive = true + statusView.statusTextLeadingToContainer.isActive = false + case .error: + statusView.spinner.isHidden = true + statusView.spinner.stopAnimation(nil) + statusView.statusIcon.isHidden = true + statusView.statusTextField.stringValue = NSLocalizedString("Scan failed. Numbers are incomplete.", comment: "Scan status text on error") + statusView.actionButton.title = NSLocalizedString("Refresh", comment: "Refresh button") + statusView.actionButton.keyEquivalent = "" + statusView.actionButton.action = #selector(CloudKitStatsViewController.refreshScan(_:)) + statusView.statusTextLeadingToSpinner.isActive = false + statusView.statusTextLeadingToContainer.isActive = true + showErrorAlertIfNeeded() + case .canceled: + statusView.spinner.isHidden = true + statusView.spinner.stopAnimation(nil) + statusView.statusIcon.isHidden = true + statusView.statusTextField.stringValue = NSLocalizedString("Canceled.", comment: "Scan status text when canceled") + statusView.actionButton.title = NSLocalizedString("Refresh", comment: "Refresh button") + statusView.actionButton.keyEquivalent = "" + statusView.actionButton.action = #selector(CloudKitStatsViewController.refreshScan(_:)) + statusView.statusTextLeadingToSpinner.isActive = false + statusView.statusTextLeadingToContainer.isActive = true + } + } + + func updateStatsValues() { + let stats = model.stats + contentView.statusRecordCountLabel.stringValue = CloudKitStatsLayout.formattedNumber(stats.statusCount) + contentView.starredCountLabel.stringValue = CloudKitStatsLayout.formattedNumber(stats.starredStatusCount) + contentView.unreadCountLabel.stringValue = CloudKitStatsLayout.formattedNumber(stats.unreadStatusCount) + contentView.readCountLabel.stringValue = CloudKitStatsLayout.formattedNumber(stats.readStatusCount) + contentView.staleCountLabel.stringValue = CloudKitStatsLayout.formattedNumber(stats.staleStatusCount) + contentView.totalContentCountLabel.stringValue = CloudKitStatsLayout.formattedNumber(stats.articleCount) + contentView.starredContentCountLabel.stringValue = CloudKitStatsLayout.formattedNumber(stats.starredArticleCount) + contentView.unreadContentCountLabel.stringValue = CloudKitStatsLayout.formattedNumber(stats.unreadArticleCount) + contentView.readContentCountLabel.stringValue = CloudKitStatsLayout.formattedNumber(stats.readArticleCount) + contentView.orphanedContentCountLabel.stringValue = CloudKitStatsLayout.formattedNumber(stats.orphanedArticleCount) + + let isFetching = model.fetchStatus.isFetching + let statusSectionDone = !isFetching || stats.articleCount > 0 + contentView.statusSectionView.animator().alphaValue = statusSectionDone ? 1.0 : CloudKitStatsLayout.fetchingAlpha + contentView.articleSectionView.animator().alphaValue = isFetching ? CloudKitStatsLayout.fetchingAlpha : 1.0 + } + + func showErrorAlertIfNeeded() { + guard let fetchError = model.fetchStatus.fetchError, !hasShownErrorAlert else { + return + } + + hasShownErrorAlert = true + let displayError: Error + if fetchError is CKError { + displayError = CloudKitError(fetchError) + } else { + displayError = fetchError + } + let alert = NSAlert() + alert.alertStyle = .warning + alert.messageText = NSLocalizedString("Couldn’t complete the iCloud scan because of an error:", comment: "Scan error alert title") + alert.informativeText = displayError.localizedDescription + alert.addButton(withTitle: NSLocalizedString("OK", comment: "OK button")) + alert.runModal() + } +}