SPB Git

Repository Public License

PrepareView.swift 22.9 KB 433 lines swift

1// ORIX Convert — App/Sources/Features/SmartDrop/PrepareView.swift2// Description: The Prepare pane: staged groups (one per detected format) in a single lazy list — group header,3//              destination chips, visible warnings, file rows — plus the options side panel and the output bar.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import ConvertCore6import SwiftUI78struct PrepareView: View {9    @Environment(AppModel.self) private var model10    @FocusState private var listFocused: Bool1112    var body: some View {13        let workspace = model.workspace14        GeometryReader { outer in15        VStack(spacing: 0) {16            GeometryReader { geo in17                let inline = geo.size.width >= ORIX.Metric.sidePanelBreakpoint18                let showPanel = workspace.selectedGroup?.choice != nil19                HStack(spacing: 0) {20                    stagedList21                    if showPanel && inline && model.showSidePanel, let group = workspace.selectedGroup {22                        ORIX.Palette.hairline.frame(width: 1)23                        OptionsPanel(group: group).frame(width: ORIX.Metric.sidePanelWidth)24                    }25                }26                .overlay(alignment: .trailing) {27                    if showPanel && !inline && model.overlayPanelRequested, let group = workspace.selectedGroup {28                        OptionsPanel(group: group)29                            .frame(width: min(ORIX.Metric.sidePanelWidth, geo.size.width - 40))30                            .overlay(alignment: .leading) { ORIX.Palette.hairlineStrong.frame(width: 1) }31                            .shadow(color: .black.opacity(0.18), radius: 16, x: -4)32                            .transition(.move(edge: .trailing))33                    }34                }35                .onChange(of: inline, initial: true) { model.sidePanelInline = inline }36            }37            OutputBar(narrow: outer.size.width < 860)38        }39        }40    }4142    private var stagedList: some View {43        let workspace = model.workspace44        return ScrollView {45            LazyVStack(spacing: 0) {46                if workspace.isAnalyzing {47                    HStack(spacing: 10) {48                        ORIXProgressRing(fraction: nil, size: 16, lineWidth: 2, label: L("Analysing"))49                        Text(L("Reading %lld items by content…", workspace.analyzingCount)).font(.callout).foregroundStyle(ORIX.Palette.textSecondary)50                        Spacer()51                    }52                    .padding(.bottom, ORIX.Space.m)53                }54                if let notice = workspace.notice {55                    Banner(kind: .caution, text: notice).padding(.bottom, ORIX.Space.m)56                }57                if workspace.truncated {58                    Banner(kind: .caution, text: L("Only the first %lld files were analysed.", workspace.fileCount), detail: L("Drop fewer items at a time to convert the rest."))59                        .padding(.bottom, ORIX.Space.m)60                }61                ForEach(workspace.skipped.prefix(5), id: \.url) { entry in62                    Banner(kind: .info, text: entry.url.lastPathComponent, detail: LE(entry.reason)).padding(.bottom, ORIX.Space.s)63                }64                if workspace.groups.isEmpty && !workspace.isAnalyzing {65                    CompactDropHint().padding(.top, ORIX.Space.xl)66                }67                ForEach(workspace.groups) { group in68                    GroupHeader(group: group)69                    ForEach(visibleFiles(group)) { file in70                        FileRow(file: file, group: group)71                    }72                    GroupFooter(group: group).padding(.bottom, ORIX.Space.l)73                }74            }75            .padding(ORIX.Space.xl)76        }77        .frame(maxWidth: .infinity, maxHeight: .infinity)78        // Keyboard, as in Queue and History: arrows move the selected file, space shows it, delete removes it.79        .focusable()80        .focusEffectDisabled()81        .focused($listFocused)82        .onKeyPress(.upArrow) { workspace.moveFileSelection(by: -1); return .handled }83        .onKeyPress(.downArrow) { workspace.moveFileSelection(by: 1); return .handled }84        .onKeyPress(.space) {85            guard let selected = workspace.selectedFileID else { return .ignored }86            QuickLook.toggle([selected])87            return .handled88        }89        .onKeyPress(.escape) { workspace.selectedFileID = nil; return .handled }90        .onDeleteCommand { workspace.removeSelectedFile() }91        .onChange(of: workspace.selectedFileID) { _, new in if new != nil { listFocused = true } }92        .accessibilityHint(L("Arrow keys select a file. Space shows it in Quick Look. Delete removes it from the batch."))93    }9495    private func visibleFiles(_ group: StagedGroup) -> [StagedFile] {96        group.expanded ? group.files : Array(group.files.prefix(StagedGroup.collapsedRows))97    }98}99100extension StagedGroup {101    static let collapsedRows = 4102}103104/// Shown in the Prepare pane when everything staged was sent to the queue.105private struct CompactDropHint: View {106    @Environment(AppModel.self) private var model107    var body: some View {108        EmptyState(symbol: "square.and.arrow.down.on.square", title: L("Drop more files"),109                   message: L("Nothing is staged. Drop files or folders anywhere in this window, or add them from the menu."),110                   actionTitle: L("Add Files…")) { model.addFiles() }111            .frame(minHeight: 280)112    }113}114115// MARK: - Card segments116117/// Borders of one slice of a card built from several rows of a lazy list.118nonisolated struct SegmentShape: Shape {119    enum Position { case top, middle, bottom }120    let position: Position121    var radius: CGFloat = 14122123    func path(in rect: CGRect) -> Path {124        let r = radius125        var path = Path()126        switch position {127        case .top:128            path.move(to: CGPoint(x: rect.minX, y: rect.maxY))129            path.addLine(to: CGPoint(x: rect.minX, y: rect.minY + r))130            path.addQuadCurve(to: CGPoint(x: rect.minX + r, y: rect.minY), control: rect.origin)131            path.addLine(to: CGPoint(x: rect.maxX - r, y: rect.minY))132            path.addQuadCurve(to: CGPoint(x: rect.maxX, y: rect.minY + r), control: CGPoint(x: rect.maxX, y: rect.minY))133            path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))134        case .middle:135            path.move(to: CGPoint(x: rect.minX, y: rect.minY)); path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))136            path.move(to: CGPoint(x: rect.maxX, y: rect.minY)); path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))137        case .bottom:138            path.move(to: CGPoint(x: rect.minX, y: rect.minY))139            path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY - r))140            path.addQuadCurve(to: CGPoint(x: rect.minX + r, y: rect.maxY), control: CGPoint(x: rect.minX, y: rect.maxY))141            path.addLine(to: CGPoint(x: rect.maxX - r, y: rect.maxY))142            path.addQuadCurve(to: CGPoint(x: rect.maxX, y: rect.maxY - r), control: CGPoint(x: rect.maxX, y: rect.maxY))143            path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))144        }145        return path146    }147}148149private struct CardSegment: ViewModifier {150    let position: SegmentShape.Position151    let selected: Bool152    func body(content: Content) -> some View {153        let r = ORIX.Radius.l154        let fill = UnevenRoundedRectangle(topLeadingRadius: position == .top ? r : 0, bottomLeadingRadius: position == .bottom ? r : 0,155                                          bottomTrailingRadius: position == .bottom ? r : 0, topTrailingRadius: position == .top ? r : 0, style: .continuous)156        content157            .frame(maxWidth: .infinity, alignment: .leading)158            .background(ORIX.Palette.surface, in: fill)159            .overlay(SegmentShape(position: position).stroke(selected ? ORIX.Palette.accent.opacity(0.55) : ORIX.Palette.hairline, lineWidth: selected ? 1.5 : 1))160    }161}162163extension View {164    func cardSegment(_ position: SegmentShape.Position, selected: Bool = false) -> some View { modifier(CardSegment(position: position, selected: selected)) }165}166167// MARK: - Group header168169struct GroupHeader: View {170    @Environment(AppModel.self) private var model171    let group: StagedGroup172    @State private var showPicker = false173174    var body: some View {175        let workspace = model.workspace176        let selected = workspace.selectedGroupID == group.id177        VStack(alignment: .leading, spacing: ORIX.Space.m) {178            HStack(spacing: ORIX.Space.m) {179                FormatBadge(format: group.format, size: .regular)180                VStack(alignment: .leading, spacing: 2) {181                    Text(group.title).font(.headline).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)182                    Text(subtitle).font(.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)183                }184                Spacer(minLength: ORIX.Space.s)185                if let choice = group.choice {186                    HStack(spacing: 6) {187                        Image(systemName: "arrow.right").font(.caption.weight(.bold)).foregroundStyle(ORIX.Palette.textTertiary).accessibilityHidden(true)188                        FormatBadge(format: choice.destination, size: .regular, selected: true)189                    }190                    .accessibilityElement(children: .ignore)191                    .accessibilityLabel(L("Converts to %@", choice.title))192                }193                if group.choice != nil {194                    IconButton(symbol: "slider.horizontal.3", label: L("Options"), tint: selected && model.isSidePanelVisible ? ORIX.Palette.accent : ORIX.Palette.textSecondary) {195                        if selected { model.setSidePanel(visible: !model.isSidePanelVisible) } else { workspace.selectedGroupID = group.id; model.setSidePanel(visible: true) }196                    }197                }198                IconButton(symbol: "xmark", label: L("Remove this group")) { workspace.remove(group) }199            }200            if group.isConvertible {201                targetChips202                if let choice = group.choice { choiceSummary(choice) }203                visibleWarnings204            } else {205                Banner(kind: .info, text: group.format == nil ? L("Not convertible: the format could not be recognised.") : L("Not convertible: no conversion exists for %@ in this build.", group.format?.displayName ?? ""),206                       detail: group.warnings.first.map { LE($0.message) })207            }208        }209        .padding(ORIX.Space.l)210        .cardSegment(.top, selected: selected)211        .contentShape(Rectangle())212        .onTapGesture { workspace.selectedGroupID = group.id }213        .accessibilityElement(children: .contain)214        .accessibilityLabel(group.title)215    }216217    private var subtitle: String {218        var parts = [Fmt.bytes(group.totalBytes)]219        if group.isFolderGroup { parts = [L("Folder operations")] }220        if group.mismatchCount > 0 { parts.append(group.mismatchCount == 1 ? L("1 wrong extension") : L("%lld wrong extensions", group.mismatchCount)) }221        return parts.joined(separator: " · ")222    }223224    private var targetChips: some View {225        let workspace = model.workspace226        let shown = chipTargets227        return FlowLayout(spacing: 6, lineSpacing: 6) {228            Text(L("Convert to")).font(.caption.weight(.medium)).foregroundStyle(ORIX.Palette.textTertiary).padding(.vertical, 6)229            ForEach(shown) { target in230                TargetChip(format: target.destination, title: target.operation == nil ? target.destination.displayName : LE(target.title),231                           selected: group.choice?.id == target.id) {232                    workspace.selectedGroupID = group.id233                    if group.choice?.id == target.id, group.isFolderGroup { workspace.clearChoice(in: group) } else { workspace.select(destination: target.destination, operation: target.operation, in: group) }234                }235            }236            Button { showPicker = true } label: {237                HStack(spacing: 4) {238                    Text(moreTitle).font(.callout)239                    Image(systemName: "chevron.down").font(.system(size: 9, weight: .bold))240                }241                .foregroundStyle(ORIX.Palette.accent)242                .padding(.horizontal, 10).padding(.vertical, 5)243                .contentShape(Rectangle())244            }245            .buttonStyle(.plain)246            .popover(isPresented: $showPicker, arrowEdge: .bottom) { FormatPicker(group: group, isPresented: $showPicker) }247            .accessibilityLabel(L("All formats and operations"))248        }249    }250251    /// Recommended targets, plus the current choice when it is not one of them.252    private var chipTargets: [ConversionTarget] {253        var shown = group.recommended.isEmpty ? Array((group.targets + group.operations).prefix(4)) : group.recommended254        if let choice = group.choice, !shown.contains(where: { $0.id == choice.id }),255           let current = (group.targets + group.operations).first(where: { $0.id == choice.id }) { shown.append(current) }256        return shown257    }258259    private var moreTitle: String {260        let hidden = group.targets.count + group.operations.count + group.chained.count - chipTargets.count261        return hidden > 0 ? L("%lld more", hidden) : L("All")262    }263264    private func choiceSummary(_ choice: TargetChoice) -> some View {265        FlowLayout(spacing: 6, lineSpacing: 6) {266            FidelityBadge(fidelity: choice.plan.fidelity)267            if choice.plan.status == .experimental { ExperimentalBadge() }268            if choice.plan.isChained {269                Pill(text: L("2 steps via %@", choice.plan.intermediates.map(\.displayName).joined(separator: ", ")), symbol: "arrow.triangle.branch", color: ORIX.Palette.info)270            }271            if group.canCombine {272                if choice.operation != nil {273                    Pill(text: L("%lld files into one", group.files.count), symbol: "square.stack.3d.down.right", color: ORIX.Palette.accent)274                } else {275                    Toggle(isOn: Binding(get: { group.combine }, set: { group.combine = $0 })) {276                        Text(L("Combine into one file")).font(.caption)277                    }278                    .toggleStyle(.checkbox).controlSize(.small)279                }280            }281            let partners = model.workspace.combinePartners(of: group)282            if !partners.isEmpty {283                Toggle(isOn: Binding(get: { model.workspace.isCrossCombined(group) }, set: { model.workspace.setCrossCombine($0, for: group) })) {284                    Text(L("One file with the %@ too", partners.compactMap { $0.format?.shortLabel }.joined(separator: ", "))).font(.caption)285                }286                .toggleStyle(.checkbox).controlSize(.small)287                .help(L("Every file of these groups goes into a single result, in the order of the groups. The settings of the first group are used."))288            }289            if group.needsMoreFiles && !model.workspace.isCrossCombined(group) { Pill(text: L("Add at least two files"), symbol: "exclamationmark.triangle.fill", color: ORIX.Palette.caution) }290            if group.isCheckingWarnings { ORIXProgressRing(fraction: nil, size: 12, lineWidth: 1.5, label: L("Checking warnings")) }291        }292    }293294    /// Data-loss and caution warnings are always visible here; path limitations are counted and listed in the panel.295    @ViewBuilder private var visibleWarnings: some View {296        let important = group.warnings.filter { $0.severity != .info }297        let notes = group.warnings.filter { $0.severity == .info }298        if !important.isEmpty || !notes.isEmpty {299            VStack(alignment: .leading, spacing: 6) {300                ForEach(important.prefix(4)) { warning in301                    Banner(kind: warning.severity == .dataLoss ? .danger : .caution, text: LE(warning.message), detail: warning.detail(total: group.files.count))302                }303                if important.count > 4 { Text(L("%lld more warnings in the options panel", important.count - 4)).font(.caption).foregroundStyle(ORIX.Palette.textSecondary) }304                if !notes.isEmpty {305                    Button {306                        model.workspace.selectedGroupID = group.id307                        model.setSidePanel(visible: true)308                    } label: {309                        Label(notes.count == 1 ? L("1 limitation of this conversion") : L("%lld limitations of this conversion", notes.count), systemImage: "info.circle")310                            .font(.caption).foregroundStyle(ORIX.Palette.info)311                    }312                    .buttonStyle(.plain)313                    .accessibilityHint(L("Shows the limitations in the options panel"))314                }315            }316        }317    }318}319320extension WarningSummary {321    func detail(total: Int) -> String? {322        if appliesToAll || total <= 1 { return nil }323        if fileCount <= 1 { return L("1 of %lld files", total) }324        return L("%lld of %lld files", fileCount, total)325    }326}327328struct TargetChip: View {329    let format: FormatID330    let title: String331    let selected: Bool332    let action: () -> Void333    var body: some View {334        Button(action: action) {335            HStack(spacing: 6) {336                Image(systemName: format == .folder ? "folder" : format.category.symbol).font(.system(size: 10, weight: .semibold))337                    .foregroundStyle(format.category.color)338                Text(title).font(.callout.weight(selected ? .semibold : .regular)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)339                if selected { Image(systemName: "checkmark").font(.system(size: 9, weight: .bold)).foregroundStyle(ORIX.Palette.accent) }340            }341            .padding(.horizontal, 10).padding(.vertical, 5)342            .background(selected ? ORIX.Palette.accentSoft : ORIX.Palette.canvas, in: Capsule())343            .overlay(Capsule().strokeBorder(selected ? AnyShapeStyle(ORIX.Palette.transformation) : AnyShapeStyle(ORIX.Palette.hairlineStrong), lineWidth: selected ? 1.5 : 1))344            .contentShape(Capsule())345        }346        .buttonStyle(.plain)347        .accessibilityLabel(L("Convert to %@", title))348        .accessibilityAddTraits(selected ? [.isSelected] : [])349    }350}351352// MARK: - File rows353354struct FileRow: View {355    @Environment(AppModel.self) private var model356    let file: StagedFile357    let group: StagedGroup358    @State private var hovering = false359    private var isSelected: Bool { model.workspace.selectedFileID == file.id }360361    var body: some View {362        HStack(spacing: ORIX.Space.m) {363            Image(systemName: file.folderFileCount != nil ? "folder" : "doc").font(.callout).foregroundStyle(ORIX.Palette.textTertiary).frame(width: 18)364                .accessibilityHidden(true)365            VStack(alignment: .leading, spacing: 2) {366                Text(file.url.lastPathComponent).font(.callout).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1).truncationMode(.middle)367                if file.mismatch, let detection = file.detection {368                    Label(L("Named .%@, but the content is %@", detection.fileExtension, detection.format?.displayName ?? "?"), systemImage: "exclamationmark.triangle.fill")369                        .font(.caption).foregroundStyle(ORIX.Palette.caution).lineLimit(1)370                        .help(detection.evidence)371                } else if group.format == nil, let detection = file.detection {372                    Text(detection.evidence).font(.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)373                }374            }375            Spacer(minLength: ORIX.Space.s)376            if let summary = file.summary { Text(summary).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1).fixedSize() }377            Text(Fmt.bytes(file.size)).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1).fixedSize().frame(minWidth: 62, alignment: .trailing)378            IconButton(symbol: "minus.circle", label: L("Remove %@", file.url.lastPathComponent), tint: ORIX.Palette.textTertiary) { model.workspace.remove(file, from: group) }379                .opacity(hovering ? 1 : 0.35)380        }381        .padding(.horizontal, ORIX.Space.l).padding(.vertical, 5)382        .background(isSelected ? AnyShapeStyle(ORIX.Palette.accentSoft) : AnyShapeStyle(hovering ? ORIX.Palette.hairline.opacity(0.35) : .clear))383        .cardSegment(.middle, selected: model.workspace.selectedGroupID == group.id)384        .overlay(alignment: .top) { ORIX.Palette.hairline.frame(height: 1).padding(.horizontal, ORIX.Space.l) }385        .onHover { hovering = $0 }386        .contentShape(Rectangle())387        .onTapGesture(count: 2) { QuickLook.show([file.url]) }388        .onTapGesture { model.workspace.selectedFileID = file.id; model.workspace.selectedGroupID = group.id }389        .contextMenu {390            Button(L("Quick Look")) { QuickLook.show([file.url]) }391            Button(L("Reveal in Finder")) { FileActions.reveal([file.url]) }392            Button(L("Inspect in Metadata Studio")) { model.section = .metadata; Task { await model.metadata.load(file.url) } }393            Divider()394            Button(L("Remove from Batch")) { model.workspace.remove(file, from: group) }395        }396        .accessibilityElement(children: .combine)397        .accessibilityLabel(file.url.lastPathComponent)398        .accessibilityValue([file.detection?.format?.displayName, file.summary, Fmt.bytes(file.size), file.mismatch ? L("wrong extension") : nil].compactMap { $0 }.joined(separator: ", "))399        .accessibilityAddTraits(isSelected ? [.isSelected] : [])400        .accessibilityAction { model.workspace.selectedFileID = file.id }401    }402}403404struct GroupFooter: View {405    @Environment(AppModel.self) private var model406    let group: StagedGroup407    var body: some View {408        let hidden = group.files.count - StagedGroup.collapsedRows409        HStack {410            if hidden > 0 {411                Button {412                    group.expanded.toggle()413                } label: {414                    Label(group.expanded ? L("Show fewer") : L("Show all %lld files", group.files.count), systemImage: group.expanded ? "chevron.up" : "chevron.down")415                        .font(.caption.weight(.medium)).foregroundStyle(ORIX.Palette.accent)416                }417                .buttonStyle(.plain)418            }419            Spacer()420            if model.workspace.isCrossCombined(group) {421                Text(L("Combined with the other groups into one file")).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)422            } else if group.jobCount > 0 {423                Text(group.jobCount == 1 ? L("1 conversion") : L("%lld conversions", group.jobCount)).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textTertiary)424            } else if group.isConvertible {425                Text(L("No destination chosen: skipped")).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)426            }427        }428        .padding(.horizontal, ORIX.Space.l).padding(.vertical, 8)429        .cardSegment(.bottom, selected: model.workspace.selectedGroupID == group.id)430        .overlay(alignment: .top) { ORIX.Palette.hairline.frame(height: 1).padding(.horizontal, ORIX.Space.l) }431    }432}433
Files main
Menu

Theme