-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathManagementViews.swift
More file actions
1743 lines (1578 loc) · 53.6 KB
/
ManagementViews.swift
File metadata and controls
1743 lines (1578 loc) · 53.6 KB
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ManagementViews.swift
// MistTray
//
import SwiftUI
// MARK: - Protocols View
struct ProtocolsView: View {
@Bindable var appState: AppState
@Binding var path: NavigationPath
@State private var showAddSheet = false
@State private var selectedConnector = ""
var body: some View {
VStack(spacing: 0) {
NavHeader(title: "Protocols")
Divider()
ScrollView {
VStack(alignment: .leading, spacing: 12) {
HStack {
Text("\(appState.configuredProtocols.count) configured")
.font(.caption)
.foregroundStyle(.secondary)
Spacer()
Button {
showAddSheet = true
} label: {
Label("Add", systemImage: "plus.circle.fill")
.font(.caption)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerOnHover()
}
if appState.configuredProtocols.isEmpty {
VStack(spacing: 8) {
Image(systemName: "network")
.font(.largeTitle)
.foregroundStyle(.tertiary)
Text("No protocols configured")
.font(.subheadline)
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity)
.padding(.vertical, 40)
} else {
ForEach(appState.sortedProtocols, id: \.index) { proto in
protocolCard(proto)
}
}
}
.padding(16)
}
}
.navigationBarBackButtonHidden(true)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.sheet(isPresented: $showAddSheet) {
addProtocolSheet
}
}
private func protocolCard(_ proto: (index: Int, connector: String, port: Int, online: Int))
-> some View
{
Button {
path.append(Route.protocolConfig(proto.connector, proto.index))
} label: {
HStack(spacing: 10) {
Circle()
.fill(proto.online == 1 ? Color.tnGreen : proto.online == 2 ? Color.tnYellow : Color.tnRed)
.frame(width: 8, height: 8)
VStack(alignment: .leading, spacing: 2) {
Text(proto.connector)
.font(.system(.body, weight: .medium))
HStack(spacing: 6) {
if proto.port > 0 {
Text("Port \(proto.port)")
.font(.caption)
.foregroundStyle(.secondary)
}
Text(proto.online == 1 ? "Online" : proto.online == 2 ? "Starting" : "Offline")
.font(.system(size: 10, weight: .medium))
.padding(.horizontal, 6)
.padding(.vertical, 1)
.background(
proto.online == 1 ? Color.tnGreen.opacity(0.1) : proto.online == 2
? Color.tnYellow.opacity(0.1) : Color.tnRed.opacity(0.1)
)
.clipShape(Capsule())
}
}
Spacer()
Image(systemName: "chevron.right")
.font(.caption2).foregroundStyle(.tertiary)
Button(role: .destructive) {
deleteProtocol(at: proto.index)
} label: {
Image(systemName: "trash")
.font(.caption)
.frame(width: 24, height: 24)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerOnHover()
}
.padding(.vertical, 4)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerOnHover()
}
private func deleteProtocol(at index: Int) {
guard index < appState.configuredProtocols.count else { return }
let proto = appState.configuredProtocols[index]
APIClient.shared.deleteProtocol(proto) { (result: Result<[String: Any], APIError>) in
DispatchQueue.main.async {
if case .success = result {
refreshData()
}
}
}
}
/// Filter out PUSHONLY connectors and already-configured ones
private var availableProtocols: [String] {
appState.availableConnectors.keys.sorted().filter { name in
guard let info = appState.availableConnectors[name] as? [String: Any] else { return true }
// Filter out PUSHONLY connectors
if let flags = info["flags"] as? [String: Any], flags["PUSHONLY"] != nil { return false }
if info["PUSHONLY"] != nil { return false }
return true
}
}
private var addProtocolSheet: some View {
VStack(spacing: 12) {
Text("Add Protocol")
.font(.headline)
Text("Select a connector to enable")
.font(.caption)
.foregroundStyle(.secondary)
ScrollView {
VStack(spacing: 4) {
ForEach(availableProtocols, id: \.self) { name in
Button {
addProtocol(name)
showAddSheet = false
} label: {
HStack {
Text(name)
.font(.subheadline.weight(.medium))
Spacer()
Image(systemName: "plus.circle")
.foregroundStyle(Color.tnAccent)
}
.padding(.vertical, 6)
.padding(.horizontal, 12)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.hoverHighlight()
}
}
}
.frame(maxHeight: 300)
Button("Cancel") { showAddSheet = false }
.buttonStyle(.bordered)
}
.padding(16)
.frame(width: 300)
}
private func addProtocol(_ connector: String) {
APIClient.shared.addProtocol(["connector": connector]) {
(result: Result<[String: Any], APIError>) in
DispatchQueue.main.async {
if case .success = result { refreshData() }
}
}
}
private func refreshData() {
appState.onDataChanged?()
}
}
// MARK: - Triggers View
struct TriggersView: View {
@Bindable var appState: AppState
@Binding var path: NavigationPath
private let triggerCategories: [(name: String, icon: String, events: [String])] = [
(
"Access Control", "shield.fill",
["USER_NEW", "CONN_OPEN", "CONN_PLAY", "STREAM_PUSH", "LIVE_BANDWIDTH"]
),
(
"Stream Lifecycle", "play.circle.fill",
[
"STREAM_ADD", "STREAM_CONFIG", "STREAM_REMOVE", "STREAM_SOURCE", "STREAM_LOAD",
"STREAM_READY", "STREAM_UNLOAD",
]
),
(
"Routing", "arrow.triangle.branch",
[
"PUSH_REWRITE", "RTMP_PUSH_REWRITE", "PUSH_OUT_START", "PLAY_REWRITE", "DEFAULT_STREAM",
]
),
(
"Monitoring", "chart.bar.fill",
[
"STREAM_BUFFER", "STREAM_END", "CONN_CLOSE", "USER_END", "RECORDING_END", "OUTPUT_END",
"PUSH_END", "LIVE_TRACK_LIST", "INPUT_ABORT",
]
),
(
"System", "server.rack",
["SYSTEM_START", "SYSTEM_STOP", "OUTPUT_START", "OUTPUT_STOP"]
),
]
var body: some View {
VStack(spacing: 0) {
NavHeader(title: "Triggers")
Divider()
ScrollView {
VStack(alignment: .leading, spacing: 12) {
HStack {
Text("\(appState.triggerCount) trigger(s)")
.font(.caption)
.foregroundStyle(.secondary)
Spacer()
Button {
path.append(Route.triggerWizard)
} label: {
Label("Add", systemImage: "plus.circle.fill")
.font(.caption)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerOnHover()
}
if appState.triggers.isEmpty {
VStack(spacing: 8) {
Image(systemName: "bolt.slash")
.font(.largeTitle)
.foregroundStyle(.tertiary)
Text("No triggers configured")
.font(.subheadline)
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity)
.padding(.vertical, 40)
} else {
ForEach(appState.sortedTriggerNames, id: \.self) { eventName in
if let handlers = appState.triggers[eventName] as? [[String: Any]] {
triggerGroup(eventName: eventName, handlers: handlers)
}
}
}
}
.padding(16)
}
}
.navigationBarBackButtonHidden(true)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
private func triggerGroup(eventName: String, handlers: [[String: Any]]) -> some View {
GroupBox {
VStack(alignment: .leading, spacing: 6) {
HStack {
Image(systemName: iconForEvent(eventName))
.font(.caption)
.foregroundStyle(Color.tnAccent)
Text(eventName)
.font(.subheadline.weight(.semibold))
Spacer()
}
ForEach(Array(handlers.enumerated()), id: \.offset) { index, handler in
HStack {
VStack(alignment: .leading, spacing: 2) {
Text(handler["handler"] as? String ?? "Unknown")
.font(.system(size: 11, design: .monospaced))
.lineLimit(1)
.truncationMode(.middle)
HStack(spacing: 6) {
if handler["sync"] as? Bool == true {
Text("Blocking")
.font(.system(size: 9, weight: .medium))
.padding(.horizontal, 5)
.padding(.vertical, 1)
.background(Color.tnOrange.opacity(0.15))
.clipShape(Capsule())
}
let streams = handler["streams"] as? [String] ?? []
Text(streams.isEmpty ? "All streams" : streams.joined(separator: ", "))
.font(.system(size: 9))
.foregroundStyle(.secondary)
}
}
Spacer()
Button {
path.append(Route.editTrigger(eventName, index))
} label: {
Image(systemName: "pencil")
.font(.system(size: 10))
.foregroundStyle(Color.tnAccent)
.frame(width: 20, height: 20)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerOnHover()
Button(role: .destructive) {
deleteTrigger(eventName: eventName, index: index)
} label: {
Image(systemName: "trash")
.font(.system(size: 10))
.frame(width: 20, height: 20)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerOnHover()
}
.padding(.vertical, 2)
}
}
}
}
private func iconForEvent(_ event: String) -> String {
for cat in triggerCategories {
if cat.events.contains(event) {
return cat.icon
}
}
return "bolt.fill"
}
private func deleteTrigger(eventName: String, index: Int) {
var triggers = appState.triggers
guard var handlers = triggers[eventName] as? [[String: Any]] else { return }
handlers.remove(at: index)
if handlers.isEmpty {
triggers.removeValue(forKey: eventName)
} else {
triggers[eventName] = handlers
}
APIClient.shared.saveTriggers(triggers) { result in
DispatchQueue.main.async {
if case .success = result {
(NSApp.delegate as? AppDelegate)?.refreshAllData()
}
}
}
}
}
// MARK: - Variables View
struct VariablesView: View {
@Bindable var appState: AppState
@State private var showAddForm = false
@State private var newVarName = ""
@State private var newVarValue = ""
@State private var newVarType = "static"
@State private var newVarCommand = ""
@State private var newVarInterval = "0"
@State private var isSubmitting = false
var body: some View {
VStack(spacing: 0) {
NavHeader(title: "Variables")
Divider()
ScrollView {
VStack(alignment: .leading, spacing: 12) {
HStack {
Text("\(appState.variables.count) variable(s)")
.font(.caption)
.foregroundStyle(.secondary)
Spacer()
Button {
showAddForm.toggle()
} label: {
Label("Add", systemImage: "plus.circle.fill")
.font(.caption)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerOnHover()
}
if showAddForm {
addVariableForm
}
if appState.variables.isEmpty && !showAddForm {
VStack(spacing: 8) {
Image(systemName: "textformat.abc")
.font(.largeTitle)
.foregroundStyle(.tertiary)
Text("No custom variables")
.font(.subheadline)
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity)
.padding(.vertical, 40)
} else {
ForEach(appState.sortedVariableNames, id: \.self) { name in
variableRow(name: name)
}
}
}
.padding(16)
}
}
.navigationBarBackButtonHidden(true)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
private var addVariableForm: some View {
GroupBox("New Variable") {
VStack(alignment: .leading, spacing: 8) {
HStack(spacing: 4) {
Text("$")
.font(.system(.body, design: .monospaced))
.foregroundStyle(Color.tnAccent)
TextField("name", text: $newVarName)
.textFieldStyle(.roundedBorder)
}
Picker("Type", selection: $newVarType) {
Text("Static value").tag("static")
Text("Dynamic (command/URL)").tag("dynamic")
}
.labelsHidden()
.pickerStyle(.segmented)
if newVarType == "static" {
TextField("Value", text: $newVarValue)
.textFieldStyle(.roundedBorder)
} else {
TextField("Command or URL", text: $newVarCommand)
.textFieldStyle(.roundedBorder)
HStack {
Text("Check interval (s):")
.font(.caption)
TextField("0", text: $newVarInterval)
.textFieldStyle(.roundedBorder)
.frame(width: 60)
Text("0 = once at startup")
.font(.system(size: 9))
.foregroundStyle(.tertiary)
}
}
HStack {
Spacer()
Button("Cancel") {
showAddForm = false
resetVarForm()
}
.buttonStyle(.bordered)
.controlSize(.small)
Button("Add") { addVariable() }
.buttonStyle(.borderedProminent)
.controlSize(.small)
.disabled(newVarName.trimmed.isEmpty || isSubmitting)
}
}
}
}
private func variableRow(name: String) -> some View {
let value = appState.variables[name]
return HStack {
VStack(alignment: .leading, spacing: 2) {
Text("$\(name)")
.font(.system(.body, design: .monospaced, weight: .medium))
if let dict = value as? [String: Any] {
if let v = dict["value"] as? String, !v.isEmpty {
Text(v)
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
} else if let target = dict["target"] as? String {
Text(target)
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.secondary)
.lineLimit(1)
}
} else if let str = value as? String {
Text(str)
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
}
}
Spacer()
Button(role: .destructive) {
removeVariable(name: name)
} label: {
Image(systemName: "trash")
.font(.caption)
.frame(width: 24, height: 24)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerOnHover()
}
.padding(.vertical, 4)
}
private func addVariable() {
isSubmitting = true
var variable: [String: Any] = ["name": "$\(newVarName.trimmed)"]
if newVarType == "static" {
variable["value"] = newVarValue.trimmed
} else {
variable["target"] = newVarCommand.trimmed
variable["interval"] = Int(newVarInterval.trimmed) ?? 0
}
APIClient.shared.addVariable(variable) { result in
DispatchQueue.main.async {
isSubmitting = false
if case .success = result {
showAddForm = false
resetVarForm()
(NSApp.delegate as? AppDelegate)?.refreshAllData()
}
}
}
}
private func removeVariable(name: String) {
APIClient.shared.removeVariable(name: name) { result in
DispatchQueue.main.async {
if case .success = result {
(NSApp.delegate as? AppDelegate)?.refreshAllData()
}
}
}
}
private func resetVarForm() {
newVarName = ""
newVarValue = ""
newVarType = "static"
newVarCommand = ""
newVarInterval = "0"
}
}
// MARK: - External Writers View
struct ExternalWritersView: View {
@Bindable var appState: AppState
@State private var showAddForm = false
@State private var newName = ""
@State private var newCmdline = ""
@State private var newProtocols = ""
@State private var isSubmitting = false
var body: some View {
VStack(spacing: 0) {
NavHeader(title: "External Writers")
Divider()
ScrollView {
VStack(alignment: .leading, spacing: 12) {
HStack {
Text("Custom push target protocols (S3, etc.)")
.font(.caption)
.foregroundStyle(.secondary)
Spacer()
Button {
showAddForm.toggle()
} label: {
Label("Add", systemImage: "plus.circle.fill")
.font(.caption)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerOnHover()
}
if showAddForm {
addWriterForm
}
if appState.externalWriters.isEmpty && !showAddForm {
VStack(spacing: 8) {
Image(systemName: "cloud")
.font(.largeTitle)
.foregroundStyle(.tertiary)
Text("No external writers configured")
.font(.subheadline)
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity)
.padding(.vertical, 40)
} else {
ForEach(Array(appState.externalWriters.keys.sorted()), id: \.self) { name in
writerRow(name: name)
}
}
}
.padding(16)
}
}
.navigationBarBackButtonHidden(true)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
private var addWriterForm: some View {
GroupBox("New External Writer") {
VStack(alignment: .leading, spacing: 8) {
TextField("Name", text: $newName)
.textFieldStyle(.roundedBorder)
TextField("Command line", text: $newCmdline)
.textFieldStyle(.roundedBorder)
TextField("URI protocols (comma-separated, e.g. s3,gs)", text: $newProtocols)
.textFieldStyle(.roundedBorder)
HStack {
Spacer()
Button("Cancel") {
showAddForm = false
}
.buttonStyle(.bordered)
.controlSize(.small)
Button("Add") { addWriter() }
.buttonStyle(.borderedProminent)
.controlSize(.small)
.disabled(
newName.trimmed.isEmpty || newCmdline.trimmed.isEmpty
|| newProtocols.trimmed.isEmpty || isSubmitting)
}
}
}
}
private func writerRow(name: String) -> some View {
let writer = appState.externalWriters[name]
return HStack {
VStack(alignment: .leading, spacing: 2) {
Text(name)
.font(.system(.body, weight: .medium))
if let dict = writer as? [String: Any] {
if let cmdline = dict["cmdline"] as? String {
Text(cmdline)
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.secondary)
.lineLimit(1)
}
if let protos = dict["protocols"] as? [String] {
Text(protos.map { $0 + "://" }.joined(separator: ", "))
.font(.system(size: 10))
.foregroundStyle(Color.tnAccent)
}
}
}
Spacer()
Button(role: .destructive) {
removeWriter(name: name)
} label: {
Image(systemName: "trash")
.font(.caption)
.frame(width: 24, height: 24)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.pointerOnHover()
}
.padding(.vertical, 4)
}
private func addWriter() {
isSubmitting = true
let protocols = newProtocols.trimmed.components(separatedBy: ",").map { $0.trimmed }
let config: [String: Any] = [
"name": newName.trimmed,
"cmdline": newCmdline.trimmed,
"protocols": protocols,
]
APIClient.shared.addExternalWriter(config) { result in
DispatchQueue.main.async {
isSubmitting = false
if case .success = result {
showAddForm = false
newName = ""
newCmdline = ""
newProtocols = ""
(NSApp.delegate as? AppDelegate)?.refreshAllData()
}
}
}
}
private func removeWriter(name: String) {
APIClient.shared.removeExternalWriter(name: name) { result in
DispatchQueue.main.async {
if case .success = result {
(NSApp.delegate as? AppDelegate)?.refreshAllData()
}
}
}
}
}
// MARK: - JWK Management View
struct JWKManagementView: View {
@Bindable var appState: AppState
private enum AddMode: String, CaseIterable { case url, inlineKey }
@State private var showAddForm = false
@State private var addMode: AddMode = .url
@State private var jwkURL = ""
@State private var jwkJSON = ""
@State private var streamScope = "*"
@State private var permitViewing = true
@State private var permitInput = true
@State private var permitAdmin = false
@State private var isSubmitting = false
@State private var errorMessage: String?
@State private var editingIndex: Int?
@State private var editPermitViewing = true
@State private var editPermitInput = true
@State private var editPermitAdmin = false
@State private var editStreamScope = "*"
@State private var deletingIndex: Int?
var body: some View {
VStack(spacing: 0) {
NavHeader(title: "JSON Web Keys")
Divider()
ScrollView {
VStack(alignment: .leading, spacing: 12) {
HStack {
Text("Token-based authentication for streams")
.font(.caption).foregroundStyle(.secondary)
Spacer()
Button { showAddForm.toggle() } label: {
Label("Add", systemImage: "plus.circle.fill")
.font(.caption).contentShape(Rectangle())
}
.buttonStyle(.plain).pointerOnHover()
}
if showAddForm { addJWKForm }
if appState.jwkEntries.isEmpty {
Text("No JWK entries configured.")
.font(.caption).foregroundStyle(.secondary).padding(.vertical, 8)
} else {
ForEach(Array(appState.jwkEntries.enumerated()), id: \.offset) { index, entry in
jwkEntryRow(entry, index: index)
}
}
}
.padding(16)
}
}
.navigationBarBackButtonHidden(true)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
// MARK: - Entry Row
private func jwkEntryRow(_ entry: [Any], index: Int) -> some View {
let source = entry.first
let permissions = entry.count > 1 ? entry[1] as? [String: Any] : nil
let (label, typeLabel, identifier, copyText) = parseEntry(source)
let isEditing = editingIndex == index
let isDeleting = deletingIndex == index
return GroupBox {
VStack(alignment: .leading, spacing: 6) {
HStack {
VStack(alignment: .leading, spacing: 2) {
Text(label).font(.caption.weight(.medium)).lineLimit(1)
Text(typeLabel).font(.system(size: 9)).foregroundStyle(.secondary)
}
Spacer()
// Copy button
Button {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(copyText, forType: .string)
} label: {
Image(systemName: "doc.on.doc")
.font(.caption).foregroundStyle(.secondary).contentShape(Rectangle())
}
.buttonStyle(.plain).pointerOnHover()
// Edit button
Button {
if isEditing {
editingIndex = nil
} else {
editingIndex = index
editPermitViewing = permissions?["output"] as? Bool ?? true
editPermitInput = permissions?["input"] as? Bool ?? true
editPermitAdmin = permissions?["admin"] as? Bool ?? false
editStreamScope = permissions?["stream"] as? String ?? "*"
}
} label: {
Image(systemName: isEditing ? "xmark" : "pencil")
.font(.caption).foregroundStyle(Color.tnAccent).contentShape(Rectangle())
}
.buttonStyle(.plain).pointerOnHover()
// Delete button
Button { deletingIndex = isDeleting ? nil : index } label: {
Image(systemName: "trash")
.font(.caption).foregroundStyle(Color.tnRed).contentShape(Rectangle())
}
.buttonStyle(.plain).pointerOnHover()
}
// Permission badges (when not editing)
if !isEditing, let perms = permissions {
HStack(spacing: 6) {
if perms["output"] as? Bool == true { permBadge("View", color: Color.tnGreen) }
if perms["input"] as? Bool == true { permBadge("Input", color: Color.tnAccent) }
if perms["admin"] as? Bool == true { permBadge("Admin", color: Color.tnOrange) }
if let scope = perms["stream"] as? String, scope != "*" {
permBadge(scope, color: Color.tnPurple)
}
}
}
// Inline delete confirmation
if isDeleting {
HStack(spacing: 8) {
Image(systemName: "exclamationmark.triangle.fill")
.font(.caption).foregroundStyle(Color.tnOrange)
Text("Delete this key?").font(.caption).foregroundStyle(.secondary)
Spacer()
Button("Cancel") { deletingIndex = nil }
.buttonStyle(.bordered).controlSize(.mini)
Button("Delete", role: .destructive) {
deletingIndex = nil
deleteJWK(identifier)
}
.buttonStyle(.borderedProminent).controlSize(.mini)
}
}
// Inline edit form
if isEditing {
Divider()
VStack(alignment: .leading, spacing: 4) {
Toggle("Permit viewing", isOn: $editPermitViewing).font(.caption)
Toggle("Permit stream input", isOn: $editPermitInput).font(.caption)
Toggle("Permit API access", isOn: $editPermitAdmin).font(.caption)
HStack {
Text("Streams:").font(.caption).foregroundStyle(.secondary)
TextField("*", text: $editStreamScope)
.textFieldStyle(.roundedBorder).font(.caption).frame(maxWidth: 150)
}
HStack {
Spacer()
Button("Cancel") { editingIndex = nil }
.buttonStyle(.bordered).controlSize(.mini)
Button("Save") { saveEditedPermissions(entry, index: index, identifier: identifier) }
.buttonStyle(.borderedProminent).controlSize(.mini)
}
}
}
}
}
}
private func parseEntry(_ source: Any?) -> (label: String, typeLabel: String, identifier: String, copyText: String) {
if let urlString = source as? String {
return (urlString, "URL", urlString, urlString)
} else if let keyObj = source as? [String: Any] {
let kid = keyObj["kid"] as? String ?? "Inline Key"
let kty = keyObj["kty"] as? String ?? "Key"
let json = (try? JSONSerialization.data(withJSONObject: keyObj, options: [.sortedKeys]))
.flatMap { String(data: $0, encoding: .utf8) } ?? kid
return (kid, kty, kid, json)
}
return ("Unknown", "?", "", "")
}
private func permBadge(_ text: String, color: Color) -> some View {
Text(text)
.font(.system(size: 9, weight: .medium))
.padding(.horizontal, 5).padding(.vertical, 1)
.background(color.opacity(0.2)).foregroundStyle(color)
.clipShape(Capsule())
}
// MARK: - Add Form
private var addJWKForm: some View {
GroupBox("Add JWK") {
VStack(alignment: .leading, spacing: 8) {
Picker("", selection: $addMode) {
Text("JWKS URL").tag(AddMode.url)
Text("Inline Key").tag(AddMode.inlineKey)
}
.pickerStyle(.segmented).labelsHidden()
if addMode == .url {
TextField("https://example.com/.well-known/jwks.json", text: $jwkURL)
.textFieldStyle(.roundedBorder)
} else {
Text("Paste JWK JSON (must contain 'kty' field)")
.font(.system(size: 9)).foregroundStyle(.secondary)
TextEditor(text: $jwkJSON)
.font(.system(.caption, design: .monospaced))
.frame(height: 80)
.overlay(RoundedRectangle(cornerRadius: 4).stroke(Color.gray.opacity(0.3)))
}
VStack(alignment: .leading, spacing: 4) {
Toggle("Permit viewing", isOn: $permitViewing).font(.caption)
Toggle("Permit stream input", isOn: $permitInput).font(.caption)
Toggle("Permit API access", isOn: $permitAdmin).font(.caption)
}
HStack {
Text("Streams:").font(.caption).foregroundStyle(.secondary)
TextField("* (all streams)", text: $streamScope)
.textFieldStyle(.roundedBorder).font(.caption)
}
if let error = errorMessage {
Text(error).font(.caption).foregroundColor(Color.tnRed)
}
HStack {
Spacer()
Button("Cancel") { showAddForm = false; errorMessage = nil }
.buttonStyle(.bordered).controlSize(.small)
Button("Add") { addJWK() }
.buttonStyle(.borderedProminent).controlSize(.small)
.disabled(addFormDisabled)
}
}
}
}
private var addFormDisabled: Bool {
if isSubmitting { return true }
if addMode == .url { return jwkURL.trimmed.isEmpty }
return jwkJSON.trimmed.isEmpty
}
// MARK: - Actions
private func addJWK() {
isSubmitting = true
errorMessage = nil
let permissions: [String: Any] = [
"output": permitViewing, "input": permitInput, "admin": permitAdmin,
"stream": streamScope.trimmed.isEmpty ? "*" : streamScope.trimmed,
]
let entries: [[Any]]
if addMode == .url {
entries = [[jwkURL.trimmed, permissions]]
} else {
// Parse inline JSON
guard let data = jwkJSON.trimmed.data(using: .utf8),
let parsed = try? JSONSerialization.jsonObject(with: data)
else {
isSubmitting = false
errorMessage = "Invalid JSON. Please enter a valid JWK object."
return
}
// Support single key object or JWKS with "keys" array
var keys: [[String: Any]] = []
if let obj = parsed as? [String: Any] {
if let keysArray = obj["keys"] as? [[String: Any]] {