aboutsummaryrefslogtreecommitdiff
path: root/Hutch/Views/Repositories/ArtifactsView.swift
blob: 8843c6fa4168f10d57a35e58c37c77eeb658fce3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import SwiftUI
import UniformTypeIdentifiers
import os

#if DEBUG
/// Temporary: diagnosing why the upload menu swallows taps.
private let artifactsLogger = Logger(subsystem: "net.cleberg.Hutch", category: "Artifacts")
#endif

struct ArtifactsView: View {
    let viewModel: RepositoryDetailViewModel
    /// Passed in rather than recomputed: RepositoryDetailView already owns this
    /// check and gates its other management surfaces on it.
    var canManage: Bool = false
    @Environment(\.openURL) private var openURL

    @State private var uploadTargetRef: String?
    @State private var isImporting = false
    @State private var pendingDeletion: ArtifactInfo?

    private var isOwnedByCurrentUser: Bool { canManage }

    /// A menu rather than a confirmation dialog: this view already presents one
    /// for delete, and two .confirmationDialog modifiers on the same view leave
    /// one of them silently dead. A menu also puts the tags one tap away.
    @ViewBuilder
    private var uploadMenu: some View {
        Menu {
            if viewModel.tags.isEmpty {
                Text("This repository has no tags")
            } else {
                ForEach(viewModel.tags.prefix(12), id: \.name) { tag in
                    Button(RepositorySummary.displayBranchName(for: tag.name)) {
                        uploadTargetRef = tag.name
                        isImporting = true
                    }
                }
            }
        } label: {
            SwiftUI.Label("Upload Artifact…", systemImage: "square.and.arrow.up")
        }
        // Deliberately not disabled when there are no tags. The explanation for
        // that state lives inside the menu, and disabling the control makes the
        // explanation unreachable — the tap just dies with no reason given.
        .disabled(viewModel.isMutatingArtifact)
    }

    var body: some View {
        @Bindable var vm = viewModel

        return List {
            // In the list rather than the toolbar: this view is a segment inside
            // RepositoryDetailView's tab switch, not its own navigation
            // destination, and a toolbar declared from there does not reliably
            // reach the navigation bar. It also has to be reachable when there are
            // no artifacts at all, which is the state a new tag is in.
            if isOwnedByCurrentUser {
                uploadMenu
                    .themedRow()
            }

            ForEach(viewModel.referenceArtifacts) { refArtifacts in
                Section {
                    ForEach(refArtifacts.artifacts) { artifact in
                        ArtifactRow(artifact: artifact) {
                            openURL(artifact.url)
                        }
                        // See MailingListListView: a full-swipe destructive
                        // action animates the row out before the confirmation.
                        .swipeActions(edge: .trailing, allowsFullSwipe: false) {
                            if isOwnedByCurrentUser {
                                Button {
                                    pendingDeletion = artifact
                                } label: {
                                    SwiftUI.Label("Delete", systemImage: "trash")
                                }
                                .tint(.red)
                            }
                        }
                    }
                    .themedRow()
                } header: {
                    HStack {
                        Text(refArtifacts.name)
                        if isOwnedByCurrentUser {
                            Spacer()
                            // Upload targets a specific tag, so the control belongs
                            // on the tag rather than in the toolbar.
                            Button {
                                uploadTargetRef = refArtifacts.name
                                isImporting = true
                            } label: {
                                SwiftUI.Label("Upload", systemImage: "plus.circle")
                                    .font(.caption)
                            }
                            .disabled(viewModel.isMutatingArtifact)
                        }
                    }
                }
            }
        }
        // isImporting drives presentation; uploadTargetRef carries the tag. They
        // have to be separate: a binding derived from uploadTargetRef clears it on
        // dismissal, and dismissal happens before the completion runs — so the
        // completion read nil and returned without uploading anything.
        .fileImporter(
            isPresented: $isImporting,
            allowedContentTypes: [.data]
        ) { result in
            let revspec = uploadTargetRef
            uploadTargetRef = nil
            guard let revspec, case .success(let fileURL) = result else { return }
            Task { await viewModel.uploadArtifact(revspec: revspec, fileURL: fileURL) }
        }
        .confirmationDialog(
            pendingDeletion.map { "Delete \($0.filename)?" } ?? "",
            isPresented: .init(
                get: { pendingDeletion != nil },
                set: { if !$0 { pendingDeletion = nil } }
            ),
            titleVisibility: .visible,
            presenting: pendingDeletion
        ) { artifact in
            Button("Delete Artifact", role: .destructive) {
                Task { await viewModel.deleteArtifact(id: artifact.id) }
            }
            Button("Cancel", role: .cancel) { pendingDeletion = nil }
        } message: { _ in
            Text("This permanently removes the artifact from the tag. This cannot be undone.")
        }
        .themedList()
        .listStyle(.insetGrouped)
        .srhtErrorBanner(error: $vm.error)
        .task {
            // Tags drive the picker above and are not otherwise needed by this tab.
            if isOwnedByCurrentUser, viewModel.tags.isEmpty {
                await viewModel.loadReferences()
            }
            #if DEBUG
            // Temporary: diagnosing why the upload menu swallows taps.
            artifactsLogger.debug(
                """
                canManage=\(canManage, privacy: .public) \
                tags=\(viewModel.tags.count, privacy: .public) \
                isMutating=\(viewModel.isMutatingArtifact, privacy: .public) \
                menuDisabled=\(viewModel.isMutatingArtifact || viewModel.tags.isEmpty, privacy: .public) \
                error=\(viewModel.error ?? "nil", privacy: .public)
                """
            )
            #endif
        }
        .overlay {
            if viewModel.isLoadingArtifacts, viewModel.referenceArtifacts.isEmpty {
                SRHTLoadingStateView(message: "Loading artifacts…")
            } else if let error = viewModel.error, viewModel.referenceArtifacts.isEmpty {
                SRHTErrorStateView(
                    title: "Couldn't Load Artifacts",
                    message: error,
                    retryAction: { await viewModel.loadArtifacts() }
                )
            } else if viewModel.referenceArtifacts.isEmpty {
                // The overlay covers the whole list, so the upload row above is
                // hidden underneath it — and a repository with no artifacts is
                // exactly the one that needs uploading. Offer it here too.
                ContentUnavailableView {
                    SwiftUI.Label("No Artifacts", systemImage: "archivebox")
                } description: {
                    Text("This repository has no release artifacts.")
                } actions: {
                    if isOwnedByCurrentUser {
                        uploadMenu
                    }
                }
            }
        }
        .task {
            if viewModel.referenceArtifacts.isEmpty {
                await viewModel.loadArtifacts()
            }
        }
        .refreshable {
            await viewModel.loadArtifacts()
        }
    }
}

private struct ArtifactRow: View {
    let artifact: ArtifactInfo
    let onDownload: () -> Void

    var body: some View {
        HStack {
            VStack(alignment: .leading, spacing: 4) {
                Text(artifact.filename)
                    .font(.subheadline)

                Text(artifact.size.formattedByteCount)
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }

            Spacer()

            Button {
                onDownload()
            } label: {
                Image(systemName: "arrow.down.circle")
                    .imageScale(.large)
            }
        }
    }
}