krz/hutch

an ios client for sourcehut

clone: git clone https://gitbay.org/krz/hutch.git

v2.9.1: Hutch/Views/Tickets/TrackerManagementView.swift · raw

   1import SwiftUI
   2
   3private struct TrackerQueryResponse: Decodable, Sendable {
   4    let tracker: TrackerSummary?
   5}
   6
   7private struct TrackerACLQueryResponse: Decodable, Sendable {
   8    let tracker: TrackerACLQueryPayload?
   9}
  10
  11private struct TrackerACLQueryPayload: Decodable, Sendable {
  12    let defaultACL: DefaultTrackerACL
  13    let acls: TrackerACLPage
  14}
  15
  16private struct TrackerACLPage: Decodable, Sendable {
  17    let results: [TrackerACL]
  18    let cursor: String?
  19}
  20
  21private struct TrackerLabelQueryResponse: Decodable, Sendable {
  22    let tracker: TrackerLabelQueryPayload?
  23}
  24
  25private struct TrackerLabelQueryPayload: Decodable, Sendable {
  26    let labels: TrackerLabelPage
  27}
  28
  29private struct TrackerLabelPage: Decodable, Sendable {
  30    let results: [TicketLabel]
  31    let cursor: String?
  32}
  33
  34private struct UpdateTrackerResponse: Decodable, Sendable {
  35    let updateTracker: TrackerSummary
  36}
  37
  38private struct DeleteTrackerResponse: Decodable, Sendable {
  39    let deleteTracker: DeletedTracker
  40}
  41
  42private struct DeletedTracker: Decodable, Sendable {
  43    let id: Int
  44}
  45
  46private struct UpdateUserACLResponse: Decodable, Sendable {
  47    let updateUserACL: TrackerACL
  48}
  49
  50private struct UpdateTrackerACLResponse: Decodable, Sendable {
  51    let updateTrackerACL: DefaultTrackerACL
  52}
  53
  54private struct DeleteTrackerACLResponse: Decodable, Sendable {
  55    let deleteACL: TrackerACL
  56}
  57
  58private struct CreateTrackerLabelResponse: Decodable, Sendable {
  59    let createLabel: TicketLabel
  60}
  61
  62private struct UpdateTrackerLabelResponse: Decodable, Sendable {
  63    let updateLabel: TicketLabel
  64}
  65
  66private struct DeleteTrackerLabelResponse: Decodable, Sendable {
  67    let deleteLabel: TicketLabel
  68}
  69
  70private struct TrackerUserLookupResponse: Decodable, Sendable {
  71    let user: UserIdPayload?
  72}
  73
  74private struct UserIdPayload: Decodable, Sendable {
  75    let id: Int
  76}
  77
  78@Observable
  79@MainActor
  80final class TrackerManagementViewModel {
  81    private(set) var tracker: TrackerSummary
  82    private(set) var acls: [TrackerACL] = []
  83    private(set) var defaultACL = DefaultTrackerACL(
  84        browse: true,
  85        submit: true,
  86        comment: true,
  87        edit: false,
  88        triage: false
  89    )
  90    private(set) var labels: [TicketLabel] = []
  91
  92    private(set) var isSavingTracker = false
  93    private(set) var isDeletingTracker = false
  94    private(set) var isLoadingACLs = false
  95    private(set) var isSavingACL = false
  96    private(set) var isDeletingACL = false
  97    private(set) var isLoadingLabels = false
  98    private(set) var isSavingLabel = false
  99    private(set) var isDeletingLabel = false
 100
 101    var error: String?
 102    var didDeleteTracker = false
 103
 104    private let client: SRHTClient
 105
 106    init(tracker: TrackerSummary, client: SRHTClient) {
 107        self.tracker = tracker
 108        self.client = client
 109    }
 110
 111    private static let trackerQuery = """
 112    query tracker($rid: ID!) {
 113        tracker(rid: $rid) {
 114            id
 115            rid
 116            name
 117            description
 118            visibility
 119            updated
 120            owner { canonicalName }
 121        }
 122    }
 123    """
 124
 125    private static let trackerACLsQuery = """
 126    query trackerACLs($rid: ID!, $cursor: Cursor) {
 127        tracker(rid: $rid) {
 128            defaultACL {
 129                browse
 130                submit
 131                comment
 132                edit
 133                triage
 134            }
 135            acls(cursor: $cursor) {
 136                results {
 137                    id
 138                    created
 139                    entity { canonicalName }
 140                    browse
 141                    submit
 142                    comment
 143                    edit
 144                    triage
 145                }
 146                cursor
 147            }
 148        }
 149    }
 150    """
 151
 152    private static let trackerLabelsQuery = """
 153    query trackerLabels($rid: ID!, $cursor: Cursor) {
 154        tracker(rid: $rid) {
 155            labels(cursor: $cursor) {
 156                results {
 157                    id
 158                    name
 159                    backgroundColor
 160                    foregroundColor
 161                }
 162                cursor
 163            }
 164        }
 165    }
 166    """
 167
 168    private static let updateTrackerMutation = """
 169    mutation updateTracker($id: Int!, $input: TrackerInput!) {
 170        updateTracker(id: $id, input: $input) {
 171            id
 172            rid
 173            name
 174            description
 175            visibility
 176            updated
 177            owner { canonicalName }
 178        }
 179    }
 180    """
 181
 182    private static let deleteTrackerMutation = """
 183    mutation deleteTracker($id: Int!) {
 184        deleteTracker(id: $id) {
 185            id
 186        }
 187    }
 188    """
 189
 190    private static let updateUserACLMutation = """
 191    mutation updateUserACL($trackerId: Int!, $userId: Int!, $input: ACLInput!) {
 192        updateUserACL(trackerId: $trackerId, userId: $userId, input: $input) {
 193            id
 194            created
 195            entity { canonicalName }
 196            browse
 197            submit
 198            comment
 199            edit
 200            triage
 201        }
 202    }
 203    """
 204
 205    private static let updateTrackerACLMutation = """
 206    mutation updateTrackerACL($trackerId: Int!, $input: ACLInput!) {
 207        updateTrackerACL(trackerId: $trackerId, input: $input) {
 208            browse
 209            submit
 210            comment
 211            edit
 212            triage
 213        }
 214    }
 215    """
 216
 217    private static let deleteACLMutation = """
 218    mutation deleteACL($id: Int!) {
 219        deleteACL(id: $id) {
 220            id
 221            created
 222            entity { canonicalName }
 223            browse
 224            submit
 225            comment
 226            edit
 227            triage
 228        }
 229    }
 230    """
 231
 232    private static let createLabelMutation = """
 233    mutation createLabel($trackerId: Int!, $name: String!, $foregroundColor: String!, $backgroundColor: String!) {
 234        createLabel(trackerId: $trackerId, name: $name, foregroundColor: $foregroundColor, backgroundColor: $backgroundColor) {
 235            id
 236            name
 237            backgroundColor
 238            foregroundColor
 239        }
 240    }
 241    """
 242
 243    private static let updateLabelMutation = """
 244    mutation updateLabel($id: Int!, $input: UpdateLabelInput!) {
 245        updateLabel(id: $id, input: $input) {
 246            id
 247            name
 248            backgroundColor
 249            foregroundColor
 250        }
 251    }
 252    """
 253
 254    private static let deleteLabelMutation = """
 255    mutation deleteLabel($id: Int!) {
 256        deleteLabel(id: $id) {
 257            id
 258            name
 259            backgroundColor
 260            foregroundColor
 261        }
 262    }
 263    """
 264
 265    private static let userLookupQuery = """
 266    query userLookup($username: String!) {
 267        user(username: $username) {
 268            id
 269        }
 270    }
 271    """
 272
 273    func refreshTracker() async {
 274        do {
 275            let result = try await client.execute(
 276                service: .todo,
 277                query: Self.trackerQuery,
 278                variables: ["rid": tracker.rid],
 279                responseType: TrackerQueryResponse.self
 280            )
 281            if let tracker = result.tracker {
 282                self.tracker = tracker
 283            }
 284        } catch {
 285            self.error = error.userFacingMessage
 286        }
 287    }
 288
 289    func updateTracker(name: String, description: String, visibility: Visibility) async -> TrackerSummary? {
 290        guard !isSavingTracker else { return nil }
 291        let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
 292        guard !trimmedName.isEmpty else {
 293            error = "Enter a tracker name."
 294            return nil
 295        }
 296
 297        isSavingTracker = true
 298        error = nil
 299        defer { isSavingTracker = false }
 300
 301        var input: [String: any Sendable] = [
 302            "name": trimmedName,
 303            "visibility": visibility.rawValue
 304        ]
 305        let trimmedDescription = description.trimmingCharacters(in: .whitespacesAndNewlines)
 306        input["description"] = trimmedDescription.isEmpty ? "" : trimmedDescription
 307
 308        do {
 309            let result = try await client.execute(
 310                service: .todo,
 311                query: Self.updateTrackerMutation,
 312                variables: [
 313                    "id": tracker.id,
 314                    "input": input
 315                ],
 316                responseType: UpdateTrackerResponse.self
 317            )
 318            tracker = result.updateTracker
 319            return result.updateTracker
 320        } catch {
 321            self.error = "Couldn’t update the tracker. \(error.userFacingMessage)"
 322            return nil
 323        }
 324    }
 325
 326    func deleteTracker() async -> Bool {
 327        guard !isDeletingTracker else { return false }
 328        isDeletingTracker = true
 329        error = nil
 330        defer { isDeletingTracker = false }
 331
 332        do {
 333            _ = try await client.execute(
 334                service: .todo,
 335                query: Self.deleteTrackerMutation,
 336                variables: ["id": tracker.id],
 337                responseType: DeleteTrackerResponse.self
 338            )
 339            didDeleteTracker = true
 340            return true
 341        } catch {
 342            self.error = "Couldn’t delete the tracker. \(error.userFacingMessage)"
 343            return false
 344        }
 345    }
 346
 347    func loadACLs() async {
 348        guard !isLoadingACLs else { return }
 349        isLoadingACLs = true
 350        error = nil
 351        defer { isLoadingACLs = false }
 352
 353        do {
 354            let result = try await client.execute(
 355                service: .todo,
 356                query: Self.trackerACLsQuery,
 357                variables: ["rid": tracker.rid],
 358                responseType: TrackerACLQueryResponse.self
 359            )
 360            defaultACL = result.tracker?.defaultACL ?? defaultACL
 361            acls = result.tracker?.acls.results ?? []
 362        } catch {
 363            self.error = error.userFacingMessage
 364        }
 365    }
 366
 367    func updateDefaultACL(_ permissions: TrackerACLPermissions) async -> Bool {
 368        guard !isSavingACL else { return false }
 369        isSavingACL = true
 370        error = nil
 371        defer { isSavingACL = false }
 372
 373        do {
 374            let result = try await client.execute(
 375                service: .todo,
 376                query: Self.updateTrackerACLMutation,
 377                variables: [
 378                    "trackerId": tracker.id,
 379                    "input": permissions.graphQLInput
 380                ],
 381                responseType: UpdateTrackerACLResponse.self
 382            )
 383            defaultACL = result.updateTrackerACL
 384            await loadACLs()
 385            return true
 386        } catch {
 387            self.error = error.userFacingMessage
 388            return false
 389        }
 390    }
 391
 392    func addOrUpdateACL(username: String, permissions: TrackerACLPermissions) async -> Bool {
 393        guard !isSavingACL else { return false }
 394        let normalizedUsername = Self.normalizedUsername(username)
 395        guard !normalizedUsername.isEmpty else {
 396            error = "Enter a SourceHut username."
 397            return false
 398        }
 399
 400        isSavingACL = true
 401        error = nil
 402        defer { isSavingACL = false }
 403
 404        do {
 405            let userResult = try await client.execute(
 406                service: .todo,
 407                query: Self.userLookupQuery,
 408                variables: ["username": normalizedUsername],
 409                responseType: TrackerUserLookupResponse.self
 410            )
 411            guard let userId = userResult.user?.id else {
 412                error = "That user couldn’t be found."
 413                return false
 414            }
 415
 416            let result = try await client.execute(
 417                service: .todo,
 418                query: Self.updateUserACLMutation,
 419                variables: [
 420                    "trackerId": tracker.id,
 421                    "userId": userId,
 422                    "input": permissions.graphQLInput
 423                ],
 424                responseType: UpdateUserACLResponse.self
 425            )
 426            if let index = acls.firstIndex(where: { $0.id == result.updateUserACL.id }) {
 427                acls[index] = result.updateUserACL
 428            } else {
 429                acls.append(result.updateUserACL)
 430                acls.sort { $0.entity.canonicalName.localizedCaseInsensitiveCompare($1.entity.canonicalName) == .orderedAscending }
 431            }
 432            await loadACLs()
 433            return true
 434        } catch {
 435            self.error = error.userFacingMessage
 436            return false
 437        }
 438    }
 439
 440    func deleteACL(_ entry: TrackerACL) async {
 441        guard !isDeletingACL else { return }
 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 }
 454            await loadACLs()
 455        } catch {
 456            self.error = error.userFacingMessage
 457        }
 458    }
 459
 460    func loadLabels() async {
 461        guard !isLoadingLabels else { return }
 462        isLoadingLabels = true
 463        error = nil
 464        defer { isLoadingLabels = false }
 465
 466        do {
 467            let result = try await client.execute(
 468                service: .todo,
 469                query: Self.trackerLabelsQuery,
 470                variables: ["rid": tracker.rid],
 471                responseType: TrackerLabelQueryResponse.self
 472            )
 473            labels = result.tracker?.labels.results ?? []
 474        } catch {
 475            self.error = error.userFacingMessage
 476        }
 477    }
 478
 479    func createLabel(name: String, foregroundColor: String, backgroundColor: String) async -> Bool {
 480        guard !isSavingLabel else { return false }
 481        let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
 482        guard !trimmedName.isEmpty else {
 483            error = "Enter a label name."
 484            return false
 485        }
 486        guard Self.isValidHexColor(foregroundColor), Self.isValidHexColor(backgroundColor) else {
 487            error = "Label colors must use #RRGGBB format."
 488            return false
 489        }
 490
 491        isSavingLabel = true
 492        error = nil
 493        defer { isSavingLabel = false }
 494
 495        do {
 496            _ = try await client.execute(
 497                service: .todo,
 498                query: Self.createLabelMutation,
 499                variables: [
 500                    "trackerId": tracker.id,
 501                    "name": trimmedName,
 502                    "foregroundColor": foregroundColor,
 503                    "backgroundColor": backgroundColor
 504                ],
 505                responseType: CreateTrackerLabelResponse.self
 506            )
 507            await loadLabels()
 508            return true
 509        } catch {
 510            self.error = error.userFacingMessage
 511            return false
 512        }
 513    }
 514
 515    func updateLabel(
 516        _ label: TicketLabel,
 517        name: String,
 518        foregroundColor: String,
 519        backgroundColor: String
 520    ) async -> Bool {
 521        guard !isSavingLabel else { return false }
 522        let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
 523        guard !trimmedName.isEmpty else {
 524            error = "Enter a label name."
 525            return false
 526        }
 527        guard Self.isValidHexColor(foregroundColor), Self.isValidHexColor(backgroundColor) else {
 528            error = "Label colors must use #RRGGBB format."
 529            return false
 530        }
 531
 532        isSavingLabel = true
 533        error = nil
 534        defer { isSavingLabel = false }
 535
 536        var input: [String: any Sendable] = [:]
 537        if trimmedName != label.name {
 538            input["name"] = trimmedName
 539        }
 540        if foregroundColor.caseInsensitiveCompare(label.foregroundColor) != .orderedSame {
 541            input["foregroundColor"] = foregroundColor
 542        }
 543        if backgroundColor.caseInsensitiveCompare(label.backgroundColor) != .orderedSame {
 544            input["backgroundColor"] = backgroundColor
 545        }
 546
 547        guard !input.isEmpty else { return true }
 548
 549        do {
 550            _ = try await client.execute(
 551                service: .todo,
 552                query: Self.updateLabelMutation,
 553                variables: [
 554                    "id": label.id,
 555                    "input": input
 556                ],
 557                responseType: UpdateTrackerLabelResponse.self
 558            )
 559            await loadLabels()
 560            return true
 561        } catch {
 562            self.error = error.userFacingMessage
 563            return false
 564        }
 565    }
 566
 567    func deleteLabel(_ label: TicketLabel) async {
 568        guard !isDeletingLabel else { return }
 569        isDeletingLabel = true
 570        error = nil
 571        defer { isDeletingLabel = false }
 572
 573        do {
 574            _ = try await client.execute(
 575                service: .todo,
 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 {
 583            self.error = error.userFacingMessage
 584        }
 585    }
 586
 587    static func normalizedUsername(_ value: String) -> String {
 588        let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
 589        guard !trimmed.isEmpty else { return "" }
 590        return trimmed.hasPrefix("~") ? String(trimmed.dropFirst()) : trimmed
 591    }
 592
 593    static func isValidHexColor(_ value: String) -> Bool {
 594        let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
 595        guard trimmed.count == 7, trimmed.first == "#" else { return false }
 596        return trimmed.dropFirst().allSatisfy { $0.isHexDigit }
 597    }
 598}
 599
 600private extension TrackerACLPermissions {
 601    var graphQLInput: [String: any Sendable] {
 602        [
 603            "browse": browse,
 604            "submit": submit,
 605            "comment": comment,
 606            "edit": edit,
 607            "triage": triage
 608        ]
 609    }
 610}
 611
 612struct TrackerEditorSheet: View {
 613    let title: String
 614    let confirmationTitle: String
 615    let isSaving: Bool
 616    let error: String?
 617    let initialName: String
 618    let initialDescription: String
 619    let initialVisibility: Visibility
 620    let onSave: (String, String, Visibility) async -> Bool
 621
 622    @Environment(\.dismiss) private var dismiss
 623    @State private var name: String
 624    @State private var description: String
 625    @State private var visibility: Visibility
 626
 627    init(
 628        title: String,
 629        confirmationTitle: String,
 630        isSaving: Bool,
 631        error: String?,
 632        initialName: String,
 633        initialDescription: String,
 634        initialVisibility: Visibility,
 635        onSave: @escaping (String, String, Visibility) async -> Bool
 636    ) {
 637        self.title = title
 638        self.confirmationTitle = confirmationTitle
 639        self.isSaving = isSaving
 640        self.error = error
 641        self.initialName = initialName
 642        self.initialDescription = initialDescription
 643        self.initialVisibility = initialVisibility
 644        self.onSave = onSave
 645        _name = State(initialValue: initialName)
 646        _description = State(initialValue: initialDescription)
 647        _visibility = State(initialValue: initialVisibility)
 648    }
 649
 650    var body: some View {
 651        NavigationStack {
 652            Form {
 653                Section("Tracker Details") {
 654                    TextField("Tracker name", text: $name)
 655                        .textInputAutocapitalization(.never)
 656                        .autocorrectionDisabled()
 657                    TextField("Short description (optional)", text: $description, axis: .vertical)
 658                        .lineLimit(2...4)
 659                    Picker("Visibility", selection: $visibility) {
 660                        Text("Public").tag(Visibility.public)
 661                        Text("Unlisted").tag(Visibility.unlisted)
 662                        Text("Private").tag(Visibility.private)
 663                    }
 664                }
 665
 666                if let error, !error.isEmpty {
 667                    Section {
 668                        Text(error)
 669                            .foregroundStyle(.red)
 670                    }
 671                }
 672            }
 673            .navigationTitle(title)
 674            .navigationBarTitleDisplayMode(.inline)
 675            .toolbar {
 676                ToolbarItem(placement: .cancellationAction) {
 677                    Button("Cancel") { dismiss() }
 678                }
 679                ToolbarItem(placement: .confirmationAction) {
 680                    Button {
 681                        Task {
 682                            let didSave = await onSave(name, description, visibility)
 683                            if didSave {
 684                                dismiss()
 685                            }
 686                        }
 687                    } label: {
 688                        if isSaving {
 689                            ProgressView()
 690                                .controlSize(.small)
 691                        } else {
 692                            Text(confirmationTitle)
 693                        }
 694                    }
 695                    .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || isSaving)
 696                }
 697            }
 698        }
 699    }
 700}
 701
 702struct TrackerACLManagementSheet: View {
 703    let viewModel: TrackerManagementViewModel
 704
 705    @Bindable private var bindableViewModel: TrackerManagementViewModel
 706    @State private var editingACL: TrackerACL?
 707    @State private var editingDefaultACL = false
 708    @State private var pendingDeletion: TrackerACL?
 709    @State private var showCreateACL = false
 710
 711    init(viewModel: TrackerManagementViewModel) {
 712        self.viewModel = viewModel
 713        self._bindableViewModel = Bindable(viewModel)
 714    }
 715
 716    var body: some View {
 717        NavigationStack {
 718            List {
 719                Section("Default Access") {
 720                    TrackerPermissionSummary(permissions: viewModel.defaultACL.permissions)
 721                    Button("Update Default ACL") {
 722                        editingDefaultACL = true
 723                    }
 724                    .disabled(viewModel.isSavingACL)
 725                }
 726
 727                Section {
 728                    if viewModel.isLoadingACLs {
 729                        HStack {
 730                            Spacer()
 731                            ProgressView()
 732                            Spacer()
 733                        }
 734                    } else if viewModel.acls.isEmpty {
 735                        Text("No tracker-specific ACLs yet.")
 736                            .foregroundStyle(.secondary)
 737                    } else {
 738                        ForEach(viewModel.acls) { entry in
 739                            VStack(alignment: .leading, spacing: 6) {
 740                                Text(entry.entity.canonicalName)
 741                                    .font(.subheadline.weight(.medium))
 742                                TrackerPermissionSummary(permissions: entry.permissions)
 743                            }
 744                            .swipeActions(edge: .trailing, allowsFullSwipe: false) {
 745                                Button(role: .destructive) {
 746                                    pendingDeletion = entry
 747                                } label: {
 748                                    Label("Delete", systemImage: "trash")
 749                                }
 750
 751                                Button {
 752                                    editingACL = entry
 753                                } label: {
 754                                    Label("Edit", systemImage: "pencil")
 755                                }
 756                                .tint(.blue)
 757                            }
 758                        }
 759                    }
 760                } header: {
 761                    Text("User ACLs")
 762                } footer: {
 763                    Text("Each ACL must include all five permission flags.")
 764                }
 765            }
 766            .navigationTitle("ACLs")
 767            .navigationBarTitleDisplayMode(.inline)
 768            .toolbar {
 769                ToolbarItem(placement: .topBarTrailing) {
 770                    Button {
 771                        showCreateACL = true
 772                    } label: {
 773                        Image(systemName: "plus")
 774                    }
 775                    .disabled(viewModel.isSavingACL)
 776                }
 777            }
 778            .task {
 779                await viewModel.loadACLs()
 780            }
 781            .srhtErrorBanner(error: $bindableViewModel.error)
 782            .sheet(isPresented: $showCreateACL) {
 783                TrackerACLEditorSheet(
 784                    title: "Add ACL",
 785                    submitTitle: "Save",
 786                    isSaving: viewModel.isSavingACL,
 787                    error: viewModel.error,
 788                    initialUsername: "",
 789                    initialPermissions: viewModel.defaultACL.permissions
 790                ) { username, permissions in
 791                    await viewModel.addOrUpdateACL(username: username, permissions: permissions)
 792                }
 793            }
 794            .sheet(item: $editingACL) { entry in
 795                TrackerACLEditorSheet(
 796                    title: "Update ACL",
 797                    submitTitle: "Save",
 798                    isSaving: viewModel.isSavingACL,
 799                    error: viewModel.error,
 800                    initialUsername: entry.entity.canonicalName,
 801                    initialPermissions: entry.permissions
 802                ) { username, permissions in
 803                    await viewModel.addOrUpdateACL(username: username, permissions: permissions)
 804                }
 805            }
 806            .sheet(isPresented: $editingDefaultACL) {
 807                TrackerDefaultACLEditorSheet(
 808                    isSaving: viewModel.isSavingACL,
 809                    error: viewModel.error,
 810                    initialPermissions: viewModel.defaultACL.permissions
 811                ) { permissions in
 812                    await viewModel.updateDefaultACL(permissions)
 813                }
 814            }
 815            .alert("Remove Access?", isPresented: Binding(
 816                get: { pendingDeletion != nil },
 817                set: { isPresented in
 818                    if !isPresented {
 819                        pendingDeletion = nil
 820                    }
 821                }
 822            )) {
 823                Button("Cancel", role: .cancel) {}
 824                Button("Delete", role: .destructive) {
 825                    guard let pendingDeletion else { return }
 826                    Task {
 827                        await viewModel.deleteACL(pendingDeletion)
 828                        self.pendingDeletion = nil
 829                    }
 830                }
 831            } message: {
 832                if let pendingDeletion {
 833                    Text("\(pendingDeletion.entity.canonicalName) will fall back to the tracker default ACL.")
 834                }
 835            }
 836        }
 837    }
 838}
 839
 840private struct TrackerPermissionSummary: View {
 841    let permissions: TrackerACLPermissions
 842
 843    var body: some View {
 844        Text(summary)
 845            .font(.caption)
 846            .foregroundStyle(.secondary)
 847    }
 848
 849    private var summary: String {
 850        let items = [
 851            permissions.browse ? "browse" : nil,
 852            permissions.submit ? "submit" : nil,
 853            permissions.comment ? "comment" : nil,
 854            permissions.edit ? "edit" : nil,
 855            permissions.triage ? "triage" : nil
 856        ].compactMap { $0 }
 857        return items.isEmpty ? "No permissions" : items.joined(separator: ", ")
 858    }
 859}
 860
 861private struct TrackerACLEditorSheet: View {
 862    let title: String
 863    let submitTitle: String
 864    let isSaving: Bool
 865    let error: String?
 866    let initialUsername: String
 867    let initialPermissions: TrackerACLPermissions
 868    let onSave: (String, TrackerACLPermissions) async -> Bool
 869
 870    @Environment(\.dismiss) private var dismiss
 871    @State private var username: String
 872    @State private var browse: Bool
 873    @State private var submit: Bool
 874    @State private var comment: Bool
 875    @State private var edit: Bool
 876    @State private var triage: Bool
 877
 878    init(
 879        title: String,
 880        submitTitle: String,
 881        isSaving: Bool,
 882        error: String?,
 883        initialUsername: String,
 884        initialPermissions: TrackerACLPermissions,
 885        onSave: @escaping (String, TrackerACLPermissions) async -> Bool
 886    ) {
 887        self.title = title
 888        self.submitTitle = submitTitle
 889        self.isSaving = isSaving
 890        self.error = error
 891        self.initialUsername = initialUsername
 892        self.initialPermissions = initialPermissions
 893        self.onSave = onSave
 894        _username = State(initialValue: initialUsername)
 895        _browse = State(initialValue: initialPermissions.browse)
 896        _submit = State(initialValue: initialPermissions.submit)
 897        _comment = State(initialValue: initialPermissions.comment)
 898        _edit = State(initialValue: initialPermissions.edit)
 899        _triage = State(initialValue: initialPermissions.triage)
 900    }
 901
 902    var body: some View {
 903        NavigationStack {
 904            Form {
 905                Section("User") {
 906                    TextField("Username or ~username", text: $username)
 907                        .autocorrectionDisabled()
 908                        .textInputAutocapitalization(.never)
 909                }
 910
 911                permissionSection
 912
 913                if let error, !error.isEmpty {
 914                    Section {
 915                        Text(error)
 916                            .foregroundStyle(.red)
 917                    }
 918                }
 919            }
 920            .navigationTitle(title)
 921            .navigationBarTitleDisplayMode(.inline)
 922            .toolbar {
 923                ToolbarItem(placement: .cancellationAction) {
 924                    Button("Cancel") { dismiss() }
 925                }
 926                ToolbarItem(placement: .confirmationAction) {
 927                    Button {
 928                        Task {
 929                            let didSave = await onSave(username, permissions)
 930                            if didSave {
 931                                dismiss()
 932                            }
 933                        }
 934                    } label: {
 935                        if isSaving {
 936                            ProgressView()
 937                                .controlSize(.small)
 938                        } else {
 939                            Text(submitTitle)
 940                        }
 941                    }
 942                    .disabled(username.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || isSaving)
 943                }
 944            }
 945        }
 946    }
 947
 948    private var permissionSection: some View {
 949        Section("Permissions") {
 950            Toggle("Browse", isOn: $browse)
 951            Toggle("Submit", isOn: $submit)
 952            Toggle("Comment", isOn: $comment)
 953            Toggle("Edit", isOn: $edit)
 954            Toggle("Triage", isOn: $triage)
 955        }
 956    }
 957
 958    private var permissions: TrackerACLPermissions {
 959        TrackerACLPermissions(
 960            browse: browse,
 961            submit: submit,
 962            comment: comment,
 963            edit: edit,
 964            triage: triage
 965        )
 966    }
 967}
 968
 969private struct TrackerDefaultACLEditorSheet: View {
 970    let isSaving: Bool
 971    let error: String?
 972    let initialPermissions: TrackerACLPermissions
 973    let onSave: (TrackerACLPermissions) async -> Bool
 974
 975    @Environment(\.dismiss) private var dismiss
 976    @State private var browse: Bool
 977    @State private var submit: Bool
 978    @State private var comment: Bool
 979    @State private var edit: Bool
 980    @State private var triage: Bool
 981
 982    init(
 983        isSaving: Bool,
 984        error: String?,
 985        initialPermissions: TrackerACLPermissions,
 986        onSave: @escaping (TrackerACLPermissions) async -> Bool
 987    ) {
 988        self.isSaving = isSaving
 989        self.error = error
 990        self.initialPermissions = initialPermissions
 991        self.onSave = onSave
 992        _browse = State(initialValue: initialPermissions.browse)
 993        _submit = State(initialValue: initialPermissions.submit)
 994        _comment = State(initialValue: initialPermissions.comment)
 995        _edit = State(initialValue: initialPermissions.edit)
 996        _triage = State(initialValue: initialPermissions.triage)
 997    }
 998
 999    var body: some View {
1000        NavigationStack {
1001            Form {
1002                Section("Permissions") {
1003                    Toggle("Browse", isOn: $browse)
1004                    Toggle("Submit", isOn: $submit)
1005                    Toggle("Comment", isOn: $comment)
1006                    Toggle("Edit", isOn: $edit)
1007                    Toggle("Triage", isOn: $triage)
1008                }
1009
1010                if let error, !error.isEmpty {
1011                    Section {
1012                        Text(error)
1013                            .foregroundStyle(.red)
1014                    }
1015                }
1016            }
1017            .navigationTitle("Default ACL")
1018            .navigationBarTitleDisplayMode(.inline)
1019            .toolbar {
1020                ToolbarItem(placement: .cancellationAction) {
1021                    Button("Cancel") { dismiss() }
1022                }
1023                ToolbarItem(placement: .confirmationAction) {
1024                    Button {
1025                        Task {
1026                            let didSave = await onSave(
1027                                TrackerACLPermissions(
1028                                    browse: browse,
1029                                    submit: submit,
1030                                    comment: comment,
1031                                    edit: edit,
1032                                    triage: triage
1033                                )
1034                            )
1035                            if didSave {
1036                                dismiss()
1037                            }
1038                        }
1039                    } label: {
1040                        if isSaving {
1041                            ProgressView()
1042                                .controlSize(.small)
1043                        } else {
1044                            Text("Save")
1045                        }
1046                    }
1047                    .disabled(isSaving)
1048                }
1049            }
1050        }
1051    }
1052}
1053
1054struct TrackerLabelManagementSheet: View {
1055    let viewModel: TrackerManagementViewModel
1056
1057    @Bindable private var bindableViewModel: TrackerManagementViewModel
1058    @State private var showCreateLabel = false
1059    @State private var editingLabel: TicketLabel?
1060    @State private var pendingDeletion: TicketLabel?
1061
1062    init(viewModel: TrackerManagementViewModel) {
1063        self.viewModel = viewModel
1064        self._bindableViewModel = Bindable(viewModel)
1065    }
1066
1067    var body: some View {
1068        NavigationStack {
1069            List {
1070                if viewModel.isLoadingLabels {
1071                    HStack {
1072                        Spacer()
1073                        ProgressView()
1074                        Spacer()
1075                    }
1076                } else if viewModel.labels.isEmpty {
1077                    ContentUnavailableView(
1078                        "No Labels",
1079                        systemImage: "tag",
1080                        description: Text("Create labels for triage and organization.")
1081                    )
1082                } else {
1083                    ForEach(viewModel.labels) { label in
1084                        HStack {
1085                            LabelPill(label: label)
1086                            Spacer()
1087                        }
1088                        .swipeActions(edge: .trailing, allowsFullSwipe: false) {
1089                            Button {
1090                                editingLabel = label
1091                            } label: {
1092                                Label("Edit", systemImage: "pencil")
1093                            }
1094                            .tint(.blue)
1095
1096                            Button(role: .destructive) {
1097                                pendingDeletion = label
1098                            } label: {
1099                                Label("Delete", systemImage: "trash")
1100                            }
1101                        }
1102                    }
1103                }
1104            }
1105            .navigationTitle("Labels")
1106            .navigationBarTitleDisplayMode(.inline)
1107            .toolbar {
1108                ToolbarItem(placement: .topBarTrailing) {
1109                    Button {
1110                        showCreateLabel = true
1111                    } label: {
1112                        Image(systemName: "plus")
1113                    }
1114                    .disabled(viewModel.isSavingLabel)
1115                }
1116            }
1117            .task {
1118                await viewModel.loadLabels()
1119            }
1120            .srhtErrorBanner(error: $bindableViewModel.error)
1121            .sheet(isPresented: $showCreateLabel) {
1122                TrackerLabelEditorSheet(
1123                    title: "New Label",
1124                    submitTitle: "Create",
1125                    isSaving: viewModel.isSavingLabel,
1126                    error: viewModel.error,
1127                    initialLabel: nil
1128                ) { name, foreground, background in
1129                    await viewModel.createLabel(
1130                        name: name,
1131                        foregroundColor: foreground,
1132                        backgroundColor: background
1133                    )
1134                }
1135            }
1136            .sheet(item: $editingLabel) { label in
1137                TrackerLabelEditorSheet(
1138                    title: "Update Label",
1139                    submitTitle: "Save",
1140                    isSaving: viewModel.isSavingLabel,
1141                    error: viewModel.error,
1142                    initialLabel: label
1143                ) { name, foreground, background in
1144                    await viewModel.updateLabel(
1145                        label,
1146                        name: name,
1147                        foregroundColor: foreground,
1148                        backgroundColor: background
1149                    )
1150                }
1151            }
1152            .alert("Delete Label?", isPresented: Binding(
1153                get: { pendingDeletion != nil },
1154                set: { isPresented in
1155                    if !isPresented {
1156                        pendingDeletion = nil
1157                    }
1158                }
1159            )) {
1160                Button("Cancel", role: .cancel) {}
1161                Button("Delete", role: .destructive) {
1162                    guard let pendingDeletion else { return }
1163                    Task {
1164                        await viewModel.deleteLabel(pendingDeletion)
1165                        self.pendingDeletion = nil
1166                    }
1167                }
1168            } message: {
1169                if let pendingDeletion {
1170                    Text("\(pendingDeletion.name)” will be removed from this tracker and from any tickets using it.")
1171                }
1172            }
1173        }
1174    }
1175}
1176
1177private struct TrackerLabelEditorSheet: View {
1178    let title: String
1179    let submitTitle: String
1180    let isSaving: Bool
1181    let error: String?
1182    let initialLabel: TicketLabel?
1183    let onSave: (String, String, String) async -> Bool
1184
1185    @Environment(\.dismiss) private var dismiss
1186    @State private var name: String
1187    @State private var foregroundColor: Color
1188    @State private var backgroundColor: Color
1189
1190    init(
1191        title: String,
1192        submitTitle: String,
1193        isSaving: Bool,
1194        error: String?,
1195        initialLabel: TicketLabel?,
1196        onSave: @escaping (String, String, String) async -> Bool
1197    ) {
1198        self.title = title
1199        self.submitTitle = submitTitle
1200        self.isSaving = isSaving
1201        self.error = error
1202        self.initialLabel = initialLabel
1203        self.onSave = onSave
1204        _name = State(initialValue: initialLabel?.name ?? "")
1205        _foregroundColor = State(initialValue: Color(hex: initialLabel?.foregroundColor ?? "#ffffff") ?? .white)
1206        _backgroundColor = State(initialValue: Color(hex: initialLabel?.backgroundColor ?? "#000000") ?? .black)
1207    }
1208
1209    var body: some View {
1210        NavigationStack {
1211            Form {
1212                Section("Details") {
1213                    TextField("Label name", text: $name)
1214                    ColorPicker("Foreground", selection: $foregroundColor, supportsOpacity: false)
1215                    ColorPicker("Background", selection: $backgroundColor, supportsOpacity: false)
1216                }
1217
1218                Section("Preview") {
1219                    LabelPill(
1220                        label: TicketLabel(
1221                            id: initialLabel?.id ?? -1,
1222                            name: name.isEmpty ? "Preview" : name,
1223                            backgroundColor: backgroundColor.hexString,
1224                            foregroundColor: foregroundColor.hexString
1225                        )
1226                    )
1227                }
1228
1229                if let error, !error.isEmpty {
1230                    Section {
1231                        Text(error)
1232                            .foregroundStyle(.red)
1233                    }
1234                }
1235            }
1236            .navigationTitle(title)
1237            .navigationBarTitleDisplayMode(.inline)
1238            .toolbar {
1239                ToolbarItem(placement: .cancellationAction) {
1240                    Button("Cancel") { dismiss() }
1241                }
1242                ToolbarItem(placement: .confirmationAction) {
1243                    Button {
1244                        Task {
1245                            let didSave = await onSave(
1246                                name,
1247                                foregroundColor.hexString,
1248                                backgroundColor.hexString
1249                            )
1250                            if didSave {
1251                                dismiss()
1252                            }
1253                        }
1254                    } label: {
1255                        if isSaving {
1256                            ProgressView()
1257                                .controlSize(.small)
1258                        } else {
1259                            Text(submitTitle)
1260                        }
1261                    }
1262                    .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || isSaving)
1263                }
1264            }
1265        }
1266    }
1267}