Commit 11590735a0

11590735a0a6f68ad75045e84042717568fb26e6

parent: 712a068156

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-23 01:59 UTC

Add Qlty config; fix test build; share repeated views and models

- HutchTests did not compile: OrgNativeRenderingTests used SwiftUI
  members without importing SwiftUI.
- SRHTLoadStateView replaces the loading/error opening of 13 screens'
  state chains; SettingsSheet, BottomToolbarButton, BuildDraftForm,
  AddKeyControls and TrackerSummaryRow replace copied views.
- Inbox thread merging, unread toggling, repository payloads and the
  profile update are each defined once; ticket label and assignment
  mutations share one rollback path.
- Build, ticket, thread, commit, profile and work views split into
  named sections and rows; RawJSON decoding flattened.
- Qlty: switch statements excluded from Swift duplication,
  return_statements and file_complexity disabled.

Layout: unified · split

.qlty/.gitignore added +7
@@ -0,0 +1,7 @@
1*
2!configs
3!configs/**
4!hooks
5!hooks/**
6!qlty.toml
7!.gitignore
.qlty/qlty.toml added +48
@@ -0,0 +1,48 @@
1config_version = "0"
2
3exclude_patterns = [
4 "**/vendor/**",
5 "**/node_modules/**",
6 "**/testdata/**",
7 "**/dist/**",
8 "**/.build/**",
9 "**/build/**",
10 "**/*.min.*",
11 "**/generated/**",
12 ".claude/**",
13 "**/Pods/**",
14]
15
16test_patterns = [
17 "**/test/**",
18 "**/tests/**",
19 "**/Tests/**",
20 "**/*_test.*",
21 "**/test_*.*",
22 "**/*.test.*",
23 "**/*Tests.swift",
24 "e2e/**",
25]
26
27[[source]]
28name = "default"
29default = true
30
31[[plugin]]
32name = "osv-scanner"
33
34[[plugin]]
35name = "trufflehog"
36
37# Early returns are guard clauses, which keep the happy path unindented.
38[smells.return_statements]
39enabled = false
40
41# Total file complexity is the sum of its functions, which function_complexity
42# already checks.
43[smells.file_complexity]
44enabled = false
45
46# Exhaustive switch-over-enum lookup tables share shape but not content.
47[language.swift.smells.duplication]
48filter_patterns = ["(import_declaration _)", "(switch_statement _)"]
Hutch/Extensions/ErrorViews.swift +22
@@ -158,3 +158,25 @@ extension View {
158158 modifier(ConnectivityOverlay(hasContent: hasContent, retryAction: retryAction))
159159 }
160160}
161
162/// A screen's loading or error state while it has nothing to show, and `content` otherwise.
163struct SRHTLoadStateView<Content: View>: View {
164 let isLoading: Bool
165 let error: String?
166 /// Whether nothing has loaded that could be shown instead.
167 let isEmpty: Bool
168 let loadingMessage: String
169 let errorTitle: String
170 let retryAction: (() async -> Void)?
171 @ViewBuilder var content: () -> Content
172
173 var body: some View {
174 if isLoading, isEmpty {
175 SRHTLoadingStateView(message: loadingMessage)
176 } else if let error, isEmpty {
177 SRHTErrorStateView(title: errorTitle, message: error, retryAction: retryAction)
178 } else {
179 content()
180 }
181 }
182}
Hutch/Models/Inbox.swift +65
@@ -235,3 +235,68 @@ nonisolated enum InboxReadStateStore {
235235 return true
236236 }
237237}
238
239extension InboxThreadSummary {
240 /// This summary marked read or unread.
241 nonisolated func withUnread(_ isUnread: Bool) -> InboxThreadSummary {
242 InboxThreadSummary(
243 rootEmailID: rootEmailID,
244 rootMessageID: rootMessageID,
245 threadRootEmailIDs: threadRootEmailIDs,
246 threadRootMessageIDs: threadRootMessageIDs,
247 listID: listID,
248 listRID: listRID,
249 listName: listName,
250 listOwner: listOwner,
251 subject: subject,
252 latestSender: latestSender,
253 lastActivityAt: lastActivityAt,
254 messageCount: messageCount,
255 repo: repo,
256 containsPatch: containsPatch,
257 isUnread: isUnread
258 )
259 }
260
261 /// One summary per thread grouping key, unsorted: the latest summary's fields, with the
262 /// root IDs, counts, patch and unread flags of every summary for that thread.
263 nonisolated static func mergedByThread(_ threads: [InboxThreadSummary]) -> [InboxThreadSummary] {
264 var grouped: [String: InboxThreadSummary] = [:]
265
266 for thread in threads {
267 guard let existing = grouped[thread.threadGroupingKey] else {
268 grouped[thread.threadGroupingKey] = thread
269 continue
270 }
271
272 let latest = thread.lastActivityAt >= existing.lastActivityAt ? thread : existing
273 let mergedRootEmailIDs = Array(Set(existing.threadRootEmailIDs + thread.threadRootEmailIDs)).sorted()
274 let mergedRootMessageIDs = Array(Set(existing.threadRootMessageIDs + thread.threadRootMessageIDs)).sorted()
275 let mergedMessageCount = max(
276 existing.messageCount ?? existing.threadRootMessageIDs.count,
277 thread.messageCount ?? thread.threadRootMessageIDs.count,
278 mergedRootMessageIDs.count
279 )
280
281 grouped[thread.threadGroupingKey] = InboxThreadSummary(
282 rootEmailID: latest.rootEmailID,
283 rootMessageID: latest.rootMessageID,
284 threadRootEmailIDs: mergedRootEmailIDs,
285 threadRootMessageIDs: mergedRootMessageIDs,
286 listID: latest.listID,
287 listRID: latest.listRID,
288 listName: latest.listName,
289 listOwner: latest.listOwner,
290 subject: latest.subject,
291 latestSender: latest.latestSender,
292 lastActivityAt: max(existing.lastActivityAt, thread.lastActivityAt),
293 messageCount: mergedMessageCount,
294 repo: latest.repo ?? existing.repo,
295 containsPatch: latest.containsPatch || existing.containsPatch,
296 isUnread: latest.isUnread || existing.isUnread
297 )
298 }
299
300 return Array(grouped.values)
301 }
302}
Hutch/Models/RepositorySummary.swift +33
@@ -94,3 +94,36 @@ nonisolated extension RepositorySummary {
9494 referenceName.replacingOccurrences(of: "refs/heads/", with: "")
9595 }
9696}
97
98/// A git repository as the GraphQL API returns it.
99nonisolated struct RepositoryPayload: Decodable, Sendable {
100 let id: Int
101 let rid: String
102 let name: String
103 let description: String?
104 let visibility: Visibility
105 let updated: Date
106 let owner: Entity
107 let head: Reference?
108
109 enum CodingKeys: String, CodingKey {
110 case id, rid, name, description, visibility, updated, owner
111 case head = "HEAD"
112 }
113
114 func repositorySummary(service: SRHTService) -> RepositorySummary {
115 RepositorySummary(
116 fields: .init(
117 id: id,
118 rid: rid,
119 service: service,
120 name: name,
121 description: description,
122 visibility: visibility,
123 updated: updated,
124 owner: owner,
125 head: head
126 )
127 )
128 }
129}
Hutch/Networking/Pagination.swift +14 −15
@@ -155,22 +155,21 @@ struct RawJSON: Decodable, Sendable {
155155
156156 init(from decoder: any Decoder) throws {
157157 let container = try decoder.singleValueContainer()
158 if let dict = try? container.decode([String: RawJSON].self) {
159 value = dict.mapValues(\.value)
160 } else if let array = try? container.decode([RawJSON].self) {
161 value = array.map(\.value)
162 } else if let string = try? container.decode(String.self) {
163 value = string
164 } else if let int = try? container.decode(Int.self) {
165 value = int
166 } else if let double = try? container.decode(Double.self) {
167 value = double
168 } else if let bool = try? container.decode(Bool.self) {
169 value = bool
170 } else if container.decodeNil() {
171 value = NSNull()
172 } else {
158 guard let value = Self.value(in: container) else {
173159 throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unsupported JSON value")
174160 }
161 self.value = value
162 }
163
164 /// The first of object, array, string, integer, double, bool or null the value decodes as.
165 private static func value(in container: any SingleValueDecodingContainer) -> Any? {
166 if let dict = try? container.decode([String: RawJSON].self) { return dict.mapValues(\.value) }
167 if let array = try? container.decode([RawJSON].self) { return array.map(\.value) }
168 if let string = try? container.decode(String.self) { return string }
169 if let int = try? container.decode(Int.self) { return int }
170 if let double = try? container.decode(Double.self) { return double }
171 if let bool = try? container.decode(Bool.self) { return bool }
172 if container.decodeNil() { return NSNull() }
173 return nil
175174 }
176175}
Hutch/Networking/ProjectService.swift +4 −28
@@ -100,13 +100,14 @@ private struct ProjectDetailPayload: Decodable, Sendable {
100100}
101101
102102private struct ProjectMailingListPage: Decodable, Sendable {
103 let results: [ProjectMailingListPayload]
103 let results: [ProjectResourcePayload]
104104 let cursor: String?
105105
106106 static let empty = ProjectMailingListPage(results: [], cursor: nil)
107107}
108108
109private struct ProjectMailingListPayload: Decodable, Sendable {
109/// A mailing list or tracker linked to a project; both decode the same fields.
110private struct ProjectResourcePayload: Decodable, Sendable {
110111 let rid: String
111112 let name: String
112113 let description: String?
@@ -167,37 +168,12 @@ private struct ProjectSourcePayload: Decodable, Sendable {
167168}
168169
169170private struct ProjectTrackerPage: Decodable, Sendable {
170 let results: [ProjectTrackerPayload]
171 let results: [ProjectResourcePayload]
171172 let cursor: String?
172173
173174 static let empty = ProjectTrackerPage(results: [], cursor: nil)
174175}
175176
176private struct ProjectTrackerPayload: Decodable, Sendable {
177 let rid: String
178 let name: String
179 let description: String?
180 let visibility: Visibility
181 let owner: Entity
182
183 private enum CodingKeys: String, CodingKey {
184 case rid
185 case name
186 case description
187 case visibility
188 case owner
189 }
190
191 init(from decoder: any Decoder) throws {
192 let container = try decoder.container(keyedBy: CodingKeys.self)
193 rid = try container.decode(String.self, forKey: .rid)
194 name = try container.decodeIfPresent(String.self, forKey: .name) ?? ""
195 description = try container.decodeIfPresent(String.self, forKey: .description)
196 visibility = try container.decodeIfPresent(Visibility.self, forKey: .visibility) ?? .publicVisibility
197 owner = try container.decodeIfPresent(Entity.self, forKey: .owner) ?? Entity(canonicalName: "~unknown")
198 }
199}
200
201177/// A public project surfaced by discovery, carrying its owner for display.
202178struct DiscoveredProject: Identifiable, Hashable, Sendable {
203179 let project: Project
Hutch/Views/Builds/BuildDetailView.swift +267 −275
@@ -156,222 +156,54 @@ struct BuildDetailView: View {
156156
157157 @ViewBuilder
158158 private func detailContent(_ viewModel: BuildDetailViewModel) -> some View {
159 if viewModel.isLoading, viewModel.job == nil {
160 SRHTLoadingStateView(message: "Loading build…")
161 } else if let error = viewModel.error, viewModel.job == nil {
162 SRHTErrorStateView(
163 title: "Couldn't Load Build",
164 message: error,
165 retryAction: { await reloadDetail(viewModel) }
166 )
167 } else if let job = viewModel.job {
168 List {
169 if let cacheMetadata = viewModel.cacheMetadata {
170 Section {
171 StaleCacheStatusRow(metadata: cacheMetadata, isRefreshing: viewModel.isRefreshingCachedData)
172 }
173 }
174
175 Section("Details") {
176 HStack {
177 Text("Status")
178 Spacer()
179 HStack(spacing: 6) {
180 JobStatusIcon(status: job.status)
181 Text(job.status.rawValue)
182 .font(.subheadline.weight(.medium))
183 }
184 }
185 .themedRow()
159 SRHTLoadStateView(
160 isLoading: viewModel.isLoading,
161 error: viewModel.error,
162 isEmpty: viewModel.job == nil,
163 loadingMessage: "Loading build…",
164 errorTitle: "Couldn't Load Build",
165 retryAction: { await reloadDetail(viewModel) }
166 ) {
167 if let job = viewModel.job {
168 List {
169 cacheSection(job, viewModel)
186170
187 if let note = job.note, !note.isEmpty {
188 LabeledContent("Note", value: note)
189 .themedRow()
190 }
171 detailsSection(job, viewModel)
191172
192 if let image = job.image {
193 LabeledContent("Image", value: image)
194 .themedRow()
195 }
173 debugSection(job, viewModel)
196174
197 if !job.tags.isEmpty {
198 LabeledContent("Tags", value: job.tags.joined(separator: ", "))
199 .themedRow()
200 }
175 sourceSection(job, viewModel)
201176
202 if let visibility = job.visibility {
203 LabeledContent("Visibility", value: visibility.rawValue.capitalized)
204 .themedRow()
205 }
177 artifactsSection(job, viewModel)
206178
207 LabeledContent("Owner", value: job.owner.canonicalName)
208 .themedRow()
209 LabeledContent("Created", value: job.created.relativeDescription)
210 .themedRow()
211 LabeledContent("Updated", value: job.updated.relativeDescription)
212 .themedRow()
213 }
179 // Per-task logs
180 taskSections(job, viewModel)
214181
215 if appState.isDebugModeEnabled {
216 Section("Debug") {
217 DebugTextBlock(
218 title: "Diagnostics",
219 content: """
220 jobId: \(job.id)
221 status: \(job.status.rawValue)
222 tasks: \(job.tasks.count)
223 artifacts: \(job.artifacts.count)
224 owner: \(job.owner.canonicalName)
225 url: \(SRHTWebURL.build(jobId: job.id, ownerCanonicalName: job.owner.canonicalName)?.absoluteString ?? "unavailable")
226 """
227 )
228 .themedRow()
182 // Cancel button
183 cancelSection(job, viewModel)
229184
230 if let rawJobResponse = viewModel.rawJobResponse {
231 DebugTextBlock(title: "Raw Response", content: rawJobResponse)
232 .themedRow()
233 }
234 }
185 rebuildSection(job, viewModel)
235186 }
236
237 if let repositoryReference = HomeViewModel.primaryRepositoryReference(in: job.manifest) {
238 Section("Source") {
239 Button {
240 openRepository(ownerCanonicalName: repositoryReference.ownerCanonicalName, repositoryName: repositoryReference.name)
241 } label: {
242 HStack {
243 Label("\(repositoryReference.ownerCanonicalName)/\(repositoryReference.name)", systemImage: "book.closed")
244 Spacer()
245 if isOpeningRepository {
246 ProgressView()
247 .controlSize(.small)
248 } else {
249 Image(systemName: "arrow.up.right")
250 .font(.caption)
251 .foregroundStyle(.tertiary)
252 }
253 }
254 }
255 .disabled(isOpeningRepository)
256 .themedRow()
257 }
187 .themedList()
188 .task(id: job.id) {
189 RecentActivityStore.recordBuild(
190 jobId: job.id,
191 title: recentActivityTitle(for: job),
192 defaults: appState.accountDefaults
193 )
258194 }
259
260 if !job.artifacts.isEmpty {
261 Section {
262 ForEach(job.artifacts) { artifact in
263 BuildArtifactRow(artifact: artifact) {
264 guard let url = artifact.url else { return }
265 openURL(url)
266 }
267 }
268 .themedRow()
269 } header: {
270 Text("Artifacts")
271 } footer: {
272 if job.artifacts.contains(where: { !$0.isDownloadable }) {
273 Text("Artifacts without a download URL are no longer available for download.")
274 }
275 }
195 .refreshable {
196 await reloadDetail(viewModel)
276197 }
277
278 // Per-task logs
279 if !job.tasks.isEmpty {
280 ForEach(job.tasks) { task in
281 Section {
282 Button {
283 selectedTaskName = task.name
284 } label: {
285 HStack {
286 Text(task.status.rawValue.capitalized)
287 .font(.subheadline)
288 .foregroundStyle(.secondary)
289 Spacer()
290 Image(systemName: "chevron.right")
291 .font(.caption)
292 .foregroundStyle(.tertiary)
293 }
294 }
295 .foregroundStyle(.primary)
296 .themedRow()
297 } header: {
298 HStack(spacing: 6) {
299 TaskStatusIcon(status: task.status)
300 Text(task.name)
301 }
302 }
303 }
304 }
305
306 // Cancel button
307 if job.status.isCancellable {
308 Section {
309 Button(role: .destructive) {
310 showCancelConfirmation = true
311 } label: {
312 HStack {
313 Text("Cancel Build")
314 if viewModel.isCancelling {
315 Spacer()
316 ProgressView()
317 }
318 }
319 }
320 .disabled(viewModel.isCancelling)
321 .themedRow()
322 }
323 }
324
325 if let manifest = job.manifest,
326 !manifest.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
327 Section {
328 Button {
329 Task {
330 rebuiltJobId = await viewModel.rebuildJob()
331 }
332 } label: {
333 HStack {
334 Text(job.status == .failed || job.status == .cancelled || job.status == .timeout ? "Retry Build" : "Rebuild")
335 if viewModel.isRebuilding {
336 Spacer()
337 ProgressView()
338 }
339 }
340 }
341 .disabled(viewModel.isRebuilding)
342 .themedRow()
343
344 Button {
345 showEditResubmitSheet = true
346 } label: {
347 Text("Edit & Resubmit")
348 }
349 .disabled(viewModel.isSubmittingEditedBuild)
350 .themedRow()
351 } footer: {
352 Text("Creates a new build using this job’s saved manifest, tags, note, and visibility.")
353 }
354 }
355 }
356 .themedList()
357 .task(id: job.id) {
358 RecentActivityStore.recordBuild(
359 jobId: job.id,
360 title: recentActivityTitle(for: job),
361 defaults: appState.accountDefaults
362 )
198 .srhtErrorBanner(error: Binding(
199 get: { viewModel.error },
200 set: { viewModel.error = $0 }
201 ))
202 .srhtErrorBanner(error: Binding(
203 get: { viewModel.actionError },
204 set: { _ in viewModel.dismissActionError() }
205 ))
363206 }
364 .refreshable {
365 await reloadDetail(viewModel)
366 }
367 .srhtErrorBanner(error: Binding(
368 get: { viewModel.error },
369 set: { viewModel.error = $0 }
370 ))
371 .srhtErrorBanner(error: Binding(
372 get: { viewModel.actionError },
373 set: { _ in viewModel.dismissActionError() }
374 ))
375207 }
376208 }
377209
@@ -407,6 +239,216 @@ struct BuildDetailView: View {
407239 }
408240 return "Job #\(job.id)"
409241 }
242
243
244 @ViewBuilder
245 private func cancelSection(_ job: JobDetail, _ viewModel: BuildDetailViewModel) -> some View {
246 if job.status.isCancellable {
247 Section {
248 Button(role: .destructive) {
249 showCancelConfirmation = true
250 } label: {
251 HStack {
252 Text("Cancel Build")
253 if viewModel.isCancelling {
254 Spacer()
255 ProgressView()
256 }
257 }
258 }
259 .disabled(viewModel.isCancelling)
260 .themedRow()
261 }
262 }
263 }
264
265 @ViewBuilder
266 private func taskSections(_ job: JobDetail, _ viewModel: BuildDetailViewModel) -> some View {
267 if !job.tasks.isEmpty {
268 ForEach(job.tasks) { task in
269 Section {
270 Button {
271 selectedTaskName = task.name
272 } label: {
273 HStack {
274 Text(task.status.rawValue.capitalized)
275 .font(.subheadline)
276 .foregroundStyle(.secondary)
277 Spacer()
278 Image(systemName: "chevron.right")
279 .font(.caption)
280 .foregroundStyle(.tertiary)
281 }
282 }
283 .foregroundStyle(.primary)
284 .themedRow()
285 } header: {
286 HStack(spacing: 6) {
287 TaskStatusIcon(status: task.status)
288 Text(task.name)
289 }
290 }
291 }
292 }
293 }
294
295 @ViewBuilder
296 private func artifactsSection(_ job: JobDetail, _ viewModel: BuildDetailViewModel) -> some View {
297 if !job.artifacts.isEmpty {
298 Section {
299 ForEach(job.artifacts) { artifact in
300 BuildArtifactRow(artifact: artifact) {
301 guard let url = artifact.url else { return }
302 openURL(url)
303 }
304 }
305 .themedRow()
306 } header: {
307 Text("Artifacts")
308 } footer: {
309 if job.artifacts.contains(where: { !$0.isDownloadable }) {
310 Text("Artifacts without a download URL are no longer available for download.")
311 }
312 }
313 }
314 }
315
316 @ViewBuilder
317 private func sourceSection(_ job: JobDetail, _ viewModel: BuildDetailViewModel) -> some View {
318 if let repositoryReference = HomeViewModel.primaryRepositoryReference(in: job.manifest) {
319 Section("Source") {
320 Button {
321 openRepository(ownerCanonicalName: repositoryReference.ownerCanonicalName, repositoryName: repositoryReference.name)
322 } label: {
323 HStack {
324 Label("\(repositoryReference.ownerCanonicalName)/\(repositoryReference.name)", systemImage: "book.closed")
325 Spacer()
326 if isOpeningRepository {
327 ProgressView()
328 .controlSize(.small)
329 } else {
330 Image(systemName: "arrow.up.right")
331 .font(.caption)
332 .foregroundStyle(.tertiary)
333 }
334 }
335 }
336 .disabled(isOpeningRepository)
337 .themedRow()
338 }
339 }
340 }
341
342 @ViewBuilder
343 private func debugSection(_ job: JobDetail, _ viewModel: BuildDetailViewModel) -> some View {
344 if appState.isDebugModeEnabled {
345 Section("Debug") {
346 DebugTextBlock(
347 title: "Diagnostics",
348 content: """
349 jobId: \(job.id)
350 status: \(job.status.rawValue)
351 tasks: \(job.tasks.count)
352 artifacts: \(job.artifacts.count)
353 owner: \(job.owner.canonicalName)
354 url: \(SRHTWebURL.build(jobId: job.id, ownerCanonicalName: job.owner.canonicalName)?.absoluteString ?? "unavailable")
355 """
356 )
357 .themedRow()
358
359 if let rawJobResponse = viewModel.rawJobResponse {
360 DebugTextBlock(title: "Raw Response", content: rawJobResponse)
361 .themedRow()
362 }
363 }
364 }
365 }
366
367 @ViewBuilder
368 private func detailsSection(_ job: JobDetail, _ viewModel: BuildDetailViewModel) -> some View {
369 Section("Details") {
370 HStack {
371 Text("Status")
372 Spacer()
373 HStack(spacing: 6) {
374 JobStatusIcon(status: job.status)
375 Text(job.status.rawValue)
376 .font(.subheadline.weight(.medium))
377 }
378 }
379 .themedRow()
380
381 if let note = job.note, !note.isEmpty {
382 LabeledContent("Note", value: note)
383 .themedRow()
384 }
385
386 if let image = job.image {
387 LabeledContent("Image", value: image)
388 .themedRow()
389 }
390
391 if !job.tags.isEmpty {
392 LabeledContent("Tags", value: job.tags.joined(separator: ", "))
393 .themedRow()
394 }
395
396 if let visibility = job.visibility {
397 LabeledContent("Visibility", value: visibility.rawValue.capitalized)
398 .themedRow()
399 }
400
401 LabeledContent("Owner", value: job.owner.canonicalName)
402 .themedRow()
403 LabeledContent("Created", value: job.created.relativeDescription)
404 .themedRow()
405 LabeledContent("Updated", value: job.updated.relativeDescription)
406 .themedRow()
407 }
408 }
409
410 @ViewBuilder
411 private func cacheSection(_ job: JobDetail, _ viewModel: BuildDetailViewModel) -> some View {
412 if let cacheMetadata = viewModel.cacheMetadata {
413 Section {
414 StaleCacheStatusRow(metadata: cacheMetadata, isRefreshing: viewModel.isRefreshingCachedData)
415 }
416 }
417 }
418
419 @ViewBuilder
420 private func rebuildSection(_ job: JobDetail, _ viewModel: BuildDetailViewModel) -> some View {
421 if let manifest = job.manifest,
422 !manifest.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
423 Section {
424 Button {
425 Task {
426 rebuiltJobId = await viewModel.rebuildJob()
427 }
428 } label: {
429 HStack {
430 Text(job.status == .failed || job.status == .cancelled || job.status == .timeout ? "Retry Build" : "Rebuild")
431 if viewModel.isRebuilding {
432 Spacer()
433 ProgressView()
434 }
435 }
436 }
437 .disabled(viewModel.isRebuilding)
438 .themedRow()
439
440 Button {
441 showEditResubmitSheet = true
442 } label: {
443 Text("Edit & Resubmit")
444 }
445 .disabled(viewModel.isSubmittingEditedBuild)
446 .themedRow()
447 } footer: {
448 Text("Creates a new build using this job’s saved manifest, tags, note, and visibility.")
449 }
450 }
451 }
410452}
411453
412454private struct BuildArtifactRow: View {
@@ -460,74 +502,28 @@ private struct EditResubmitBuildSheet: View {
460502 let onSubmitted: (Int) -> Void
461503
462504 @Environment(\.dismiss) private var dismiss
463 @State private var manifest: String
464 @State private var tagsText: String
465 @State private var note: String
466 @State private var secrets = false
467 @State private var execute = true
468 @State private var visibility: Visibility
505 @State private var draft: BuildDraft
469506
470507 init(viewModel: BuildDetailViewModel, job: JobDetail, onSubmitted: @escaping (Int) -> Void) {
471508 self.viewModel = viewModel
472509 self.job = job
473510 self.onSubmitted = onSubmitted
474 _manifest = State(initialValue: job.manifest ?? "")
475 _tagsText = State(initialValue: job.tags.joined(separator: ", "))
476 _note = State(initialValue: job.note ?? "")
477 _visibility = State(initialValue: job.visibility ?? .publicVisibility)
511 _draft = State(initialValue: BuildDraft(
512 manifest: job.manifest ?? "",
513 tagsText: job.tags.joined(separator: ", "),
514 note: job.note ?? "",
515 visibility: job.visibility ?? .publicVisibility
516 ))
478517 }
479518
480519 var body: some View {
481520 NavigationStack {
482 Form {
483 Section("Build Manifest") {
484 TextField("Build manifest", text: $manifest, axis: .vertical)
485 .font(.system(.body, design: .monospaced))
486 .lineLimit(12...24)
487 .textInputAutocapitalization(.never)
488 .autocorrectionDisabled()
489 .themedRow()
490 }
491
492 Section("Build Options") {
493 TextField("Note (optional)", text: $note)
494 .themedRow()
495 TextField("Tags (comma-separated, optional)", text: $tagsText)
496 .textInputAutocapitalization(.never)
497 .autocorrectionDisabled()
498 .themedRow()
499 Picker("Visibility", selection: $visibility) {
500 Text("Public").tag(Visibility.publicVisibility)
501 Text("Unlisted").tag(Visibility.unlisted)
502 Text("Private").tag(Visibility.privateVisibility)
503 }
504 .themedRow()
505 Toggle("Start build now", isOn: $execute)
506 .themedRow()
507 Toggle("Allow build secrets", isOn: $secrets)
508 .themedRow()
509 }
510
511 Section {
512 Text("This submits a new build. “Start build now” and “Allow build secrets” use local defaults because the current job does not include those original values.")
513 .font(.footnote)
514 .foregroundStyle(.secondary)
515 .themedRow()
516 }
517
518 if let actionError = viewModel.actionError {
519 Section {
520 Label {
521 Text(actionError)
522 } icon: {
523 Image(systemName: "exclamationmark.triangle.fill")
524 .foregroundStyle(.red)
525 }
526 .foregroundStyle(.red)
527 .themedRow()
528 }
529 }
530 }
521 BuildDraftForm(
522 draft: $draft,
523 manifestPlaceholder: "Build manifest",
524 footnote: "This submits a new build. “Start build now” and “Allow build secrets” use local defaults because the current job does not include those original values.",
525 error: viewModel.actionError
526 )
531527 .navigationTitle("Edit & Resubmit")
532528 .navigationBarTitleDisplayMode(.inline)
533529 .onDisappear {
@@ -543,17 +539,13 @@ private struct EditResubmitBuildSheet: View {
543539 ToolbarItem(placement: .confirmationAction) {
544540 Button {
545541 Task {
546 let tags = tagsText
547 .split(separator: ",")
548 .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
549 .filter { !$0.isEmpty }
550542 if let jobId = await viewModel.submitBuild(
551 manifest: manifest,
552 tags: tags,
553 note: note,
554 secrets: secrets,
555 execute: execute,
556 visibility: visibility
543 manifest: draft.manifest,
544 tags: draft.tags,
545 note: draft.note,
546 secrets: draft.secrets,
547 execute: draft.execute,
548 visibility: draft.visibility
557549 ) {
558550 onSubmitted(jobId)
559551 }
@@ -566,7 +558,7 @@ private struct EditResubmitBuildSheet: View {
566558 Text("Submit Build")
567559 }
568560 }
569 .disabled(manifest.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || viewModel.isSubmittingEditedBuild)
561 .disabled(!draft.hasManifest || viewModel.isSubmittingEditedBuild)
570562 }
571563 }
572564 .themedList()
Hutch/Views/Builds/BuildDraftForm.swift added +83
@@ -0,0 +1,83 @@
1import SwiftUI
2
3/// A build about to be submitted: its manifest and the options it runs with.
4struct BuildDraft {
5 var manifest = ""
6 var tagsText = ""
7 var note = ""
8 var secrets = false
9 var execute = true
10 var visibility: Visibility = .publicVisibility
11
12 /// The comma-separated tags, trimmed, without empties.
13 var tags: [String] {
14 tagsText
15 .split(separator: ",")
16 .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
17 .filter { !$0.isEmpty }
18 }
19
20 var hasManifest: Bool {
21 !manifest.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
22 }
23}
24
25/// The fields of a build submission, with a note under them and the last error, if any.
26struct BuildDraftForm: View {
27 @Binding var draft: BuildDraft
28 let manifestPlaceholder: String
29 let footnote: String
30 let error: String?
31
32 var body: some View {
33 Form {
34 Section("Build Manifest") {
35 TextField(manifestPlaceholder, text: $draft.manifest, axis: .vertical)
36 .font(.system(.body, design: .monospaced))
37 .lineLimit(12...24)
38 .textInputAutocapitalization(.never)
39 .autocorrectionDisabled()
40 .themedRow()
41 }
42
43 Section("Build Options") {
44 TextField("Note (optional)", text: $draft.note)
45 .themedRow()
46 TextField("Tags (comma-separated, optional)", text: $draft.tagsText)
47 .textInputAutocapitalization(.never)
48 .autocorrectionDisabled()
49 .themedRow()
50 Picker("Visibility", selection: $draft.visibility) {
51 Text("Public").tag(Visibility.publicVisibility)
52 Text("Unlisted").tag(Visibility.unlisted)
53 Text("Private").tag(Visibility.privateVisibility)
54 }
55 .themedRow()
56 Toggle("Start build now", isOn: $draft.execute)
57 .themedRow()
58 Toggle("Allow build secrets", isOn: $draft.secrets)
59 .themedRow()
60 }
61
62 Section {
63 Text(footnote)
64 .font(.footnote)
65 .foregroundStyle(.secondary)
66 .themedRow()
67 }
68
69 if let error {
70 Section {
71 Label {
72 Text(error)
73 } icon: {
74 Image(systemName: "exclamationmark.triangle.fill")
75 .foregroundStyle(.red)
76 }
77 .foregroundStyle(.red)
78 .themedRow()
79 }
80 }
81 }
82 }
83}
Hutch/Views/Builds/BuildListView.swift +82 −123
@@ -168,48 +168,7 @@ struct BuildListView: View {
168168 .listRowSeparator(.hidden)
169169
170170 ForEach(viewModel.filteredJobs) { job in
171 NavigationLink(value: job) {
172 BuildRowView(job: job)
173 .equatable()
174 }
175 .contextMenu {
176 Button {
177 appState.copyToPasteboard(String(job.id), label: "job ID")
178 } label: {
179 Label("Copy Job ID", systemImage: "doc.on.doc")
180 }
181
182 if let note = job.note, !note.isEmpty {
183 Button {
184 appState.copyToPasteboard(note, label: "build note")
185 } label: {
186 Label("Copy Note", systemImage: "text.alignleft")
187 }
188 }
189
190 if !job.tags.isEmpty {
191 Button {
192 appState.copyToPasteboard(job.tags.joined(separator: ", "), label: "build tags")
193 } label: {
194 Label("Copy Tags", systemImage: "tag")
195 }
196 }
197 }
198 .swipeActions(edge: .leading, allowsFullSwipe: true) {
199 if swipeActionsEnabled, job.status.isCancellable {
200 Button {
201 Task {
202 await viewModel.cancelJob(job)
203 }
204 } label: {
205 Label("Cancel", systemImage: "xmark.circle")
206 }
207 .tint(.red)
208 }
209 }
210 .task {
211 await viewModel.loadMoreIfNeeded(currentItem: job)
212 }
171 jobRow(job, viewModel)
213172 }
214173 .themedRow()
215174
@@ -250,16 +209,29 @@ struct BuildListView: View {
250209 viewModel.recordRecentSearch(query)
251210 }
252211 .overlay {
253 if viewModel.isLoading, viewModel.jobs.isEmpty {
254 SRHTLoadingStateView(message: "Loading builds…")
255 } else if let error = viewModel.error, viewModel.jobs.isEmpty {
256 SRHTErrorStateView(
257 title: "Couldn't Load Builds",
258 message: error,
259 retryAction: { await viewModel.loadJobs() }
260 )
261 } else if !viewModel.searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
262 viewModel.filteredJobs.isEmpty {
212 emptyState(viewModel)
213 }
214 .connectivityOverlay(hasContent: !viewModel.jobs.isEmpty) {
215 await viewModel.loadJobs()
216 }
217 .srhtErrorBanner(error: $vm.error)
218 .refreshable {
219 await viewModel.loadJobs()
220 }
221 }
222
223 @ViewBuilder
224 private func emptyState(_ viewModel: BuildListViewModel) -> some View {
225 SRHTLoadStateView(
226 isLoading: viewModel.isLoading,
227 error: viewModel.error,
228 isEmpty: viewModel.jobs.isEmpty,
229 loadingMessage: "Loading builds…",
230 errorTitle: "Couldn't Load Builds",
231 retryAction: { await viewModel.loadJobs() }
232 ) {
233 if !viewModel.searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
234 viewModel.filteredJobs.isEmpty {
263235 ContentUnavailableView(
264236 "No Build Matches",
265237 systemImage: "magnifyingglass",
@@ -279,12 +251,51 @@ struct BuildListView: View {
279251 )
280252 }
281253 }
282 .connectivityOverlay(hasContent: !viewModel.jobs.isEmpty) {
283 await viewModel.loadJobs()
254 }
255
256 @ViewBuilder
257 private func jobRow(_ job: JobSummary, _ viewModel: BuildListViewModel) -> some View {
258 NavigationLink(value: job) {
259 BuildRowView(job: job)
260 .equatable()
284261 }
285 .srhtErrorBanner(error: $vm.error)
286 .refreshable {
287 await viewModel.loadJobs()
262 .contextMenu {
263 Button {
264 appState.copyToPasteboard(String(job.id), label: "job ID")
265 } label: {
266 Label("Copy Job ID", systemImage: "doc.on.doc")
267 }
268
269 if let note = job.note, !note.isEmpty {
270 Button {
271 appState.copyToPasteboard(note, label: "build note")
272 } label: {
273 Label("Copy Note", systemImage: "text.alignleft")
274 }
275 }
276
277 if !job.tags.isEmpty {
278 Button {
279 appState.copyToPasteboard(job.tags.joined(separator: ", "), label: "build tags")
280 } label: {
281 Label("Copy Tags", systemImage: "tag")
282 }
283 }
284 }
285 .swipeActions(edge: .leading, allowsFullSwipe: true) {
286 if swipeActionsEnabled, job.status.isCancellable {
287 Button {
288 Task {
289 await viewModel.cancelJob(job)
290 }
291 } label: {
292 Label("Cancel", systemImage: "xmark.circle")
293 }
294 .tint(.red)
295 }
296 }
297 .task {
298 await viewModel.loadMoreIfNeeded(currentItem: job)
288299 }
289300 }
290301}
@@ -295,12 +306,7 @@ private struct SubmitBuildSheet: View {
295306
296307 @Environment(\.dismiss) private var dismiss
297308 @Bindable var viewModelBindable: BuildListViewModel
298 @State private var manifest = ""
299 @State private var tagsText = ""
300 @State private var note = ""
301 @State private var secrets = false
302 @State private var execute = true
303 @State private var visibility: Visibility = .publicVisibility
309 @State private var draft = BuildDraft()
304310
305311 init(viewModel: BuildListViewModel, onSubmitted: @escaping (Int) -> Void) {
306312 self.viewModel = viewModel
@@ -310,55 +316,12 @@ private struct SubmitBuildSheet: View {
310316
311317 var body: some View {
312318 NavigationStack {
313 Form {
314 Section("Build Manifest") {
315 TextField("Paste a build manifest", text: $manifest, axis: .vertical)
316 .font(.system(.body, design: .monospaced))
317 .lineLimit(12...24)
318 .textInputAutocapitalization(.never)
319 .autocorrectionDisabled()
320 .themedRow()
321 }
322
323 Section("Build Options") {
324 TextField("Note (optional)", text: $note)
325 .themedRow()
326 TextField("Tags (comma-separated, optional)", text: $tagsText)
327 .textInputAutocapitalization(.never)
328 .autocorrectionDisabled()
329 .themedRow()
330 Picker("Visibility", selection: $visibility) {
331 Text("Public").tag(Visibility.publicVisibility)
332 Text("Unlisted").tag(Visibility.unlisted)
333 Text("Private").tag(Visibility.privateVisibility)
334 }
335 .themedRow()
336 Toggle("Start build now", isOn: $execute)
337 .themedRow()
338 Toggle("Allow build secrets", isOn: $secrets)
339 .themedRow()
340 }
341
342 Section {
343 Text("You need a valid builds.sr.ht manifest and a token with BUILDS:RW.")
344 .font(.footnote)
345 .foregroundStyle(.secondary)
346 .themedRow()
347 }
348
349 if let error = viewModel.error {
350 Section {
351 Label {
352 Text(error)
353 } icon: {
354 Image(systemName: "exclamationmark.triangle.fill")
355 .foregroundStyle(.red)
356 }
357 .foregroundStyle(.red)
358 .themedRow()
359 }
360 }
361 }
319 BuildDraftForm(
320 draft: $draft,
321 manifestPlaceholder: "Paste a build manifest",
322 footnote: "You need a valid builds.sr.ht manifest and a token with BUILDS:RW.",
323 error: viewModel.error
324 )
362325 .themedList()
363326 .navigationTitle("Submit Build")
364327 .navigationBarTitleDisplayMode(.inline)
@@ -375,17 +338,13 @@ private struct SubmitBuildSheet: View {
375338 ToolbarItem(placement: .confirmationAction) {
376339 Button {
377340 Task {
378 let tags = tagsText
379 .split(separator: ",")
380 .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
381 .filter { !$0.isEmpty }
382341 if let jobId = await viewModel.submitBuild(
383 manifest: manifest,
384 tags: tags,
385 note: note,
386 secrets: secrets,
387 execute: execute,
388 visibility: visibility
342 manifest: draft.manifest,
343 tags: draft.tags,
344 note: draft.note,
345 secrets: draft.secrets,
346 execute: draft.execute,
347 visibility: draft.visibility
389348 ) {
390349 onSubmitted(jobId)
391350 }
@@ -398,7 +357,7 @@ private struct SubmitBuildSheet: View {
398357 Text("Submit Build")
399358 }
400359 }
401 .disabled(manifest.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || viewModel.isSubmitting)
360 .disabled(!draft.hasManifest || viewModel.isSubmitting)
402361 }
403362 }
404363 }
Hutch/Views/Home/HomeView.swift +1 −7
@@ -438,13 +438,7 @@ struct HomeView: View {
438438 return viewModel
439439 }
440440
441 let newViewModel = HomeViewModel(
442 currentUser: currentUser,
443 client: appState.client,
444 systemStatusRepository: appState.systemStatusRepository,
445 defaults: appState.accountDefaults,
446 accountID: appState.activeAccountID
447 )
441 let newViewModel = HomeViewModel(currentUser: currentUser, appState: appState)
448442 viewModel = newViewModel
449443 return newViewModel
450444 }
Hutch/Views/Home/HomeViewModel.swift +13 −54
@@ -329,6 +329,17 @@ final class HomeViewModel {
329329 private let defaults: UserDefaults
330330 private let accountID: String
331331
332 /// A view model for `currentUser` on the app's active account.
333 convenience init(currentUser: User, appState: AppState) {
334 self.init(
335 currentUser: currentUser,
336 client: appState.client,
337 systemStatusRepository: appState.systemStatusRepository,
338 defaults: appState.accountDefaults,
339 accountID: appState.activeAccountID
340 )
341 }
342
332343 init(
333344 currentUser: User,
334345 client: SRHTClient,
@@ -694,23 +705,7 @@ final class HomeViewModel {
694705 InboxReadStateStore.markUnread(for: thread.threadGroupingKey, defaults: defaults)
695706 if unreadInboxThreads.contains(where: { $0.id == thread.id }) == false {
696707 unreadInboxThreads.append(
697 InboxThreadSummary(
698 rootEmailID: thread.rootEmailID,
699 rootMessageID: thread.rootMessageID,
700 threadRootEmailIDs: thread.threadRootEmailIDs,
701 threadRootMessageIDs: thread.threadRootMessageIDs,
702 listID: thread.listID,
703 listRID: thread.listRID,
704 listName: thread.listName,
705 listOwner: thread.listOwner,
706 subject: thread.subject,
707 latestSender: thread.latestSender,
708 lastActivityAt: thread.lastActivityAt,
709 messageCount: thread.messageCount,
710 repo: thread.repo,
711 containsPatch: thread.containsPatch,
712 isUnread: true
713 )
708 thread.withUnread(true)
714709 )
715710 unreadInboxThreads.sort(by: Self.sortInboxThreadsForTriage)
716711 }
@@ -1203,43 +1198,7 @@ final class HomeViewModel {
12031198 }
12041199
12051200 nonisolated static func deduplicateInboxThreads(_ threads: [InboxThreadSummary]) -> [InboxThreadSummary] {
1206 var grouped: [String: InboxThreadSummary] = [:]
1207
1208 for thread in threads {
1209 guard let existing = grouped[thread.threadGroupingKey] else {
1210 grouped[thread.threadGroupingKey] = thread
1211 continue
1212 }
1213
1214 let latest = thread.lastActivityAt >= existing.lastActivityAt ? thread : existing
1215 let mergedRootEmailIDs = Array(Set(existing.threadRootEmailIDs + thread.threadRootEmailIDs)).sorted()
1216 let mergedRootMessageIDs = Array(Set(existing.threadRootMessageIDs + thread.threadRootMessageIDs)).sorted()
1217 let mergedMessageCount = max(
1218 existing.messageCount ?? existing.threadRootMessageIDs.count,
1219 thread.messageCount ?? thread.threadRootMessageIDs.count,
1220 mergedRootMessageIDs.count
1221 )
1222
1223 grouped[thread.threadGroupingKey] = InboxThreadSummary(
1224 rootEmailID: latest.rootEmailID,
1225 rootMessageID: latest.rootMessageID,
1226 threadRootEmailIDs: mergedRootEmailIDs,
1227 threadRootMessageIDs: mergedRootMessageIDs,
1228 listID: latest.listID,
1229 listRID: latest.listRID,
1230 listName: latest.listName,
1231 listOwner: latest.listOwner,
1232 subject: latest.subject,
1233 latestSender: latest.latestSender,
1234 lastActivityAt: max(existing.lastActivityAt, thread.lastActivityAt),
1235 messageCount: mergedMessageCount,
1236 repo: latest.repo ?? existing.repo,
1237 containsPatch: latest.containsPatch || existing.containsPatch,
1238 isUnread: latest.isUnread || existing.isUnread
1239 )
1240 }
1241
1242 return grouped.values.sorted(by: sortInboxThreadsForTriage)
1201 return InboxThreadSummary.mergedByThread(threads).sorted(by: sortInboxThreadsForTriage)
12431202 }
12441203
12451204 nonisolated static func matchesCurrentUserAssignee(_ entity: Entity, currentUser: User) -> Bool {
Hutch/Views/Inbox/ThreadDetailView.swift +89 −79
@@ -114,54 +114,9 @@ struct ThreadDetailView: View {
114114
115115 List {
116116 if let thread = viewModel.thread {
117 Section {
118 VStack(alignment: .leading, spacing: 6) {
119 Text(thread.displaySubject)
120 .font(.headline)
121 Text(headerMetadata(thread))
122 .font(.caption)
123 .foregroundStyle(.secondary)
124 }
125 .padding(.vertical, 4)
126 .themedRow()
127 }
117 headerSection(thread)
128118
129 Section("Related") {
130 Button {
131 appState.navigateToMailingList(
132 InboxMailingListReference(
133 id: thread.listID,
134 rid: thread.listRID,
135 name: thread.listName,
136 owner: thread.listOwner
137 )
138 )
139 } label: {
140 Label(thread.listDisplayName, systemImage: "list.bullet")
141 }
142 .themedRow()
143
144 if let repo = self.thread.repo {
145 Button {
146 openRepository(named: repo, ownerCanonicalName: thread.listOwner.canonicalName)
147 } label: {
148 HStack {
149 Label("\(thread.listOwner.canonicalName)/\(repo)", systemImage: "book.closed")
150 Spacer()
151 if isOpeningRepository {
152 ProgressView()
153 .controlSize(.small)
154 } else {
155 Image(systemName: "arrow.up.right")
156 .font(.caption)
157 .foregroundStyle(.tertiary)
158 }
159 }
160 }
161 .disabled(isOpeningRepository)
162 .themedRow()
163 }
164 }
119 relatedSection(thread)
165120
166121 if let partialWarning = viewModel.partialWarning {
167122 Section {
@@ -179,11 +134,7 @@ struct ThreadDetailView: View {
179134 canCollapse: thread.messages.count > 1,
180135 onToggleCollapse: {
181136 withAnimation(.easeInOut(duration: 0.2)) {
182 if collapsedMessageIDs.contains(message.id) {
183 collapsedMessageIDs.remove(message.id)
184 } else {
185 collapsedMessageIDs.insert(message.id)
186 }
137 collapsedMessageIDs.formSymmetricDifference([message.id])
187138 }
188139 }
189140 )
@@ -195,36 +146,18 @@ struct ThreadDetailView: View {
195146 .listStyle(.plain)
196147 .toolbar {
197148 ToolbarItem(placement: .topBarTrailing) {
198 HStack {
199 if onMarkRead != nil || onMarkUnread != nil {
200 Button(isUnread ? "Mark Read" : "Mark Unread") {
201 suppressAutoMarkViewed = !isUnread
202 if isUnread {
203 onMarkRead?()
204 isUnread = false
205 } else {
206 onMarkUnread?()
207 isUnread = true
208 }
209 }
210 }
211
212 Button("Reply") {
213 viewModel.prepareReply()
214 }
215 }
149 toolbarButtons(viewModel)
216150 }
217151 }
218152 .overlay {
219 if viewModel.isLoading, viewModel.thread == nil {
220 SRHTLoadingStateView(message: "Loading thread…")
221 } else if let error = viewModel.error, viewModel.thread == nil {
222 SRHTErrorStateView(
223 title: "Failed to load thread",
224 message: error,
225 retryAction: { await viewModel.loadThread() }
226 )
227 }
153 SRHTLoadStateView(
154 isLoading: viewModel.isLoading,
155 error: viewModel.error,
156 isEmpty: viewModel.thread == nil,
157 loadingMessage: "Loading thread…",
158 errorTitle: "Failed to load thread",
159 retryAction: { await viewModel.loadThread() }
160 ) {}
228161 }
229162 .srhtErrorBanner(error: $vm.error)
230163 .refreshable {
@@ -255,6 +188,83 @@ struct ThreadDetailView: View {
255188 }
256189 }
257190 }
191
192 @ViewBuilder
193 private func relatedSection(_ thread: InboxThreadDetail) -> some View {
194 Section("Related") {
195 Button {
196 appState.navigateToMailingList(
197 InboxMailingListReference(
198 id: thread.listID,
199 rid: thread.listRID,
200 name: thread.listName,
201 owner: thread.listOwner
202 )
203 )
204 } label: {
205 Label(thread.listDisplayName, systemImage: "list.bullet")
206 }
207 .themedRow()
208
209 if let repo = self.thread.repo {
210 Button {
211 openRepository(named: repo, ownerCanonicalName: thread.listOwner.canonicalName)
212 } label: {
213 HStack {
214 Label("\(thread.listOwner.canonicalName)/\(repo)", systemImage: "book.closed")
215 Spacer()
216 if isOpeningRepository {
217 ProgressView()
218 .controlSize(.small)
219 } else {
220 Image(systemName: "arrow.up.right")
221 .font(.caption)
222 .foregroundStyle(.tertiary)
223 }
224 }
225 }
226 .disabled(isOpeningRepository)
227 .themedRow()
228 }
229 }
230 }
231
232 @ViewBuilder
233 private func headerSection(_ thread: InboxThreadDetail) -> some View {
234 Section {
235 VStack(alignment: .leading, spacing: 6) {
236 Text(thread.displaySubject)
237 .font(.headline)
238 Text(headerMetadata(thread))
239 .font(.caption)
240 .foregroundStyle(.secondary)
241 }
242 .padding(.vertical, 4)
243 .themedRow()
244 }
245 }
246
247 @ViewBuilder
248 private func toolbarButtons(_ viewModel: ThreadViewModel) -> some View {
249 HStack {
250 if onMarkRead != nil || onMarkUnread != nil {
251 Button(isUnread ? "Mark Read" : "Mark Unread") {
252 suppressAutoMarkViewed = !isUnread
253 if isUnread {
254 onMarkRead?()
255 isUnread = false
256 } else {
257 onMarkUnread?()
258 isUnread = true
259 }
260 }
261 }
262
263 Button("Reply") {
264 viewModel.prepareReply()
265 }
266 }
267 }
258268}
259269
260270private struct InboxMessageRow: View {
Hutch/Views/Lists/MailingListListView.swift +17 −16
@@ -461,22 +461,23 @@ struct MailingListListView: View {
461461 Text("This permanently deletes the list and its entire archive, for everyone. This cannot be undone.")
462462 }
463463 .overlay {
464 if viewModel.isLoading, viewModel.mailingLists.isEmpty {
465 SRHTLoadingStateView(message: "Loading mailing lists…")
466 } else if let error = viewModel.error, viewModel.mailingLists.isEmpty {
467 SRHTErrorStateView(
468 title: "Couldn't Load Mailing Lists",
469 message: error,
470 retryAction: { await viewModel.loadMailingLists() }
471 )
472 } else if !viewModel.mailingLists.isEmpty, viewModel.filteredMailingLists.isEmpty {
473 ContentUnavailableView.search(text: viewModel.searchText)
474 } else if viewModel.mailingLists.isEmpty {
475 ContentUnavailableView(
476 "No Mailing Lists",
477 systemImage: "list.bullet.rectangle",
478 description: Text("Your subscribed mailing lists will appear here.")
479 )
464 SRHTLoadStateView(
465 isLoading: viewModel.isLoading,
466 error: viewModel.error,
467 isEmpty: viewModel.mailingLists.isEmpty,
468 loadingMessage: "Loading mailing lists…",
469 errorTitle: "Couldn't Load Mailing Lists",
470 retryAction: { await viewModel.loadMailingLists() }
471 ) {
472 if !viewModel.mailingLists.isEmpty, viewModel.filteredMailingLists.isEmpty {
473 ContentUnavailableView.search(text: viewModel.searchText)
474 } else if viewModel.mailingLists.isEmpty {
475 ContentUnavailableView(
476 "No Mailing Lists",
477 systemImage: "list.bullet.rectangle",
478 description: Text("Your subscribed mailing lists will appear here.")
479 )
480 }
480481 }
481482 }
482483 .srhtErrorBanner(error: $vm.error)
Hutch/Views/Lookup/UserProfileView.swift +3 −2
@@ -177,7 +177,7 @@ struct UserProfileView: View {
177177 NavigationLink {
178178 TicketListView(tracker: tracker)
179179 } label: {
180 UserProfileTrackerRowView(tracker: tracker)
180 TrackerSummaryRow(tracker: tracker)
181181 }
182182 }
183183 .themedRow()
@@ -260,7 +260,8 @@ struct UserProfileView: View {
260260 }
261261}
262262
263struct UserProfileTrackerRowView: View {
263/// A tracker's name, visibility, owner, description and last update.
264struct TrackerSummaryRow: View {
264265 let tracker: TrackerSummary
265266
266267 var body: some View {
Hutch/Views/Lookup/UserProfileViewModel.swift −33
@@ -169,39 +169,6 @@ final class UserProfileViewModel {
169169 let results: [RepositoryPayload]
170170 let cursor: String?
171171 }
172
173 private struct RepositoryPayload: Decodable, Sendable {
174 let id: Int
175 let rid: String
176 let name: String
177 let description: String?
178 let visibility: Visibility
179 let updated: Date
180 let owner: Entity
181 let head: Reference?
182
183 enum CodingKeys: String, CodingKey {
184 case id, rid, name, description, visibility, updated, owner
185 case head = "HEAD"
186 }
187
188 func repositorySummary(service: SRHTService) -> RepositorySummary {
189 RepositorySummary(
190 fields: .init(
191 id: id,
192 rid: rid,
193 service: service,
194 name: name,
195 description: description,
196 visibility: visibility,
197 updated: updated,
198 owner: owner,
199 head: head
200 )
201 )
202 }
203 }
204
205172 private struct UserTrackersResponse: Decodable, Sendable {
206173 let user: UserTrackersContainer
207174 }
Hutch/Views/Lookup/UserTrackersView.swift +1 −1
@@ -9,7 +9,7 @@ struct UserTrackersView: View {
99 NavigationLink {
1010 TicketListView(tracker: tracker)
1111 } label: {
12 UserProfileTrackerRowView(tracker: tracker)
12 TrackerSummaryRow(tracker: tracker)
1313 }
1414 }
1515 .themedRow()
Hutch/Views/More/ProfileView.swift +146 −141
@@ -89,15 +89,14 @@ struct ProfileView: View {
8989 }
9090 .themedList()
9191 .overlay {
92 if viewModel.isLoading, viewModel.profile == nil {
93 SRHTLoadingStateView(message: "Loading profile…")
94 } else if let error = viewModel.error, viewModel.profile == nil {
95 SRHTErrorStateView(
96 title: "Couldn't Load Profile",
97 message: error,
98 retryAction: { await viewModel.loadProfile() }
99 )
100 }
92 SRHTLoadStateView(
93 isLoading: viewModel.isLoading,
94 error: viewModel.error,
95 isEmpty: viewModel.profile == nil,
96 loadingMessage: "Loading profile…",
97 errorTitle: "Couldn't Load Profile",
98 retryAction: { await viewModel.loadProfile() }
99 ) {}
101100 }
102101 .sheet(isPresented: Binding(
103102 get: { viewModel.isEditingProfile },
@@ -160,36 +159,7 @@ struct ProfileView: View {
160159 @ViewBuilder
161160 private func profileSection(_ profile: UserProfile, viewModel: SettingsViewModel) -> some View {
162161 Section("Profile") {
163 HStack(spacing: 12) {
164 AsyncImage(url: profile.avatar.flatMap { URL(string: $0) }) { phase in
165 if case .success(let image) = phase {
166 image
167 .resizable()
168 .scaledToFill()
169 } else {
170 Image(systemName: "person.crop.circle.fill")
171 .resizable()
172 .foregroundStyle(.secondary)
173 }
174 }
175 .frame(width: 56, height: 56)
176 .clipShape(Circle())
177
178 VStack(alignment: .leading, spacing: 2) {
179 Text(profile.canonicalName)
180 .font(.headline)
181 Text(profile.email)
182 .font(.subheadline)
183 .foregroundStyle(.secondary)
184 if let userType = profile.userType {
185 Text(userType.capitalized)
186 .font(.caption)
187 .foregroundStyle(.tertiary)
188 }
189 }
190 }
191 .padding(.vertical, 4)
192 .themedRow()
162 profileHeader(profile)
193163
194164 if let bio = profile.bio, !bio.isEmpty {
195165 VStack(alignment: .leading, spacing: 2) {
@@ -216,16 +186,7 @@ struct ProfileView: View {
216186 .themedRow()
217187 }
218188
219 if let sub = profile.subscription {
220 if let status = sub.status {
221 LabeledContent("Subscription", value: status.capitalized)
222 .themedRow()
223 }
224 if let interval = sub.interval {
225 LabeledContent("Interval", value: interval.capitalized)
226 .themedRow()
227 }
228 }
189 subscriptionRows(profile)
229190
230191 Button("Edit Profile") {
231192 viewModel.isEditingProfile = true
@@ -275,39 +236,13 @@ struct ProfileView: View {
275236 }
276237 .themedRow()
277238
278 if viewModel.isAddingSSHKey {
279 TextField(
280 "Paste SSH public key",
281 text: Binding(
282 get: { viewModel.newSSHKey },
283 set: { viewModel.newSSHKey = $0 }
284 ),
285 axis: .vertical
286 )
287 .font(.caption.monospaced())
288 .lineLimit(3...6)
289 .themedRow()
290
291 HStack {
292 Button("Cancel") {
293 viewModel.isAddingSSHKey = false
294 viewModel.newSSHKey = ""
295 }
296 Spacer()
297 Button("Add") {
298 Task { await viewModel.addSSHKey() }
299 }
300 .buttonStyle(.borderedProminent)
301 .disabled(viewModel.newSSHKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
302 }
303 .themedRow()
304 } else {
305 Button {
306 viewModel.isAddingSSHKey = true
307 } label: {
308 SwiftUI.Label("Add SSH Key", systemImage: "key")
309 }
310 .themedRow()
239 AddKeyControls(
240 kind: "SSH",
241 systemImage: "key",
242 isAdding: Binding(get: { viewModel.isAddingSSHKey }, set: { viewModel.isAddingSSHKey = $0 }),
243 key: Binding(get: { viewModel.newSSHKey }, set: { viewModel.newSSHKey = $0 })
244 ) {
245 await viewModel.addSSHKey()
311246 }
312247 } header: {
313248 Text("SSH Keys")
@@ -338,39 +273,13 @@ struct ProfileView: View {
338273 }
339274 .themedRow()
340275
341 if viewModel.isAddingPGPKey {
342 TextField(
343 "Paste PGP public key",
344 text: Binding(
345 get: { viewModel.newPGPKey },
346 set: { viewModel.newPGPKey = $0 }
347 ),
348 axis: .vertical
349 )
350 .font(.caption.monospaced())
351 .lineLimit(3...6)
352 .themedRow()
353
354 HStack {
355 Button("Cancel") {
356 viewModel.isAddingPGPKey = false
357 viewModel.newPGPKey = ""
358 }
359 Spacer()
360 Button("Add") {
361 Task { await viewModel.addPGPKey() }
362 }
363 .buttonStyle(.borderedProminent)
364 .disabled(viewModel.newPGPKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
365 }
366 .themedRow()
367 } else {
368 Button {
369 viewModel.isAddingPGPKey = true
370 } label: {
371 SwiftUI.Label("Add PGP Key", systemImage: "key.fill")
372 }
373 .themedRow()
276 AddKeyControls(
277 kind: "PGP",
278 systemImage: "key.fill",
279 isAdding: Binding(get: { viewModel.isAddingPGPKey }, set: { viewModel.isAddingPGPKey = $0 }),
280 key: Binding(get: { viewModel.newPGPKey }, set: { viewModel.newPGPKey = $0 })
281 ) {
282 await viewModel.addPGPKey()
374283 }
375284 } header: {
376285 Text("PGP Keys")
@@ -396,32 +305,7 @@ struct ProfileView: View {
396305 .themedRow()
397306 } else {
398307 ForEach(viewModel.personalAccessTokens) { token in
399 VStack(alignment: .leading, spacing: 4) {
400 HStack {
401 Text(token.comment ?? "Token #\(token.id)")
402 .font(.subheadline)
403 Spacer()
404 }
405
406 HStack(spacing: 12) {
407 Text("Issued \(token.issued.relativeDescription)")
408 .font(.caption2)
409 .foregroundStyle(.secondary)
410
411 if let expires = token.expires {
412 Text("Expires \(expires.relativeDescription)")
413 .font(.caption2)
414 .foregroundStyle(expires < Date.now ? .red : .secondary)
415 }
416 }
417
418 if let grants = token.grants, !grants.isEmpty {
419 Text(grants)
420 .font(.caption2.monospaced())
421 .foregroundStyle(.tertiary)
422 .lineLimit(2)
423 }
424 }
308 PersonalAccessTokenRow(token: token)
425309 }
426310 .themedRow()
427311 }
@@ -488,6 +372,127 @@ struct ProfileView: View {
488372 Text("Recent security-relevant activity on your account, newest first. The full log lives on meta.sr.ht.")
489373 }
490374 }
375
376 @ViewBuilder
377 private func subscriptionRows(_ profile: UserProfile) -> some View {
378 if let sub = profile.subscription {
379 if let status = sub.status {
380 LabeledContent("Subscription", value: status.capitalized)
381 .themedRow()
382 }
383 if let interval = sub.interval {
384 LabeledContent("Interval", value: interval.capitalized)
385 .themedRow()
386 }
387 }
388 }
389
390 @ViewBuilder
391 private func profileHeader(_ profile: UserProfile) -> some View {
392 HStack(spacing: 12) {
393 AsyncImage(url: profile.avatar.flatMap { URL(string: $0) }) { phase in
394 if case .success(let image) = phase {
395 image
396 .resizable()
397 .scaledToFill()
398 } else {
399 Image(systemName: "person.crop.circle.fill")
400 .resizable()
401 .foregroundStyle(.secondary)
402 }
403 }
404 .frame(width: 56, height: 56)
405 .clipShape(Circle())
406
407 VStack(alignment: .leading, spacing: 2) {
408 Text(profile.canonicalName)
409 .font(.headline)
410 Text(profile.email)
411 .font(.subheadline)
412 .foregroundStyle(.secondary)
413 if let userType = profile.userType {
414 Text(userType.capitalized)
415 .font(.caption)
416 .foregroundStyle(.tertiary)
417 }
418 }
419 }
420 .padding(.vertical, 4)
421 .themedRow()
422 }
423}
424
425/// A key list's add field and its Cancel and Add buttons, or the button that opens them.
426private struct AddKeyControls: View {
427 /// "SSH", "PGP".
428 let kind: String
429 let systemImage: String
430 @Binding var isAdding: Bool
431 @Binding var key: String
432 let add: () async -> Void
433
434 var body: some View {
435 if isAdding {
436 TextField("Paste \(kind) public key", text: $key, axis: .vertical)
437 .font(.caption.monospaced())
438 .lineLimit(3...6)
439 .themedRow()
440
441 HStack {
442 Button("Cancel") {
443 isAdding = false
444 key = ""
445 }
446 Spacer()
447 Button("Add") {
448 Task { await add() }
449 }
450 .buttonStyle(.borderedProminent)
451 .disabled(key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
452 }
453 .themedRow()
454 } else {
455 Button {
456 isAdding = true
457 } label: {
458 SwiftUI.Label("Add \(kind) Key", systemImage: systemImage)
459 }
460 .themedRow()
461 }
462 }
463}
464
465private struct PersonalAccessTokenRow: View {
466 let token: PersonalAccessToken
467
468 var body: some View {
469 VStack(alignment: .leading, spacing: 4) {
470 HStack {
471 Text(token.comment ?? "Token #\(token.id)")
472 .font(.subheadline)
473 Spacer()
474 }
475
476 HStack(spacing: 12) {
477 Text("Issued \(token.issued.relativeDescription)")
478 .font(.caption2)
479 .foregroundStyle(.secondary)
480
481 if let expires = token.expires {
482 Text("Expires \(expires.relativeDescription)")
483 .font(.caption2)
484 .foregroundStyle(expires < Date.now ? .red : .secondary)
485 }
486 }
487
488 if let grants = token.grants, !grants.isEmpty {
489 Text(grants)
490 .font(.caption2.monospaced())
491 .foregroundStyle(.tertiary)
492 .lineLimit(2)
493 }
494 }
495 }
491496}
492497
493498private struct ProfileBioView: View {
Hutch/Views/Pastes/PasteDetailView.swift +35 −54
@@ -110,38 +110,39 @@ struct PasteDetailView: View {
110110 private func content(_ viewModel: PasteDetailViewModel) -> some View {
111111 @Bindable var vm = viewModel
112112
113 if viewModel.isLoading, viewModel.paste == nil {
114 SRHTLoadingStateView(message: "Loading paste…")
115 } else if let error = viewModel.error, viewModel.paste == nil {
116 SRHTErrorStateView(
117 title: "Couldn't Load Paste",
118 message: error,
119 retryAction: { await viewModel.loadPaste() }
120 )
121 } else if let paste = viewModel.paste {
122 VStack(spacing: 0) {
123 fileHeaderBar(paste: paste, viewModel: viewModel)
124 Divider()
125 fileContentArea(viewModel: viewModel)
126 }
127 .safeAreaInset(edge: .bottom, spacing: 0) {
128 actionToolbar(viewModel: viewModel)
129 }
130 .srhtErrorBanner(error: $vm.error)
131 .sheet(isPresented: $showInfoSheet) {
132 PasteInfoSheet(paste: paste, selectedFile: viewModel.selectedFile)
133 }
134 .sheet(isPresented: $showFileShareSheet) {
135 if let contents = viewModel.selectedFileContents {
136 FileContentShareSheet(activityItems: [contents])
113 SRHTLoadStateView(
114 isLoading: viewModel.isLoading,
115 error: viewModel.error,
116 isEmpty: viewModel.paste == nil,
117 loadingMessage: "Loading paste…",
118 errorTitle: "Couldn't Load Paste",
119 retryAction: { await viewModel.loadPaste() }
120 ) {
121 if let paste = viewModel.paste {
122 VStack(spacing: 0) {
123 fileHeaderBar(paste: paste, viewModel: viewModel)
124 Divider()
125 fileContentArea(viewModel: viewModel)
137126 }
138 }
139 .alert("Share Unavailable", isPresented: $showShareUnavailableAlert) {
140 Button("OK", role: .cancel) {
141 // Alert dismissal is implicit; no additional action required.
127 .safeAreaInset(edge: .bottom, spacing: 0) {
128 actionToolbar(viewModel: viewModel)
129 }
130 .srhtErrorBanner(error: $vm.error)
131 .sheet(isPresented: $showInfoSheet) {
132 PasteInfoSheet(paste: paste, selectedFile: viewModel.selectedFile)
133 }
134 .sheet(isPresented: $showFileShareSheet) {
135 if let contents = viewModel.selectedFileContents {
136 FileContentShareSheet(activityItems: [contents])
137 }
138 }
139 .alert("Share Unavailable", isPresented: $showShareUnavailableAlert) {
140 Button("OK", role: .cancel) {
141 // Alert dismissal is implicit; no additional action required.
142 }
143 } message: {
144 Text(SRHTShareTarget.file.fallbackMessage)
142145 }
143 } message: {
144 Text(SRHTShareTarget.file.fallbackMessage)
145146 }
146147 }
147148 }
@@ -240,7 +241,7 @@ struct PasteDetailView: View {
240241
241242 private func actionToolbar(viewModel: PasteDetailViewModel) -> some View {
242243 HStack(spacing: 0) {
243 toolbarButton(
244 BottomToolbarButton(
244245 title: didCopyContents ? "Copied" : "Copy All",
245246 systemImage: didCopyContents ? "checkmark" : "doc.on.doc"
246247 ) {
@@ -257,7 +258,7 @@ struct PasteDetailView: View {
257258 }
258259 .disabled(viewModel.selectedFileContents == nil)
259260
260 toolbarButton(
261 BottomToolbarButton(
261262 title: "Share",
262263 systemImage: "square.and.arrow.up"
263264 ) {
@@ -269,14 +270,14 @@ struct PasteDetailView: View {
269270 }
270271 .disabled(viewModel.selectedFileContents == nil)
271272
272 toolbarButton(
273 BottomToolbarButton(
273274 title: wrapLines ? "Wrap On" : "Wrap Off",
274275 systemImage: "text.word.spacing"
275276 ) {
276277 wrapLines.toggle()
277278 }
278279
279 toolbarButton(
280 BottomToolbarButton(
280281 title: "Details",
281282 systemImage: "info.circle"
282283 ) {
@@ -291,26 +292,6 @@ struct PasteDetailView: View {
291292 Divider()
292293 }
293294 }
294
295 private func toolbarButton(
296 title: String,
297 systemImage: String,
298 action: @escaping () -> Void
299 ) -> some View {
300 Button(action: action) {
301 VStack(spacing: 4) {
302 Image(systemName: systemImage)
303 .font(.system(size: 17, weight: .semibold))
304 Text(title)
305 .font(.caption2)
306 .lineLimit(1)
307 }
308 .frame(maxWidth: .infinity)
309 .contentShape(Rectangle())
310 }
311 .buttonStyle(.plain)
312 .foregroundStyle(.primary)
313 }
314295}
315296
316297// MARK: - Paste Info Sheet
Hutch/Views/Pastes/PasteListView.swift +17 −16
@@ -123,22 +123,23 @@ struct PasteListView: View {
123123 prompt: "Search pastes"
124124 )
125125 .overlay {
126 if viewModel.isLoading, viewModel.pastes.isEmpty {
127 SRHTLoadingStateView(message: "Loading pastes…")
128 } else if let error = viewModel.error, viewModel.pastes.isEmpty {
129 SRHTErrorStateView(
130 title: "Couldn't Load Pastes",
131 message: error,
132 retryAction: { await viewModel.loadPastes() }
133 )
134 } else if !viewModel.pastes.isEmpty, viewModel.filteredPastes.isEmpty {
135 ContentUnavailableView.search(text: viewModel.searchText)
136 } else if viewModel.pastes.isEmpty {
137 ContentUnavailableView(
138 "No Pastes",
139 systemImage: "doc.on.clipboard",
140 description: Text("Your pastes will appear here.")
141 )
126 SRHTLoadStateView(
127 isLoading: viewModel.isLoading,
128 error: viewModel.error,
129 isEmpty: viewModel.pastes.isEmpty,
130 loadingMessage: "Loading pastes…",
131 errorTitle: "Couldn't Load Pastes",
132 retryAction: { await viewModel.loadPastes() }
133 ) {
134 if !viewModel.pastes.isEmpty, viewModel.filteredPastes.isEmpty {
135 ContentUnavailableView.search(text: viewModel.searchText)
136 } else if viewModel.pastes.isEmpty {
137 ContentUnavailableView(
138 "No Pastes",
139 systemImage: "doc.on.clipboard",
140 description: Text("Your pastes will appear here.")
141 )
142 }
142143 }
143144 }
144145 .connectivityOverlay(hasContent: !viewModel.pastes.isEmpty) {
Hutch/Views/Projects/DiscoverProjectsView.swift +15 −14
@@ -113,20 +113,21 @@ struct DiscoverProjectsView: View {
113113 .themedList()
114114 .listStyle(.plain)
115115 .overlay {
116 if viewModel.isLoading, viewModel.projects.isEmpty {
117 SRHTLoadingStateView(message: "Loading projects…")
118 } else if let error = viewModel.error, viewModel.projects.isEmpty {
119 SRHTErrorStateView(
120 title: "Couldn't Load Projects",
121 message: error,
122 retryAction: { await viewModel.reload() }
123 )
124 } else if viewModel.projects.isEmpty {
125 ContentUnavailableView(
126 "No Public Projects",
127 systemImage: "sparkle.magnifyingglass",
128 description: Text("Public projects on SourceHut will appear here.")
129 )
116 SRHTLoadStateView(
117 isLoading: viewModel.isLoading,
118 error: viewModel.error,
119 isEmpty: viewModel.projects.isEmpty,
120 loadingMessage: "Loading projects…",
121 errorTitle: "Couldn't Load Projects",
122 retryAction: { await viewModel.reload() }
123 ) {
124 if viewModel.projects.isEmpty {
125 ContentUnavailableView(
126 "No Public Projects",
127 systemImage: "sparkle.magnifyingglass",
128 description: Text("Public projects on SourceHut will appear here.")
129 )
130 }
130131 }
131132 }
132133 .srhtErrorBanner(
Hutch/Views/Projects/ProjectMailingListView.swift +72 −124
@@ -304,23 +304,7 @@ final class MailingListDetailViewModel {
304304
305305 threads = threads.map { thread in
306306 guard thread.isUnread else { return thread }
307 return InboxThreadSummary(
308 rootEmailID: thread.rootEmailID,
309 rootMessageID: thread.rootMessageID,
310 threadRootEmailIDs: thread.threadRootEmailIDs,
311 threadRootMessageIDs: thread.threadRootMessageIDs,
312 listID: thread.listID,
313 listRID: thread.listRID,
314 listName: thread.listName,
315 listOwner: thread.listOwner,
316 subject: thread.subject,
317 latestSender: thread.latestSender,
318 lastActivityAt: thread.lastActivityAt,
319 messageCount: thread.messageCount,
320 repo: thread.repo,
321 containsPatch: thread.containsPatch,
322 isUnread: false
323 )
307 return thread.withUnread(false)
324308 }
325309
326310 NeedsAttentionSnapshotStore.adjustUnreadInboxThreads(by: -unreadThreads.count, accountID: accountID)
@@ -363,63 +347,11 @@ final class MailingListDetailViewModel {
363347 private func updateThread(_ thread: InboxThreadSummary, isUnread: Bool) {
364348 guard let index = threads.firstIndex(where: { $0.id == thread.id }) else { return }
365349 let current = threads[index]
366 threads[index] = InboxThreadSummary(
367 rootEmailID: current.rootEmailID,
368 rootMessageID: current.rootMessageID,
369 threadRootEmailIDs: current.threadRootEmailIDs,
370 threadRootMessageIDs: current.threadRootMessageIDs,
371 listID: current.listID,
372 listRID: current.listRID,
373 listName: current.listName,
374 listOwner: current.listOwner,
375 subject: current.subject,
376 latestSender: current.latestSender,
377 lastActivityAt: current.lastActivityAt,
378 messageCount: current.messageCount,
379 repo: current.repo,
380 containsPatch: current.containsPatch,
381 isUnread: isUnread
382 )
350 threads[index] = current.withUnread(isUnread)
383351 }
384352
385353 private func deduplicateThreads(_ threads: [InboxThreadSummary]) -> [InboxThreadSummary] {
386 var grouped: [String: InboxThreadSummary] = [:]
387
388 for thread in threads {
389 guard let existing = grouped[thread.threadGroupingKey] else {
390 grouped[thread.threadGroupingKey] = thread
391 continue
392 }
393
394 let latest = thread.lastActivityAt >= existing.lastActivityAt ? thread : existing
395 let mergedRootEmailIDs = Array(Set(existing.threadRootEmailIDs + thread.threadRootEmailIDs)).sorted()
396 let mergedRootMessageIDs = Array(Set(existing.threadRootMessageIDs + thread.threadRootMessageIDs)).sorted()
397 let mergedMessageCount = max(
398 existing.messageCount ?? existing.threadRootMessageIDs.count,
399 thread.messageCount ?? thread.threadRootMessageIDs.count,
400 mergedRootMessageIDs.count
401 )
402
403 grouped[thread.threadGroupingKey] = InboxThreadSummary(
404 rootEmailID: latest.rootEmailID,
405 rootMessageID: latest.rootMessageID,
406 threadRootEmailIDs: mergedRootEmailIDs,
407 threadRootMessageIDs: mergedRootMessageIDs,
408 listID: latest.listID,
409 listRID: latest.listRID,
410 listName: latest.listName,
411 listOwner: latest.listOwner,
412 subject: latest.subject,
413 latestSender: latest.latestSender,
414 lastActivityAt: max(existing.lastActivityAt, thread.lastActivityAt),
415 messageCount: mergedMessageCount,
416 repo: latest.repo ?? existing.repo,
417 containsPatch: latest.containsPatch || existing.containsPatch,
418 isUnread: latest.isUnread || existing.isUnread
419 )
420 }
421
422 return grouped.values.sorted { lhs, rhs in
354 return InboxThreadSummary.mergedByThread(threads).sorted { lhs, rhs in
423355 if lhs.lastActivityAt == rhs.lastActivityAt {
424356 return lhs.displaySubject.localizedCaseInsensitiveCompare(rhs.displaySubject) == .orderedAscending
425357 }
@@ -578,48 +510,11 @@ struct MailingListDetailView: View {
578510 ForEach(viewModel.filteredPatchsets) { patchset in
579511 // Pushed directly rather than by value: this view is also shown
580512 // from a project, whose stack declares no MoreRoute destination.
581 NavigationLink {
582 PatchsetDetailView(patchsetID: patchset.id, listName: mailingList.name)
583 } label: {
584 PatchsetRow(patchset: patchset)
585 }
586 .themedRow()
513 patchsetRow(patchset, viewModel)
587514 }
588515 } else {
589516 ForEach(viewModel.filteredThreads) { thread in
590 NavigationLink {
591 ThreadDetailView(
592 thread: thread,
593 onViewed: {
594 viewModel.markThreadRead(thread)
595 },
596 onMarkRead: {
597 viewModel.markThreadRead(thread)
598 },
599 onMarkUnread: {
600 viewModel.markThreadUnread(thread)
601 }
602 )
603 } label: {
604 InboxThreadRow(thread: thread)
605 }
606 .swipeActions(edge: .trailing, allowsFullSwipe: true) {
607 Button {
608 withAnimation(.easeInOut(duration: 0.2)) {
609 if thread.isUnread {
610 viewModel.markThreadRead(thread)
611 } else {
612 viewModel.markThreadUnread(thread)
613 }
614 }
615 } label: {
616 Label(
617 thread.isUnread ? "Mark as Read" : "Mark as Unread",
618 systemImage: thread.isUnread ? "envelope.open" : "envelope.badge"
619 )
620 }
621 .tint(thread.isUnread ? .blue : .gray)
622 }
517 threadRow(thread, viewModel)
623518 }
624519 .themedRow()
625520 }
@@ -632,15 +527,29 @@ struct MailingListDetailView: View {
632527 prompt: showingPatches(viewModel) ? "Search patches" : "Search messages"
633528 )
634529 .overlay {
635 if viewModel.isLoading, viewModel.threads.isEmpty {
636 SRHTLoadingStateView(message: "Loading mailing list…")
637 } else if let error = viewModel.error, viewModel.threads.isEmpty {
638 SRHTErrorStateView(
639 title: "Couldn't Load Mailing List",
640 message: error,
641 retryAction: { await viewModel.loadThreads() }
642 )
643 } else if showingPatches(viewModel) {
530 emptyState(viewModel)
531 }
532 .refreshable {
533 await viewModel.loadThreads()
534 }
535 .srhtErrorBanner(error: $vm.error)
536 }
537
538 private func showingPatches(_ viewModel: MailingListDetailViewModel) -> Bool {
539 scope == .patches && !viewModel.patchsets.isEmpty
540 }
541
542 @ViewBuilder
543 private func emptyState(_ viewModel: MailingListDetailViewModel) -> some View {
544 SRHTLoadStateView(
545 isLoading: viewModel.isLoading,
546 error: viewModel.error,
547 isEmpty: viewModel.threads.isEmpty,
548 loadingMessage: "Loading mailing list…",
549 errorTitle: "Couldn't Load Mailing List",
550 retryAction: { await viewModel.loadThreads() }
551 ) {
552 if showingPatches(viewModel) {
644553 if !viewModel.patchsets.isEmpty, viewModel.filteredPatchsets.isEmpty {
645554 ContentUnavailableView.search(text: viewModel.searchText)
646555 }
@@ -654,14 +563,53 @@ struct MailingListDetailView: View {
654563 )
655564 }
656565 }
657 .refreshable {
658 await viewModel.loadThreads()
566 }
567
568 @ViewBuilder
569 private func threadRow(_ thread: InboxThreadSummary, _ viewModel: MailingListDetailViewModel) -> some View {
570 NavigationLink {
571 ThreadDetailView(
572 thread: thread,
573 onViewed: {
574 viewModel.markThreadRead(thread)
575 },
576 onMarkRead: {
577 viewModel.markThreadRead(thread)
578 },
579 onMarkUnread: {
580 viewModel.markThreadUnread(thread)
581 }
582 )
583 } label: {
584 InboxThreadRow(thread: thread)
585 }
586 .swipeActions(edge: .trailing, allowsFullSwipe: true) {
587 Button {
588 withAnimation(.easeInOut(duration: 0.2)) {
589 if thread.isUnread {
590 viewModel.markThreadRead(thread)
591 } else {
592 viewModel.markThreadUnread(thread)
593 }
594 }
595 } label: {
596 Label(
597 thread.isUnread ? "Mark as Read" : "Mark as Unread",
598 systemImage: thread.isUnread ? "envelope.open" : "envelope.badge"
599 )
600 }
601 .tint(thread.isUnread ? .blue : .gray)
659602 }
660 .srhtErrorBanner(error: $vm.error)
661603 }
662604
663 private func showingPatches(_ viewModel: MailingListDetailViewModel) -> Bool {
664 scope == .patches && !viewModel.patchsets.isEmpty
605 @ViewBuilder
606 private func patchsetRow(_ patchset: PatchsetSummary, _ viewModel: MailingListDetailViewModel) -> some View {
607 NavigationLink {
608 PatchsetDetailView(patchsetID: patchset.id, listName: mailingList.name)
609 } label: {
610 PatchsetRow(patchset: patchset)
611 }
612 .themedRow()
665613 }
666614}
667615
Hutch/Views/Projects/ProjectsListView.swift +17 −16
@@ -144,22 +144,23 @@ struct ProjectsListView: View {
144144 prompt: "Search projects"
145145 )
146146 .overlay {
147 if viewModel.isLoading, viewModel.projects.isEmpty {
148 SRHTLoadingStateView(message: "Loading projects…")
149 } else if let error = viewModel.error, viewModel.projects.isEmpty {
150 SRHTErrorStateView(
151 title: "Couldn't Load Projects",
152 message: error,
153 retryAction: { await viewModel.loadProjects() }
154 )
155 } else if !viewModel.projects.isEmpty, viewModel.filteredProjects.isEmpty {
156 ContentUnavailableView.search(text: viewModel.searchText)
157 } else if viewModel.projects.isEmpty {
158 ContentUnavailableView(
159 "No Projects",
160 systemImage: "square.stack.3d.up",
161 description: Text("Projects from your SourceHut account will appear here when available.")
162 )
147 SRHTLoadStateView(
148 isLoading: viewModel.isLoading,
149 error: viewModel.error,
150 isEmpty: viewModel.projects.isEmpty,
151 loadingMessage: "Loading projects…",
152 errorTitle: "Couldn't Load Projects",
153 retryAction: { await viewModel.loadProjects() }
154 ) {
155 if !viewModel.projects.isEmpty, viewModel.filteredProjects.isEmpty {
156 ContentUnavailableView.search(text: viewModel.searchText)
157 } else if viewModel.projects.isEmpty {
158 ContentUnavailableView(
159 "No Projects",
160 systemImage: "square.stack.3d.up",
161 description: Text("Projects from your SourceHut account will appear here when available.")
162 )
163 }
163164 }
164165 }
165166 .srhtErrorBanner(
Hutch/Views/Repositories/CommitDetailView.swift +51 −46
@@ -85,52 +85,7 @@ struct CommitDetailView: View {
8585 }
8686 }
8787 } else if let commit = viewModel.commit {
88 ScrollView {
89 LazyVStack(alignment: .leading, spacing: 0) {
90 // Header
91 commitHeader(commit)
92
93 sectionDivider
94
95 // Message
96 commitMessage(commit)
97
98 // Trailers
99 if !commit.trailers.isEmpty {
100 sectionDivider
101 trailersSection(commit.trailers)
102 }
103
104 // Parents
105 if !commit.parents.isEmpty {
106 sectionDivider
107 parentsSection(commit.parents)
108 }
109
110 // Diff
111 if let diff = commit.diff, !diff.isEmpty {
112 sectionDivider
113 diffSection(diff)
114 }
115
116 // Tree
117 if let tree = commit.tree, !tree.entries.results.isEmpty {
118 sectionDivider
119 treeSection(tree.entries.results)
120 }
121 }
122 }
123 .navigationDestination(for: ParentCommit.self) { parent in
124 CommitDetailView(
125 commitSummary: CommitSummary(
126 id: parent.id,
127 shortId: parent.shortId,
128 author: CommitAuthor(name: parent.author.name, email: nil, time: .now),
129 message: ""
130 ),
131 repository: repository
132 )
133 }
88 commitBody(commit)
13489 }
13590 }
13691
@@ -362,4 +317,54 @@ struct CommitDetailView: View {
362317 default: return .secondary
363318 }
364319 }
320
321 @ViewBuilder
322 private func commitBody(_ commit: CommitDetail) -> some View {
323 ScrollView {
324 LazyVStack(alignment: .leading, spacing: 0) {
325 // Header
326 commitHeader(commit)
327
328 sectionDivider
329
330 // Message
331 commitMessage(commit)
332
333 // Trailers
334 if !commit.trailers.isEmpty {
335 sectionDivider
336 trailersSection(commit.trailers)
337 }
338
339 // Parents
340 if !commit.parents.isEmpty {
341 sectionDivider
342 parentsSection(commit.parents)
343 }
344
345 // Diff
346 if let diff = commit.diff, !diff.isEmpty {
347 sectionDivider
348 diffSection(diff)
349 }
350
351 // Tree
352 if let tree = commit.tree, !tree.entries.results.isEmpty {
353 sectionDivider
354 treeSection(tree.entries.results)
355 }
356 }
357 }
358 .navigationDestination(for: ParentCommit.self) { parent in
359 CommitDetailView(
360 commitSummary: CommitSummary(
361 id: parent.id,
362 shortId: parent.shortId,
363 author: CommitAuthor(name: parent.author.name, email: nil, time: .now),
364 message: ""
365 ),
366 repository: repository
367 )
368 }
369 }
365370}
Hutch/Views/Repositories/FileTreeView.swift +3 −23
@@ -321,21 +321,21 @@ private struct FileTreeContentView: View {
321321
322322 private func fileActionToolbar(text: String) -> some View {
323323 HStack(spacing: 0) {
324 toolbarButton(
324 BottomToolbarButton(
325325 title: "Share",
326326 systemImage: "square.and.arrow.up"
327327 ) {
328328 shareFileContents(text)
329329 }
330330
331 toolbarButton(
331 BottomToolbarButton(
332332 title: didCopyFileContents ? "Copied" : "Copy All",
333333 systemImage: didCopyFileContents ? "checkmark" : "doc.on.doc"
334334 ) {
335335 copyFileContents(text)
336336 }
337337
338 toolbarButton(
338 BottomToolbarButton(
339339 title: wrapRepositoryFileLines ? "Wrap On" : "Wrap Off",
340340 systemImage: "text.word.spacing"
341341 ) {
@@ -350,26 +350,6 @@ private struct FileTreeContentView: View {
350350 Divider()
351351 }
352352 }
353
354 private func toolbarButton(
355 title: String,
356 systemImage: String,
357 action: @escaping () -> Void
358 ) -> some View {
359 Button(action: action) {
360 VStack(spacing: 4) {
361 Image(systemName: systemImage)
362 .font(.system(size: 17, weight: .semibold))
363 Text(title)
364 .font(.caption2)
365 .lineLimit(1)
366 }
367 .frame(maxWidth: .infinity)
368 .contentShape(Rectangle())
369 }
370 .buttonStyle(.plain)
371 .foregroundStyle(.primary)
372 }
373353}
374354
375355struct CodeFileTextView: UIViewRepresentable {
Hutch/Views/Repositories/HgRepositoryDetailView.swift +4 −24
@@ -622,7 +622,7 @@ struct HgRepositoryDetailView: View {
622622
623623 private func fileActionToolbar(fileContent: String, viewModel: HgRepositoryDetailViewModel) -> some View {
624624 HStack(spacing: 0) {
625 toolbarButton(
625 BottomToolbarButton(
626626 title: "Share",
627627 systemImage: "square.and.arrow.up"
628628 ) {
@@ -633,21 +633,21 @@ struct HgRepositoryDetailView: View {
633633 }
634634 }
635635
636 toolbarButton(
636 BottomToolbarButton(
637637 title: didCopyFileContents ? "Copied" : "Copy All",
638638 systemImage: didCopyFileContents ? "checkmark" : "doc.on.doc"
639639 ) {
640640 copyFileContents(fileContent)
641641 }
642642
643 toolbarButton(
643 BottomToolbarButton(
644644 title: wrapRepositoryFileLines ? "Wrap On" : "Wrap Off",
645645 systemImage: "text.word.spacing"
646646 ) {
647647 wrapRepositoryFileLines.toggle()
648648 }
649649
650 toolbarButton(
650 BottomToolbarButton(
651651 title: "Back",
652652 systemImage: "chevron.left"
653653 ) {
@@ -662,26 +662,6 @@ struct HgRepositoryDetailView: View {
662662 Divider()
663663 }
664664 }
665
666 private func toolbarButton(
667 title: String,
668 systemImage: String,
669 action: @escaping () -> Void
670 ) -> some View {
671 Button(action: action) {
672 VStack(spacing: 4) {
673 Image(systemName: systemImage)
674 .font(.system(size: 17, weight: .semibold))
675 Text(title)
676 .font(.caption2)
677 .lineLimit(1)
678 }
679 .frame(maxWidth: .infinity)
680 .contentShape(Rectangle())
681 }
682 .buttonStyle(.plain)
683 .foregroundStyle(.primary)
684 }
685665}
686666
687667private struct HgBrowseRefPickerSheet: View {
Hutch/Views/Repositories/HgRepositorySettingsView.swift +21 −46
@@ -11,22 +11,7 @@ struct HgRepositorySettingsView: View {
1111 @State private var pendingACLDeletion: HgACLEntry?
1212
1313 var body: some View {
14 NavigationStack {
15 Group {
16 if let viewModel {
17 settingsForm(viewModel)
18 } else {
19 SRHTLoadingStateView(message: "Loading settings…")
20 }
21 }
22 .navigationTitle("Settings")
23 .navigationBarTitleDisplayMode(.inline)
24 .toolbar {
25 ToolbarItem(placement: .cancellationAction) {
26 Button("Done") { dismiss() }
27 }
28 }
29 }
14 SettingsSheet(model: viewModel) { settingsForm($0) }
3015 .task {
3116 if viewModel == nil {
3217 let vm = HgRepositorySettingsViewModel(repository: repository, client: client)
@@ -38,6 +23,24 @@ struct HgRepositorySettingsView: View {
3823 }
3924 }
4025
26 private func saveInfoButton(_ viewModel: HgRepositorySettingsViewModel) -> some View {
27 Button {
28 Task {
29 _ = await viewModel.saveInfo()
30 }
31 } label: {
32 if viewModel.isSavingInfo {
33 ProgressView()
34 .frame(maxWidth: .infinity)
35 } else {
36 Text("Save Changes")
37 .frame(maxWidth: .infinity)
38 }
39 }
40 .disabled(viewModel.isSavingInfo || !viewModel.isInfoDirty)
41 .themedRow()
42 }
43
4144 @ViewBuilder
4245 private func settingsForm(_ viewModel: HgRepositorySettingsViewModel) -> some View {
4346 @Bindable var vm = viewModel
@@ -127,21 +130,7 @@ struct HgRepositorySettingsView: View {
127130 }
128131 .themedRow()
129132
130 Button {
131 Task {
132 _ = await viewModel.saveInfo()
133 }
134 } label: {
135 if viewModel.isSavingInfo {
136 ProgressView()
137 .frame(maxWidth: .infinity)
138 } else {
139 Text("Save Changes")
140 .frame(maxWidth: .infinity)
141 }
142 }
143 .disabled(viewModel.isSavingInfo || !viewModel.isInfoDirty)
144 .themedRow()
133 saveInfoButton(viewModel)
145134 }
146135 }
147136
@@ -220,21 +209,7 @@ struct HgRepositorySettingsView: View {
220209 .foregroundStyle(.secondary)
221210 .themedRow()
222211
223 Button {
224 Task {
225 _ = await viewModel.saveInfo()
226 }
227 } label: {
228 if viewModel.isSavingInfo {
229 ProgressView()
230 .frame(maxWidth: .infinity)
231 } else {
232 Text("Save Changes")
233 .frame(maxWidth: .infinity)
234 }
235 }
236 .disabled(viewModel.isSavingInfo || !viewModel.isInfoDirty)
237 .themedRow()
212 saveInfoButton(viewModel)
238213 }
239214 }
240215
Hutch/Views/Repositories/RepositoryListView.swift +22 −21
@@ -127,27 +127,28 @@ struct RepositoryListView: View {
127127 }
128128 }
129129 .overlay {
130 if viewModel.isLoading, viewModel.repositories.isEmpty {
131 SRHTLoadingStateView(message: "Loading repositories…")
132 } else if let error = viewModel.error, viewModel.repositories.isEmpty {
133 SRHTErrorStateView(
134 title: "Couldn't Load Repositories",
135 message: error,
136 retryAction: { await viewModel.loadRepositories() }
137 )
138 } else if viewModel.repositories.isEmpty, viewModel.error == nil {
139 if viewModel.searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
140 ContentUnavailableView(
141 "No Repositories",
142 systemImage: "book.closed",
143 description: Text("You don't have any repositories yet.")
144 )
145 } else {
146 ContentUnavailableView(
147 "No Repository Matches",
148 systemImage: "magnifyingglass",
149 description: Text("No repositories matched “\(viewModel.searchText)”.")
150 )
130 SRHTLoadStateView(
131 isLoading: viewModel.isLoading,
132 error: viewModel.error,
133 isEmpty: viewModel.repositories.isEmpty,
134 loadingMessage: "Loading repositories…",
135 errorTitle: "Couldn't Load Repositories",
136 retryAction: { await viewModel.loadRepositories() }
137 ) {
138 if viewModel.repositories.isEmpty, viewModel.error == nil {
139 if viewModel.searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
140 ContentUnavailableView(
141 "No Repositories",
142 systemImage: "book.closed",
143 description: Text("You don't have any repositories yet.")
144 )
145 } else {
146 ContentUnavailableView(
147 "No Repository Matches",
148 systemImage: "magnifyingglass",
149 description: Text("No repositories matched “\(viewModel.searchText)”.")
150 )
151 }
151152 }
152153 }
153154 }
Hutch/Views/Repositories/RepositoryListViewModel.swift +16 −69
@@ -384,39 +384,6 @@ final class RepositoryListViewModel {
384384 }
385385
386386 private static let emptyPage = Page(results: [], cursor: nil)
387
388 private struct RepositoryPayload: Decodable, Sendable {
389 let id: Int
390 let rid: String
391 let name: String
392 let description: String?
393 let visibility: Visibility
394 let updated: Date
395 let owner: Entity
396 let head: Reference?
397
398 enum CodingKeys: String, CodingKey {
399 case id, rid, name, description, visibility, updated, owner
400 case head = "HEAD"
401 }
402
403 func repositorySummary(service: SRHTService) -> RepositorySummary {
404 RepositorySummary(
405 fields: .init(
406 id: id,
407 rid: rid,
408 service: service,
409 name: name,
410 description: description,
411 visibility: visibility,
412 updated: updated,
413 owner: owner,
414 head: head
415 )
416 )
417 }
418 }
419
420387 private struct HGRepositoryPayload: Decodable, Sendable {
421388 let id: Int
422389 let rid: String
@@ -428,18 +395,20 @@ final class RepositoryListViewModel {
428395 let tip: HGTipReference?
429396
430397 func repositorySummary(service: SRHTService) -> RepositorySummary {
431 RepositorySummary(
432 fields: .init(
433 id: id,
434 rid: rid,
435 service: service,
436 name: name,
437 description: description,
438 visibility: visibility,
439 updated: updated,
440 owner: owner,
441 head: tip.map { Reference(name: $0.branch, target: nil) }
442 )
398 repositoryPayload.repositorySummary(service: service)
399 }
400
401 /// The shape the git API returns, with the tip's branch as HEAD.
402 var repositoryPayload: RepositoryPayload {
403 RepositoryPayload(
404 id: id,
405 rid: rid,
406 name: name,
407 description: description,
408 visibility: visibility,
409 updated: updated,
410 owner: owner,
411 head: tip.map { Reference(name: $0.branch, target: nil) }
443412 )
444413 }
445414 }
@@ -486,18 +455,7 @@ final class RepositoryListViewModel {
486455 )
487456 let result = cached.value
488457 return Page(
489 results: result.repositories?.results.map {
490 RepositoryPayload(
491 id: $0.id,
492 rid: $0.rid,
493 name: $0.name,
494 description: $0.description,
495 visibility: $0.visibility,
496 updated: $0.updated,
497 owner: $0.owner,
498 head: $0.tip.map { Reference(name: $0.branch, target: nil) }
499 )
500 } ?? [],
458 results: result.repositories?.results.map(\.repositoryPayload) ?? [],
501459 cursor: result.repositories?.cursor
502460 )
503461 }
@@ -522,18 +480,7 @@ final class RepositoryListViewModel {
522480 responseType: HGRepositoriesResponse.self
523481 )
524482 return Page(
525 results: result.repositories?.results.map {
526 RepositoryPayload(
527 id: $0.id,
528 rid: $0.rid,
529 name: $0.name,
530 description: $0.description,
531 visibility: $0.visibility,
532 updated: $0.updated,
533 owner: $0.owner,
534 head: $0.tip.map { Reference(name: $0.branch, target: nil) }
535 )
536 } ?? [],
483 results: result.repositories?.results.map(\.repositoryPayload) ?? [],
537484 cursor: result.repositories?.cursor
538485 )
539486 }
Hutch/Views/Repositories/RepositorySettingsView.swift +1 −16
@@ -13,22 +13,7 @@ struct RepositorySettingsView: View {
1313 @State private var showDeleteConfirmation = false
1414
1515 var body: some View {
16 NavigationStack {
17 Group {
18 if let viewModel {
19 settingsForm(viewModel)
20 } else {
21 SRHTLoadingStateView(message: "Loading settings…")
22 }
23 }
24 .navigationTitle("Settings")
25 .navigationBarTitleDisplayMode(.inline)
26 .toolbar {
27 ToolbarItem(placement: .cancellationAction) {
28 Button("Done") { dismiss() }
29 }
30 }
31 }
16 SettingsSheet(model: viewModel) { settingsForm($0) }
3217 .task {
3318 if viewModel == nil {
3419 viewModel = RepositorySettingsViewModel(
Hutch/Views/Settings/SettingsViewModel.swift +22 −34
@@ -19,6 +19,26 @@ private struct UpdatedUser: Decodable, Sendable {
1919 let avatar: String?
2020}
2121
22private extension UserProfile {
23 /// This profile with the fields an update returns; the avatar is kept when the update has none.
24 func applying(_ updated: UpdatedUser) -> UserProfile {
25 UserProfile(
26 username: username,
27 canonicalName: canonicalName,
28 email: updated.email,
29 url: updated.url,
30 location: updated.location,
31 bio: updated.bio,
32 avatar: updated.avatar ?? avatar,
33 userType: userType,
34 sshKeys: sshKeys,
35 pgpKeys: pgpKeys,
36 paymentStatus: paymentStatus,
37 subscription: subscription
38 )
39 }
40}
41
2242private struct CreateSSHKeyResponse: Decodable, Sendable {
2343 let createSSHKey: SSHKey
2444}
@@ -208,23 +228,7 @@ final class SettingsViewModel {
208228 variables: ["input": input],
209229 responseType: UpdateUserResponse.self
210230 )
211 let updated = result.updateUser
212 if let p = profile {
213 profile = UserProfile(
214 username: p.username,
215 canonicalName: p.canonicalName,
216 email: updated.email,
217 url: updated.url,
218 location: updated.location,
219 bio: updated.bio,
220 avatar: updated.avatar ?? p.avatar,
221 userType: p.userType,
222 sshKeys: p.sshKeys,
223 pgpKeys: p.pgpKeys,
224 paymentStatus: p.paymentStatus,
225 subscription: p.subscription
226 )
227 }
231 profile = profile?.applying(result.updateUser)
228232 isEditingProfile = false
229233 } catch {
230234 self.error = error.userFacingMessage
@@ -256,23 +260,7 @@ final class SettingsViewModel {
256260 ),
257261 responseType: UpdateUserResponse.self
258262 )
259 let updated = result.updateUser
260 if let p = profile {
261 profile = UserProfile(
262 username: p.username,
263 canonicalName: p.canonicalName,
264 email: updated.email,
265 url: updated.url,
266 location: updated.location,
267 bio: updated.bio,
268 avatar: updated.avatar ?? p.avatar,
269 userType: p.userType,
270 sshKeys: p.sshKeys,
271 pgpKeys: p.pgpKeys,
272 paymentStatus: p.paymentStatus,
273 subscription: p.subscription
274 )
275 }
263 profile = profile?.applying(result.updateUser)
276264 } catch {
277265 self.error = error.userFacingMessage
278266 }
Hutch/Views/Shared/BottomToolbarButton.swift added +24
@@ -0,0 +1,24 @@
1import SwiftUI
2
3/// An icon over a short title, filling its share of a bottom toolbar.
4struct BottomToolbarButton: View {
5 let title: String
6 let systemImage: String
7 let action: () -> Void
8
9 var body: some View {
10 Button(action: action) {
11 VStack(spacing: 4) {
12 Image(systemName: systemImage)
13 .font(.system(size: 17, weight: .semibold))
14 Text(title)
15 .font(.caption2)
16 .lineLimit(1)
17 }
18 .frame(maxWidth: .infinity)
19 .contentShape(Rectangle())
20 }
21 .buttonStyle(.plain)
22 .foregroundStyle(.primary)
23 }
24}
Hutch/Views/Shared/SettingsSheet.swift added +28
@@ -0,0 +1,28 @@
1import SwiftUI
2
3/// A settings sheet: a loading state until `model` exists, then `form` for it, with Done to dismiss.
4struct SettingsSheet<Model, Form: View>: View {
5 let model: Model?
6 @ViewBuilder let form: (Model) -> Form
7
8 @Environment(\.dismiss) private var dismiss
9
10 var body: some View {
11 NavigationStack {
12 Group {
13 if let model {
14 form(model)
15 } else {
16 SRHTLoadingStateView(message: "Loading settings…")
17 }
18 }
19 .navigationTitle("Settings")
20 .navigationBarTitleDisplayMode(.inline)
21 .toolbar {
22 ToolbarItem(placement: .cancellationAction) {
23 Button("Done") { dismiss() }
24 }
25 }
26 }
27 }
28}
Hutch/Views/Tickets/TicketDetailView.swift +82 −71
@@ -216,86 +216,58 @@ struct TicketDetailView: View {
216216 private func detailContent(_ viewModel: TicketDetailViewModel) -> some View {
217217 @Bindable var vm = viewModel
218218
219 if viewModel.isLoading, viewModel.ticket == nil {
220 SRHTLoadingStateView(message: "Loading ticket…")
221 } else if let error = viewModel.error, viewModel.ticket == nil {
222 SRHTErrorStateView(
223 title: "Couldn't Load Ticket",
224 message: error,
225 retryAction: { await reloadDetail(viewModel) }
226 )
227 } else if let ticket = viewModel.ticket {
228 ScrollView {
229 VStack(alignment: .leading, spacing: 0) {
230 if let cacheMetadata = viewModel.cacheMetadata {
231 StaleCacheStatusRow(metadata: cacheMetadata, isRefreshing: viewModel.isRefreshingCachedData)
232 .padding(.horizontal)
233 .padding(.vertical, 8)
234 }
235
236 // Header
237 ticketHeader(ticket, viewModel: viewModel)
238
239 Divider()
240 .padding(.vertical, 12)
219 SRHTLoadStateView(
220 isLoading: viewModel.isLoading,
221 error: viewModel.error,
222 isEmpty: viewModel.ticket == nil,
223 loadingMessage: "Loading ticket…",
224 errorTitle: "Couldn't Load Ticket",
225 retryAction: { await reloadDetail(viewModel) }
226 ) {
227 if let ticket = viewModel.ticket {
228 ScrollView {
229 VStack(alignment: .leading, spacing: 0) {
230 if let cacheMetadata = viewModel.cacheMetadata {
231 StaleCacheStatusRow(metadata: cacheMetadata, isRefreshing: viewModel.isRefreshingCachedData)
232 .padding(.horizontal)
233 .padding(.vertical, 8)
234 }
241235
242 // Description
243 if let description = ticket.description, !description.isEmpty {
244 MarkdownContentView(markdown: description)
245 .padding(.horizontal)
246 .padding(.bottom, 16)
236 // Header
237 ticketHeader(ticket, viewModel: viewModel)
247238
248239 Divider()
249 .padding(.bottom, 12)
250 }
240 .padding(.vertical, 12)
251241
252 // Event timeline
253 if !viewModel.events.isEmpty {
254 Text("Activity")
255 .font(.headline)
256 .padding(.horizontal)
257 .padding(.bottom, 8)
258
259 LazyVStack(alignment: .leading, spacing: 0) {
260 ForEach(viewModel.events) { event in
261 EventRow(
262 event: event,
263 ticketSubmitter: viewModel.ticket?.submitter.canonicalName,
264 ticketAssignees: viewModel.ticket?.assignees.map { $0.canonicalName }
265 )
266 if event.id != viewModel.events.last?.id {
267 Divider()
268 .padding(.leading, 40)
269 }
270 }
271 }
242 // Description
243 descriptionSection(ticket)
272244
273 Divider()
274 .padding(.vertical, 12)
275 }
245 // Event timeline
246 eventsSection(viewModel)
276247
277 if appState.isDebugModeEnabled {
278 Divider()
279 .padding(.vertical, 12)
248 if appState.isDebugModeEnabled {
249 Divider()
250 .padding(.vertical, 12)
280251
281 debugSection(viewModel: viewModel, ticket: ticket)
282 }
252 debugSection(viewModel: viewModel, ticket: ticket)
253 }
283254
284 commentInput(viewModel)
255 commentInput(viewModel)
256 }
257 }
258 .task(id: ticket.id) {
259 RecentActivityStore.recordTicket(
260 ownerUsername: ownerUsername,
261 trackerName: trackerName,
262 ticketId: ticket.id,
263 title: ticket.title,
264 defaults: appState.accountDefaults
265 )
266 }
267 .srhtErrorBanner(error: $vm.error)
268 .refreshable {
269 await reloadDetail(viewModel)
285270 }
286 }
287 .task(id: ticket.id) {
288 RecentActivityStore.recordTicket(
289 ownerUsername: ownerUsername,
290 trackerName: trackerName,
291 ticketId: ticket.id,
292 title: ticket.title,
293 defaults: appState.accountDefaults
294 )
295 }
296 .srhtErrorBanner(error: $vm.error)
297 .refreshable {
298 await reloadDetail(viewModel)
299271 }
300272 }
301273 }
@@ -528,6 +500,45 @@ struct TicketDetailView: View {
528500 await viewModel.loadTicket()
529501 }
530502 }
503
504 @ViewBuilder
505 private func eventsSection(_ viewModel: TicketDetailViewModel) -> some View {
506 if !viewModel.events.isEmpty {
507 Text("Activity")
508 .font(.headline)
509 .padding(.horizontal)
510 .padding(.bottom, 8)
511
512 LazyVStack(alignment: .leading, spacing: 0) {
513 ForEach(viewModel.events) { event in
514 EventRow(
515 event: event,
516 ticketSubmitter: viewModel.ticket?.submitter.canonicalName,
517 ticketAssignees: viewModel.ticket?.assignees.map { $0.canonicalName }
518 )
519 if event.id != viewModel.events.last?.id {
520 Divider()
521 .padding(.leading, 40)
522 }
523 }
524 }
525
526 Divider()
527 .padding(.vertical, 12)
528 }
529 }
530
531 @ViewBuilder
532 private func descriptionSection(_ ticket: TicketDetail) -> some View {
533 if let description = ticket.description, !description.isEmpty {
534 MarkdownContentView(markdown: description)
535 .padding(.horizontal)
536 .padding(.bottom, 16)
537
538 Divider()
539 .padding(.bottom, 12)
540 }
541 }
531542}
532543
533544// MARK: - Self-Sizing Markdown Web View
Hutch/Views/Tickets/TicketDetailViewModel.swift +9 −26
@@ -82,11 +82,11 @@ private struct UnassignUserResponse: Decodable, Sendable {
8282 let unassignUser: MutationEventResponse
8383}
8484
85private struct LabelTicketResponse: Decodable, Sendable {
85private nonisolated struct LabelTicketResponse: Decodable, Sendable {
8686 let labelTicket: MutationEventResponse
8787}
8888
89private struct UnlabelTicketResponse: Decodable, Sendable {
89private nonisolated struct UnlabelTicketResponse: Decodable, Sendable {
9090 let unlabelTicket: MutationEventResponse
9191}
9292
@@ -723,31 +723,14 @@ final class TicketDetailViewModel {
723723 }
724724
725725 func labelTicket(labelId: Int) async {
726 guard !isPerformingAction else { return }
727 isPerformingAction = true
728 error = nil
729
730 do {
731 _ = try await client.execute(
732 service: .todo,
733 query: Self.labelTicketMutation,
734 variables: [
735 "trackerId": trackerId,
736 "ticketId": ticketId,
737 "labelId": labelId
738 ],
739 responseType: LabelTicketResponse.self
740 )
741 await invalidateAfterMutation()
742 await reloadTicketPreservingDebugState()
743 } catch {
744 self.error = error.userFacingMessage
745 }
746
747 isPerformingAction = false
726 await runLabelMutation(Self.labelTicketMutation, labelId: labelId, response: LabelTicketResponse.self)
748727 }
749728
750729 func unlabelTicket(labelId: Int) async {
730 await runLabelMutation(Self.unlabelTicketMutation, labelId: labelId, response: UnlabelTicketResponse.self)
731 }
732
733 private func runLabelMutation<Response: Decodable & Sendable>(_ query: String, labelId: Int, response: Response.Type) async {
751734 guard !isPerformingAction else { return }
752735 isPerformingAction = true
753736 error = nil
@@ -755,13 +738,13 @@ final class TicketDetailViewModel {
755738 do {
756739 _ = try await client.execute(
757740 service: .todo,
758 query: Self.unlabelTicketMutation,
741 query: query,
759742 variables: [
760743 "trackerId": trackerId,
761744 "ticketId": ticketId,
762745 "labelId": labelId
763746 ],
764 responseType: UnlabelTicketResponse.self
747 responseType: response
765748 )
766749 await invalidateAfterMutation()
767750 await reloadTicketPreservingDebugState()
Hutch/Views/Tickets/TicketListView.swift +95 −84
@@ -283,68 +283,7 @@ struct TicketListView: View {
283283 .listRowSeparator(.hidden)
284284
285285 ForEach(viewModel.filteredTickets) { ticket in
286 Group {
287 if viewModel.isSelectionMode {
288 Button {
289 viewModel.toggleTicketSelection(ticket)
290 } label: {
291 SelectableTicketRow(
292 ticket: ticket,
293 isSelected: viewModel.selectedTicketIDs.contains(ticket.id)
294 )
295 .equatable()
296 }
297 .buttonStyle(.plain)
298 } else {
299 NavigationLink {
300 TicketDetailView(
301 ownerUsername: String(tracker.owner.canonicalName.dropFirst()),
302 trackerName: tracker.name,
303 trackerId: tracker.id,
304 trackerRid: tracker.rid,
305 ticketId: ticket.id
306 )
307 } label: {
308 TicketRowView(ticket: ticket)
309 .equatable()
310 }
311 .contextMenu {
312 if let url = SRHTWebURL.ticket(ownerUsername: ownerUsername(for: tracker), trackerName: tracker.name, ticketId: ticket.id) {
313 Button {
314 openURL(url)
315 } label: {
316 Label("Open in Browser", systemImage: "safari")
317 }
318
319 Button {
320 appState.copyToPasteboard(url.absoluteString, label: "ticket URL")
321 } label: {
322 Label("Copy URL", systemImage: "doc.on.doc")
323 }
324 }
325
326 Button {
327 appState.copyToPasteboard(String(ticket.id), label: "ticket ID")
328 } label: {
329 Label("Copy Ticket ID", systemImage: "number")
330 }
331 }
332 .swipeActions(edge: .leading, allowsFullSwipe: true) {
333 if swipeActionsEnabled {
334 ticketAssignSwipeAction(ticket, viewModel: viewModel)
335 }
336 }
337 .swipeActions(edge: .trailing, allowsFullSwipe: false) {
338 if swipeActionsEnabled {
339 ticketStatusSwipeAction(ticket, viewModel: viewModel)
340 ticketLabelSwipeAction(ticket, viewModel: viewModel)
341 }
342 }
343 }
344 }
345 .task {
346 await viewModel.loadMoreIfNeeded(currentItem: ticket)
347 }
286 ticketRow(ticket, viewModel)
348287 }
349288 .themedRow()
350289
@@ -385,28 +324,7 @@ struct TicketListView: View {
385324 viewModel.recordRecentSearch(query)
386325 }
387326 .overlay {
388 if viewModel.isLoading, viewModel.tickets.isEmpty {
389 SRHTLoadingStateView(message: "Loading tickets…")
390 } else if let error = viewModel.error, viewModel.tickets.isEmpty {
391 SRHTErrorStateView(
392 title: "Couldn't Load Tickets",
393 message: error,
394 retryAction: { await viewModel.loadTickets() }
395 )
396 } else if !viewModel.searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
397 viewModel.filteredTickets.isEmpty {
398 ContentUnavailableView(
399 "No Ticket Matches",
400 systemImage: "magnifyingglass",
401 description: Text("No tickets in \(tracker.name) matched “\(viewModel.searchText)”.")
402 )
403 } else if viewModel.filteredTickets.isEmpty, viewModel.error == nil {
404 ContentUnavailableView(
405 "No Tickets",
406 systemImage: "ticket",
407 description: Text(emptyStateDescription(for: viewModel))
408 )
409 }
327 emptyState(viewModel)
410328 }
411329 .connectivityOverlay(hasContent: !viewModel.filteredTickets.isEmpty) {
412330 await viewModel.loadTickets()
@@ -636,6 +554,99 @@ struct TicketListView: View {
636554 let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
637555 return trimmed.hasPrefix("~") ? String(trimmed.dropFirst()) : trimmed
638556 }
557
558 @ViewBuilder
559 private func emptyState(_ viewModel: TicketListViewModel) -> some View {
560 SRHTLoadStateView(
561 isLoading: viewModel.isLoading,
562 error: viewModel.error,
563 isEmpty: viewModel.tickets.isEmpty,
564 loadingMessage: "Loading tickets…",
565 errorTitle: "Couldn't Load Tickets",
566 retryAction: { await viewModel.loadTickets() }
567 ) {
568 if !viewModel.searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
569 viewModel.filteredTickets.isEmpty {
570 ContentUnavailableView(
571 "No Ticket Matches",
572 systemImage: "magnifyingglass",
573 description: Text("No tickets in \(tracker.name) matched “\(viewModel.searchText)”.")
574 )
575 } else if viewModel.filteredTickets.isEmpty, viewModel.error == nil {
576 ContentUnavailableView(
577 "No Tickets",
578 systemImage: "ticket",
579 description: Text(emptyStateDescription(for: viewModel))
580 )
581 }
582 }
583 }
584
585 @ViewBuilder
586 private func ticketRow(_ ticket: TicketSummary, _ viewModel: TicketListViewModel) -> some View {
587 Group {
588 if viewModel.isSelectionMode {
589 Button {
590 viewModel.toggleTicketSelection(ticket)
591 } label: {
592 SelectableTicketRow(
593 ticket: ticket,
594 isSelected: viewModel.selectedTicketIDs.contains(ticket.id)
595 )
596 .equatable()
597 }
598 .buttonStyle(.plain)
599 } else {
600 NavigationLink {
601 TicketDetailView(
602 ownerUsername: String(tracker.owner.canonicalName.dropFirst()),
603 trackerName: tracker.name,
604 trackerId: tracker.id,
605 trackerRid: tracker.rid,
606 ticketId: ticket.id
607 )
608 } label: {
609 TicketRowView(ticket: ticket)
610 .equatable()
611 }
612 .contextMenu {
613 if let url = SRHTWebURL.ticket(ownerUsername: ownerUsername(for: tracker), trackerName: tracker.name, ticketId: ticket.id) {
614 Button {
615 openURL(url)
616 } label: {
617 Label("Open in Browser", systemImage: "safari")
618 }
619
620 Button {
621 appState.copyToPasteboard(url.absoluteString, label: "ticket URL")
622 } label: {
623 Label("Copy URL", systemImage: "doc.on.doc")
624 }
625 }
626
627 Button {
628 appState.copyToPasteboard(String(ticket.id), label: "ticket ID")
629 } label: {
630 Label("Copy Ticket ID", systemImage: "number")
631 }
632 }
633 .swipeActions(edge: .leading, allowsFullSwipe: true) {
634 if swipeActionsEnabled {
635 ticketAssignSwipeAction(ticket, viewModel: viewModel)
636 }
637 }
638 .swipeActions(edge: .trailing, allowsFullSwipe: false) {
639 if swipeActionsEnabled {
640 ticketStatusSwipeAction(ticket, viewModel: viewModel)
641 ticketLabelSwipeAction(ticket, viewModel: viewModel)
642 }
643 }
644 }
645 }
646 .task {
647 await viewModel.loadMoreIfNeeded(currentItem: ticket)
648 }
649 }
639650}
640651
641652private struct LabelEditorTicket: Identifiable {
Hutch/Views/Tickets/TicketListViewModel.swift +26 −66
@@ -15,7 +15,7 @@ private struct TicketsPage: Decodable, Sendable {
1515 let cursor: String?
1616}
1717
18private struct AssignmentMutationResponse: Decodable, Sendable {
18private nonisolated struct AssignmentMutationResponse: Decodable, Sendable {
1919 struct EventRef: Decodable, Sendable {
2020 let id: Int
2121 }
@@ -24,7 +24,7 @@ private struct AssignmentMutationResponse: Decodable, Sendable {
2424 let unassignUser: EventRef?
2525}
2626
27private struct LabelMutationResponse: Decodable, Sendable {
27private nonisolated struct LabelMutationResponse: Decodable, Sendable {
2828 struct EventRef: Decodable, Sendable {
2929 let id: Int
3030 }
@@ -499,22 +499,7 @@ final class TicketListViewModel {
499499 tickets[index] = updated
500500 }
501501
502 do {
503 _ = try await client.execute(
504 service: .todo,
505 query: Self.assignUserMutation,
506 variables: [
507 "trackerId": trackerId,
508 "ticketId": ticket.id,
509 "userId": user.id
510 ],
511 responseType: AssignmentMutationResponse.self
512 )
513 await invalidateTicketCaches()
514 } catch {
515 tickets = original
516 self.error = error.userFacingMessage
517 }
502 await commitTicketMutation(Self.assignUserMutation, ticketID: ticket.id, subject: ["userId": user.id], response: AssignmentMutationResponse.self, original: original)
518503
519504 isPerformingAction = false
520505 }
@@ -542,22 +527,7 @@ final class TicketListViewModel {
542527 tickets[index] = updated
543528 }
544529
545 do {
546 _ = try await client.execute(
547 service: .todo,
548 query: Self.unassignUserMutation,
549 variables: [
550 "trackerId": trackerId,
551 "ticketId": ticket.id,
552 "userId": user.id
553 ],
554 responseType: AssignmentMutationResponse.self
555 )
556 await invalidateTicketCaches()
557 } catch {
558 tickets = original
559 self.error = error.userFacingMessage
560 }
530 await commitTicketMutation(Self.unassignUserMutation, ticketID: ticket.id, subject: ["userId": user.id], response: AssignmentMutationResponse.self, original: original)
561531
562532 isPerformingAction = false
563533 }
@@ -743,22 +713,7 @@ final class TicketListViewModel {
743713 tickets[index] = updated
744714 }
745715
746 do {
747 _ = try await client.execute(
748 service: .todo,
749 query: Self.labelTicketMutation,
750 variables: [
751 "trackerId": trackerId,
752 "ticketId": ticket.id,
753 "labelId": label.id
754 ],
755 responseType: LabelMutationResponse.self
756 )
757 await invalidateTicketCaches()
758 } catch {
759 tickets = original
760 self.error = error.userFacingMessage
761 }
716 await commitTicketMutation(Self.labelTicketMutation, ticketID: ticket.id, subject: ["labelId": label.id], response: LabelMutationResponse.self, original: original)
762717
763718 isPerformingAction = false
764719 }
@@ -784,22 +739,7 @@ final class TicketListViewModel {
784739 tickets[index] = updated
785740 }
786741
787 do {
788 _ = try await client.execute(
789 service: .todo,
790 query: Self.unlabelTicketMutation,
791 variables: [
792 "trackerId": trackerId,
793 "ticketId": ticket.id,
794 "labelId": label.id
795 ],
796 responseType: LabelMutationResponse.self
797 )
798 await invalidateTicketCaches()
799 } catch {
800 tickets = original
801 self.error = error.userFacingMessage
802 }
742 await commitTicketMutation(Self.unlabelTicketMutation, ticketID: ticket.id, subject: ["labelId": label.id], response: LabelMutationResponse.self, original: original)
803743
804744 isPerformingAction = false
805745 }
@@ -1070,6 +1010,26 @@ final class TicketListViewModel {
10701010 )
10711011 }
10721012
1013 /// Sends an assignment or label mutation for one ticket, restoring `original`
1014 /// if it fails. `subject` is the user or label added or removed, e.g. `["userId": 7]`.
1015 private func commitTicketMutation<Response: Decodable & Sendable>(
1016 _ query: String,
1017 ticketID: Int,
1018 subject: [String: Int],
1019 response: Response.Type,
1020 original: [TicketSummary]
1021 ) async {
1022 var variables: [String: any Sendable] = ["trackerId": trackerId, "ticketId": ticketID]
1023 for (key, id) in subject { variables[key] = id }
1024 do {
1025 _ = try await client.execute(service: .todo, query: query, variables: variables, responseType: response)
1026 await invalidateTicketCaches()
1027 } catch {
1028 tickets = original
1029 self.error = error.userFacingMessage
1030 }
1031 }
1032
10731033 private func invalidateTicketCaches() async {
10741034 await client.invalidateCache(prefix: APICacheKeys.prefix(SRHTService.todo.rawValue, "tickets"))
10751035 await client.invalidateCache(prefix: APICacheKeys.prefix(SRHTService.todo.rawValue, "ticket"))
Hutch/Views/Tickets/TrackerListView.swift +18 −44
@@ -184,22 +184,23 @@ struct TrackerListView: View {
184184 prompt: "Search trackers"
185185 )
186186 .overlay {
187 if viewModel.isLoading, viewModel.trackers.isEmpty {
188 SRHTLoadingStateView(message: "Loading trackers…")
189 } else if let error = viewModel.error, viewModel.trackers.isEmpty {
190 SRHTErrorStateView(
191 title: "Couldn't Load Trackers",
192 message: error,
193 retryAction: { await viewModel.loadTrackers() }
194 )
195 } else if !viewModel.trackers.isEmpty, viewModel.filteredTrackers.isEmpty {
196 ContentUnavailableView.search(text: viewModel.searchText)
197 } else if viewModel.trackers.isEmpty, viewModel.error == nil {
198 ContentUnavailableView(
199 "No Trackers",
200 systemImage: "checklist",
201 description: Text("Your bug trackers will appear here.")
202 )
187 SRHTLoadStateView(
188 isLoading: viewModel.isLoading,
189 error: viewModel.error,
190 isEmpty: viewModel.trackers.isEmpty,
191 loadingMessage: "Loading trackers…",
192 errorTitle: "Couldn't Load Trackers",
193 retryAction: { await viewModel.loadTrackers() }
194 ) {
195 if !viewModel.trackers.isEmpty, viewModel.filteredTrackers.isEmpty {
196 ContentUnavailableView.search(text: viewModel.searchText)
197 } else if viewModel.trackers.isEmpty, viewModel.error == nil {
198 ContentUnavailableView(
199 "No Trackers",
200 systemImage: "checklist",
201 description: Text("Your bug trackers will appear here.")
202 )
203 }
203204 }
204205 }
205206 .connectivityOverlay(hasContent: !viewModel.trackers.isEmpty) {
@@ -235,34 +236,7 @@ private struct TrackerRowView: View {
235236 let tracker: TrackerSummary
236237
237238 var body: some View {
238 VStack(alignment: .leading, spacing: 4) {
239 HStack {
240 Text(tracker.name)
241 .font(.subheadline.weight(.medium))
242
243 Spacer()
244
245 VisibilityBadge(visibility: tracker.visibility)
246 }
247
248 if let owner = tracker.owner.canonicalName.split(separator: "~").last {
249 Text("~\(owner)")
250 .font(.caption)
251 .foregroundStyle(.secondary)
252 }
253
254 if let description = tracker.description, !description.isEmpty {
255 Text(description)
256 .font(.caption)
257 .foregroundStyle(.secondary)
258 .lineLimit(2)
259 }
260
261 Text(tracker.updated.relativeDescription)
262 .font(.caption2)
263 .foregroundStyle(.tertiary)
264 }
265 .padding(.vertical, 2)
239 TrackerSummaryRow(tracker: tracker)
266240 .contextMenu {
267241 if let url = SRHTWebURL.tracker(tracker) {
268242 Button {
Hutch/Views/Work/WorkView.swift +46 −47
@@ -183,46 +183,7 @@ struct WorkView: View {
183183 .themedRow()
184184 } else {
185185 ForEach(viewModel.assignedTickets) { ticket in
186 NavigationLink {
187 TicketDetailView(
188 ownerUsername: ticket.ownerUsername,
189 trackerName: ticket.trackerName,
190 trackerId: ticket.trackerId,
191 trackerRid: ticket.trackerRid,
192 ticketId: ticket.ticket.id
193 )
194 } label: {
195 WorkAssignedTicketRow(ticket: ticket)
196 }
197 .swipeActions(edge: .leading, allowsFullSwipe: true) {
198 if swipeActionsEnabled {
199 if ticket.ticket.status.isOpen {
200 Button {
201 Task { await viewModel.resolveTicket(ticket) }
202 } label: {
203 Label("Resolve", systemImage: "checkmark.circle")
204 }
205 .tint(.green)
206 } else {
207 Button {
208 Task { await viewModel.reopenTicket(ticket) }
209 } label: {
210 Label("Reopen", systemImage: "arrow.uturn.backward")
211 }
212 .tint(.blue)
213 }
214 }
215 }
216 .swipeActions(edge: .trailing, allowsFullSwipe: false) {
217 if swipeActionsEnabled {
218 Button {
219 Task { await viewModel.unassignFromMe(ticket) }
220 } label: {
221 Label("Unassign", systemImage: "person.badge.minus")
222 }
223 .tint(.orange)
224 }
225 }
186 assignedTicketRow(ticket, viewModel)
226187 }
227188 .themedRow()
228189 }
@@ -272,16 +233,54 @@ struct WorkView: View {
272233 return viewModel
273234 }
274235
275 let newViewModel = HomeViewModel(
276 currentUser: currentUser,
277 client: appState.client,
278 systemStatusRepository: appState.systemStatusRepository,
279 defaults: appState.accountDefaults,
280 accountID: appState.activeAccountID
281 )
236 let newViewModel = HomeViewModel(currentUser: currentUser, appState: appState)
282237 viewModel = newViewModel
283238 return newViewModel
284239 }
240
241 @ViewBuilder
242 private func assignedTicketRow(_ ticket: HomeAssignedTicket, _ viewModel: HomeViewModel) -> some View {
243 NavigationLink {
244 TicketDetailView(
245 ownerUsername: ticket.ownerUsername,
246 trackerName: ticket.trackerName,
247 trackerId: ticket.trackerId,
248 trackerRid: ticket.trackerRid,
249 ticketId: ticket.ticket.id
250 )
251 } label: {
252 WorkAssignedTicketRow(ticket: ticket)
253 }
254 .swipeActions(edge: .leading, allowsFullSwipe: true) {
255 if swipeActionsEnabled {
256 if ticket.ticket.status.isOpen {
257 Button {
258 Task { await viewModel.resolveTicket(ticket) }
259 } label: {
260 Label("Resolve", systemImage: "checkmark.circle")
261 }
262 .tint(.green)
263 } else {
264 Button {
265 Task { await viewModel.reopenTicket(ticket) }
266 } label: {
267 Label("Reopen", systemImage: "arrow.uturn.backward")
268 }
269 .tint(.blue)
270 }
271 }
272 }
273 .swipeActions(edge: .trailing, allowsFullSwipe: false) {
274 if swipeActionsEnabled {
275 Button {
276 Task { await viewModel.unassignFromMe(ticket) }
277 } label: {
278 Label("Unassign", systemImage: "person.badge.minus")
279 }
280 .tint(.orange)
281 }
282 }
283 }
285284}
286285
287286private struct WorkThreadRow: View {
HutchTests/OrgNativeRenderingTests.swift +1
@@ -1,5 +1,6 @@
11import Foundation
22import OrgSwiftUI
3import SwiftUI
34import Testing
45@testable import Hutch
56