Refactor command client

This commit is contained in:
世界
2023-08-15 17:20:44 +08:00
parent 1ac5df7f72
commit dbd8700145
20 changed files with 378 additions and 572 deletions
+4
View File
@@ -1,12 +1,16 @@
import Foundation
import Library
import SwiftUI
@main
struct Application: App {
@UIApplicationDelegateAdaptor private var appDelegate: ApplicationDelegate
@StateObject private var environments = ExtensionEnvironments()
var body: some Scene {
WindowGroup {
MainView()
.environmentObject(environments)
}
}
}
+19 -74
View File
@@ -4,90 +4,35 @@ import Library
import SwiftUI
struct MainView: View {
@Environment(\.scenePhase) var scenePhase
@Environment(\.scenePhase) private var scenePhase
@EnvironmentObject private var environments: ExtensionEnvironments
@State private var selection = NavigationPage.dashboard
@State private var extensionProfile: ExtensionProfile?
@State private var profileLoading = true
@State private var logClient: LogClient!
@State private var importRemoteProfile: LibboxImportRemoteProfile?
var body: some View {
viewBuilder {
if profileLoading {
ProgressView().onAppear {
Task.detached {
logClient = LogClient(SharedPreferences.maxLogLines)
await loadProfile()
}
}
} else {
TabView(selection: $selection) {
ForEach(NavigationPage.allCases, id: \.self) { page in
NavigationStackCompat {
page.contentView
.navigationTitle(page.title)
.focusSection()
}
.tag(page)
.tabItem { page.label }
}
TabView(selection: $selection) {
ForEach(NavigationPage.allCases, id: \.self) { page in
NavigationStackCompat {
page.contentView
.navigationTitle(page.title)
.focusSection()
}
.tag(page)
.tabItem { page.label }
}
}
.onAppear {
environments.postReload()
}
.onChangeCompat(of: scenePhase) { newValue in
if newValue == .active {
Task.detached {
await loadProfile()
}
environments.postReload()
}
}
.onChangeCompat(of: selection) { newValue in
if newValue == .logs {
environments.connectLog()
}
}
.environment(\.selection, $selection)
.environment(\.extensionProfile, $extensionProfile)
.environment(\.logClient, $logClient)
.environment(\.importRemoteProfile, $importRemoteProfile)
.onOpenURL(perform: openURL)
}
private func openURL(url: URL) {
if url.host == "import-remote-profile" {
var error: NSError?
importRemoteProfile = LibboxParseRemoteProfileImportLink(url.absoluteString, &error)
if error != nil {
return
}
if selection != .profiles {
selection = .profiles
}
}
}
private func loadProfile() async {
defer {
profileLoading = false
}
if ApplicationLibrary.inPreview {
return
}
if let newProfile = try? await ExtensionProfile.load() {
if extensionProfile == nil || extensionProfile?.status == .invalid {
newProfile.register()
extensionProfile = newProfile
}
} else {
extensionProfile = nil
}
}
private func connectLog() {
guard let profile = extensionProfile else {
return
}
guard let logClient else {
return
}
if profile.status.isConnected, !logClient.isConnected {
logClient.reconnect()
}
}
}