SPB Git

Repository Public License

DownloadsPanel.swift 7.4 KB 161 lines swift

1import DownloadEngine2import LunarDesign3import NavigatorCore4import SwiftUI56#if canImport(AppKit)7import AppKit8#endif910struct DownloadsPanel: View {11    @Environment(\.lunarTheme) private var theme12    @Environment(BrowserStore.self) private var store13    let window: WindowModel14    @State private var riskyItem: DownloadItem?1516    var body: some View {17        let items = store.downloads?.items ?? []18        VStack(spacing: LunarSpacing.xs) {19            if items.isEmpty {20                LunarEmptyState(icon: .symbol("arrow.down.circle"), title: L("No downloads"),21                                message: L("Files you download appear here."))22                    .frame(maxHeight: .infinity)23            } else {24                ScrollView {25                    LazyVStack(spacing: LunarSpacing.xs) {26                        ForEach(items) { item in row(item) }27                    }28                    .padding(.horizontal, LunarSpacing.sm)29                    .padding(.bottom, LunarSpacing.sm)30                }31                .scrollIndicators(.never)32                LunarHairline()33                Button(L("Clear Finished Downloads")) { store.downloads?.clearInactive() }34                    .buttonStyle(.lunar(.secondary, size: .compact))35                    .disabled(!items.contains { $0.download.state.isTerminal })36                    .padding(.bottom, LunarSpacing.sm)37                    .accessibilityIdentifier("downloads.clear")38            }39        }40        .confirmationDialog(L("Open this file?"), isPresented: Binding(get: { riskyItem != nil }, set: { if !$0 { riskyItem = nil } }),41                            titleVisibility: .visible) {42            Button(L("Open Anyway"), role: .destructive) { if let item = riskyItem { open(item, confirmed: true) } }43            Button(L("Cancel"), role: .cancel) {}44        } message: {45            Text(L("“%@” is a type of file that can run code or change settings on your device. Open it only if you trust where it came from.", riskyItem?.download.filename ?? ""))46        }47    }4849    private func row(_ item: DownloadItem) -> some View {50        let download = item.download51        return LunarCard(padding: LunarSpacing.sm, shape: .sm, elevation: .flat) {52            VStack(alignment: .leading, spacing: LunarSpacing.xs) {53                HStack(spacing: LunarSpacing.sm) {54                    LunarIconView(.symbol(symbol(download.state)), size: 22).foregroundStyle(tone(download.state))55                    VStack(alignment: .leading, spacing: 1) {56                        Text(download.filename).lunarFont(.bodyEmphasized).foregroundStyle(theme.textPrimary).lineLimit(1)57                            .truncationMode(.middle)58                        Text(Self.status(item)).lunarFont(.caption).lunarTabularDigits().foregroundStyle(theme.textSecondary)59                            .lineLimit(2)60                    }61                    Spacer(minLength: 0)62                }63                .accessibilityElement(children: .combine)64                .accessibilityIdentifier("downloads.row")65                if download.state.isActive {66                    LunarProgressBar(value: download.fractionCompleted, label: L("Download progress"))67                }68                HStack(spacing: LunarSpacing.unit) {69                    switch download.state {70                    case .pending, .running:71                        action("pause", L("Pause")) { store.downloads?.pause(item.id) }72                        action("xmark", L("Cancel")) { store.downloads?.cancel(item.id) }73                    case .paused, .failed, .cancelled:74                        if item.canResume { action("play", L("Resume")) { store.downloads?.resume(item.id) } }75                        action("arrow.clockwise", L("Download again")) { store.downloads?.downloadAgain(item) }76                        action("trash", L("Remove from list")) { store.downloads?.remove(item.id) }77                    case .finished:78                        action("arrow.up.forward.square", L("Open")) { open(item, confirmed: false) }79                        #if os(macOS)80                        action("folder", L("Show in Finder")) { reveal(item) }81                        #endif82                        action("trash", L("Remove from list")) { store.downloads?.remove(item.id) }83                    }84                    Spacer(minLength: 0)85                }86            }87        }88    }8990    private func action(_ symbol: String, _ label: String, _ run: @escaping () -> Void) -> some View {91        LunarIconButton(systemName: symbol, label: label, diameter: 28, action: run)92    }9394    private func symbol(_ state: Download.State) -> String {95        switch state {96        case .pending, .running: "arrow.down.circle"97        case .paused: "pause.circle"98        case .finished: "checkmark.circle.fill"99        case .failed: "exclamationmark.triangle"100        case .cancelled: "xmark.circle"101        }102    }103104    private func tone(_ state: Download.State) -> LunarRGBA {105        switch state {106        case .pending, .running: theme.accent107        case .finished: theme.success108        case .failed: theme.warning109        case .paused, .cancelled: theme.textSecondary110        }111    }112113    static func status(_ item: DownloadItem) -> String {114        let download = item.download115        let received = download.bytesReceived.formatted(.byteCount(style: .file))116        switch download.state {117        case .pending: return L("Starting…")118        case .running:119            var parts = [download.totalBytes.map { L("%@ of %@", received, $0.formatted(.byteCount(style: .file))) } ?? received]120            if let speed = item.bytesPerSecond, speed > 0 { parts.append(L("%@/s", Int64(speed).formatted(.byteCount(style: .file)))) }121            if let seconds = item.estimatedSecondsRemaining, seconds.isFinite, seconds > 0 {122                parts.append(L("%@ left", Duration.seconds(seconds.rounded()).formatted(.units(allowed: [.hours, .minutes, .seconds], width: .abbreviated))))123            }124            return parts.joined(separator: " · ")125        case .paused: return L("Paused · %@", received)126        case .finished: return L("Finished · %@", (download.totalBytes ?? download.bytesReceived).formatted(.byteCount(style: .file)))127        case .failed: return item.wasInterrupted ? L("Interrupted when the app closed") : L("Failed")128        case .cancelled: return L("Cancelled")129        }130    }131132    private func open(_ item: DownloadItem, confirmed: Bool) {133        guard let manager = store.downloads?.manager else { return }134        Task {135            switch await manager.openDecision(item.id, confirmed: confirmed) {136            case .open(let url):137                #if os(macOS)138                NSWorkspace.shared.open(url)139                #else140                window.shareRequest = ShareRequest(url: url, title: item.download.filename)141                #endif142            case .needsConfirmation: riskyItem = item143            case .unavailable: window.showToast(L("The file is no longer there"), status: .warning)144            }145        }146    }147148    #if os(macOS)149    private func reveal(_ item: DownloadItem) {150        guard let manager = store.downloads?.manager else { return }151        Task {152            if case .success(let url) = await manager.revealURL(item.id) {153                NSWorkspace.shared.activateFileViewerSelecting([url])154            } else {155                window.showToast(L("The file is no longer there"), status: .warning)156            }157        }158    }159    #endif160}161
Files main
Menu

Theme