1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
|
import SwiftUI
import os
private let lookupLogger = Logger(subsystem: "net.cleberg.Hutch", category: "Lookup")
enum LookupType: String, CaseIterable, Identifiable, Codable, Sendable {
case user = "User"
case gitRepo = "Git Repo"
case hgRepo = "Hg Repo"
case mailingList = "Mailing List"
case tracker = "Tracker"
case buildJob = "Build Job"
var id: String { rawValue }
var placeholder: String {
switch self {
case .user:
"~username"
case .gitRepo, .hgRepo:
"~username/repo-name"
case .mailingList:
"~username/list-name"
case .tracker:
"~username/tracker-name"
case .buildJob:
"Job ID (e.g. 123456)"
}
}
var inputLabel: String {
switch self {
case .user:
"Username"
case .gitRepo, .hgRepo:
"Repository"
case .mailingList:
"Mailing List"
case .tracker:
"Tracker"
case .buildJob:
"Build Job ID"
}
}
}
enum LookupResult: Identifiable {
case user(User)
case repository(RepositorySummary)
case mailingList(InboxMailingListReference)
case tracker(TrackerSummary)
case buildJob(Int)
var id: String {
switch self {
case .user(let user):
"user:\(user.id)"
case .repository(let repository):
"repo:\(repository.id)"
case .mailingList(let mailingList):
"list:\(mailingList.id)"
case .tracker(let tracker):
"tracker:\(tracker.id)"
case .buildJob(let jobId):
"job:\(jobId)"
}
}
}
@Observable
@MainActor
final class LookupViewModel {
var selectedType: LookupType = .user
var inputText: String = ""
private(set) var result: LookupResult?
private(set) var isLooking = false
private(set) var history: [LookupHistoryEntry]
var error: String?
private let client: SRHTClient
private let appState: AppState
private let defaults: UserDefaults
var resultBinding: Binding<LookupResult?> {
Binding(
get: { self.result },
set: { newValue in
if newValue == nil {
self.result = nil
}
}
)
}
init(
client: SRHTClient,
appState: AppState,
defaults: UserDefaults = .standard,
initialQuery: String = ""
) {
self.client = client
self.appState = appState
self.defaults = defaults
self.history = LookupHistoryStore.load(defaults: defaults)
self.inputText = initialQuery.trimmingCharacters(in: .whitespacesAndNewlines)
}
func lookup() async {
result = nil
error = nil
isLooking = true
defer { isLooking = false }
do {
switch selectedType {
case .user:
result = try await lookupUser()
case .gitRepo:
result = try await lookupRepository(service: .git)
case .hgRepo:
result = try await lookupRepository(service: .hg)
case .mailingList:
result = try await lookupMailingList()
case .tracker:
result = try await lookupTracker()
case .buildJob:
result = try await lookupBuildJob()
}
} catch LookupError.invalidInput {
return
} catch {
self.error = error.userFacingMessage
}
}
func rerun(_ entry: LookupHistoryEntry) async {
selectedType = entry.type
inputText = entry.query
await lookup()
}
func clearHistory() {
LookupHistoryStore.clear(defaults: defaults)
history = []
}
private func parseOwnerAndName() -> (owner: String, name: String)? {
let trimmed = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
let normalized = trimmed.hasPrefix("~") ? String(trimmed.dropFirst()) : trimmed
let parts = normalized.split(separator: "/", omittingEmptySubsequences: false)
guard parts.count == 2, !parts[0].isEmpty, !parts[1].isEmpty else {
error = "Enter a value in the format ~username/name."
return nil
}
return (String(parts[0]), String(parts[1]))
}
private func parseUsername() -> String? {
let trimmed = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
let normalized = trimmed.hasPrefix("~") ? String(trimmed.dropFirst()) : trimmed
guard !normalized.isEmpty else {
error = "Enter a username."
return nil
}
return normalized
}
private func parseBuildJobId() -> Int? {
let trimmed = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
guard let jobId = Int(trimmed) else {
error = "Enter a numeric build job ID."
return nil
}
return jobId
}
private func lookupUser() async throws -> LookupResult {
guard let username = parseUsername() else { throw LookupError.invalidInput }
recordHistory(type: .user, query: "~\(username)")
struct Response: Decodable, Sendable {
let user: User
}
let query = """
query userLookup($username: String!) {
user: userByName(username: $username) {
id
created
updated
canonicalName
username
email
url
location
bio
avatar
pronouns
userType
}
}
"""
let result: Response
do {
result = try await client.execute(
service: .meta,
query: query,
variables: ["username": username],
responseType: Response.self
)
} catch {
lookupLogger.error(
"""
User lookup failed
username: \(username, privacy: .public)
query:
\(query, privacy: .public)
error:
\(String(describing: error), privacy: .public)
"""
)
throw error
}
return .user(result.user)
}
private func lookupRepository(service: SRHTService) async throws -> LookupResult {
guard let (owner, name) = parseOwnerAndName() else { throw LookupError.invalidInput }
let type: LookupType = service == .git ? .gitRepo : .hgRepo
recordHistory(type: type, query: "~\(owner)/\(name)")
let repository = try await appState.resolveRepository(owner: owner, name: name, service: service)
let resolvedRepository = RepositorySummary(
fields: .init(
id: repository.id,
rid: repository.rid,
service: service,
name: repository.name,
description: repository.description,
visibility: repository.visibility,
updated: repository.updated,
owner: repository.owner,
head: repository.head
)
)
return .repository(resolvedRepository)
}
private func lookupMailingList() async throws -> LookupResult {
guard let (owner, name) = parseOwnerAndName() else { throw LookupError.invalidInput }
recordHistory(type: .mailingList, query: "~\(owner)/\(name)")
struct Response: Decodable, Sendable {
let user: UserWithList
}
struct UserWithList: Decodable, Sendable {
let mailingList: InboxMailingListReference
}
let query = """
query mailingListLookup($owner: String!, $name: String!) {
user(username: $owner) {
mailingList: list(name: $name) {
id rid name owner { canonicalName }
}
}
}
"""
let result = try await client.execute(
service: .lists,
query: query,
variables: ["owner": owner, "name": name],
responseType: Response.self
)
return .mailingList(result.user.mailingList)
}
private func lookupTracker() async throws -> LookupResult {
guard let (owner, name) = parseOwnerAndName() else { throw LookupError.invalidInput }
recordHistory(type: .tracker, query: "~\(owner)/\(name)")
let tracker = try await appState.resolveTracker(owner: owner, name: name)
return .tracker(tracker)
}
private func lookupBuildJob() async throws -> LookupResult {
guard let jobId = parseBuildJobId() else { throw LookupError.invalidInput }
recordHistory(type: .buildJob, query: String(jobId))
struct Response: Decodable, Sendable {
let job: JobIdOnly
}
struct JobIdOnly: Decodable, Sendable {
let id: Int
}
let query = """
query buildLookup($id: Int!) {
job(id: $id) { id }
}
"""
_ = try await client.execute(
service: .builds,
query: query,
variables: ["id": jobId],
responseType: Response.self
)
return .buildJob(jobId)
}
private enum LookupError: Error {
case invalidInput
}
private func recordHistory(type: LookupType, query: String) {
LookupHistoryStore.record(type: type, query: query, defaults: defaults)
history = LookupHistoryStore.load(defaults: defaults)
}
}
struct LookupView: View {
@Environment(AppState.self) private var appState
@State private var viewModel: LookupViewModel?
private let initialQuery: String
init(initialQuery: String = "") {
self.initialQuery = initialQuery
}
var body: some View {
Group {
if let viewModel {
content(viewModel)
} else {
SRHTLoadingStateView(message: "Preparing lookup…")
}
}
.navigationTitle("Look Up")
.task {
if viewModel == nil {
viewModel = LookupViewModel(
client: appState.client,
appState: appState,
defaults: appState.accountDefaults,
initialQuery: initialQuery
)
}
}
}
@ViewBuilder
private func content(_ viewModel: LookupViewModel) -> some View {
@Bindable var vm = viewModel
Form {
Section {
Picker("Type", selection: $vm.selectedType) {
ForEach(LookupType.allCases) { type in
Text(type.rawValue).tag(type)
}
}
.pickerStyle(.menu)
.themedRow()
TextField(
vm.selectedType.inputLabel,
text: $vm.inputText,
prompt: Text(vm.selectedType.placeholder)
)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.submitLabel(.search)
.onSubmit {
Task { await vm.lookup() }
}
.themedRow()
}
Section {
HStack {
Button("Look Up") {
Task { await vm.lookup() }
}
.disabled(vm.inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || vm.isLooking)
if vm.isLooking {
Spacer()
ProgressView()
}
}
.themedRow()
}
if !vm.history.isEmpty {
Section("Recent Searches") {
ForEach(vm.history) { entry in
Button {
Task { await vm.rerun(entry) }
} label: {
HStack {
VStack(alignment: .leading, spacing: 2) {
Text(entry.query)
.foregroundStyle(.primary)
Text(entry.type.rawValue)
.font(.caption)
.foregroundStyle(.secondary)
}
Spacer()
}
}
.disabled(vm.isLooking)
}
.themedRow()
Button("Clear History", role: .destructive) {
vm.clearHistory()
}
.disabled(vm.isLooking)
.themedRow()
}
}
}
.themedList()
.formStyle(.grouped)
.srhtErrorBanner(error: $vm.error)
.sheet(item: vm.resultBinding) { result in
NavigationStack {
lookupDestination(result)
}
.navigationDestination(for: MoreRoute.self) { route in
switch route {
case .lookup(let query):
LookupView(initialQuery: query ?? "")
case .projects:
ProjectsListView()
case .lists:
MailingListListView()
case .pastes:
PasteListView()
case .profile:
ProfileView()
case .systemStatus:
SystemStatusView()
case .settings:
SettingsView()
case .about:
AboutView()
case .userProfile(let owner):
UserProfileDeepLinkView(owner: owner)
case .projectDashboard(let id, let title):
ProjectDashboardDeepLinkView(projectID: id, title: title)
case .mailingList(let mailingList):
MailingListDetailView(mailingList: mailingList)
case .thread(let thread):
ThreadDetailView(
thread: thread,
onViewed: {
InboxReadStateStore.markViewed(max(Date(), thread.lastActivityAt), for: thread.threadGroupingKey, defaults: appState.accountDefaults)
NeedsAttentionSnapshotStore.adjustUnreadInboxThreads(by: -1, accountID: appState.activeAccountID)
},
onMarkRead: {
InboxReadStateStore.markViewed(max(Date(), thread.lastActivityAt), for: thread.threadGroupingKey, defaults: appState.accountDefaults)
NeedsAttentionSnapshotStore.adjustUnreadInboxThreads(by: -1, accountID: appState.activeAccountID)
},
onMarkUnread: {
InboxReadStateStore.markUnread(for: thread.threadGroupingKey, defaults: appState.accountDefaults)
NeedsAttentionSnapshotStore.adjustUnreadInboxThreads(by: 1, accountID: appState.activeAccountID)
}
)
case .manPageBrowser:
ManPageBrowserView()
case .manPage(let url):
ManPageDetailView(url: url)
}
}
.environment(appState)
}
}
@ViewBuilder
private func lookupDestination(_ result: LookupResult) -> some View {
switch result {
case .user(let user):
UserProfileView(user: user)
case .repository(let repository):
RepositoryDetailView(repository: repository)
case .mailingList(let mailingList):
MailingListDetailView(mailingList: mailingList)
case .tracker(let tracker):
TicketListView(tracker: tracker)
case .buildJob(let jobId):
BuildDetailView(jobId: jobId)
}
}
}
|