summaryrefslogtreecommitdiff
path: root/Hutch/Views/Lists/MailingListListView.swift
blob: 1b159bf0dfc42f43693b4654f390ca4a28f5cd31 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
import SwiftUI

private struct ListIDPayload: Decodable, Sendable {
    let id: Int
}

@Observable
@MainActor
final class MailingListListViewModel {
    private(set) var mailingLists: [InboxMailingListReference] = []
    private(set) var isLoading = false
    private(set) var isPerformingAction = false
    var error: String?
    var searchText = ""

    private let client: SRHTClient

    private static let subscriptionsQuery = """
    query mailingLists($cursor: Cursor) {
        subscriptions(cursor: $cursor) {
            results {
                ... on MailingListSubscription {
                    list {
                        id
                        rid
                        name
                        owner { canonicalName }
                    }
                }
            }
            cursor
        }
    }
    """

    private static let unsubscribeMutation = """
    mutation mailingListUnsubscribe($listID: Int!) {
        subscription: mailingListUnsubscribe(listID: $listID) { id }
    }
    """

    private static let createMailingListMutation = """
    mutation createMailingList($name: String!, $description: String, $visibility: Visibility!) {
        createMailingList(name: $name, description: $description, visibility: $visibility) {
            id
            rid
            name
            owner { canonicalName }
        }
    }
    """

    /// InboxMailingListReference carries only id/rid/name/owner, so the settings
    /// sheet has to read the current values before it can offer to change them —
    /// otherwise saving would blank the description and reset visibility.
    private static let listSettingsQuery = """
    query listSettings($rid: ID!) {
        list(rid: $rid) {
            description
            visibility
        }
    }
    """

    private static let updateMailingListMutation = """
    mutation updateMailingList($id: Int!, $input: MailingListInput!) {
        updateMailingList(id: $id, input: $input) { id }
    }
    """

    private static let deleteMailingListMutation = """
    mutation deleteMailingList($id: Int!) {
        deleteMailingList(id: $id) { id }
    }
    """

    init(client: SRHTClient) {
        self.client = client
    }

    /// Creates a list. sr.ht subscribes the owner automatically, so a reload is
    /// enough to surface it — this view is built from the subscriptions query.
    @discardableResult
    func createMailingList(name: String, description: String, visibility: Visibility) async -> Bool {
        guard !isPerformingAction else { return false }
        isPerformingAction = true
        error = nil
        defer { isPerformingAction = false }

        let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
        let trimmedDescription = description.trimmingCharacters(in: .whitespacesAndNewlines)

        do {
            struct Response: Decodable, Sendable {
                let createMailingList: InboxMailingListReference
            }

            _ = try await client.execute(
                service: .lists,
                query: Self.createMailingListMutation,
                variables: [
                    "name": trimmedName,
                    "description": trimmedDescription.isEmpty ? nil as String? as Any : trimmedDescription,
                    "visibility": visibility.rawValue
                ],
                responseType: Response.self
            )
            await loadMailingLists()
            return true
        } catch {
            self.error = "Couldn't create \(trimmedName). \(error.userFacingMessage)"
            return false
        }
    }

    /// Reads a list's current description and visibility, so the settings sheet
    /// can seed itself rather than overwrite with blanks.
    func listSettings(rid: String) async -> (description: String, visibility: Visibility)? {
        struct Response: Decodable, Sendable {
            let list: ListSettingsPayload?
        }

        struct ListSettingsPayload: Decodable, Sendable {
            let description: String?
            let visibility: Visibility
        }

        do {
            let response = try await client.execute(
                service: .lists,
                query: Self.listSettingsQuery,
                variables: ["rid": rid],
                responseType: Response.self
            )
            guard let list = response.list else { return nil }
            return (list.description ?? "", list.visibility)
        } catch {
            self.error = "Couldn't load the list's settings. \(error.userFacingMessage)"
            return nil
        }
    }

