SPB Git

Repository Public License

FormatsView.swift 16.3 KB 289 lines swift

1// ORIX Convert — App/Sources/Features/Formats/FormatsView.swift2// Description: The in-app conversion matrix, read live from the registry: every format with at least one real path,3//              what it converts to and from (engine, status, fidelity, preserves, limitations), engine availability,4//              real counts, and the Markdown / JSON export of FormatRegistry.matrix.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import AppKit7import ConvertCore8import SwiftUI9import UniformTypeIdentifiers1011struct FormatsView: View {12    @Environment(AppModel.self) private var model13    @State private var search = ""14    @State private var selection: FormatID?15    @FocusState private var searchFocused: Bool1617    private var registry: FormatRegistry { model.registry }1819    /// Formats that are the source or destination of at least one available path.20    private var formats: [FormatID] {21        Set(registry.sourceFormats).union(registry.destinationFormats).sorted { $0.displayName.localizedCaseInsensitiveCompare($1.displayName) == .orderedAscending }22    }2324    private var filtered: [(FormatCategory, [FormatID])] {25        let needle = search.trimmingCharacters(in: .whitespaces).lowercased()26        let matching = formats.filter { format in27            needle.isEmpty || format.displayName.lowercased().contains(needle) || format.rawValue.contains(needle)28                || (format.catalogEntry?.extensions.contains { $0.contains(needle) } ?? false)29        }30        let grouped = Dictionary(grouping: matching, by: \.category)31        return FormatCategory.allCases.compactMap { category in grouped[category].map { (category, $0) } }32    }3334    var body: some View {35        let counts = registry.counts36        VStack(spacing: 0) {37            HeaderBar(title: L("Formats"), subtitle: L("%lld formats · %lld verified conversions · %lld operations", counts.formatsWithPath, counts.verifiedPairs, counts.operations)) {38                SearchField(text: $search, prompt: L("Search formats"), focus: $searchFocused).frame(maxWidth: 220)39                Menu {40                    Button(L("Markdown…")) { export(json: false) }41                    Button(L("JSON…")) { export(json: true) }42                } label: { Label(L("Export Matrix…"), systemImage: "square.and.arrow.up") }43                .menuStyle(.button).buttonStyle(SecondaryButtonStyle()).fixedSize()44            }45            HStack(spacing: 0) {46                formatList.frame(width: 250)47                ORIX.Palette.hairline.frame(width: 1)48                Group {49                    if let selection { FormatDetail(format: selection, select: { self.selection = $0 }) } else { RegistryOverview(select: { selection = $0 }) }50                }51                .frame(maxWidth: .infinity, maxHeight: .infinity)52            }53        }54        .onChange(of: model.searchRequest) { searchFocused = true }55        .onAppear { if selection == nil, let wanted = model.launch.select.map({ FormatID($0) }), formats.contains(wanted) { selection = wanted } }56    }5758    private var formatList: some View {59        ScrollView {60            LazyVStack(alignment: .leading, spacing: 2) {61                listRow(title: L("Overview"), subtitle: L("Engines and totals"), badge: nil, selected: selection == nil) { selection = nil }62                ForEach(filtered, id: \.0) { category, items in63                    SectionLabel(category.title).padding(.horizontal, ORIX.Space.s).padding(.top, ORIX.Space.m).padding(.bottom, 2)64                    ForEach(items, id: \.self) { format in65                        listRow(title: format.displayName, subtitle: (format.catalogEntry?.extensions.prefix(3).map { "." + $0 }.joined(separator: " ")) ?? "",66                                badge: format, selected: selection == format) { selection = format }67                    }68                }69                if filtered.isEmpty { Text(L("No format matches “%@”.", search)).font(.callout).foregroundStyle(ORIX.Palette.textSecondary).padding(ORIX.Space.m) }70            }71            .padding(ORIX.Space.s)72        }73        .background(ORIX.Palette.surfaceSunken.opacity(0.5))74        .accessibilityLabel(L("Formats"))75    }7677    private func listRow(title: String, subtitle: String, badge: FormatID?, selected: Bool, action: @escaping () -> Void) -> some View {78        Button(action: action) {79            HStack(spacing: ORIX.Space.s) {80                if let badge { FormatBadge(format: badge, size: .small) } else {81                    Image(systemName: "square.grid.3x3").font(.callout).foregroundStyle(ORIX.Palette.accent).frame(width: 28, height: 28)82                }83                VStack(alignment: .leading, spacing: 0) {84                    Text(title).font(.callout.weight(selected ? .semibold : .regular)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)85                    if !subtitle.isEmpty { Text(subtitle).font(.caption2).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1) }86                }87                Spacer(minLength: 0)88            }89            .padding(.horizontal, ORIX.Space.s).padding(.vertical, 4)90            .background(selected ? ORIX.Palette.accentSoft : .clear, in: RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous))91            .contentShape(Rectangle())92        }93        .buttonStyle(.plain)94        .accessibilityLabel(title)95        .accessibilityAddTraits(selected ? [.isSelected] : [])96    }9798    private func export(json: Bool) {99        let panel = NSSavePanel()100        panel.nameFieldStringValue = json ? "orix-convert-matrix.json" : "orix-convert-matrix.md"101        panel.allowedContentTypes = [json ? .json : (UTType(filenameExtension: "md") ?? .plainText)]102        guard panel.runModal() == .OK, let url = panel.url else { return }103        let data: Data? = json ? try? registry.matrixJSON() : Data(registry.matrixMarkdown().utf8)104        try? data?.write(to: url, options: .atomic)105    }106}107108/// Totals and engine availability.109private struct RegistryOverview: View {110    @Environment(AppModel.self) private var model111    let select: (FormatID) -> Void112113    var body: some View {114        let registry = model.registry, counts = registry.counts115        ScrollView {116            VStack(alignment: .leading, spacing: ORIX.Space.xl) {117                AdaptiveColumns(minColumnWidth: 150, spacing: ORIX.Space.m) {118                    stat(Fmt.count(counts.formatsWithPath), L("Formats with a real path"))119                    stat(Fmt.count(counts.verifiedPairs), L("Verified pairs"))120                    stat(Fmt.count(counts.operations), L("Named operations"))121                }122                Text(L("Counts come from the engines of this build: %lld available paths, %lld distinct source → destination pairs, %lld of them plain conversions.",123                       counts.availablePaths, counts.distinctPairs, counts.conversionPairs))124                    .font(.callout).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)125                VStack(alignment: .leading, spacing: ORIX.Space.s) {126                    SectionLabel(L("Engines"))127                    ForEach(registry.engines, id: \.id) { engine in128                        EngineRow(name: LE(engine.displayName), id: engine.id, paths: registry.paths(engine: engine.id).count,129                                  unavailableReason: registry.unavailableEngines.first { $0.id == engine.id }?.reason,130                                  unavailablePaths: registry.unavailableEngines.first { $0.id == engine.id }?.paths.count ?? 0)131                    }132                    if registry.engines.isEmpty { Text(L("No engine is registered in this build.")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary) }133                }134                if !registry.diagnostics.isEmpty {135                    VStack(alignment: .leading, spacing: ORIX.Space.s) {136                        SectionLabel(L("Registry diagnostics"))137                        ForEach(registry.diagnostics, id: \.self) { Banner(kind: .caution, text: $0) }138                    }139                }140            }141            .padding(ORIX.Space.xl)142        }143    }144145    private func stat(_ value: String, _ label: String) -> some View {146        VStack(alignment: .leading, spacing: 2) {147            Text(value).font(.system(size: 30, weight: .bold).monospacedDigit()).foregroundStyle(ORIX.Palette.transformation)148            Text(label).font(.caption).foregroundStyle(ORIX.Palette.textSecondary)149        }150        .padding(ORIX.Space.l)151        .frame(maxWidth: .infinity, alignment: .leading)152        .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.l, style: .continuous))153        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.l, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))154        .accessibilityElement(children: .ignore)155        .accessibilityLabel(label)156        .accessibilityValue(value)157    }158}159160struct EngineRow: View {161    let name: String162    let id: String163    let paths: Int164    let unavailableReason: String?165    let unavailablePaths: Int166    var body: some View {167        HStack(alignment: .firstTextBaseline, spacing: ORIX.Space.m) {168            Image(systemName: unavailableReason == nil ? "checkmark.circle.fill" : "exclamationmark.triangle.fill")169                .foregroundStyle(unavailableReason == nil ? ORIX.Palette.success : ORIX.Palette.caution).accessibilityHidden(true)170            VStack(alignment: .leading, spacing: 2) {171                HStack(spacing: 6) {172                    Text(name).font(.callout.weight(.medium))173                    Text(id).font(.caption.monospaced()).foregroundStyle(ORIX.Palette.textTertiary)174                }175                if let unavailableReason {176                    Text(L("Unavailable: %@", LE(unavailableReason))).font(.caption).foregroundStyle(ORIX.Palette.caution).fixedSize(horizontal: false, vertical: true)177                    Text(L("%lld paths cannot run until the component is present.", unavailablePaths)).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)178                } else {179                    Text(L("Available · %lld paths", paths)).font(.caption).foregroundStyle(ORIX.Palette.textSecondary)180                }181            }182            Spacer(minLength: 0)183        }184        .padding(ORIX.Space.m)185        .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous))186        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))187        .accessibilityElement(children: .combine)188    }189}190191private struct FormatDetail: View {192    @Environment(AppModel.self) private var model193    let format: FormatID194    let select: (FormatID) -> Void195196    var body: some View {197        let registry = model.registry198        let outgoing = registry.paths(from: format)199        let incoming = registry.paths(to: format).filter { $0.source != format }200        let missing = registry.unavailablePaths(from: format) + registry.unavailablePaths(to: format).filter { $0.path.source != format }201        ScrollView {202            LazyVStack(alignment: .leading, spacing: ORIX.Space.l) {203                HStack(spacing: ORIX.Space.l) {204                    FormatBadge(format: format, size: .large)205                    VStack(alignment: .leading, spacing: 4) {206                        Text(format.displayName).font(.title2.weight(.semibold))207                        HStack(spacing: 6) {208                            Pill(text: format.category.title, symbol: format.category.symbol, color: format.category.color)209                            if let entry = format.catalogEntry {210                                Text(entry.extensions.map { "." + $0 }.joined(separator: "  ")).font(.caption.monospaced()).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)211                            }212                        }213                        if let mime = format.catalogEntry?.mime { Text(mime).font(.caption.monospaced()).foregroundStyle(ORIX.Palette.textTertiary) }214                    }215                    Spacer()216                }217                if !outgoing.isEmpty {218                    SectionLabel(L("Converts to · %lld", outgoing.count))219                    ForEach(outgoing) { PathCard(path: $0, other: $0.destination, outgoing: true, unavailableReason: nil, select: select) }220                }221                if !incoming.isEmpty {222                    SectionLabel(L("Created from · %lld", incoming.count)).padding(.top, ORIX.Space.s)223                    ForEach(incoming) { PathCard(path: $0, other: $0.source, outgoing: false, unavailableReason: nil, select: select) }224                }225                if !missing.isEmpty {226                    SectionLabel(L("Unavailable in this build · %lld", missing.count)).padding(.top, ORIX.Space.s)227                    ForEach(missing, id: \.path.id) { entry in228                        PathCard(path: entry.path, other: entry.path.source == format ? entry.path.destination : entry.path.source, outgoing: entry.path.source == format,229                                 unavailableReason: entry.reason, select: select)230                    }231                }232            }233            .padding(ORIX.Space.xl)234        }235        .id(format)236    }237}238239private struct PathCard: View {240    @Environment(AppModel.self) private var model241    let path: ConversionPath242    let other: FormatID243    let outgoing: Bool244    let unavailableReason: String?245    let select: (FormatID) -> Void246    @State private var expanded = false247248    var body: some View {249        VStack(alignment: .leading, spacing: ORIX.Space.s) {250            HStack(spacing: ORIX.Space.m) {251                Button { select(other) } label: { FormatBadge(format: other, size: .small) }.buttonStyle(.plain)252                    .accessibilityLabel(L("Show %@", other.displayName))253                VStack(alignment: .leading, spacing: 1) {254                    Text(path.title.map { LE($0) } ?? (outgoing ? L("To %@", other.displayName) : L("From %@", other.displayName))).font(.callout.weight(.medium)).lineLimit(1)255                    Text(L("Engine: %@", model.registry.engine(id: path.engine).map { LE($0.displayName) } ?? path.engine)256                         + (path.acceptsMultipleSources ? " · " + L("accepts several files") : "")).font(.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)257                }258                Spacer(minLength: 4)259                if unavailableReason != nil { Pill(text: L("Unavailable"), symbol: "exclamationmark.triangle.fill", color: ORIX.Palette.caution) }260                else if path.status == .experimental { ExperimentalBadge() } else { Pill(text: L("Verified"), symbol: "checkmark", color: ORIX.Palette.success) }261                FidelityBadge(fidelity: path.fidelity)262                IconButton(symbol: expanded ? "chevron.up" : "chevron.down", label: expanded ? L("Hide details") : L("Show details")) { expanded.toggle() }263            }264            if expanded {265                VStack(alignment: .leading, spacing: 6) {266                    if let unavailableReason { Banner(kind: .caution, text: LE(unavailableReason)) }267                    KeyValueRow(key: L("Preserves"), value: path.preserves.isEmpty ? nil : path.preserves.map(\.title).sorted().joined(separator: ", "))268                    if let operation = path.operation { KeyValueRow(key: L("Operation"), value: operation, monospaced: true) }269                    if path.limitations.isEmpty {270                        Text(L("No limitation declared.")).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)271                    } else {272                        ForEach(path.limitations, id: \.self) { limitation in273                            HStack(alignment: .firstTextBaseline, spacing: 6) {274                                Image(systemName: "minus").font(.caption2).foregroundStyle(ORIX.Palette.textTertiary).accessibilityHidden(true)275                                Text(LE(limitation)).font(.caption).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)276                            }277                        }278                    }279                }280                .padding(.leading, 40)281            }282        }283        .padding(ORIX.Space.m)284        .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous))285        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))286        .accessibilityElement(children: .contain)287    }288}289
Files main
Menu

Theme