Commit 886645fa08

886645fa082a86877fb509f1b7a11e2bee3b3084

parent: fa473b2f8c

Verified · cmc ci/accessibility: success

cmc <hello@cleberg.net> · 2026-10-23 05:35 UTC

Share more list, settings and profile pieces

- SearchableListState, LoadingMoreRow, ProgressButton, SegmentedTabs,
  SwipeDeleteButton and SwipeEditButton.
- Settings key mutations, notification preference toggles and tracker
  deletes each go through one helper.
- One LabelToggleRow; UserProfileViewModel.reusing for both profiles.
- References sections and load states use the shared views.

Layout: unified · split

Hutch/Extensions/ErrorViews.swift +32
@@ -180,3 +180,35 @@ struct SRHTLoadStateView<Content: View>: View {
180 } 180 }
181 } 181 }
182} 182}
183
184/// A searchable list's loading and error states, then no matches for the search, or nothing at all.
185struct SearchableListState: View {
186 let isLoading: Bool
187 let error: String?
188 let isEmpty: Bool
189 let hasMatches: Bool
190 let searchText: String
191 let loadingMessage: String
192 let errorTitle: String
193 let emptyTitle: LocalizedStringKey
194 let emptySystemImage: String
195 let emptyDescription: LocalizedStringKey
196 let retryAction: () async -> Void
197
198 var body: some View {
199 SRHTLoadStateView(
200 isLoading: isLoading,
201 error: error,
202 isEmpty: isEmpty,
203 loadingMessage: loadingMessage,
204 errorTitle: errorTitle,
205 retryAction: retryAction
206 ) {
207 if !isEmpty, !hasMatches {
208 ContentUnavailableView.search(text: searchText)
209 } else if isEmpty {
210 ContentUnavailableView(emptyTitle, systemImage: emptySystemImage, description: Text(emptyDescription))
211 }
212 }
213 }
214}
Hutch/Views/Builds/BuildListView.swift +1 −6
@@ -155,12 +155,7 @@ struct BuildListView: View {
155 .themedRow() 155 .themedRow()
156 156
157 if viewModel.isLoadingMore { 157 if viewModel.isLoadingMore {
158 HStack { 158 LoadingMoreRow()
159 Spacer()
160 ProgressView()
161 Spacer()
162 }
163 .listRowSeparator(.hidden)
164 .themedRow() 159 .themedRow()
165 } 160 }
166 } 161 }
Hutch/Views/Lists/MailingListListView.swift +7 −12
@@ -455,24 +455,19 @@ struct MailingListListView: View {
455 Text("This permanently deletes the list and its entire archive, for everyone. This cannot be undone.") 455 Text("This permanently deletes the list and its entire archive, for everyone. This cannot be undone.")
456 } 456 }
457 .overlay { 457 .overlay {
458 SRHTLoadStateView( 458 SearchableListState(
459 isLoading: viewModel.isLoading, 459 isLoading: viewModel.isLoading,
460 error: viewModel.error, 460 error: viewModel.error,
461 isEmpty: viewModel.mailingLists.isEmpty, 461 isEmpty: viewModel.mailingLists.isEmpty,
462 hasMatches: !viewModel.filteredMailingLists.isEmpty,
463 searchText: viewModel.searchText,
462 loadingMessage: "Loading mailing lists…", 464 loadingMessage: "Loading mailing lists…",
463 errorTitle: "Couldn't Load Mailing Lists", 465 errorTitle: "Couldn't Load Mailing Lists",
466 emptyTitle: "No Mailing Lists",
467 emptySystemImage: "list.bullet.rectangle",
468 emptyDescription: "Your subscribed mailing lists will appear here.",
464 retryAction: { await viewModel.loadMailingLists() } 469 retryAction: { await viewModel.loadMailingLists() }
465 ) { 470 )
466 if !viewModel.mailingLists.isEmpty, viewModel.filteredMailingLists.isEmpty {
467 ContentUnavailableView.search(text: viewModel.searchText)
468 } else if viewModel.mailingLists.isEmpty {
469 ContentUnavailableView(
470 "No Mailing Lists",
471 systemImage: "list.bullet.rectangle",
472 description: Text("Your subscribed mailing lists will appear here.")
473 )
474 }
475 }
476 } 471 }
477 .srhtErrorBanner(error: $vm.error) 472 .srhtErrorBanner(error: $vm.error)
478 .refreshable { 473 .refreshable {
Hutch/Views/Lookup/UserProfileView.swift +3 −17
@@ -215,23 +215,9 @@ struct UserProfileView: View {
215 : user.canonicalName 215 : user.canonicalName
216 let actor = user.canonicalName.hasPrefix("~") ? user.canonicalName : "~\(user.canonicalName)" 216 let actor = user.canonicalName.hasPrefix("~") ? user.canonicalName : "~\(user.canonicalName)"
217 217
218 let vm: UserProfileViewModel 218 let vm = UserProfileViewModel.reusing(profileViewModel, owner: owner, actor: actor, appState: appState)
219 if let existingViewModel = profileViewModel, 219 if vm !== profileViewModel {
220 existingViewModel.actor == actor, 220 profileViewModel = vm
221 existingViewModel.ownerUsername == owner {
222 vm = existingViewModel
223 } else {
224 let newViewModel = UserProfileViewModel(
225 ownerUsername: owner,
226 actor: actor,
227 client: appState.client,
228 statsService: HutchStatsService(
229 configuration: appState.configuration,
230 currentActor: appState.currentUser?.canonicalName
231 )
232 )
233 profileViewModel = newViewModel
234 vm = newViewModel
235 } 221 }
236 222
237 async let repos: () = vm.loadRepositories() 223 async let repos: () = vm.loadRepositories()
Hutch/Views/Lookup/UserProfileViewModel.swift +18
@@ -210,3 +210,21 @@ final class UserProfileViewModel {
210 } 210 }
211 211
212} 212}
213
214extension UserProfileViewModel {
215 /// `existing` when it already shows `owner` to `actor`, else a new model for them.
216 static func reusing(_ existing: UserProfileViewModel?, owner: String, actor: String, appState: AppState) -> UserProfileViewModel {
217 if let existing, existing.actor == actor, existing.ownerUsername == owner {
218 return existing
219 }
220 return UserProfileViewModel(
221 ownerUsername: owner,
222 actor: actor,
223 client: appState.client,
224 statsService: HutchStatsService(
225 configuration: appState.configuration,
226 currentActor: appState.currentUser?.canonicalName
227 )
228 )
229 }
230}
Hutch/Views/More/ProfileView.swift +3 −17
@@ -30,23 +30,9 @@ struct ProfileView: View {
30 : currentUser.canonicalName 30 : currentUser.canonicalName
31 let actor = currentUser.canonicalName.hasPrefix("~") ? currentUser.canonicalName : "~\(currentUser.canonicalName)" 31 let actor = currentUser.canonicalName.hasPrefix("~") ? currentUser.canonicalName : "~\(currentUser.canonicalName)"
32 32
33 let vm: UserProfileViewModel 33 let vm = UserProfileViewModel.reusing(contributionViewModel, owner: owner, actor: actor, appState: appState)
34 if let existingViewModel = contributionViewModel, 34 if vm !== contributionViewModel {
35 existingViewModel.actor == actor, 35 contributionViewModel = vm
36 existingViewModel.ownerUsername == owner {
37 vm = existingViewModel
38 } else {
39 let newViewModel = UserProfileViewModel(
40 ownerUsername: owner,
41 actor: actor,
42 client: appState.client,
43 statsService: HutchStatsService(
44 configuration: appState.configuration,
45 currentActor: appState.currentUser?.canonicalName
46 )
47 )
48 contributionViewModel = newViewModel
49 vm = newViewModel
50 } 36 }
51 37
52 await vm.loadContributions() 38 await vm.loadContributions()
Hutch/Views/Pastes/PasteListView.swift +9 −24
@@ -73,12 +73,7 @@ struct PasteListView: View {
73 } 73 }
74 .swipeActions(edge: .trailing, allowsFullSwipe: false) { 74 .swipeActions(edge: .trailing, allowsFullSwipe: false) {
75 if swipeActionsEnabled { 75 if swipeActionsEnabled {
76 Button { 76 SwipeDeleteButton { pasteToDelete = paste }
77 pasteToDelete = paste
78 } label: {
79 Label("Delete", systemImage: "trash")
80 }
81 .tint(.red)
82 } 77 }
83 } 78 }
84 .task { 79 .task {
@@ -88,12 +83,7 @@ struct PasteListView: View {
88 .themedRow() 83 .themedRow()
89 84
90 if viewModel.isLoadingMore { 85 if viewModel.isLoadingMore {
91 HStack { 86 LoadingMoreRow()
92 Spacer()
93 ProgressView()
94 Spacer()
95 }
96 .listRowSeparator(.hidden)
97 .themedRow() 87 .themedRow()
98 } 88 }
99 } 89 }
@@ -105,24 +95,19 @@ struct PasteListView: View {
105 prompt: "Search pastes" 95 prompt: "Search pastes"
106 ) 96 )
107 .overlay { 97 .overlay {
108 SRHTLoadStateView( 98 SearchableListState(
109 isLoading: viewModel.isLoading, 99 isLoading: viewModel.isLoading,
110 error: viewModel.error, 100 error: viewModel.error,
111 isEmpty: viewModel.pastes.isEmpty, 101 isEmpty: viewModel.pastes.isEmpty,
102 hasMatches: !viewModel.filteredPastes.isEmpty,
103 searchText: viewModel.searchText,
112 loadingMessage: "Loading pastes…", 104 loadingMessage: "Loading pastes…",
113 errorTitle: "Couldn't Load Pastes", 105 errorTitle: "Couldn't Load Pastes",
106 emptyTitle: "No Pastes",
107 emptySystemImage: "doc.on.clipboard",
108 emptyDescription: "Your pastes will appear here.",
114 retryAction: { await viewModel.loadPastes() } 109 retryAction: { await viewModel.loadPastes() }
115 ) { 110 )
116 if !viewModel.pastes.isEmpty, viewModel.filteredPastes.isEmpty {
117 ContentUnavailableView.search(text: viewModel.searchText)
118 } else if viewModel.pastes.isEmpty {
119 ContentUnavailableView(
120 "No Pastes",
121 systemImage: "doc.on.clipboard",
122 description: Text("Your pastes will appear here.")
123 )
124 }
125 }
126 } 111 }
127 .connectivityOverlay(hasContent: !viewModel.pastes.isEmpty) { 112 .connectivityOverlay(hasContent: !viewModel.pastes.isEmpty) {
128 await viewModel.loadPastes() 113 await viewModel.loadPastes()
Hutch/Views/Projects/DiscoverProjectsView.swift +1 −6
@@ -95,12 +95,7 @@ struct DiscoverProjectsView: View {
95 .themedRow() 95 .themedRow()
96 96
97 if viewModel.isLoadingMore { 97 if viewModel.isLoadingMore {
98 HStack { 98 LoadingMoreRow()
99 Spacer()
100 ProgressView()
101 Spacer()
102 }
103 .listRowSeparator(.hidden)
104 .themedRow() 99 .themedRow()
105 } 100 }
106 } 101 }
Hutch/Views/Projects/ProjectsListView.swift +7 −12
@@ -139,24 +139,19 @@ struct ProjectsListView: View {
139 prompt: "Search projects" 139 prompt: "Search projects"
140 ) 140 )
141 .overlay { 141 .overlay {
142 SRHTLoadStateView( 142 SearchableListState(
143 isLoading: viewModel.isLoading, 143 isLoading: viewModel.isLoading,
144 error: viewModel.error, 144 error: viewModel.error,
145 isEmpty: viewModel.projects.isEmpty, 145 isEmpty: viewModel.projects.isEmpty,
146 hasMatches: !viewModel.filteredProjects.isEmpty,
147 searchText: viewModel.searchText,
146 loadingMessage: "Loading projects…", 148 loadingMessage: "Loading projects…",
147 errorTitle: "Couldn't Load Projects", 149 errorTitle: "Couldn't Load Projects",
150 emptyTitle: "No Projects",
151 emptySystemImage: "square.stack.3d.up",
152 emptyDescription: "Projects from your SourceHut account will appear here when available.",
148 retryAction: { await viewModel.loadProjects() } 153 retryAction: { await viewModel.loadProjects() }
149 ) { 154 )
150 if !viewModel.projects.isEmpty, viewModel.filteredProjects.isEmpty {
151 ContentUnavailableView.search(text: viewModel.searchText)
152 } else if viewModel.projects.isEmpty {
153 ContentUnavailableView(
154 "No Projects",
155 systemImage: "square.stack.3d.up",
156 description: Text("Projects from your SourceHut account will appear here when available.")
157 )
158 }
159 }
160 } 155 }
161 .srhtErrorBanner( 156 .srhtErrorBanner(
162 error: Binding( 157 error: Binding(
Hutch/Views/Repositories/ArtifactsView.swift +20 −19
@@ -142,25 +142,26 @@ struct ArtifactsView: View {
142 } 142 }
143 } 143 }
144 .overlay { 144 .overlay {
145 if viewModel.isLoadingArtifacts, viewModel.referenceArtifacts.isEmpty { 145 SRHTLoadStateView(
146 SRHTLoadingStateView(message: "Loading artifacts…") 146 isLoading: viewModel.isLoadingArtifacts,
147 } else if let error = viewModel.error, viewModel.referenceArtifacts.isEmpty { 147 error: viewModel.error,
148 SRHTErrorStateView( 148 isEmpty: viewModel.referenceArtifacts.isEmpty,
149 title: "Couldn't Load Artifacts", 149 loadingMessage: "Loading artifacts…",
150 message: error, 150 errorTitle: "Couldn't Load Artifacts",
151 retryAction: { await viewModel.loadArtifacts() } 151 retryAction: { await viewModel.loadArtifacts() }
152 ) 152 ) {
153 } else if viewModel.referenceArtifacts.isEmpty { 153 if viewModel.referenceArtifacts.isEmpty {
154 // The overlay covers the whole list, so the upload row above is 154 // The overlay covers the whole list, so the upload row above is
155 // hidden underneath it — and a repository with no artifacts is 155 // hidden underneath it — and a repository with no artifacts is
156 // exactly the one that needs uploading. Offer it here too. 156 // exactly the one that needs uploading. Offer it here too.
157 ContentUnavailableView { 157 ContentUnavailableView {
158 SwiftUI.Label("No Artifacts", systemImage: "archivebox") 158 SwiftUI.Label("No Artifacts", systemImage: "archivebox")
159 } description: { 159 } description: {
160 Text("This repository has no release artifacts.") 160 Text("This repository has no release artifacts.")
161 } actions: { 161 } actions: {
162 if isOwnedByCurrentUser { 162 if isOwnedByCurrentUser {
163 uploadMenu 163 uploadMenu
164 }
164 } 165 }
165 } 166 }
166 } 167 }
Hutch/Views/Repositories/CommitLogView.swift +16 −20
@@ -16,32 +16,28 @@ struct CommitLogView: View {
16 .themedRow() 16 .themedRow()
17 17
18 if viewModel.isLoadingMoreCommits { 18 if viewModel.isLoadingMoreCommits {
19 HStack { 19 LoadingMoreRow()
20 Spacer()
21 ProgressView()
22 Spacer()
23 }
24 .listRowSeparator(.hidden)
25 .themedRow() 20 .themedRow()
26 } 21 }
27 } 22 }
28 .themedList() 23 .themedList()
29 .listStyle(.plain) 24 .listStyle(.plain)
30 .overlay { 25 .overlay {
31 if viewModel.isLoadingCommits, viewModel.commits.isEmpty { 26 SRHTLoadStateView(
32 SRHTLoadingStateView(message: "Loading commits…") 27 isLoading: viewModel.isLoadingCommits,
33 } else if let error = viewModel.error, viewModel.commits.isEmpty { 28 error: viewModel.error,
34 SRHTErrorStateView( 29 isEmpty: viewModel.commits.isEmpty,
35 title: "Couldn't Load Commits", 30 loadingMessage: "Loading commits…",
36 message: error, 31 errorTitle: "Couldn't Load Commits",
37 retryAction: { await viewModel.loadCommits() } 32 retryAction: { await viewModel.loadCommits() }
38 ) 33 ) {
39 } else if viewModel.commits.isEmpty { 34 if viewModel.commits.isEmpty {
40 ContentUnavailableView( 35 ContentUnavailableView(
41 "No Commits", 36 "No Commits",
42 systemImage: "clock.arrow.trianglehead.counterclockwise.rotate.90", 37 systemImage: "clock.arrow.trianglehead.counterclockwise.rotate.90",
43 description: Text("This repository has no commit history.") 38 description: Text("This repository has no commit history.")
44 ) 39 )
40 }
45 } 41 }
46 } 42 }
47 .task { 43 .task {
Hutch/Views/Repositories/HgRepositoryDetailView.swift +17 −30
@@ -182,16 +182,7 @@ struct HgRepositoryDetailView: View {
182 @ViewBuilder 182 @ViewBuilder
183 private func content(_ viewModel: HgRepositoryDetailViewModel) -> some View { 183 private func content(_ viewModel: HgRepositoryDetailViewModel) -> some View {
184 VStack(spacing: 0) { 184 VStack(spacing: 0) {
185 Picker("Tab", selection: $selectedTab) { 185 SegmentedTabs(selection: $selectedTab)
186 ForEach(HgRepositoryDetailViewModel.Tab.allCases, id: \.self) { tab in
187 Text(tab.rawValue).tag(tab)
188 }
189 }
190 .pickerStyle(.segmented)
191 .padding(.horizontal)
192 .padding(.vertical, 8)
193
194 Divider()
195 186
196 switch selectedTab { 187 switch selectedTab {
197 case .summary: 188 case .summary:
@@ -453,32 +444,28 @@ struct HgRepositoryDetailView: View {
453 .themedRow() 444 .themedRow()
454 445
455 if viewModel.isLoadingMoreLog { 446 if viewModel.isLoadingMoreLog {
456 HStack { 447 LoadingMoreRow()
457 Spacer()
458 ProgressView()
459 Spacer()
460 }
461 .listRowSeparator(.hidden)
462 .themedRow() 448 .themedRow()
463 } 449 }
464 } 450 }
465 .themedList() 451 .themedList()
466 .listStyle(.plain) 452 .listStyle(.plain)
467 .overlay { 453 .overlay {
468 if viewModel.isLoadingLog, viewModel.log.isEmpty { 454 SRHTLoadStateView(
469 SRHTLoadingStateView(message: "Loading revisions…") 455 isLoading: viewModel.isLoadingLog,
470 } else if let error = viewModel.error, viewModel.log.isEmpty { 456 error: viewModel.error,
471 SRHTErrorStateView( 457 isEmpty: viewModel.log.isEmpty,
472 title: "Couldn't Load Revisions", 458 loadingMessage: "Loading revisions…",
473 message: error, 459 errorTitle: "Couldn't Load Revisions",
474 retryAction: { await viewModel.loadLog() } 460 retryAction: { await viewModel.loadLog() }
475 ) 461 ) {
476 } else if viewModel.log.isEmpty { 462 if viewModel.log.isEmpty {
477 ContentUnavailableView( 463 ContentUnavailableView(
478 "No Revisions", 464 "No Revisions",
479 systemImage: "clock.arrow.trianglehead.counterclockwise.rotate.90", 465 systemImage: "clock.arrow.trianglehead.counterclockwise.rotate.90",
480 description: Text("This repository has no revision history.") 466 description: Text("This repository has no revision history.")
481 ) 467 )
468 }
482 } 469 }
483 } 470 }
484 .refreshable { 471 .refreshable {
Hutch/Views/Repositories/HgRepositorySettingsView.swift +2 −18
@@ -24,18 +24,10 @@ struct HgRepositorySettingsView: View {
24 } 24 }
25 25
26 private func saveInfoButton(_ viewModel: HgRepositorySettingsViewModel) -> some View { 26 private func saveInfoButton(_ viewModel: HgRepositorySettingsViewModel) -> some View {
27 Button { 27 ProgressButton("Save Changes", isWorking: viewModel.isSavingInfo) {
28 Task { 28 Task {
29 _ = await viewModel.saveInfo() 29 _ = await viewModel.saveInfo()
30 } 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 } 31 }
40 .disabled(viewModel.isSavingInfo || !viewModel.isInfoDirty) 32 .disabled(viewModel.isSavingInfo || !viewModel.isInfoDirty)
41 .themedRow() 33 .themedRow()
@@ -232,16 +224,8 @@ struct HgRepositorySettingsView: View {
232 @ViewBuilder 224 @ViewBuilder
233 private func deleteSection(_ viewModel: HgRepositorySettingsViewModel) -> some View { 225 private func deleteSection(_ viewModel: HgRepositorySettingsViewModel) -> some View {
234 Section { 226 Section {
235 Button(role: .destructive) { 227 ProgressButton("Delete Repository", isWorking: viewModel.isDeleting, role: .destructive) {
236 showDeleteConfirmation = true 228 showDeleteConfirmation = true
237 } label: {
238 if viewModel.isDeleting {
239 ProgressView()
240 .frame(maxWidth: .infinity)
241 } else {
242 Text("Delete Repository")
243 .frame(maxWidth: .infinity)
244 }
245 } 229 }
246 .disabled(viewModel.isDeleting) 230 .disabled(viewModel.isDeleting)
247 .themedRow() 231 .themedRow()
Hutch/Views/Repositories/ReferencesListView.swift +53 −44
@@ -6,58 +6,45 @@ struct ReferencesListView: View {
6 var body: some View { 6 var body: some View {
7 List { 7 List {
8 if let defaultBranch = viewModel.defaultBranchReference { 8 if let defaultBranch = viewModel.defaultBranchReference {
9 Section { 9 referenceSection(
10 ReferenceRow(reference: defaultBranch, prefix: "refs/heads/") 10 defaultBranch,
11 .themedRow() 11 header: "Default Branch",
12 12 seeAll: "See All Branches",
13 NavigationLink("See All Branches") { 13 title: "Branches",
14 ReferencesDetailListView( 14 references: viewModel.branches,
15 title: "Branches", 15 prefix: "refs/heads/"
16 references: viewModel.branches, 16 )
17 prefix: "refs/heads/"
18 )
19 }
20 .themedRow()
21 } header: {
22 sectionHeader(title: "Default Branch")
23 }
24 } 17 }
25 18
26 if let latestTag = viewModel.latestTagReference { 19 if let latestTag = viewModel.latestTagReference {
27 Section { 20 referenceSection(
28 ReferenceRow(reference: latestTag, prefix: "refs/tags/") 21 latestTag,
29 .themedRow() 22 header: "Latest Tag",
30 23 seeAll: "See All Tags",
31 NavigationLink("See All Tags") { 24 title: "Tags",
32 ReferencesDetailListView( 25 references: viewModel.tags,
33 title: "Tags", 26 prefix: "refs/tags/"
34 references: viewModel.tags, 27 )
35 prefix: "refs/tags/"
36 )
37 }
38 .themedRow()
39 } header: {
40 sectionHeader(title: "Latest Tag")
41 }
42 } 28 }
43 } 29 }
44 .themedList() 30 .themedList()
45 .listStyle(.insetGrouped) 31 .listStyle(.insetGrouped)
46 .overlay { 32 .overlay {
47 if viewModel.isLoadingRefs, viewModel.branches.isEmpty, viewModel.tags.isEmpty { 33 SRHTLoadStateView(
48 SRHTLoadingStateView(message: "Loading references…") 34 isLoading: viewModel.isLoadingRefs,
49 } else if let error = viewModel.error, viewModel.branches.isEmpty, viewModel.tags.isEmpty { 35 error: viewModel.error,
50 SRHTErrorStateView( 36 isEmpty: viewModel.branches.isEmpty && viewModel.tags.isEmpty,
51 title: "Couldn't Load References", 37 loadingMessage: "Loading references…",
52 message: error, 38 errorTitle: "Couldn't Load References",
53 retryAction: { await viewModel.loadReferences() } 39 retryAction: { await viewModel.loadReferences() }
54 ) 40 ) {
55 } else if viewModel.branches.isEmpty, viewModel.tags.isEmpty { 41 if viewModel.branches.isEmpty, viewModel.tags.isEmpty {
56 ContentUnavailableView( 42 ContentUnavailableView(
57 "No References", 43 "No References",
58 systemImage: "arrow.triangle.branch", 44 systemImage: "arrow.triangle.branch",
59 description: Text("This repository has no branches or tags.") 45 description: Text("This repository has no branches or tags.")
60 ) 46 )
47 }
61 } 48 }
62 } 49 }
63 .task { 50 .task {
@@ -71,6 +58,28 @@ struct ReferencesListView: View {
71 } 58 }
72 59
73 @ViewBuilder 60 @ViewBuilder
61 /// One reference with a link to all of its kind.
62 private func referenceSection(
63 _ reference: ReferenceDetail,
64 header: String,
65 seeAll: LocalizedStringKey,
66 title: String,
67 references: [ReferenceDetail],
68 prefix: String
69 ) -> some View {
70 Section {
71 ReferenceRow(reference: reference, prefix: prefix)
72 .themedRow()
73
74 NavigationLink(seeAll) {
75 ReferencesDetailListView(title: title, references: references, prefix: prefix)
76 }
77 .themedRow()
78 } header: {
79 sectionHeader(title: header)
80 }
81 }
82
74 private func sectionHeader(title: String) -> some View { 83 private func sectionHeader(title: String) -> some View {
75 HStack { 84 HStack {
76 Text(title) 85 Text(title)
Hutch/Views/Repositories/RepositoryDetailView.swift +1 −10
@@ -101,16 +101,7 @@ struct RepositoryDetailView: View {
101 @ViewBuilder 101 @ViewBuilder
102 private func detailContent(_ viewModel: RepositoryDetailViewModel) -> some View { 102 private func detailContent(_ viewModel: RepositoryDetailViewModel) -> some View {
103 VStack(spacing: 0) { 103 VStack(spacing: 0) {
104 Picker("Tab", selection: $selectedTab) { 104 SegmentedTabs(selection: $selectedTab)
105 ForEach(RepositoryDetailViewModel.Tab.allCases, id: \.self) { tab in
106 Text(tab.rawValue).tag(tab)
107 }
108 }
109 .pickerStyle(.segmented)
110 .padding(.horizontal)
111 .padding(.vertical, 8)
112
113 Divider()
114 105
115 switch selectedTab { 106 switch selectedTab {
116 case .summary: 107 case .summary:
Hutch/Views/Repositories/RepositoryListView.swift +1 −6
@@ -75,12 +75,7 @@ struct RepositoryListView: View {
75 .themedRow() 75 .themedRow()
76 76
77 if viewModel.isLoadingMore { 77 if viewModel.isLoadingMore {
78 HStack { 78 LoadingMoreRow()
79 Spacer()
80 ProgressView()
81 Spacer()
82 }
83 .listRowSeparator(.hidden)
84 .themedRow() 79 .themedRow()
85 } 80 }
86 } 81 }
Hutch/Views/Repositories/RepositorySettingsView.swift +4 −36
@@ -127,20 +127,12 @@ struct RepositorySettingsView: View {
127 .themedRow() 127 .themedRow()
128 } 128 }
129 129
130 Button { 130 ProgressButton("Save Details", isWorking: viewModel.isSavingMetadata) {
131 Task { 131 Task {
132 if let updatedRepository = await viewModel.saveMetadata() { 132 if let updatedRepository = await viewModel.saveMetadata() {
133 onUpdated(updatedRepository) 133 onUpdated(updatedRepository)
134 } 134 }
135 } 135 }
136 } label: {
137 if viewModel.isSavingMetadata {
138 ProgressView()
139 .frame(maxWidth: .infinity)
140 } else {
141 Text("Save Details")
142 .frame(maxWidth: .infinity)
143 }
144 } 136 }
145 .disabled( 137 .disabled(
146 viewModel.isMutating || 138 viewModel.isMutating ||
@@ -181,20 +173,12 @@ struct RepositorySettingsView: View {
181 .foregroundStyle(.secondary) 173 .foregroundStyle(.secondary)
182 .themedRow() 174 .themedRow()
183 175
184 Button { 176 ProgressButton("Set Default Branch", isWorking: viewModel.isSavingDefaultBranch) {
185 Task { 177 Task {
186 if let updatedRepository = await viewModel.saveDefaultBranch() { 178 if let updatedRepository = await viewModel.saveDefaultBranch() {
187 onUpdated(updatedRepository) 179 onUpdated(updatedRepository)
188 } 180 }
189 } 181 }
190 } label: {
191 if viewModel.isSavingDefaultBranch {
192 ProgressView()
193 .frame(maxWidth: .infinity)
194 } else {
195 Text("Set Default Branch")
196 .frame(maxWidth: .infinity)
197 }
198 } 182 }
199 .disabled( 183 .disabled(
200 viewModel.isMutating || 184 viewModel.isMutating ||
@@ -223,16 +207,8 @@ struct RepositorySettingsView: View {
223 .foregroundStyle(.secondary) 207 .foregroundStyle(.secondary)
224 .themedRow() 208 .themedRow()
225 209
226 Button { 210 ProgressButton("Apply Visibility Change", isWorking: viewModel.isUpdatingVisibility) {
227 showVisibilityConfirmation = true 211 showVisibilityConfirmation = true
228 } label: {
229 if viewModel.isUpdatingVisibility {
230 ProgressView()
231 .frame(maxWidth: .infinity)
232 } else {
233 Text("Apply Visibility Change")
234 .frame(maxWidth: .infinity)
235 }
236 } 212 }
237 .disabled(viewModel.isMutating || !viewModel.isVisibilityDirty) 213 .disabled(viewModel.isMutating || !viewModel.isVisibilityDirty)
238 .themedRow() 214 .themedRow()
@@ -244,16 +220,8 @@ struct RepositorySettingsView: View {
244 @ViewBuilder 220 @ViewBuilder
245 private func deleteSection(_ viewModel: RepositorySettingsViewModel) -> some View { 221 private func deleteSection(_ viewModel: RepositorySettingsViewModel) -> some View {
246 Section { 222 Section {
247 Button(role: .destructive) { 223 ProgressButton("Delete Repository", isWorking: viewModel.isDeleting, role: .destructive) {
248 showDeleteConfirmation = true 224 showDeleteConfirmation = true
249 } label: {
250 if viewModel.isDeleting {
251 ProgressView()
252 .frame(maxWidth: .infinity)
253 } else {
254 Text("Delete Repository")
255 .frame(maxWidth: .infinity)
256 }
257 } 225 }
258 .disabled(viewModel.isMutating) 226 .disabled(viewModel.isMutating)
259 .themedRow() 227 .themedRow()
Hutch/Views/Settings/NotificationPreferencesViewModel.swift +32 −29
@@ -126,48 +126,51 @@ final class NotificationPreferencesViewModel {
126 } 126 }
127 127
128 func setNotifySelf(_ newValue: Bool) async { 128 func setNotifySelf(_ newValue: Bool) async {
129 guard !isSavingNotifySelf else { return } 129 await setPreference(\.notifySelf, saving: \.isSavingNotifySelf, to: newValue,
130 isSavingNotifySelf = true 130 failure: "Couldn't update ticket email preference.") {
131 error = nil 131 try await self.client.execute(
132 defer { isSavingNotifySelf = false }
133
134 let previous = notifySelf
135 notifySelf = newValue
136
137 do {
138 let response = try await client.execute(
139 service: .todo, 132 service: .todo,
140 query: Self.updateNotifySelfMutation, 133 query: Self.updateNotifySelfMutation,
141 variables: ["notifySelf": newValue], 134 variables: ["notifySelf": newValue],
142 responseType: TodoPreferencesResponse.self 135 responseType: TodoPreferencesResponse.self
143 ) 136 ).preferences.notifySelf
144 notifySelf = response.preferences.notifySelf
145 } catch {
146 notifySelf = previous
147 self.error = "Couldn't update ticket email preference. \(error.userFacingMessage)"
148 } 137 }
149 } 138 }
150 139
151 func setCopySelf(_ newValue: Bool) async { 140 func setCopySelf(_ newValue: Bool) async {
152 guard !isSavingCopySelf else { return } 141 await setPreference(\.copySelf, saving: \.isSavingCopySelf, to: newValue,
153 isSavingCopySelf = true 142 failure: "Couldn't update mailing list email preference.") {
154 error = nil 143 try await self.client.execute(
155 defer { isSavingCopySelf = false }
156
157 let previous = copySelf
158 copySelf = newValue
159
160 do {
161 let response = try await client.execute(
162 service: .lists, 144 service: .lists,
163 query: Self.updateCopySelfMutation, 145 query: Self.updateCopySelfMutation,
164 variables: ["copySelf": newValue], 146 variables: ["copySelf": newValue],
165 responseType: ListsPreferencesResponse.self 147 responseType: ListsPreferencesResponse.self
166 ) 148 ).preferences.copySelf
167 copySelf = response.preferences.copySelf 149 }
150 }
151
152 /// Shows `newValue` at once and saves it with `save`, which answers what the server kept. On
153 /// failure the previous value comes back and the error says what `failure` couldn't do.
154 private func setPreference(
155 _ value: ReferenceWritableKeyPath<NotificationPreferencesViewModel, Bool>,
156 saving: ReferenceWritableKeyPath<NotificationPreferencesViewModel, Bool>,
157 to newValue: Bool,
158 failure: String,
159 save: () async throws -> Bool
160 ) async {
161 guard !self[keyPath: saving] else { return }
162 self[keyPath: saving] = true
163 error = nil
164 defer { self[keyPath: saving] = false }
165
166 let previous = self[keyPath: value]
167 self[keyPath: value] = newValue
168
169 do {
170 self[keyPath: value] = try await save()
168 } catch { 171 } catch {
169 copySelf = previous 172 self[keyPath: value] = previous
170 self.error = "Couldn't update mailing list email preference. \(error.userFacingMessage)" 173 self.error = "\(failure) \(error.userFacingMessage)"
171 } 174 }
172 } 175 }
173} 176}
Hutch/Views/Settings/SettingsViewModel.swift +26 −53
@@ -309,75 +309,48 @@ final class SettingsViewModel {
309 309
310 func addSSHKey() async { 310 func addSSHKey() async {
311 let key = newSSHKey.trimmingCharacters(in: .whitespacesAndNewlines) 311 let key = newSSHKey.trimmingCharacters(in: .whitespacesAndNewlines)
312 guard !key.isEmpty else { return } 312 guard !key.isEmpty,
313 error = nil 313 let result = await metaMutation(Self.createSSHKeyMutation, ["key": key], as: CreateSSHKeyResponse.self)
314 314 else { return }
315 do { 315 sshKeys.append(result.createSSHKey)
316 let result = try await client.execute( 316 newSSHKey = ""
317 service: .meta, 317 isAddingSSHKey = false
318 query: Self.createSSHKeyMutation,
319 variables: ["key": key],
320 responseType: CreateSSHKeyResponse.self
321 )
322 sshKeys.append(result.createSSHKey)
323 newSSHKey = ""
324 isAddingSSHKey = false
325 } catch {
326 self.error = error.userFacingMessage
327 }
328 } 318 }
329 319
330 func deleteSSHKey(_ key: SSHKey) async { 320 func deleteSSHKey(_ key: SSHKey) async {
331 error = nil 321 guard await metaMutation(Self.deleteSSHKeyMutation, ["id": key.id], as: DeleteSSHKeyResponse.self) != nil else { return }
332 322 sshKeys.removeAll { $0.id == key.id }
333 do {
334 _ = try await client.execute(
335 service: .meta,
336 query: Self.deleteSSHKeyMutation,
337 variables: ["id": key.id],
338 responseType: DeleteSSHKeyResponse.self
339 )
340 sshKeys.removeAll { $0.id == key.id }
341 } catch {
342 self.error = error.userFacingMessage
343 }
344 } 323 }
345 324
346 // MARK: - PGP Keys 325 // MARK: - PGP Keys
347 326
348 func addPGPKey() async { 327 func addPGPKey() async {
349 let key = newPGPKey.trimmingCharacters(in: .whitespacesAndNewlines) 328 let key = newPGPKey.trimmingCharacters(in: .whitespacesAndNewlines)
350 guard !key.isEmpty else { return } 329 guard !key.isEmpty,
351 error = nil 330 let result = await metaMutation(Self.createPGPKeyMutation, ["key": key], as: CreatePGPKeyResponse.self)
352 331 else { return }
353 do { 332 pgpKeys.append(result.createPGPKey)
354 let result = try await client.execute( 333 newPGPKey = ""
355 service: .meta, 334 isAddingPGPKey = false
356 query: Self.createPGPKeyMutation,
357 variables: ["key": key],
358 responseType: CreatePGPKeyResponse.self
359 )
360 pgpKeys.append(result.createPGPKey)
361 newPGPKey = ""
362 isAddingPGPKey = false
363 } catch {
364 self.error = error.userFacingMessage
365 }
366 } 335 }
367 336
368 func deletePGPKey(_ key: PGPKey) async { 337 func deletePGPKey(_ key: PGPKey) async {
369 error = nil 338 guard await metaMutation(Self.deletePGPKeyMutation, ["id": key.id], as: DeletePGPKeyResponse.self) != nil else { return }
339 pgpKeys.removeAll { $0.id == key.id }
340 }
370 341
342 /// Runs a meta.sr.ht mutation, clearing the last error first and keeping the new one on failure.
343 private func metaMutation<Response: Decodable>(
344 _ query: String,
345 _ variables: [String: any Sendable],
346 as responseType: Response.Type
347 ) async -> Response? {
348 error = nil
371 do { 349 do {
372 _ = try await client.execute( 350 return try await client.execute(service: .meta, query: query, variables: variables, responseType: responseType)
373 service: .meta,
374 query: Self.deletePGPKeyMutation,
375 variables: ["id": key.id],
376 responseType: DeletePGPKeyResponse.self
377 )
378 pgpKeys.removeAll { $0.id == key.id }
379 } catch { 351 } catch {
380 self.error = error.userFacingMessage 352 self.error = error.userFacingMessage
353 return nil
381 } 354 }
382 } 355 }
383 356
Hutch/Views/Shared/LoadingMoreRow.swift added +13
@@ -0,0 +1,13 @@
1import SwiftUI
2
3/// The spinner at the foot of a list while its next page loads.
4struct LoadingMoreRow: View {
5 var body: some View {
6 HStack {
7 Spacer()
8 ProgressView()
9 Spacer()
10 }
11 .listRowSeparator(.hidden)
12 }
13}
Hutch/Views/Shared/ProgressButton.swift added +28
@@ -0,0 +1,28 @@
1import SwiftUI
2
3/// A full-width button that shows a spinner in place of its title while `isWorking`.
4struct ProgressButton: View {
5 let title: LocalizedStringKey
6 let isWorking: Bool
7 var role: ButtonRole?
8 let action: () -> Void
9
10 init(_ title: LocalizedStringKey, isWorking: Bool, role: ButtonRole? = nil, action: @escaping () -> Void) {
11 self.title = title
12 self.isWorking = isWorking
13 self.role = role
14 self.action = action
15 }
16
17 var body: some View {
18 Button(role: role, action: action) {
19 if isWorking {
20 ProgressView()
21 .frame(maxWidth: .infinity)
22 } else {
23 Text(title)
24 .frame(maxWidth: .infinity)
25 }
26 }
27 }
28}
Hutch/Views/Shared/SegmentedTabs.swift added +19
@@ -0,0 +1,19 @@
1import SwiftUI
2
3/// The segmented tab bar across the top of a detail screen, with a divider under it.
4struct SegmentedTabs<Tab: CaseIterable & Hashable & RawRepresentable<String>>: View where Tab.AllCases: RandomAccessCollection {
5 @Binding var selection: Tab
6
7 var body: some View {
8 Picker("Tab", selection: $selection) {
9 ForEach(Tab.allCases, id: \.self) { tab in
10 Text(tab.rawValue).tag(tab)
11 }
12 }
13 .pickerStyle(.segmented)
14 .padding(.horizontal)
15 .padding(.vertical, 8)
16
17 Divider()
18 }
19}
Hutch/Views/Shared/SwipeButtons.swift added +25
@@ -0,0 +1,25 @@
1import SwiftUI
2
3/// The red Delete swipe action.
4struct SwipeDeleteButton: View {
5 let action: () -> Void
6
7 var body: some View {
8 Button(action: action) {
9 Label("Delete", systemImage: "trash")
10 }
11 .tint(.red)
12 }
13}
14
15/// The blue Edit swipe action.
16struct SwipeEditButton: View {
17 let action: () -> Void
18
19 var body: some View {
20 Button(action: action) {
21 Label("Edit", systemImage: "pencil")
22 }
23 .tint(.blue)
24 }
25}
Hutch/Views/Tickets/TicketDetailView.swift +2 −1
@@ -1139,7 +1139,8 @@ private struct CreateLabelSheet: View {
1139 } 1139 }
1140} 1140}
1141 1141
1142private struct LabelToggleRow: View { 1142/// A label with a checkmark when it is applied; tapping asks for the opposite.
1143struct LabelToggleRow: View {
1143 let label: TicketLabel 1144 let label: TicketLabel
1144 let isApplied: Bool 1145 let isApplied: Bool
1145 let isLoading: Bool 1146 let isLoading: Bool
Hutch/Views/Tickets/TicketListView.swift +2 −31
@@ -275,12 +275,7 @@ struct TicketListView: View {
275 .themedRow() 275 .themedRow()
276 276
277 if viewModel.isLoadingMore { 277 if viewModel.isLoadingMore {
278 HStack { 278 LoadingMoreRow()
279 Spacer()
280 ProgressView()
281 Spacer()
282 }
283 .listRowSeparator(.hidden)
284 .themedRow() 279 .themedRow()
285 } 280 }
286 } 281 }
@@ -711,7 +706,7 @@ private struct TicketLabelsSheet: View {
711 } else { 706 } else {
712 List { 707 List {
713 ForEach(viewModel.trackerLabels) { label in 708 ForEach(viewModel.trackerLabels) { label in
714 TicketListLabelToggleRow( 709 LabelToggleRow(
715 label: label, 710 label: label,
716 isApplied: ticket.labels.contains(where: { $0.id == label.id }), 711 isApplied: ticket.labels.contains(where: { $0.id == label.id }),
717 isLoading: viewModel.isPerformingAction 712 isLoading: viewModel.isPerformingAction
@@ -1035,30 +1030,6 @@ private struct SaveTicketFilterSheet: View {
1035 } 1030 }
1036} 1031}
1037 1032
1038private struct TicketListLabelToggleRow: View {
1039 let label: TicketLabel
1040 let isApplied: Bool
1041 let isLoading: Bool
1042 let onToggle: (Bool) -> Void
1043
1044 var body: some View {
1045 Button {
1046 onToggle(!isApplied)
1047 } label: {
1048 HStack {
1049 LabelPill(label: label)
1050 Spacer()
1051 if isApplied {
1052 Image(systemName: "checkmark")
1053 .foregroundStyle(.blue)
1054 }
1055 }
1056 }
1057 .disabled(isLoading)
1058 .accessibilityAddTraits(isApplied ? [.isSelected] : [])
1059 }
1060}
1061
1062private struct TicketBulkActionBar: View { 1033private struct TicketBulkActionBar: View {
1063 let selectedCount: Int 1034 let selectedCount: Int
1064 let isPerformingAction: Bool 1035 let isPerformingAction: Bool
Hutch/Views/Tickets/TrackerListView.swift +3 −18
@@ -121,19 +121,9 @@ struct TrackerListView: View {
121 TrackerRowView(tracker: tracker) 121 TrackerRowView(tracker: tracker)
122 } 122 }
123 .swipeActions(edge: .trailing, allowsFullSwipe: false) { 123 .swipeActions(edge: .trailing, allowsFullSwipe: false) {
124 Button { 124 SwipeDeleteButton { pendingDeletion = tracker }
125 pendingDeletion = tracker
126 } label: {
127 Label("Delete", systemImage: "trash")
128 }
129 .tint(.red)
130 125
131 Button { 126 SwipeEditButton { editingTracker = tracker }
132 editingTracker = tracker
133 } label: {
134 Label("Edit", systemImage: "pencil")
135 }
136 .tint(.blue)
137 } 127 }
138 .task { 128 .task {
139 await viewModel.loadMoreIfNeeded(currentItem: tracker) 129 await viewModel.loadMoreIfNeeded(currentItem: tracker)
@@ -142,12 +132,7 @@ struct TrackerListView: View {
142 .themedRow() 132 .themedRow()
143 133
144 if viewModel.isLoadingMore { 134 if viewModel.isLoadingMore {
145 HStack { 135 LoadingMoreRow()
146 Spacer()
147 ProgressView()
148 Spacer()
149 }
150 .listRowSeparator(.hidden)
151 .themedRow() 136 .themedRow()
152 } 137 }
153 } 138 }
Hutch/Views/Tickets/TrackerManagementView.swift +26 −50
@@ -438,22 +438,9 @@ final class TrackerManagementViewModel {
438 } 438 }
439 439
440 func deleteACL(_ entry: TrackerACL) async { 440 func deleteACL(_ entry: TrackerACL) async {
441 guard !isDeletingACL else { return } 441 await todoMutation(Self.deleteACLMutation, ["id": entry.id], as: DeleteTrackerACLResponse.self, while: \.isDeletingACL) { _ in
442 isDeletingACL = true
443 error = nil
444 defer { isDeletingACL = false }
445
446 do {
447 _ = try await client.execute(
448 service: .todo,
449 query: Self.deleteACLMutation,
450 variables: ["id": entry.id],
451 responseType: DeleteTrackerACLResponse.self
452 )
453 acls.removeAll { $0.id == entry.id } 442 acls.removeAll { $0.id == entry.id }
454 await loadACLs() 443 await loadACLs()
455 } catch {
456 self.error = error.userFacingMessage
457 } 444 }
458 } 445 }
459 446
@@ -565,20 +552,29 @@ final class TrackerManagementViewModel {
565 } 552 }
566 553
567 func deleteLabel(_ label: TicketLabel) async { 554 func deleteLabel(_ label: TicketLabel) async {
568 guard !isDeletingLabel else { return } 555 await todoMutation(Self.deleteLabelMutation, ["id": label.id], as: DeleteTrackerLabelResponse.self, while: \.isDeletingLabel) { _ in
569 isDeletingLabel = true 556 labels.removeAll { $0.id == label.id }
557 await loadLabels()
558 }
559 }
560
561 /// Runs a todo.sr.ht mutation and then `apply` while `busy` is set, clearing the last error
562 /// first and keeping the new one on failure. Does nothing while `busy` is already set.
563 private func todoMutation<Response: Decodable>(
564 _ query: String,
565 _ variables: [String: any Sendable],
566 as responseType: Response.Type,
567 while busy: ReferenceWritableKeyPath<TrackerManagementViewModel, Bool>,
568 apply: (Response) async -> Void
569 ) async {
570 guard !self[keyPath: busy] else { return }
571 self[keyPath: busy] = true
570 error = nil 572 error = nil
571 defer { isDeletingLabel = false } 573 defer { self[keyPath: busy] = false }
572 574
573 do { 575 do {
574 _ = try await client.execute( 576 let response = try await client.execute(service: .todo, query: query, variables: variables, responseType: responseType)
575 service: .todo, 577 await apply(response)
576 query: Self.deleteLabelMutation,
577 variables: ["id": label.id],
578 responseType: DeleteTrackerLabelResponse.self
579 )
580 labels.removeAll { $0.id == label.id }
581 await loadLabels()
582 } catch { 578 } catch {
583 self.error = error.userFacingMessage 579 self.error = error.userFacingMessage
584 } 580 }
@@ -751,19 +747,9 @@ struct TrackerACLManagementSheet: View {
751 TrackerPermissionSummary(permissions: entry.permissions) 747 TrackerPermissionSummary(permissions: entry.permissions)
752 } 748 }
753 .swipeActions(edge: .trailing, allowsFullSwipe: false) { 749 .swipeActions(edge: .trailing, allowsFullSwipe: false) {
754 Button { 750 SwipeDeleteButton { pendingDeletion = entry }
755 pendingDeletion = entry 751
756 } label: { 752 SwipeEditButton { editingACL = entry }
757 Label("Delete", systemImage: "trash")
758 }
759 .tint(.red)
760
761 Button {
762 editingACL = entry
763 } label: {
764 Label("Edit", systemImage: "pencil")
765 }
766 .tint(.blue)
767 } 753 }
768 } 754 }
769 .themedRow() 755 .themedRow()
@@ -1120,19 +1106,9 @@ struct TrackerLabelManagementSheet: View {
1120 } 1106 }
1121 .buttonStyle(.plain) 1107 .buttonStyle(.plain)
1122 .swipeActions(edge: .trailing, allowsFullSwipe: false) { 1108 .swipeActions(edge: .trailing, allowsFullSwipe: false) {
1123 Button { 1109 SwipeEditButton { editingLabel = label }
1124 editingLabel = label
1125 } label: {
1126 Label("Edit", systemImage: "pencil")
1127 }
1128 .tint(.blue)
1129 1110
1130 Button { 1111 SwipeDeleteButton { pendingDeletion = label }
1131 pendingDeletion = label
1132 } label: {
1133 Label("Delete", systemImage: "trash")
1134 }
1135 .tint(.red)
1136 } 1112 }
1137 } 1113 }
1138 .themedRow() 1114 .themedRow()