    /// Edits a list's description and visibility.
    ///
    /// `MailingListInput` also carries `permitMime` / `rejectMime`; those are left
    /// alone rather than sent as empty, which would clear the list's filters.
    @discardableResult
    func updateMailingList(id: Int, description: String, visibility: Visibility) async -> Bool {
        guard !isPerformingAction else { return false }
        isPerformingAction = true
        error = nil
        defer { isPerformingAction = false }

        let trimmedDescription = description.trimmingCharacters(in: .whitespacesAndNewlines)
        var input: [String: any Sendable] = ["visibility": visibility.rawValue]
        if trimmedDescription.isEmpty {
            // A nil subscript assignment would drop the key and leave the old
            // description in place instead of clearing it.
            input.updateValue(Optional<String>.none as any Sendable, forKey: "description")
        } else {
            input["description"] = trimmedDescription
        }

        do {
            struct Response: Decodable, Sendable {
                let updateMailingList: ListIDPayload?
            }

            _ = try await client.execute(
                service: .lists,
                query: Self.updateMailingListMutation,
                variables: ["id": id, "input": input],
                responseType: Response.self
            )
            await loadMailingLists()
            return true
        } catch {
            self.error = "Couldn't update the list. \(error.userFacingMessage)"
            return false
        }
    }

    @discardableResult
    func deleteMailingList(_ mailingList: InboxMailingListReference) async -> Bool {
        guard !isPerformingAction else { return false }
        isPerformingAction = true
        error = nil
        defer { isPerformingAction = false }

        let previousLists = mailingLists
        mailingLists.removeAll { $0.rid == mailingList.rid }

        do {
            struct Response: Decodable, Sendable {
                let deleteMailingList: ListIDPayload?
            }

            _ = try await client.execute(
                service: .lists,
                query: Self.deleteMailingListMutation,
                variables: ["id": mailingList.id],
                responseType: Response.self
            )
            return true
        } catch {
            mailingLists = previousLists
            self.error = "Couldn't delete \(mailingList.name). \(error.userFacingMessage)"
            return false
        }
    }

    /// Unsubscribes from a list and drops it from the list on success. This view
    /// is built from the subscriptions query, so a successful unsubscribe means
    /// the row no longer belongs here.
    func unsubscribe(from mailingList: InboxMailingListReference) async {
        guard !isPerformingAction else { return }
        isPerformingAction = true
        error = nil
        defer { isPerformingAction = false }

        let previousLists = mailingLists
        mailingLists.removeAll { $0.rid == mailingList.rid }

        do {
            struct Response: Decodable, Sendable {
                // mailingListUnsubscribe is nullable: sr.ht returns null when there
                // was no subscription to remove, which is still a success.
                let subscription: SubscriptionPayload?
            }

            struct SubscriptionPayload: Decodable, Sendable {
                let id: Int
            }

            _ = try await client.execute(
                service: .lists,
                query: Self.unsubscribeMutation,
                variables: ["listID": mailingList.id],
                responseType: Response.self
            )
        } catch {
            mailingLists = previousLists
            self.error = "Couldn't unsubscribe from \(mailingList.name). \(error.userFacingMessage)"
        }
    }

    var filteredMailingLists: [InboxMailingListReference] {
        let q = searchText.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        guard !q.isEmpty else { return mailingLists }
        return mailingLists.filter {
            $0.name.lowercased().contains(q) ||
            $0.owner.canonicalName.lowercased().contains(q)
        }
    }

    func loadMailingLists() async {
        guard !isLoading else { return }
        isLoading = true
        error = nil
        defer { isLoading = false }

        do {
            mailingLists = try await fetchMailingLists()
        } catch {
            self.error = "Failed to load mailing lists"
        }
    }

    private func fetchMailingLists() async throws -> [InboxMailingListReference] {
        struct Response: Decodable, Sendable {
            let subscriptions: Page
        }

        struct Page: Decodable, Sendable {
            let results: [Subscription]
            let cursor: String?
        }

        struct Subscription: Decodable, Sendable {
            let list: InboxMailingListReference?
        }

        var results: [InboxMailingListReference] = []
        var cursor: String?

        while true {
            var variables: [String: any Sendable] = [:]
            if let cursor {
                variables["cursor"] = cursor
            }

            let response = try await client.execute(
                service: .lists,
                query: Self.subscriptionsQuery,
                variables: variables.isEmpty ? nil : variables,
                responseType: Response.self
            )

            results.append(contentsOf: response.subscriptions.results.compactMap(\.list))
            guard let nextCursor = response.subscriptions.cursor else {
                break
            }
            cursor = nextCursor
        }

        var seen = Set<String>()
        return results
            .filter { seen.insert($0.rid).inserted }
            .sorted {
                if $0.owner.canonicalName == $1.owner.canonicalName {
                    return $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending
                }
                return $0.owner.canonicalName.localizedCaseInsensitiveCompare($1.owner.canonicalName) == .orderedAscending
            }
    }
}

