SPB Git

Repository Public License

HistoryView.swift 15.2 KB 266 lines swift

1// ORIX Convert — App/Sources/Features/History/HistoryView.swift2// Description: History: searchable, filterable list of ended conversions with a detail panel (options used — never3//              secrets —, warnings, verification, sizes, duration), reveal, convert again, delete, clear.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import ConvertCore6import SwiftUI78struct HistoryView: View {9    @Environment(AppModel.self) private var model10    @FocusState private var searchFocused: Bool11    @State private var confirmClear = false1213    var body: some View {14        @Bindable var history = model.history15        VStack(spacing: 0) {16            HeaderBar(title: L("History"), subtitle: countLine) {17                SearchField(text: $history.search, prompt: L("Search names and paths"), focus: $searchFocused).frame(maxWidth: 240)18                Button(L("Clear History…")) { confirmClear = true }.buttonStyle(SecondaryButtonStyle()).disabled(history.totalCount == 0)19            }20            if !model.settings.stored.historyEnabled {21                Banner(kind: .info, text: L("History is turned off: new conversions are not recorded."), detail: L("Turn it back on in Settings › Privacy."))22                    .padding(.horizontal, ORIX.Space.xl).padding(.top, ORIX.Space.m)23            }24            filters25            if let error = history.error {26                EmptyState(symbol: "exclamationmark.triangle", title: L("The history could not be read"), message: error)27            } else if history.entries.isEmpty {28                if history.hasFilters {29                    EmptyState(symbol: "line.3.horizontal.decrease.circle", title: L("No conversion matches"), message: L("Nothing in the history matches these filters."),30                               actionTitle: L("Clear Filters")) { history.clearFilters() }31                } else {32                    EmptyState(symbol: "clock.arrow.circlepath", title: L("No conversion yet"),33                               message: L("Every conversion that ends is recorded here with its settings, warnings and verification. File contents are never stored."))34                }35            } else {36                GeometryReader { geo in37                    let inline = geo.size.width >= ORIX.Metric.sidePanelBreakpoint38                    HStack(spacing: 0) {39                        list40                        if let entry = history.selected, inline {41                            ORIX.Palette.hairline.frame(width: 1)42                            HistoryDetail(entry: entry).frame(width: ORIX.Metric.sidePanelWidth)43                        }44                    }45                    .overlay(alignment: .trailing) {46                        if let entry = history.selected, !inline {47                            HistoryDetail(entry: entry).frame(width: min(ORIX.Metric.sidePanelWidth, geo.size.width - 40))48                                .overlay(alignment: .leading) { ORIX.Palette.hairlineStrong.frame(width: 1) }49                                .shadow(color: .black.opacity(0.18), radius: 16, x: -4)50                        }51                    }52                }53            }54        }55        .onAppear { history.setNeedsReload(); history.reloadIfNeeded() }56        .onChange(of: model.searchRequest) { searchFocused = true }57        .confirmationDialog(L("Clear the whole history?"), isPresented: $confirmClear) {58            Button(L("Clear History"), role: .destructive) { history.clearAll() }59            Button(L("Cancel"), role: .cancel) {}60        } message: {61            Text(L("%lld entries will be removed. Converted files are not touched.", history.totalCount))62        }63    }6465    private var countLine: String? {66        let history = model.history67        guard history.totalCount > 0 else { return nil }68        if history.hasFilters { return L("%lld of %lld conversions", history.matchingCount, history.totalCount) }69        return history.totalCount == 1 ? L("1 conversion") : L("%lld conversions", history.totalCount)70    }7172    private var filters: some View {73        @Bindable var history = model.history74        return HStack(spacing: ORIX.Space.s) {75            FilterMenu(title: L("Status"), value: history.status.flatMap { JobState(rawValue: $0)?.title } ?? L("Any status"), active: history.status != nil) {76                Button(L("Any status")) { history.status = nil }77                ForEach([JobState.finished, .failed, .skipped, .cancelled], id: \.self) { state in Button(state.title) { history.status = state.rawValue } }78            }79            FilterMenu(title: L("Format"), value: history.format?.displayName ?? L("Any format"), active: history.format != nil) {80                Button(L("Any format")) { history.format = nil }81                ForEach(history.formatsInUse, id: \.self) { format in Button(format.displayName) { history.format = format } }82            }83            FilterMenu(title: L("Date"), value: history.period.title, active: history.period != .all) {84                ForEach(HistoryPeriod.allCases) { period in Button(period.title) { history.period = period } }85            }86            if history.hasFilters { Button(L("Clear Filters")) { history.clearFilters() }.buttonStyle(.plain).font(.callout).foregroundStyle(ORIX.Palette.accent) }87            Spacer()88            if history.matchingCount > history.entries.count {89                Text(L("Showing the %lld most recent", history.entries.count)).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)90            }91        }92        .padding(.horizontal, ORIX.Space.xl).padding(.vertical, ORIX.Space.m)93    }9495    private var list: some View {96        @Bindable var history = model.history97        return List(selection: $history.selection) {98            ForEach(history.entries) { entry in99                HistoryRow(entry: entry)100                    .tag(entry.id)101                    .listRowInsets(EdgeInsets(top: 0, leading: ORIX.Space.m, bottom: 0, trailing: ORIX.Space.m))102                    .listRowSeparatorTint(ORIX.Palette.hairline)103                    .contextMenu {104                        Button(L("Reveal Result in Finder")) { reveal(entry) }.disabled(entry.destinationPaths.isEmpty)105                        Button(L("Convert Again")) { convertAgain(entry) }106                        Divider()107                        Button(L("Delete Entry"), role: .destructive) { history.delete(entry) }108                    }109            }110        }111        .listStyle(.plain)112        .scrollContentBackground(.hidden)113        .padding(.horizontal, ORIX.Space.s)114        .onDeleteCommand { if let entry = history.selected { history.delete(entry) } }115        .accessibilityLabel(L("Conversion history"))116    }117118    private func reveal(_ entry: HistoryEntry) {119        if !FileActions.reveal(entry.outputURLs) { model.history.error = nil }120    }121122    private func convertAgain(_ entry: HistoryEntry) {123        _ = model.history.convertAgain(entry)124    }125}126127private struct FilterMenu<Content: View>: View {128    let title: String129    let value: String130    let active: Bool131    @ViewBuilder var content: Content132    var body: some View {133        Menu { content } label: {134            HStack(spacing: 5) {135                Text(value).font(.callout.weight(active ? .semibold : .regular))136                Image(systemName: "chevron.down").font(.system(size: 8, weight: .bold))137            }138            .foregroundStyle(active ? ORIX.Palette.accent : ORIX.Palette.textPrimary)139            .padding(.horizontal, 10).padding(.vertical, 5)140            .background(active ? ORIX.Palette.accentSoft : ORIX.Palette.surface, in: Capsule())141            .overlay(Capsule().strokeBorder(active ? ORIX.Palette.accent.opacity(0.4) : ORIX.Palette.hairlineStrong, lineWidth: 1))142        }143        .menuStyle(.button).buttonStyle(.plain).fixedSize()144        .accessibilityLabel(title)145        .accessibilityValue(value)146    }147}148149private struct HistoryRow: View {150    let entry: HistoryEntry151    var body: some View {152        HStack(spacing: ORIX.Space.m) {153            ConversionPairBadge(source: entry.sourceFormat, destination: entry.destinationFormat)154            VStack(alignment: .leading, spacing: 2) {155                Text(entry.sourceName + (entry.additionalSourcePaths.isEmpty ? "" : " " + L("+ %lld more", entry.additionalSourcePaths.count)))156                    .font(.callout.weight(.medium)).lineLimit(1).truncationMode(.middle)157                HStack(spacing: 6) {158                    Label(entry.state.title, systemImage: entry.state.symbol).font(.caption).foregroundStyle(entry.state.color)159                    if let error = entry.error { Text(LE(error)).font(.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1) }160                    else if !entry.warnings.isEmpty { Text(entry.warnings.count == 1 ? L("1 warning") : L("%lld warnings", entry.warnings.count)).font(.caption).foregroundStyle(ORIX.Palette.caution) }161                }162            }163            .layoutPriority(1)164            Spacer(minLength: ORIX.Space.s)165            VStack(alignment: .trailing, spacing: 2) {166                Text(Fmt.date(entry.finishedAt)).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textSecondary)167                if let before = entry.bytesBefore, let after = entry.bytesAfter, entry.state == .finished {168                    Text("\(Fmt.bytes(before)) → \(Fmt.bytes(after))").font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textTertiary)169                }170            }171            .lineLimit(1)172        }173        .padding(.vertical, 7)174        .accessibilityElement(children: .combine)175        .accessibilityLabel(entry.sourceName)176        .accessibilityValue([L("%@ to %@", entry.sourceFormat?.displayName ?? L("Unknown format"), entry.destinationFormat.displayName), entry.state.title, Fmt.date(entry.finishedAt)].joined(separator: ", "))177    }178}179180struct HistoryDetail: View {181    @Environment(AppModel.self) private var model182    let entry: HistoryEntry183    @State private var message: String?184185    var body: some View {186        VStack(spacing: 0) {187            HStack(spacing: ORIX.Space.s) {188                ConversionPairBadge(source: entry.sourceFormat, destination: entry.destinationFormat)189                VStack(alignment: .leading, spacing: 1) {190                    Text(entry.sourceName).font(.headline).lineLimit(1).truncationMode(.middle)191                    Label(entry.state.title, systemImage: entry.state.symbol).font(.caption).foregroundStyle(entry.state.color)192                }193                Spacer(minLength: 4)194                IconButton(symbol: "xmark", label: L("Close details")) { model.history.selection = nil }195            }196            .padding(.horizontal, ORIX.Space.l).frame(height: 54)197            ORIX.Palette.hairline.frame(height: 1)198            ScrollView {199                VStack(alignment: .leading, spacing: ORIX.Space.xl) {200                    if let message { Banner(kind: .caution, text: message) }201                    if let error = entry.error { Banner(kind: .danger, text: LE(error)) }202                    HStack(spacing: ORIX.Space.s) {203                        Button(L("Reveal Result")) {204                            message = FileActions.reveal(entry.outputURLs) ? nil : L("The converted file is no longer at its location. It may have been moved, renamed or deleted.")205                        }206                        .buttonStyle(SecondaryButtonStyle(prominent: true)).disabled(entry.destinationPaths.isEmpty)207                        Button(L("Convert Again")) {208                            message = model.history.convertAgain(entry) ? nil : L("The source file is no longer at its location, so this conversion cannot be repeated.")209                        }210                        .buttonStyle(SecondaryButtonStyle())211                    }212                    VStack(alignment: .leading, spacing: ORIX.Space.s) {213                        SectionLabel(L("Conversion"))214                        KeyValueRow(key: L("From"), value: entry.sourceFormat?.displayName)215                        KeyValueRow(key: L("To"), value: entry.destinationFormat.displayName)216                        KeyValueRow(key: L("Operation"), value: entry.operation)217                        KeyValueRow(key: L("Engine"), value: entry.engine.isEmpty ? nil : entry.engine.split(separator: "+").map { id in model.registry.engine(id: String(id)).map { LE($0.displayName) } ?? String(id) }.joined(separator: " → "))218                        KeyValueRow(key: L("Finished"), value: Fmt.date(entry.finishedAt))219                        KeyValueRow(key: L("Duration"), value: entry.duration.map { Fmt.duration($0) })220                        KeyValueRow(key: L("Size"), value: entry.bytesBefore.map { before in entry.bytesAfter.map { "\(Fmt.bytes(before)) → \(Fmt.bytes($0))" } ?? Fmt.bytes(before) })221                    }222                    VStack(alignment: .leading, spacing: ORIX.Space.s) {223                        SectionLabel(L("Files"))224                        pathRow(L("Source"), entry.sourcePath)225                        ForEach(entry.additionalSourcePaths, id: \.self) { pathRow(L("Source"), $0) }226                        ForEach(entry.destinationPaths, id: \.self) { pathRow(L("Result"), $0) }227                        if entry.destinationPaths.isEmpty { Text(L("No file was written.")).font(.caption).foregroundStyle(ORIX.Palette.textTertiary) }228                    }229                    VStack(alignment: .leading, spacing: ORIX.Space.s) {230                        SectionLabel(L("Options used"))231                        let options = entry.options.redactingSecrets().values.sorted { $0.key < $1.key }232                        if options.isEmpty { Text(L("Default settings.")).font(.caption).foregroundStyle(ORIX.Palette.textTertiary) }233                        ForEach(options, id: \.key) { KeyValueRow(key: $0.key, value: $0.value.plainText, monospaced: true) }234                    }235                    if !entry.warnings.isEmpty {236                        VStack(alignment: .leading, spacing: ORIX.Space.s) {237                            SectionLabel(L("Warnings"))238                            ForEach(entry.warnings, id: \.self) { warning in239                                Banner(kind: warning.severity == .dataLoss ? .danger : (warning.severity == .caution ? .caution : .info), text: LE(warning.message))240                            }241                        }242                    }243                    if !entry.checks.isEmpty { ChecksList(checks: entry.checks) }244                    Button(L("Delete Entry"), role: .destructive) { model.history.delete(entry) }.buttonStyle(SecondaryButtonStyle())245                }246                .padding(ORIX.Space.l)247            }248        }249        .background(ORIX.Palette.surface)250        .onChange(of: entry.id) { message = nil }251    }252253    private func pathRow(_ label: String, _ path: String) -> some View {254        let exists = FileManager.default.fileExists(atPath: path)255        return VStack(alignment: .leading, spacing: 1) {256            HStack(spacing: 5) {257                Text(label).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)258                if !exists { Pill(text: L("Missing"), symbol: "questionmark.folder", color: ORIX.Palette.caution) }259            }260            Text(path).font(.caption.monospaced()).foregroundStyle(exists ? ORIX.Palette.textPrimary : ORIX.Palette.textSecondary).textSelection(.enabled)261                .lineLimit(3).truncationMode(.middle)262        }263        .accessibilityElement(children: .combine)264    }265}266
Files main
Menu

Theme