forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppsPage.swift
More file actions
3880 lines (3472 loc) · 125 KB
/
Copy pathAppsPage.swift
File metadata and controls
3880 lines (3472 loc) · 125 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
import AppKit
import Combine
@preconcurrency import GRDB
import OmiTheme
import SwiftUI
// MARK: - Safe Dismiss Button
/// A dismiss button that prevents click-through to underlying views on macOS.
/// Uses onTapGesture with async delay to ensure the click is fully consumed before dismissing.
/// The key is to wait for the full mouse event cycle to complete before triggering dismiss.
struct SafeDismissButton: View {
let dismiss: DismissAction
var icon: String = "xmark"
var showBackground: Bool = true
@State private var isPressed = false
var body: some View {
Image(systemName: icon)
.scaledFont(size: OmiType.body, weight: .medium)
.foregroundColor(Ink.secondary)
.frame(width: 28, height: 28)
.background(showBackground ? Ink.wash : Color.clear)
.clipShape(Circle())
.contentShape(Circle())
.opacity(isPressed ? 0.7 : 1.0)
.onTapGesture {
guard !isPressed else { return } // Prevent double-tap
isPressed = true
let mouseLocation = NSEvent.mouseLocation
log("DISMISS: Tap gesture fired at mouse position: \(mouseLocation)")
// Consume the click by resigning first responder
NSApp.keyWindow?.makeFirstResponder(nil)
// Post a mouse-up event to ensure any pending click is consumed
if let window = NSApp.keyWindow {
let event = NSEvent.mouseEvent(
with: .leftMouseUp,
location: window.mouseLocationOutsideOfEventStream,
modifierFlags: [],
timestamp: ProcessInfo.processInfo.systemUptime,
windowNumber: window.windowNumber,
context: nil,
eventNumber: 0,
clickCount: 1,
pressure: 0
)
if let event = event {
window.sendEvent(event)
log("DISMISS: Sent synthetic mouse-up event")
}
}
// Use async with longer delay to ensure mouse event fully completes
Task { @MainActor in
log("DISMISS: Starting 250ms delay before dismiss")
// Longer delay to ensure mouse-up event is fully processed
try? await Task.sleep(nanoseconds: 250_000_000) // 250ms
log("DISMISS: Delay complete, calling dismiss()")
log("DISMISS: Mouse position before dismiss: \(NSEvent.mouseLocation)")
dismiss()
log("DISMISS: dismiss() called")
}
}
}
}
// MARK: - Dismiss Button (Action-based)
/// A dismiss button that takes a closure instead of a DismissAction.
/// Used for overlay-based sheets where the dismiss is controlled externally.
/// A real Button (not a tap gesture) so accessibility exposes it as a labeled
/// "Close" control and keyboard users can reach it.
struct DismissButton: View {
let action: () -> Void
var icon: String = "xmark"
var showBackground: Bool = true
var accessibilityLabel: String = "Close"
var body: some View {
Button {
log("DISMISS_BUTTON: Activated")
// Commit any in-progress field editing before tearing the sheet down.
NSApp.keyWindow?.makeFirstResponder(nil)
OmiMotion.withGated(.easeOut(duration: 0.2)) {
action()
}
} label: {
Image(systemName: icon)
.scaledFont(size: OmiType.body, weight: .medium)
.foregroundColor(Ink.secondary)
.frame(width: 28, height: 28)
.background(showBackground ? Ink.wash : Color.clear)
.clipShape(Circle())
.contentShape(Circle())
}
.buttonStyle(DismissButtonPressStyle())
.accessibilityLabel(accessibilityLabel)
}
}
private struct DismissButtonPressStyle: ButtonStyle {
func makeBody(configuration: ButtonStyleConfiguration) -> some View {
configuration.label
.opacity(configuration.isPressed ? 0.7 : 1.0)
}
}
enum AppsPageCategoryFilter {
static let allCategoriesOptionId = ""
static let allCategoriesTitle = "All Categories"
enum Selection: Equatable {
case allCategories
case category(String)
}
static func categoryDropdownOptions(categories: [OmiAppCategory]) -> [SearchableDropdownOption] {
[SearchableDropdownOption(id: allCategoriesOptionId, title: allCategoriesTitle)]
+ categories.map { SearchableDropdownOption(id: $0.id, title: $0.title) }
}
static func selectedCategoryDropdownId(_ selectedCategory: String?) -> String {
selectedCategory ?? allCategoriesOptionId
}
static func categorySelection(forOptionId optionId: String) -> Selection {
optionId.isEmpty ? .allCategories : .category(optionId)
}
}
enum AppsFilteredResultsPresentation: Equatable {
case loading
case empty
case results
case failure
static func resolve(
queryState: AppFilterResultsQueryState,
resultsCount: Int
) -> AppsFilteredResultsPresentation {
switch queryState {
case .unknown, .loading:
return .loading
case .completed:
return resultsCount == 0 ? .empty : .results
case .failed:
return .failure
}
}
}
enum AppsAllSearchPresentation: Equatable {
case loading
case empty
case results(total: Int)
case failure
static func resolve(
importsCount: Int,
exportsCount: Int,
appsCount: Int,
marketplace: AppsFilteredResultsPresentation
) -> AppsAllSearchPresentation {
let localCount = importsCount + exportsCount
let visibleAppsCount = marketplace == .results ? appsCount : 0
let total = localCount + visibleAppsCount
if total > 0 { return .results(total: total) }
switch marketplace {
case .loading: return .loading
case .failure: return .failure
case .empty, .results: return .empty
}
}
}
struct AppsPage: View {
@ObservedObject var appProvider: AppProvider
var appState: AppState? = nil
@ObservedObject var connectorStatusStore: ImportConnectorStatusStore = ImportConnectorStatusStore()
@ObservedObject private var automationPresentationCoordinator =
DesktopAutomationPresentationCoordinator.shared
var handlesAutomationPresentations = false
@State private var searchText = ""
@State private var selectedApp: OmiApp?
@State private var selectedConnector: ImportConnector?
@State private var selectedExportDestination: MemoryExportDestination?
@State private var activeAutomationCommand: DesktopAutomationPresentationCommand?
@State private var visibleAutomationPresentationTarget: DesktopAutomationPresentationTarget?
@State private var exportStatuses: [MemoryExportDestination: MemoryExportStatus] = [:]
@State private var viewAllSection: String? = nil // "featured", "integrations", "notifications"
@State private var selectedKind: AppsCatalogKind = .all
@State private var showAddMcpServerSheet = false
@State private var selectedLocalMcpServer: LocalMcpStore.Entry?
@State private var showAddSkillSheet = false
@State private var editingSkill: LocalSkillsStore.Skill?
@State private var selectedCatalogEntry: ExtensionCatalog.Entry?
@AppStorage(AppsSectionDestination.storageKey) private var selectedSectionRawValue =
AppsSectionDestination.apps.rawValue
private var selectedSection: AppsSectionDestination {
AppsSectionDestination(rawValue: selectedSectionRawValue) ?? .apps
}
var body: some View {
GeometryReader { proxy in
let lane = QueryShellLayout.laneWidth(for: proxy.size.width)
VStack(spacing: QueryShellLayout.panelGap) {
QuerySearchBar(
text: $searchText,
accessibilityID: "apps-search-field",
placeholder: searchPlaceholder, searchSurface: .apps
)
VStack(spacing: 0) {
appsControlsBar
.pagePanelFirstRowInsets()
// Content is scoped by Kind. Marketplace-only filters never replace
// the local Imports/Exports catalog with an empty app result.
if appProvider.isLoading {
loadingShimmerView
} else {
ScrollView {
LazyVStack(alignment: .leading, spacing: PagePanelVerticalRhythm.sectionGap) {
catalogContent
}
.padding(.horizontal, PagePanelVerticalRhythm.horizontalPadding)
.padding(.top, PagePanelVerticalRhythm.contentGap)
.padding(.bottom, PagePanelVerticalRhythm.contentBottomPadding)
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.inkGlassPanel(cornerRadius: QueryShellLayout.panelCornerRadius, shadow: .ambient)
}
.frame(width: lane)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
.padding(.top, QueryShellLayout.surfaceTopInset)
}
.background(Color.clear)
.onChange(of: searchText) { _, newValue in
// Search never changes scope on the user's behalf. In All, the same
// query is applied to apps, imports, and exports; a narrower Kind keeps
// the query local to that catalog.
guard selectedSection == .apps else { return }
guard selectedKind == .apps || selectedKind == .all else {
SearchAnalytics.scheduleQueryEntered(surface: .apps, query: newValue) { appsSearchResultCount }
return
}
appProvider.searchQuery = newValue
if !newValue.isEmpty {
viewAllSection = nil
appProvider.clearCategoryFilter()
}
scheduleAppSearch(for: newValue)
}
.dismissableSheet(isPresented: $showAddMcpServerSheet) {
AddMcpServerSheet(appProvider: appProvider, onDismiss: { showAddMcpServerSheet = false })
.frame(width: 460, height: 424)
}
.dismissableSheet(item: $selectedLocalMcpServer) { server in
LocalMcpDetailSheet(
server: server, appProvider: appProvider, onDismiss: { selectedLocalMcpServer = nil }
)
.frame(width: 460, height: 420)
}
.dismissableSheet(isPresented: $showAddSkillSheet) {
SkillEditorSheet(appProvider: appProvider, editingSkill: nil, onDismiss: { showAddSkillSheet = false })
.frame(width: 520, height: 460)
}
.dismissableSheet(item: $selectedCatalogEntry) { entry in
ExtensionDetailSheet(
entry: entry, appProvider: appProvider, onDismiss: { selectedCatalogEntry = nil }
)
.frame(width: 460, height: entry.install.needsInput ? 420 : 340)
}
.dismissableSheet(item: $editingSkill) { skill in
SkillEditorSheet(appProvider: appProvider, editingSkill: skill, onDismiss: { editingSkill = nil })
.frame(width: 520, height: 460)
}
.dismissableSheet(item: $selectedApp) { app in
AppDetailSheet(app: app, appProvider: appProvider, onDismiss: { selectedApp = nil })
.frame(width: 480, height: 560)
.onAppear {
AnalyticsManager.shared.appDetailViewed(appId: app.id, appName: app.name)
}
}
.dismissableSheet(item: $selectedConnector) { connector in
ImportConnectorSheet(
connector: connector,
appState: appState,
statusStore: connectorStatusStore,
onDismiss: {
selectedConnector = nil
}
)
.frame(width: 500, height: 540)
.onAppear {
automationPresentationDidAppear(.importConnector(connector.id))
}
.onDisappear {
automationPresentationDidDisappear(.importConnector(connector.id))
}
}
.dismissableSheet(item: $selectedExportDestination) { destination in
ConnectDestinationSheet(
destination: destination,
statuses: $exportStatuses,
onDismiss: {
selectedExportDestination = nil
}
)
.frame(width: 500, height: 540)
.onAppear {
automationPresentationDidAppear(.exportDestination(destination.rawValue))
}
.onDisappear {
automationPresentationDidDisappear(.exportDestination(destination.rawValue))
}
}
.onChange(of: automationPresentationCoordinator.activeCommand?.generation) { _, _ in
consumeAutomationPresentationCommand()
}
.onChange(of: handlesAutomationPresentations) { _, isReady in
guard isReady else { return }
consumeAutomationPresentationCommand()
}
.onAppear {
consumeAutomationPresentationCommand()
Task { await appProvider.fetchUserExtensions() }
// If apps are already loaded, notify sidebar to clear loading indicator
if !appProvider.isLoading {
NotificationCenter.default.post(name: .appsPageDidLoad, object: nil)
}
// Retry fetch if initial load failed and apps are empty
if appProvider.apps.isEmpty && !appProvider.isLoading {
Task {
await appProvider.fetchApps()
}
}
}
.onDisappear {
rejectActiveAutomationPresentationIfNeeded()
}
.task {
await connectorStatusStore.refresh()
exportStatuses = await MemoryExportService.shared.allStatuses()
}
.onChange(of: selectedExportDestination) { _, newValue in
guard newValue == nil else { return }
Task {
exportStatuses = await MemoryExportService.shared.allStatuses()
}
}
}
private func selectApp(_ app: OmiApp) {
SearchAnalytics.resultOpened(
surface: .apps, resultIndex: filteredApps.firstIndex { $0.id == app.id },
searchIsActive: hasSearchQuery)
selectedApp = app
}
private func selectConnector(_ connector: ImportConnector) {
SearchAnalytics.resultOpened(
surface: .apps, resultIndex: visibleImportConnectors.firstIndex { $0.id == connector.id },
searchIsActive: hasSearchQuery)
selectedConnector = connector
}
private func selectDestination(_ destination: MemoryExportDestination) {
SearchAnalytics.resultOpened(
surface: .apps, resultIndex: visibleExportEntries.firstIndex { $0.destination == destination },
searchIsActive: hasSearchQuery)
selectedExportDestination = destination
}
private func consumeAutomationPresentationCommand() {
guard handlesAutomationPresentations else { return }
guard let command = automationPresentationCoordinator.activeCommand else {
activeAutomationCommand = nil
return
}
activeAutomationCommand = command
if visibleAutomationPresentationTarget == command.target {
acknowledgeAutomationPresentation(command.target)
return
}
selectedApp = nil
switch command.target {
case .importConnector(let identifier):
selectedExportDestination = nil
guard let connector = ImportConnector.all.first(where: { $0.id == identifier }) else {
rejectActiveAutomationPresentationIfNeeded()
return
}
selectConnector(connector)
case .exportDestination(let identifier):
selectedConnector = nil
guard let destination = MemoryExportDestination(rawValue: identifier) else {
rejectActiveAutomationPresentationIfNeeded()
return
}
selectDestination(destination)
}
}
private func automationPresentationDidAppear(
_ target: DesktopAutomationPresentationTarget
) {
visibleAutomationPresentationTarget = target
acknowledgeAutomationPresentation(target)
}
private func automationPresentationDidDisappear(
_ target: DesktopAutomationPresentationTarget
) {
guard visibleAutomationPresentationTarget == target else { return }
visibleAutomationPresentationTarget = nil
}
private func acknowledgeAutomationPresentation(
_ target: DesktopAutomationPresentationTarget
) {
guard handlesAutomationPresentations,
let command = activeAutomationCommand,
command.target == target
else { return }
if automationPresentationCoordinator.acknowledgeVisible(
generation: command.generation,
target: target
) {
activeAutomationCommand = nil
}
}
private func rejectActiveAutomationPresentationIfNeeded() {
guard handlesAutomationPresentations, let command = activeAutomationCommand else { return }
_ = automationPresentationCoordinator.rejectUnavailable(
generation: command.generation,
target: command.target
)
activeAutomationCommand = nil
}
private var appsControlsBar: some View {
PageQueryToolbar(
refinement: {
if selectedSection == .apps {
kindMenu
if selectedKind == .apps {
appsFiltersMenu
}
}
},
activeFilters: {
ActivePageFilterStrip(filters: activeAppFilters, onClearAll: clearAppFilters)
},
actions: {
AppsSectionNavigation(
selected: selectedSection,
onSelect: { selectedSectionRawValue = $0.rawValue }
)
appsMoreMenu
}
)
}
private var searchPlaceholder: String {
switch selectedSection {
case .mcp: return "Search MCP servers…"
case .skills: return "Search skills…"
case .apps: break
}
switch selectedKind {
case .all: return "Search apps, imports, and exports…"
case .apps: return "Search apps…"
case .imports: return "Search imports…"
case .exports: return "Search exports…"
}
}
private var activeAppFilters: [PageActiveFilter] {
guard selectedKind == .apps else { return [] }
var filters: [PageActiveFilter] = []
if appProvider.showInstalledOnly {
filters.append(
PageActiveFilter(id: "installed", title: "Installed") {
setConnectionFilter(installedOnly: false)
})
}
if appProvider.selectedCategory != nil {
filters.append(
PageActiveFilter(id: "category", title: selectedCategoryTitle) {
appProvider.clearCategoryFilter()
scheduleAppSearch(for: searchText)
})
}
return filters
}
private var kindMenu: some View {
Menu {
ForEach(AppsCatalogKind.allCases) { kind in
Button {
selectKind(kind)
} label: {
Label(kind.rawValue, systemImage: kind.icon)
}
}
} label: {
PageQueryControlLabel(
icon: selectedKind.icon,
dimension: "Kind",
value: selectedKind.rawValue,
isActive: selectedKind != .all
)
}
.menuStyle(.button)
.buttonStyle(.plain)
.accessibilityIdentifier("apps-kind-filter")
.help("Choose which app catalog to show")
}
private var appsFiltersMenu: some View {
Menu {
Section("Connection") {
Button {
setConnectionFilter(installedOnly: false)
} label: {
Label("All apps", systemImage: "square.grid.2x2")
}
Button {
setConnectionFilter(installedOnly: true)
} label: {
Label("Installed", systemImage: "checkmark.circle")
}
}
Section("Category") {
ForEach(AppsPageCategoryFilter.categoryDropdownOptions(categories: appProvider.categories)) { option in
Button(option.title) {
viewAllSection = nil
switch AppsPageCategoryFilter.categorySelection(forOptionId: option.id) {
case .allCategories:
appProvider.clearCategoryFilter()
case .category(let categoryId):
appProvider.selectedCategory = categoryId
}
scheduleAppSearch(for: searchText)
}
}
}
if !activeAppFilters.isEmpty {
Divider()
Button("Clear all filters", action: clearAppFilters)
}
} label: {
PageQueryControlLabel(
icon: "line.3.horizontal.decrease",
dimension: activeAppFilters.isEmpty ? nil : "Filter",
value: activeAppFilters.isEmpty ? "Filter" : "\(activeAppFilters.count)",
isActive: !activeAppFilters.isEmpty,
dimensionSeparator: " ·"
)
}
.menuStyle(.button)
.buttonStyle(.plain)
.accessibilityIdentifier("apps-filter-menu")
.help("Filter apps by connection or category")
}
private var selectedCategoryTitle: String {
guard let selectedCategory = appProvider.selectedCategory,
let category = appProvider.categories.first(where: { $0.id == selectedCategory })
else {
return "All"
}
return category.title
}
private func selectKind(_ kind: AppsCatalogKind) {
guard selectedKind != kind else { return }
viewAllSection = nil
selectedKind = kind
// Connection and Category are marketplace dimensions. Search is a page-
// wide intent, so changing scope never discards what the user typed.
if kind != .apps {
clearMarketplaceFiltersPreservingSearch()
}
if kind == .apps || kind == .all {
appProvider.searchQuery = searchText
scheduleAppSearch(for: searchText)
}
}
private func setConnectionFilter(installedOnly: Bool) {
guard selectedKind == .apps else { return }
viewAllSection = nil
appProvider.showInstalledOnly = installedOnly
scheduleAppSearch(for: searchText)
}
private func clearAppFilters() {
viewAllSection = nil
clearMarketplaceFiltersPreservingSearch()
scheduleAppSearch(for: searchText)
}
private func clearMarketplaceFiltersPreservingSearch() {
let query = searchText
appProvider.clearFilters()
appProvider.searchQuery = query
}
private func scheduleAppSearch(for query: String) {
Task {
// Debounce search and keep the provider's current query authoritative.
try? await Task.sleep(for: .milliseconds(300))
guard selectedKind == .apps || selectedKind == .all,
appProvider.searchQuery == query
else { return }
await appProvider.searchApps()
SearchAnalytics.queryEntered(surface: .apps, query: query, resultsCount: appsSearchResultCount)
}
}
private var appsMoreMenu: some View {
Menu {
Button {
if let url = URL(string: "https://docs.omi.me/docs/developer/apps/Introduction") {
NSWorkspace.shared.open(url)
}
} label: {
Label("Build an app…", systemImage: "app.badge.fill")
}
} label: {
PageQueryActionLabel(icon: "ellipsis", title: "More")
}
.menuStyle(.borderlessButton)
.menuIndicator(.hidden)
.fixedSize()
.help("More app actions")
.accessibilityLabel("More app actions")
.accessibilityIdentifier("apps-more-actions")
}
@ViewBuilder
private var catalogContent: some View {
switch selectedSection {
case .apps:
appsCatalogContent
case .mcp:
McpServersSection(
appProvider: appProvider,
searchText: searchText,
onAdd: { showAddMcpServerSheet = true },
onSelectLocal: { selectedLocalMcpServer = $0 },
onSelectCatalogEntry: { selectedCatalogEntry = $0 }
)
case .skills:
SkillsSection(
appProvider: appProvider,
searchText: searchText,
onAdd: { showAddSkillSheet = true },
onSelect: { editingSkill = $0 },
onSelectCatalogEntry: { selectedCatalogEntry = $0 }
)
}
}
@ViewBuilder
private var appsCatalogContent: some View {
switch selectedKind {
case .imports:
ImportsSection(
statusStore: connectorStatusStore,
onSelectConnector: { connector in
selectConnector(connector)
},
connectors: visibleImportConnectors,
searchText: searchText,
onClearSearch: { searchText = "" }
)
case .exports:
ExportsSection(statuses: exportStatuses, searchText: searchText) { destination in
selectDestination(destination)
}
case .apps:
marketplaceContent
case .all:
if hasSearchQuery {
allCatalogSearchContent
} else {
localAndMarketplaceContent
}
}
}
@ViewBuilder
private var allCatalogSearchContent: some View {
switch allSearchPresentation {
case .loading:
searchLoadingState
case .failure:
searchFailureState
case .empty:
globalSearchEmptyState
case .results(let total):
Text("Search Results (\(total))")
.scaledFont(size: OmiType.heading, weight: .semibold)
.foregroundStyle(Ink.primary)
if !visibleImportConnectors.isEmpty {
ImportsSection(
statusStore: connectorStatusStore,
onSelectConnector: { connector in selectConnector(connector) },
connectors: visibleImportConnectors,
title: "Imports (\(visibleImportConnectors.count))"
)
}
if !visibleExportEntries.isEmpty {
ExportsSection(
statuses: exportStatuses,
title: "Exports (\(visibleExportEntries.count))",
entriesOverride: visibleExportEntries
) { destination in
selectDestination(destination)
}
}
if !visibleMarketplaceSearchApps.isEmpty {
AppGridSection(
title: "Apps (\(visibleMarketplaceSearchApps.count))",
apps: visibleMarketplaceSearchApps,
appProvider: appProvider,
onSelectApp: selectApp,
titleSize: OmiType.subheading
)
}
if filteredAppsPresentation == .loading {
marketplaceSearchProgress
} else if filteredAppsPresentation == .failure {
marketplaceSearchFailure
}
}
}
@ViewBuilder
private var localAndMarketplaceContent: some View {
ImportsSection(statusStore: connectorStatusStore) { connector in
selectConnector(connector)
}
ExportsSection(statuses: exportStatuses) { destination in
selectDestination(destination)
}
marketplaceSections
}
@ViewBuilder
private var marketplaceContent: some View {
if hasMarketplaceQuery {
filteredAppsContent
} else {
marketplaceSections
}
}
@ViewBuilder
private var marketplaceSections: some View {
if !appProvider.popularApps.isEmpty {
AppGridSection(
title: "Other",
apps: Array(appProvider.popularApps.prefix(6)),
appProvider: appProvider,
onSelectApp: selectApp,
showSeeMore: appProvider.popularApps.count > 6,
onSeeMore: {
selectedKind = .apps
viewAllSection = "featured"
}
)
}
if !appProvider.integrationApps.isEmpty {
AppGridSection(
title: "Integrations",
apps: Array(appProvider.integrationApps.prefix(6)),
appProvider: appProvider,
onSelectApp: selectApp,
showSeeMore: appProvider.integrationApps.count > 6,
onSeeMore: {
selectedKind = .apps
viewAllSection = "integrations"
}
)
}
if !appProvider.notificationApps.isEmpty {
AppGridSection(
title: "Realtime Notifications",
apps: Array(appProvider.notificationApps.prefix(6)),
appProvider: appProvider,
onSelectApp: selectApp,
showSeeMore: appProvider.notificationApps.count > 6,
onSeeMore: {
selectedKind = .apps
viewAllSection = "notifications"
}
)
}
}
private var hasMarketplaceQuery: Bool {
appProvider.hasActiveFilters || viewAllSection != nil
}
private var hasSearchQuery: Bool {
!searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
private var appsSearchResultCount: Int {
selectedKind.searchResultCount(
apps: filteredApps.count, imports: visibleImportConnectors.count,
exports: visibleExportEntries.count)
}
private var visibleImportConnectors: [ImportConnector] {
let query = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
guard !query.isEmpty else { return ImportConnector.all }
return ImportConnector.all
.filter { connector in
[connector.title, connector.subtitle, connector.description]
.contains { $0.localizedCaseInsensitiveContains(query) }
}
.sorted { catalogMatchRank($0.title, query: query) < catalogMatchRank($1.title, query: query) }
}
private var visibleExportEntries: [MemoryExportCatalogEntry] {
MemoryExportCatalog.matching(searchText)
}
private var visibleMarketplaceSearchApps: [OmiApp] {
guard filteredAppsPresentation == .results else { return [] }
let query = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
return filteredApps.sorted {
catalogMatchRank($0.name, query: query) < catalogMatchRank($1.name, query: query)
}
}
private var allSearchPresentation: AppsAllSearchPresentation {
AppsAllSearchPresentation.resolve(
importsCount: visibleImportConnectors.count,
exportsCount: visibleExportEntries.count,
appsCount: filteredApps.count,
marketplace: filteredAppsPresentation
)
}
private func catalogMatchRank(_ title: String, query: String) -> Int {
if title.localizedCaseInsensitiveCompare(query) == .orderedSame { return 0 }
if title.range(of: query, options: [.anchored, .caseInsensitive, .diacriticInsensitive]) != nil {
return 1
}
return 2
}
private var searchLoadingState: some View {
VStack(spacing: OmiSpacing.md) {
ProgressView()
Text("Searching apps, imports, and exports…")
.scaledFont(size: OmiType.body)
.foregroundStyle(Ink.secondary)
}
.frame(maxWidth: .infinity, minHeight: QueryShellLayout.minimumBodyHeight)
}
private var searchFailureState: some View {
VStack(spacing: OmiSpacing.md) {
Image(systemName: "exclamationmark.circle")
.scaledFont(size: 28)
.foregroundStyle(Ink.secondary)
Text("Couldn't finish searching apps")
.scaledFont(size: OmiType.subheading, weight: .medium)
Button("Try Again") { Task { await appProvider.searchApps() } }
.buttonStyle(.bordered)
}
.frame(maxWidth: .infinity, minHeight: QueryShellLayout.minimumBodyHeight)
}
private var globalSearchEmptyState: some View {
VStack(spacing: OmiSpacing.md) {
Image(systemName: "magnifyingglass")
.scaledFont(size: 28)
.foregroundStyle(Ink.secondary)
Text("No results for “\(searchText.trimmingCharacters(in: .whitespacesAndNewlines))”")
.scaledFont(size: OmiType.subheading, weight: .medium)
.foregroundStyle(Ink.primary)
Button("Clear Search") { searchText = "" }
.buttonStyle(.bordered)
}
.frame(maxWidth: .infinity, minHeight: QueryShellLayout.minimumBodyHeight)
}
private var marketplaceSearchProgress: some View {
HStack(spacing: OmiSpacing.sm) {
ProgressView().controlSize(.small)
Text("Searching marketplace apps…")
.scaledFont(size: OmiType.caption)
.foregroundStyle(Ink.secondary)
}
}
private var marketplaceSearchFailure: some View {
HStack(spacing: OmiSpacing.sm) {
Text("Marketplace apps couldn't be loaded.")
.scaledFont(size: OmiType.caption)
.foregroundStyle(Ink.secondary)
Button("Try Again") { Task { await appProvider.searchApps() } }
.buttonStyle(.plain)
.foregroundStyle(Ink.primary)
}
}
/// Apps for the selected filter/search result set or "See more" section.
private var filteredApps: [OmiApp] {
// "See more" section takes priority
if let section = viewAllSection {
switch section {
case "featured": return appProvider.popularApps
case "integrations": return appProvider.integrationApps
case "notifications": return appProvider.notificationApps
default: return []
}
}
return appProvider.filteredApps ?? []
}
private var filterResultsTitle: String {
let apps = filteredApps
// "See more" section title
if let section = viewAllSection {
let title =
switch section {
case "featured": "Featured"
case "integrations": "Integrations"
case "notifications": "Realtime Notifications"
default: "Apps"
}
return "\(title) (\(apps.count))"
}
if !searchText.isEmpty {
return "Search Results (\(apps.count))"
}
if let categoryId = appProvider.selectedCategory,
let category = appProvider.categories.first(where: { $0.id == categoryId })
{
return "\(category.title) (\(apps.count))"
}
return "Results (\(apps.count))"
}
private var filteredAppsPresentation: AppsFilteredResultsPresentation {
let queryState: AppFilterResultsQueryState =
viewAllSection == nil
? appProvider.filteredAppsQueryState
: .completed
return AppsFilteredResultsPresentation.resolve(
queryState: queryState,
resultsCount: filteredApps.count
)
}
@ViewBuilder
private var filteredAppsContent: some View {
switch filteredAppsPresentation {
case .loading:
VStack(spacing: OmiSpacing.lg) {
ProgressView()
.scaleEffect(1.2)
Text("Searching...")
.scaledFont(size: OmiType.body)