struct MailingListListView: View {
    @Environment(AppState.self) private var appState
    @State private var viewModel: MailingListListViewModel?
    @State private var pendingUnsubscribe: InboxMailingListReference?
    @State private var pendingDeletion: InboxMailingListReference?
    @State private var editingList: InboxMailingListReference?
    @State private var showCreateSheet = false

    /// The subscriptions query returns lists the user follows, which is not the
    /// same as lists they own — only the owner may edit or delete one.
    private func isOwned(_ mailingList: InboxMailingListReference) -> Bool {
        guard let currentUser = appState.currentUser else { return false }
        let owner = mailingList.owner.canonicalName.hasPrefix("~")
            ? String(mailingList.owner.canonicalName.dropFirst())
            : mailingList.owner.canonicalName
        return owner.caseInsensitiveCompare(currentUser.username) == .orderedSame
    }

    var body: some View {
        Group {
            if let viewModel {
                content(viewModel)
            } else {
                SRHTLoadingStateView(message: "Loading mailing lists…")
            }
        }
        .navigationTitle("Mailing Lists")
        .task {
            if viewModel == nil {
                let vm = MailingListListViewModel(client: appState.client)
                viewModel = vm
                await vm.loadMailingLists()
            }
        }
    }

    @ViewBuilder
    private func content(_ viewModel: MailingListListViewModel) -> some View {
        @Bindable var vm = viewModel

        List {
            ForEach(viewModel.filteredMailingLists, id: \.rid) { mailingList in
                NavigationLink(value: MoreRoute.mailingList(mailingList)) {
                    VStack(alignment: .leading, spacing: 4) {
                        Text(mailingList.name)
                            .font(.subheadline.weight(.medium))
                        Text(mailingList.owner.canonicalName)
                            .font(.caption)
                            .foregroundStyle(.secondary)
                    }
                    .padding(.vertical, 2)
                }
                // allowsFullSwipe: false, as in PasteListView. A destructive
                // action left to full-swipe animates the row out on the gesture,
                // before the confirmation is answered, so it flickers back when
                // the data has not actually changed.
                .swipeActions(edge: .trailing, allowsFullSwipe: false) {
                    if isOwned(mailingList) {
                        Button {
                            pendingDeletion = mailingList
                        } label: {
                            SwiftUI.Label("Delete", systemImage: "trash")
                        }
                        .tint(.red)
                        Button {
                            editingList = mailingList
                        } label: {
                            SwiftUI.Label("Settings", systemImage: "gear")
                        }
                        .tint(.gray)
                    } else {
                        Button {
                            pendingUnsubscribe = mailingList
                        } label: {
                            SwiftUI.Label("Unsubscribe", systemImage: "bell.slash")
                        }
                        .tint(.orange)
                    }
                }
            }
            .themedRow()
        }
        .themedList()
        .listStyle(.plain)
        .searchable(
            text: $vm.searchText,
            placement: .navigationBarDrawer(displayMode: .always),
            prompt: "Search lists"
        )
        .confirmationDialog(
            pendingUnsubscribe.map { "Unsubscribe from \($0.name)?" } ?? "",
            isPresented: .init(
                get: { pendingUnsubscribe != nil },
                set: { if !$0 { pendingUnsubscribe = nil } }
            ),
            titleVisibility: .visible,
            presenting: pendingUnsubscribe
        ) { mailingList in
            Button("Unsubscribe", role: .destructive) {
                Task { await viewModel.unsubscribe(from: mailingList) }
            }
            Button("Cancel", role: .cancel) { pendingUnsubscribe = nil }
        } message: { _ in
            Text("You will stop receiving email from this list. Hutch cannot resubscribe you — you would need to do that from the list's page on the web.")
        }
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                Button {
                    showCreateSheet = true
                } label: {
                    SwiftUI.Label("New List", systemImage: "plus")
                }
                .disabled(viewModel.isPerformingAction)
            }
        }
        .sheet(isPresented: $showCreateSheet) {
            MailingListEditSheet(mode: .create, isPresented: $showCreateSheet) { name, description, visibility in
                await viewModel.createMailingList(name: name, description: description, visibility: visibility)
            }
        }
        .sheet(item: $editingList) { mailingList in
            MailingListEditSheet(
                mode: .edit(mailingList.name),
                isPresented: .init(get: { true }, set: { if !$0 { editingList = nil } }),
                loadInitialValues: { await viewModel.listSettings(rid: mailingList.rid) }
            ) { _, description, visibility in
                await viewModel.updateMailingList(id: mailingList.id, description: description, visibility: visibility)
            }
        }
        .confirmationDialog(
            pendingDeletion.map { "Delete \($0.name)?" } ?? "",
            isPresented: .init(
                get: { pendingDeletion != nil },
                set: { if !$0 { pendingDeletion = nil } }
            ),
            titleVisibility: .visible,
            presenting: pendingDeletion
        ) { mailingList in
            Button("Delete List", role: .destructive) {
                Task { await viewModel.deleteMailingList(mailingList) }
            }
            Button("Cancel", role: .cancel) { pendingDeletion = nil }
        } message: { _ in
            Text("This permanently deletes the list and its entire archive, for everyone. This cannot be undone.")
        }
        .overlay {
            if viewModel.isLoading, viewModel.mailingLists.isEmpty {
                SRHTLoadingStateView(message: "Loading mailing lists…")
            } else if let error = viewModel.error, viewModel.mailingLists.isEmpty {
                SRHTErrorStateView(
                    title: "Couldn't Load Mailing Lists",
                    message: error,
                    retryAction: { await viewModel.loadMailingLists() }
                )
            } else if !viewModel.mailingLists.isEmpty, viewModel.filteredMailingLists.isEmpty {
                ContentUnavailableView.search(text: viewModel.searchText)
            } else if viewModel.mailingLists.isEmpty {
                ContentUnavailableView(
                    "No Mailing Lists",
                    systemImage: "list.bullet.rectangle",
                    description: Text("Your subscribed mailing lists will appear here.")
                )
            }
        }
        .srhtErrorBanner(error: $vm.error)
        .refreshable {
            await viewModel.loadMailingLists()
        }
    }
}

