Files
2026-09-08 20:06:58 +01:00

200 lines
8.5 KiB
Swift

import SwiftUI
import SwiftData
import AppKit
import UniformTypeIdentifiers
struct RunHistoryView: View {
@Environment(\.modelContext) private var modelContext
@Query(sort: \SyncRun.startedAt, order: .reverse) private var runs: [SyncRun]
@State private var selection: SyncRun?
@State private var persistenceError: String?
@State private var searchText = ""
@State private var filter: HistoryFilter = .all
let onBack: () -> Void
var body: some View {
HSplitView {
VStack(spacing: 0) {
HStack(spacing: 10) {
VStack(alignment: .leading, spacing: 2) {
Text("Recent Runs")
.font(.headline)
Text("\(runs.count) recorded")
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer()
Menu {
Button("Export Selected…") { exportRuns(selection.map { [$0] } ?? []) }
.disabled(selection == nil)
Button("Export All…") { exportRuns(runs) }
.disabled(runs.isEmpty)
} label: {
Image(systemName: "square.and.arrow.up")
}
.menuStyle(.borderlessButton)
.help("Export run logs")
Button("Clear", role: .destructive) {
runs.forEach(modelContext.delete)
selection = nil
saveHistoryChanges()
}
.buttonStyle(.bordered)
.controlSize(.small)
.disabled(runs.isEmpty)
}
.padding(14)
VStack(spacing: 8) {
TextField("Search history", text: $searchText)
.textFieldStyle(.roundedBorder)
Picker("History filter", selection: $filter) {
ForEach(HistoryFilter.allCases) { item in Text(item.title).tag(item) }
}
.pickerStyle(.segmented)
.labelsHidden()
}
.padding(.horizontal, 14)
.padding(.bottom, 10)
Divider()
if filteredRuns.isEmpty {
ContentUnavailableView(
"No Run History",
systemImage: "clock.arrow.circlepath",
description: Text(runs.isEmpty ? "Completed, failed and background synchronisations will appear here." : "No runs match the current search or filter.")
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
List(selection: $selection) {
ForEach(filteredRuns) { run in
HStack(spacing: 11) {
Image(systemName: statusIcon(run))
.foregroundStyle(statusColour(run))
VStack(alignment: .leading, spacing: 4) {
HStack {
Text(run.jobName)
.fontWeight(.semibold)
.lineLimit(1)
Spacer()
StatusBadge(run: run)
}
Text(run.startedAt, format: .dateTime.day().month(.abbreviated).year().hour().minute())
.font(.caption)
.foregroundStyle(.secondary)
HStack(spacing: 6) {
Label(run.trigger.title, systemImage: run.trigger.systemImage)
.font(.caption2.weight(.semibold))
.foregroundStyle(run.trigger == .watched ? Color.purple : Color.blue)
if run.wasDryRun {
Text("Dry run")
.font(.caption2.weight(.semibold))
.foregroundStyle(.blue)
}
}
}
}
.padding(.vertical, 3)
.tag(run)
.contextMenu {
Button("Delete Log", role: .destructive) {
if selection?.id == run.id { selection = nil }
modelContext.delete(run)
saveHistoryChanges()
}
}
}
}
.listStyle(.sidebar)
}
}
.frame(minWidth: 300, idealWidth: 340, maxWidth: 390)
Group {
if let selection {
RunLogView(run: selection)
} else {
ContentUnavailableView(
"Select a Run",
systemImage: "clock.arrow.circlepath",
description: Text("Select a completed or failed run to inspect its summary and full log.")
)
}
}
.frame(minWidth: 620, maxWidth: .infinity, maxHeight: .infinity)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.alert("Database Error", isPresented: Binding(
get: { persistenceError != nil },
set: { if !$0 { persistenceError = nil } }
)) {
Button("OK", role: .cancel) { persistenceError = nil }
} message: {
Text(persistenceError ?? "Unable to update run history.")
}
}
private var filteredRuns: [SyncRun] {
runs.filter { run in
let matchesSearch = searchText.isEmpty || run.jobName.localizedCaseInsensitiveContains(searchText) || run.output.localizedCaseInsensitiveContains(searchText) || run.errorOutput.localizedCaseInsensitiveContains(searchText)
let matchesFilter: Bool
switch filter {
case .all: matchesFilter = true
case .failed: matchesFilter = !run.isRunning && !run.succeeded && !run.wasCancelled
case .successful: matchesFilter = run.succeeded
case .automatic: matchesFilter = run.trigger == .scheduled || run.trigger == .watched
}
return matchesSearch && matchesFilter
}
}
private func exportRuns(_ items: [SyncRun]) {
guard !items.isEmpty else { return }
let panel = NSSavePanel()
panel.allowedContentTypes = [.plainText]
panel.nameFieldStringValue = items.count == 1 ? "Rsync Studio-\(items[0].jobName)-Run.txt" : "Rsync Studio-History.txt"
guard panel.runModal() == .OK, let url = panel.url else { return }
let text = items.map(\.exportText).joined(separator: "\n\n" + String(repeating: "=", count: 72) + "\n\n")
do { try text.write(to: url, atomically: true, encoding: .utf8) }
catch { persistenceError = "Could not export history: \(error.localizedDescription)" }
}
private func saveHistoryChanges() {
do { try modelContext.save() }
catch { persistenceError = error.localizedDescription }
}
private func statusIcon(_ run: SyncRun) -> String {
if run.isRunning { return "arrow.triangle.2.circlepath" }
if run.wasCancelled { return "xmark.circle.fill" }
return run.succeeded ? "checkmark.circle.fill" : "exclamationmark.triangle.fill"
}
private func statusColour(_ run: SyncRun) -> Color {
if run.isRunning { return .blue }
if run.wasCancelled { return .secondary }
return run.succeeded ? .green : .orange
}
}
private enum HistoryFilter: String, CaseIterable, Identifiable {
case all, failed, successful, automatic
var id: String { rawValue }
var title: String {
switch self {
case .all: return "All"
case .failed: return "Failed"
case .successful: return "Success"
case .automatic: return "Automatic"
}
}
}