// MARK: - Edit Sheet

/// Create and settings share a sheet: sr.ht takes name only at creation, and
/// description plus visibility in both cases.
private struct MailingListEditSheet: View {
    enum Mode {
        case create
        case edit(String)

        var title: String {
            switch self {
            case .create: "New Mailing List"
            case .edit(let name): name
            }
        }

        var isCreate: Bool {
            if case .create = self { return true }
            return false
        }
    }

    let mode: Mode
    @Binding var isPresented: Bool
    /// Seeds the sheet with the list's current values. Editing without this would
    /// save blanks over whatever is already there.
    var loadInitialValues: (() async -> (description: String, visibility: Visibility)?)?
    let onSubmit: (String, String, Visibility) async -> Bool

    @State private var name = ""
    @State private var description = ""
    @State private var visibility: Visibility = .publicVisibility
    @State private var isSubmitting = false
    @State private var isLoadingInitialValues = false
    @State private var hasLoadedInitialValues = false

    private var trimmedName: String {
        name.trimmingCharacters(in: .whitespacesAndNewlines)
    }

    private var canSubmit: Bool {
        guard !isSubmitting, !isLoadingInitialValues else { return false }
        if mode.isCreate { return !trimmedName.isEmpty }
        // Never offer to save values we have not read back yet.
        return hasLoadedInitialValues
    }

    var body: some View {
        NavigationStack {
            Form {
                if mode.isCreate {
                    Section("Name") {
                        TextField("list-name", text: $name)
                            .textInputAutocapitalization(.never)
                            .autocorrectionDisabled()
                            .themedRow()
                    }
                }

                Section("Description") {
                    TextField("Description", text: $description, axis: .vertical)
                        .lineLimit(2...6)
                        .themedRow()
                }

                Section("Visibility") {
                    Picker("Visibility", selection: $visibility) {
                        Text("Public").tag(Visibility.publicVisibility)
                        Text("Unlisted").tag(Visibility.unlisted)
                        Text("Private").tag(Visibility.privateVisibility)
                    }
                    .pickerStyle(.inline)
                    .labelsHidden()
                    .themedRow()
                }
            }
            .themedList()
            .navigationTitle(mode.title)
            .navigationBarTitleDisplayMode(.inline)
            .task {
                guard let loadInitialValues, !hasLoadedInitialValues else { return }
                isLoadingInitialValues = true
                if let current = await loadInitialValues() {
                    description = current.description
                    visibility = current.visibility
                    hasLoadedInitialValues = true
                }
                isLoadingInitialValues = false
            }
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") { isPresented = false }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button(mode.isCreate ? "Create" : "Save") {
                        Task {
                            isSubmitting = true
                            let ok = await onSubmit(trimmedName, description, visibility)
                            isSubmitting = false
                            if ok { isPresented = false }
                        }
                    }
                    .disabled(!canSubmit)
                }
            }
            .overlay {
                if isSubmitting || isLoadingInitialValues {
                    ProgressView()
                }
            }
        }
    }
}