diff --git a/Apps/BizBase b/Apps/BizBase new file mode 160000 index 0000000..b66b3ef --- /dev/null +++ b/Apps/BizBase @@ -0,0 +1 @@ +Subproject commit b66b3ef056e2db7eb47a369be41d150f590a5610 diff --git a/Example/Example.xcodeproj/project.pbxproj b/Example/Example.xcodeproj/project.pbxproj deleted file mode 100644 index c16a238..0000000 --- a/Example/Example.xcodeproj/project.pbxproj +++ /dev/null @@ -1,401 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 56; - objects = { - -/* Begin PBXBuildFile section */ - 8F4D9D562DF37B1C00692972 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F4D9D552DF37B1C00692972 /* ContentView.swift */; }; - 8F4D9D582DF37B1E00692972 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 8F4D9D572DF37B1E00692972 /* Assets.xcassets */; }; - 8F4D9D5C2DF37B1E00692972 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 8F4D9D5B2DF37B1E00692972 /* Preview Assets.xcassets */; }; - 8FB35B932DF37BC40051E31A /* DFBase in Frameworks */ = {isa = PBXBuildFile; productRef = 8FB35B922DF37BC40051E31A /* DFBase */; }; - 8FB35B952DF37DE70051E31A /* AppModule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FB35B942DF37DE70051E31A /* AppModule.swift */; }; -/* End PBXBuildFile section */ - -/* Begin PBXFileReference section */ - 8F4D9D502DF37B1C00692972 /* Example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Example.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 8F4D9D552DF37B1C00692972 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; - 8F4D9D572DF37B1E00692972 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 8F4D9D592DF37B1E00692972 /* Example.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Example.entitlements; sourceTree = ""; }; - 8F4D9D5B2DF37B1E00692972 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; }; - 8F4D9D632DF37B3300692972 /* DFBase */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = DFBase; path = Libs/DFBase; sourceTree = ""; }; - 8FB35B942DF37DE70051E31A /* AppModule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppModule.swift; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 8F4D9D4D2DF37B1C00692972 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 8FB35B932DF37BC40051E31A /* DFBase in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 8F4D9D472DF37B1C00692972 = { - isa = PBXGroup; - children = ( - 8F4D9D622DF37B3300692972 /* Packages */, - 8F4D9D522DF37B1C00692972 /* Example */, - 8F4D9D512DF37B1C00692972 /* Products */, - 8FB35B912DF37BC40051E31A /* Frameworks */, - ); - sourceTree = ""; - }; - 8F4D9D512DF37B1C00692972 /* Products */ = { - isa = PBXGroup; - children = ( - 8F4D9D502DF37B1C00692972 /* Example.app */, - ); - name = Products; - sourceTree = ""; - }; - 8F4D9D522DF37B1C00692972 /* Example */ = { - isa = PBXGroup; - children = ( - 8FB35B942DF37DE70051E31A /* AppModule.swift */, - 8F4D9D552DF37B1C00692972 /* ContentView.swift */, - 8F4D9D572DF37B1E00692972 /* Assets.xcassets */, - 8F4D9D592DF37B1E00692972 /* Example.entitlements */, - 8F4D9D5A2DF37B1E00692972 /* Preview Content */, - ); - path = Example; - sourceTree = ""; - }; - 8F4D9D5A2DF37B1E00692972 /* Preview Content */ = { - isa = PBXGroup; - children = ( - 8F4D9D5B2DF37B1E00692972 /* Preview Assets.xcassets */, - ); - path = "Preview Content"; - sourceTree = ""; - }; - 8F4D9D622DF37B3300692972 /* Packages */ = { - isa = PBXGroup; - children = ( - 8F4D9D632DF37B3300692972 /* DFBase */, - ); - name = Packages; - sourceTree = ""; - }; - 8FB35B912DF37BC40051E31A /* Frameworks */ = { - isa = PBXGroup; - children = ( - ); - name = Frameworks; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 8F4D9D4F2DF37B1C00692972 /* Example */ = { - isa = PBXNativeTarget; - buildConfigurationList = 8F4D9D5F2DF37B1E00692972 /* Build configuration list for PBXNativeTarget "Example" */; - buildPhases = ( - 8F4D9D4C2DF37B1C00692972 /* Sources */, - 8F4D9D4D2DF37B1C00692972 /* Frameworks */, - 8F4D9D4E2DF37B1C00692972 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 8FB35B902DF37BBE0051E31A /* PBXTargetDependency */, - ); - name = Example; - packageProductDependencies = ( - 8FB35B922DF37BC40051E31A /* DFBase */, - ); - productName = Example; - productReference = 8F4D9D502DF37B1C00692972 /* Example.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 8F4D9D482DF37B1C00692972 /* Project object */ = { - isa = PBXProject; - attributes = { - BuildIndependentTargetsInParallel = 1; - LastSwiftUpdateCheck = 1420; - LastUpgradeCheck = 1420; - TargetAttributes = { - 8F4D9D4F2DF37B1C00692972 = { - CreatedOnToolsVersion = 14.2; - }; - }; - }; - buildConfigurationList = 8F4D9D4B2DF37B1C00692972 /* Build configuration list for PBXProject "Example" */; - compatibilityVersion = "Xcode 14.0"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 8F4D9D472DF37B1C00692972; - productRefGroup = 8F4D9D512DF37B1C00692972 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 8F4D9D4F2DF37B1C00692972 /* Example */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 8F4D9D4E2DF37B1C00692972 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 8F4D9D5C2DF37B1E00692972 /* Preview Assets.xcassets in Resources */, - 8F4D9D582DF37B1E00692972 /* Assets.xcassets in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 8F4D9D4C2DF37B1C00692972 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 8FB35B952DF37DE70051E31A /* AppModule.swift in Sources */, - 8F4D9D562DF37B1C00692972 /* ContentView.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 8FB35B902DF37BBE0051E31A /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - productRef = 8FB35B8F2DF37BBE0051E31A /* DFBase */; - }; -/* End PBXTargetDependency section */ - -/* Begin XCBuildConfiguration section */ - 8F4D9D5D2DF37B1E00692972 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - ONLY_ACTIVE_ARCH = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - }; - name = Debug; - }; - 8F4D9D5E2DF37B1E00692972 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MTL_ENABLE_DEBUG_INFO = NO; - MTL_FAST_MATH = YES; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - }; - name = Release; - }; - 8F4D9D602DF37B1E00692972 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; - CODE_SIGN_ENTITLEMENTS = Example/Example.entitlements; - CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 1; - DEVELOPMENT_ASSET_PATHS = "\"Example/Preview Content\""; - DEVELOPMENT_TEAM = ""; - ENABLE_HARDENED_RUNTIME = YES; - ENABLE_PREVIEWS = YES; - GENERATE_INFOPLIST_FILE = YES; - "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; - "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES; - "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES; - "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphonesimulator*]" = YES; - "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphoneos*]" = YES; - "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphonesimulator*]" = YES; - "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphoneos*]" = UIStatusBarStyleDefault; - "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphonesimulator*]" = UIStatusBarStyleDefault; - INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; - INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; - LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks"; - "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks"; - MACOSX_DEPLOYMENT_TARGET = 11.0; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.github.yaochenfeng.Example; - PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = auto; - SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx"; - SWIFT_EMIT_LOC_STRINGS = YES; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Debug; - }; - 8F4D9D612DF37B1E00692972 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; - CODE_SIGN_ENTITLEMENTS = Example/Example.entitlements; - CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 1; - DEVELOPMENT_ASSET_PATHS = "\"Example/Preview Content\""; - DEVELOPMENT_TEAM = ""; - ENABLE_HARDENED_RUNTIME = YES; - ENABLE_PREVIEWS = YES; - GENERATE_INFOPLIST_FILE = YES; - "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; - "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES; - "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES; - "INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphonesimulator*]" = YES; - "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphoneos*]" = YES; - "INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphonesimulator*]" = YES; - "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphoneos*]" = UIStatusBarStyleDefault; - "INFOPLIST_KEY_UIStatusBarStyle[sdk=iphonesimulator*]" = UIStatusBarStyleDefault; - INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; - INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; - LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks"; - "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks"; - MACOSX_DEPLOYMENT_TARGET = 11.0; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.github.yaochenfeng.Example; - PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = auto; - SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx"; - SWIFT_EMIT_LOC_STRINGS = YES; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 8F4D9D4B2DF37B1C00692972 /* Build configuration list for PBXProject "Example" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 8F4D9D5D2DF37B1E00692972 /* Debug */, - 8F4D9D5E2DF37B1E00692972 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 8F4D9D5F2DF37B1E00692972 /* Build configuration list for PBXNativeTarget "Example" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 8F4D9D602DF37B1E00692972 /* Debug */, - 8F4D9D612DF37B1E00692972 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - -/* Begin XCSwiftPackageProductDependency section */ - 8FB35B8F2DF37BBE0051E31A /* DFBase */ = { - isa = XCSwiftPackageProductDependency; - productName = DFBase; - }; - 8FB35B922DF37BC40051E31A /* DFBase */ = { - isa = XCSwiftPackageProductDependency; - productName = DFBase; - }; -/* End XCSwiftPackageProductDependency section */ - }; - rootObject = 8F4D9D482DF37B1C00692972 /* Project object */; -} diff --git a/Example/Example.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Example/Example.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 919434a..0000000 --- a/Example/Example.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/Example/Example.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Example/Example.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d9810..0000000 --- a/Example/Example.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/Example/Example/AppModule.swift b/Example/Example/AppModule.swift deleted file mode 100644 index 013d73c..0000000 --- a/Example/Example/AppModule.swift +++ /dev/null @@ -1,27 +0,0 @@ -import DFBase -// -// EntryModule.swift -// Example -// -// Created by yaochenfeng on 2025/6/7. -// -import DFService -import SwiftUI - -class AppModule: ServiceModuleType { - required init(_ manager: DFService.ServiceManager) { - - } - - var taskPhases: [DFService.ServicePhase] = [.initial] - - func run(phase: DFService.ServicePhase) { - AppState.store(.setRoot(AnyView(SplashPageView()))) - } - - func handle(event: DFService.ServiceEvent) { - // 处理事件逻辑 - print("Received event: \(event.name) with payload: \(event.payload)") - } - -} diff --git a/Example/Example/Assets.xcassets/AccentColor.colorset/Contents.json b/Example/Example/Assets.xcassets/AccentColor.colorset/Contents.json deleted file mode 100644 index eb87897..0000000 --- a/Example/Example/Assets.xcassets/AccentColor.colorset/Contents.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "colors" : [ - { - "idiom" : "universal" - } - ], - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Example/Example/Assets.xcassets/AppIcon.appiconset/Contents.json b/Example/Example/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index 532cd72..0000000 --- a/Example/Example/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "platform" : "ios", - "size" : "1024x1024" - }, - { - "idiom" : "mac", - "scale" : "1x", - "size" : "16x16" - }, - { - "idiom" : "mac", - "scale" : "2x", - "size" : "16x16" - }, - { - "idiom" : "mac", - "scale" : "1x", - "size" : "32x32" - }, - { - "idiom" : "mac", - "scale" : "2x", - "size" : "32x32" - }, - { - "idiom" : "mac", - "scale" : "1x", - "size" : "128x128" - }, - { - "idiom" : "mac", - "scale" : "2x", - "size" : "128x128" - }, - { - "idiom" : "mac", - "scale" : "1x", - "size" : "256x256" - }, - { - "idiom" : "mac", - "scale" : "2x", - "size" : "256x256" - }, - { - "idiom" : "mac", - "scale" : "1x", - "size" : "512x512" - }, - { - "idiom" : "mac", - "scale" : "2x", - "size" : "512x512" - } - ], - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Example/Example/Assets.xcassets/Contents.json b/Example/Example/Assets.xcassets/Contents.json deleted file mode 100644 index 73c0059..0000000 --- a/Example/Example/Assets.xcassets/Contents.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Example/Example/ContentView.swift b/Example/Example/ContentView.swift deleted file mode 100644 index 123d4c6..0000000 --- a/Example/Example/ContentView.swift +++ /dev/null @@ -1,76 +0,0 @@ -// -// ContentView.swift -// Example -// -// Created by yaochenfeng on 2025/6/7. -// - -import SwiftUI -import DFService - -struct SplashPageView: View { - @Environment(\.appStore) var store - - var body: some View { - VStack { - Image(systemName: "globe") - .imageScale(.large) - .foregroundColor(.accentColor) - Text("Splash Page") - - Button("Go to Login Page") { - store.dispatch(.setRoot(AnyView(LoginPageView()))) - } - - Button("send event") { - // Example of sending an event - let event = ServiceEvent(name: "exampleEvent", payload: "Hello, World!") - ServiceManager.shared.sendEvent(event) - } - } - .padding() - } -} - -struct LoginPageView: View { - @Environment(\.appStore) var store - - var body: some View { - VStack { - Image(systemName: "lock") - .imageScale(.large) - .foregroundColor(.accentColor) - Text("Login Page") - - Button("Main") { - // Perform login action - store.dispatch(.setRoot(AnyView(MainPageView()))) - } - } - .padding() - } -} - -struct MainPageView: View { - @Environment(\.appStore) var store - - var body: some View { - VStack { - Image(systemName: "house") - .imageScale(.large) - .foregroundColor(.accentColor) - Text("Main Page") - - Button("Go to Splash Page") { - store.dispatch(.setRoot(AnyView(SplashPageView()))) - } - } - .padding() - } -} - -struct ContentView_Previews: PreviewProvider { - static var previews: some View { - SplashPageView() - } -} diff --git a/Example/Example/Example.entitlements b/Example/Example/Example.entitlements deleted file mode 100644 index f2ef3ae..0000000 --- a/Example/Example/Example.entitlements +++ /dev/null @@ -1,10 +0,0 @@ - - - - - com.apple.security.app-sandbox - - com.apple.security.files.user-selected.read-only - - - diff --git a/Example/Example/Preview Content/Preview Assets.xcassets/Contents.json b/Example/Example/Preview Content/Preview Assets.xcassets/Contents.json deleted file mode 100644 index 73c0059..0000000 --- a/Example/Example/Preview Content/Preview Assets.xcassets/Contents.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Example/Libs/DFBase/.gitignore b/Example/Libs/DFBase/.gitignore deleted file mode 100644 index 0023a53..0000000 --- a/Example/Libs/DFBase/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -.DS_Store -/.build -/Packages -xcuserdata/ -DerivedData/ -.swiftpm/configuration/registries.json -.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata -.netrc diff --git a/Example/Libs/DFBase/Package.swift b/Example/Libs/DFBase/Package.swift deleted file mode 100644 index fee043d..0000000 --- a/Example/Libs/DFBase/Package.swift +++ /dev/null @@ -1,25 +0,0 @@ -// swift-tools-version: 5.7 -// The swift-tools-version declares the minimum version of Swift required to build this package. - -import PackageDescription - -let package = Package( - name: "DFBase", - platforms: [.iOS(.v14), .macOS(.v11), .tvOS(.v14), .watchOS(.v7)], - products: [ - // Products define the executables and libraries a package produces, making them visible to other packages. - .library( - name: "DFBase", - targets: ["DFBase"]) - ], - dependencies: [ - .package(path: "../../../") - ], - targets: [ - // Targets are the basic building blocks of a package, defining a module or a test suite. - // Targets can depend on other targets in this package and products from dependencies. - .target( - name: "DFBase", dependencies: [.byName(name: "DFService")]) - - ] -) diff --git a/Example/Libs/DFBase/Sources/DFBase/AppState.swift b/Example/Libs/DFBase/Sources/DFBase/AppState.swift deleted file mode 100644 index a8f7e2c..0000000 --- a/Example/Libs/DFBase/Sources/DFBase/AppState.swift +++ /dev/null @@ -1,55 +0,0 @@ -// The Swift Programming Language -// https://docs.swift.org/swift-book - -import DFService -import SwiftUI - -public struct AppState: ServiceStateType { - public init() {} - public var root: AnyView = AnyView(EmptyView()) - - nonisolated public static func reducer(state: AppState, action: Action) -> AppState? { - var newState = state - switch action { - - case .setRoot(let root): - newState.root = root - } - return newState - } - - public static func effect( - action: Action, context: DFService.ServiceStore.EffectContext - ) { - - } - - public enum Action { - case setRoot(AnyView) - } - - @MainActor public static var store = ServiceStore(state: AppState()) -} - -extension EnvironmentValues { - public var appStore: ServiceStore { - get { self[AppStoreKey.self] } - set { self[AppStoreKey.self] = newValue } - } - -} - -private struct AppStoreKey { - @MainActor - static var defaultValue: ServiceStore { - return AppState.store - } -} - -#if swift(>=5.8) -extension AppStoreKey: @preconcurrency EnvironmentKey { -} -#else -extension AppStoreKey: EnvironmentKey { -} -#endif diff --git a/Example/Libs/DFBase/Sources/DFBase/ExampleApp.swift b/Example/Libs/DFBase/Sources/DFBase/ExampleApp.swift deleted file mode 100644 index a1dd3dc..0000000 --- a/Example/Libs/DFBase/Sources/DFBase/ExampleApp.swift +++ /dev/null @@ -1,46 +0,0 @@ -// -// ExampleApp.swift -// Example -// -// Created by yaochenfeng on 2025/6/7. -// - -import DFService -import SwiftUI - -@main -struct ExampleApp: App { - let manager = ServiceManager.shared - init() { - // 注册模块 AppModule - // bundle main name - if let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String, - let cls = NSClassFromString("\(appName).AppModule") as? ServiceModuleType.Type { - manager.register(cls) - } - manager.runAll(phase: .initial) - - } - var body: some Scene { - - WindowGroup { - PagePrviewView() - - } - } -} - -struct PagePrviewView: View { - @ObservedObject var store: ServiceStore = AppState.store - init(@ViewBuilder content: () -> Page) { - store.dispatch(.setRoot(AnyView(content()))) - } - init() { - - } - - var body: some View { - store.state.root - .environment(\.appStore, store) - } -} diff --git a/Sources/DFService/DFAppContext.swift b/Sources/DFService/DFAppContext.swift new file mode 100644 index 0000000..cd45267 --- /dev/null +++ b/Sources/DFService/DFAppContext.swift @@ -0,0 +1,16 @@ +import Foundation + +public final class DFAppContext { + public static var shared = DFAppContext() + public init() { + } + var moduleMap: [String: DFModuleType] = [:] +} + +#if canImport(SwiftUI) +import SwiftUI +@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) +extension DFAppContext: ObservableObject { + +} +#endif diff --git a/Sources/DFService/ServiceManager.swift b/Sources/DFService/ServiceManager.swift deleted file mode 100644 index 338cce3..0000000 --- a/Sources/DFService/ServiceManager.swift +++ /dev/null @@ -1,43 +0,0 @@ -public final class ServiceManager { - public static var shared = ServiceManager() - public init() {} - - private var modules: [String: DFModuleType] = [:] - - @MainActor - public func runAll(phase: ServicePhase) { - modules.values - .filter { $0.taskPhases.contains(phase) } - .forEach { $0.run(phase: phase) } - } -} - -extension ServiceManager { - public func register(_ module: Module) { - modules[Module.name] = module - } - public func register(_ module: Module.Type = Module.self) { - let value = module.init(self) - register(value) - } - // 通过模块名称获取模块实例 - public func getModule(named name: String) -> DFModuleType? { - return modules[name] - } - - // 通过模块类型获取模块实例 - public func getModule(byType type: T.Type) -> T? { - return modules.values.first(where: { $0 is T }) as? T - } - public func sendEvent(_ event: ServiceEvent, to moduleName: String? = nil) { - if let moduleName = moduleName { - // 只发给指定模块 - modules[moduleName]?.handle(event: event) - } else { - // 广播给所有模块 - for module in modules.values { - module.handle(event: event) - } - } - } -} diff --git a/Sources/DFService/ServiceStore.swift b/Sources/DFService/ServiceStore.swift index 64b10ea..b887a9f 100644 --- a/Sources/DFService/ServiceStore.swift +++ b/Sources/DFService/ServiceStore.swift @@ -1,7 +1,7 @@ import Foundation -public final class ServiceStore { +open class ServiceStore { public private(set) var state: State { didSet { diff --git a/Sources/DFService/types/DFModuleType.swift b/Sources/DFService/types/DFModuleType.swift index 85273d5..d8abba7 100644 --- a/Sources/DFService/types/DFModuleType.swift +++ b/Sources/DFService/types/DFModuleType.swift @@ -1,64 +1,30 @@ -// -// File.swift -// -// -// Created by yaochenfeng on 2025/6/7. -// - import Foundation -public struct ServiceEvent { - public let name: String - public let payload: Any - public init(name: String, payload: Any = ()) { - self.name = name - self.payload = payload - } -} -public struct ServicePhase: Comparable, RawRepresentable { - // 内置阶段 - public static let initial = ServicePhase(rawValue: 0) // 初始阶段 - public static let splash = Self.initial.next(step: 10) // 启动阶段 - - public var rawValue: Int - public init(rawValue: Int) { - self.rawValue = rawValue - } - - public static func == (lhs: ServicePhase, rhs: ServicePhase) -> Bool { - lhs.rawValue == rhs.rawValue - } - - public static func < (lhs: ServicePhase, rhs: ServicePhase) -> Bool { - lhs.rawValue < rhs.rawValue - } - // 通过已有阶段生成新阶段示例 - public func next(step: Int = 1) -> ServicePhase { - return ServicePhase(rawValue: self.rawValue + step) - } -} public protocol DFModuleType: AnyObject { - init(_ manager: ServiceManager) - static var name: String { get } - // ren阶段 - var taskPhases: [ServicePhase] { get } - - @MainActor func run(phase: ServicePhase) - /// 处理事件(可选实现) - func handle(event: ServiceEvent) + static var moduleName: String { get } + init() + } - extension DFModuleType { - public static var name: String { + public static var moduleName: String { return String(describing: self) } +} - // 默认实现,子类可以覆盖 - public var taskPhases: [ServicePhase] { - return [.splash] +extension DFAppContext { + public func contain(moduleName: String) -> Bool { + return moduleMap[moduleName] != nil } - - func handle(event: ServiceEvent) { - + public func get(module: M.Type = M.self) -> M { + if let module = moduleMap[M.moduleName] as? M { + return module + } + let module = M.init() + moduleMap[M.moduleName] = module + return module + } + + public func getAllModules() -> [DFModuleType] { + return Array(moduleMap.values) } } diff --git a/Sources/DFUI/Resources/Assets.swift b/Sources/DFUI/Resources/Assets.swift deleted file mode 100644 index cd9531c..0000000 --- a/Sources/DFUI/Resources/Assets.swift +++ /dev/null @@ -1,122 +0,0 @@ -// swiftlint:disable all -// Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen - -#if os(macOS) - import AppKit -#elseif os(iOS) - import UIKit -#elseif os(tvOS) || os(watchOS) - import UIKit -#endif -#if canImport(SwiftUI) - import SwiftUI -#endif - -// Deprecated typealiases -@available(*, deprecated, renamed: "ImageAsset.Image", message: "This typealias will be removed in SwiftGen 7.0") -internal typealias AssetImageTypeAlias = ImageAsset.Image - -// swiftlint:disable superfluous_disable_command file_length implicit_return - -// MARK: - Asset Catalogs - -// swiftlint:disable identifier_name line_length nesting type_body_length type_name -internal enum Asset { - internal static let pageError = ImageAsset(name: "pageError") -} -// swiftlint:enable identifier_name line_length nesting type_body_length type_name - -// MARK: - Implementation Details - -internal struct ImageAsset { - internal fileprivate(set) var name: String - - #if os(macOS) - internal typealias Image = NSImage - #elseif os(iOS) || os(tvOS) || os(watchOS) - internal typealias Image = UIImage - #endif - - @available(iOS 8.0, tvOS 9.0, watchOS 2.0, macOS 10.7, *) - internal var image: Image { - let bundle = BundleToken.bundle - #if os(iOS) || os(tvOS) - let image = Image(named: name, in: bundle, compatibleWith: nil) - #elseif os(macOS) - let name = NSImage.Name(self.name) - let image = (bundle == .main) ? NSImage(named: name) : bundle.image(forResource: name) - #elseif os(watchOS) - let image = Image(named: name) - #endif - guard let result = image else { - fatalError("Unable to load image asset named \(name).") - } - return result - } - - #if os(iOS) || os(tvOS) - @available(iOS 8.0, tvOS 9.0, *) - internal func image(compatibleWith traitCollection: UITraitCollection) -> Image { - let bundle = BundleToken.bundle - guard let result = Image(named: name, in: bundle, compatibleWith: traitCollection) else { - fatalError("Unable to load image asset named \(name).") - } - return result - } - #endif - - #if canImport(SwiftUI) - @available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *) - internal var swiftUIImage: SwiftUI.Image { - SwiftUI.Image(asset: self) - } - #endif -} - -internal extension ImageAsset.Image { - @available(iOS 8.0, tvOS 9.0, watchOS 2.0, *) - @available(macOS, deprecated, - message: "This initializer is unsafe on macOS, please use the ImageAsset.image property") - convenience init?(asset: ImageAsset) { - #if os(iOS) || os(tvOS) - let bundle = BundleToken.bundle - self.init(named: asset.name, in: bundle, compatibleWith: nil) - #elseif os(macOS) - self.init(named: NSImage.Name(asset.name)) - #elseif os(watchOS) - self.init(named: asset.name) - #endif - } -} - -#if canImport(SwiftUI) -@available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *) -internal extension SwiftUI.Image { - init(asset: ImageAsset) { - let bundle = BundleToken.bundle - self.init(asset.name, bundle: bundle) - } - - init(asset: ImageAsset, label: Text) { - let bundle = BundleToken.bundle - self.init(asset.name, bundle: bundle, label: label) - } - - init(decorative asset: ImageAsset) { - let bundle = BundleToken.bundle - self.init(decorative: asset.name, bundle: bundle) - } -} -#endif - -// swiftlint:disable convenience_type -private final class BundleToken { - static let bundle: Bundle = { - #if SWIFT_PACKAGE - return Bundle.module - #else - return Bundle(for: BundleToken.self) - #endif - }() -} -// swiftlint:enable convenience_type diff --git a/Sources/DFUI/Resources/Assets.xcassets/Contents.json b/Sources/DFUI/Resources/Assets.xcassets/Contents.json deleted file mode 100644 index 73c0059..0000000 --- a/Sources/DFUI/Resources/Assets.xcassets/Contents.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Sources/DFUI/Resources/Assets.xcassets/pageError.imageset/Contents.json b/Sources/DFUI/Resources/Assets.xcassets/pageError.imageset/Contents.json deleted file mode 100644 index ff9550f..0000000 --- a/Sources/DFUI/Resources/Assets.xcassets/pageError.imageset/Contents.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "scale" : "1x" - }, - { - "filename" : "pageError@2x.svg", - "idiom" : "universal", - "scale" : "2x" - }, - { - "idiom" : "universal", - "scale" : "3x" - } - ], - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Sources/DFUI/Resources/Assets.xcassets/pageError.imageset/pageError@2x.svg b/Sources/DFUI/Resources/Assets.xcassets/pageError.imageset/pageError@2x.svg deleted file mode 100644 index ae8c28f..0000000 --- a/Sources/DFUI/Resources/Assets.xcassets/pageError.imageset/pageError@2x.svg +++ /dev/null @@ -1,71 +0,0 @@ - - - 2_404 Error@2x - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 404 - - - - - - - \ No newline at end of file diff --git a/Sources/DFUI/old/Application.swift b/Sources/DFUI/old/Application.swift deleted file mode 100644 index 160cb9a..0000000 --- a/Sources/DFUI/old/Application.swift +++ /dev/null @@ -1,94 +0,0 @@ -import SwiftUI - -public class Application { - public static let version = "0.1.0" - fileprivate static var _instance: Application? - public var loadProviders: [DFService.ServiceProvider] = [] - private var storage: [FactoryKey: Any] = [:] - private var serviceNames: [ServiceName: FactoryKey] = [:] - public required init() {} -} - -extension Application: DFApplication { - public subscript(service: Service.Type, tag: String = "") -> Service.Value where Service : DFServiceKey { - get { - let key = FactoryKey(type: service, tag: tag) - if let value = storage[key] as? Service.Value { - return value - } - return service.defaultValue - } - set { - let key = FactoryKey(type: service, tag: tag) - storage[key] = newValue - } - } - - public var providerType: [DFService.ServiceProvider.Type] { - return [] - } - - public static var shared: Application { - if let value = _instance { - return value - } - let value = Application() - _instance = value - do { - let provider = try Bundle.main.app.loadClass(ofType: ServiceProvider.self, named: "AppServiceProvider") - value.provider(provider) - } catch { - - } - return value - } -} - -extension Application { - public subscript(_ name: ServiceName, tag: String = "") -> Service.Type? { - set { - guard newValue != nil else { - serviceNames[name] = nil - return - } - let value = FactoryKey(type: Service.self) - serviceNames[name] = value - if(storage[value] == nil) { - storage[value] = Service.defaultValue - } - } - - get { - serviceNames[name]?.type as? Service.Type - } - } - - public func findBy(_ name: ServiceName) -> DFApiCall? { - guard let key = serviceNames[name] else { - return nil - } - guard let value = storage[key] as? DFApiCall else { - return nil - } - return value - } -} - -extension Application: ObservableObject {} - -struct AppEnvironmentKey: EnvironmentKey { - static var defaultValue = Application.shared -} - -extension EnvironmentValues { - public var application: Application { - get { - return self[AppEnvironmentKey.self] - } - set { - self[AppEnvironmentKey.self] = newValue - } - } -} - -public let DF = Application.shared diff --git a/Sources/DFUI/old/CommonError.swift b/Sources/DFUI/old/CommonError.swift deleted file mode 100644 index b5fa0b1..0000000 --- a/Sources/DFUI/old/CommonError.swift +++ /dev/null @@ -1,14 +0,0 @@ -import Foundation -/// 常用错误定义 -public enum CommonError: Error { - /// 业务错误 - case biz(code: Int, msg: String) - /// 未实现 - case unImplemented(String = #function) - /// 自定义错误 - case custom(Error) - /// 未找到 - case notFound(Any = ()) - /// 转换失败 - case convert(from: String, to: String) -} diff --git a/Sources/DFUI/old/Injected.swift b/Sources/DFUI/old/Injected.swift deleted file mode 100644 index 5ce6bfd..0000000 --- a/Sources/DFUI/old/Injected.swift +++ /dev/null @@ -1,11 +0,0 @@ -@propertyWrapper -public struct Injected { - let app: Application - public init(_ service:Service.Type = Service.self, - _ app: Application = .shared) { - self.app = app - } - public var wrappedValue: Service.Value { - return app[Service.self] - } -} diff --git a/Sources/DFUI/old/Space.swift b/Sources/DFUI/old/Space.swift deleted file mode 100644 index 7daf736..0000000 --- a/Sources/DFUI/old/Space.swift +++ /dev/null @@ -1,34 +0,0 @@ -import Foundation - -public struct Space { - public let base: Base - public init(_ base: Base) { - self.base = base - } -} - -/// app命名空间 -public protocol AppCompatible { - associatedtype Base - - static var app: Space.Type { get set } - - var app: Space { get set } -} - - -extension AppCompatible { - public static var app: Space.Type { - get { Space.self } - // swiftlint:disable:next unused_setter_value - set { } - } - - public var app: Space { - get { Space(self) } - // swiftlint:disable:next unused_setter_value - set { } - } -} - -extension NSObject: AppCompatible {} diff --git a/Sources/DFUI/old/contract/DFApiCall.swift b/Sources/DFUI/old/contract/DFApiCall.swift deleted file mode 100644 index 9ad1eeb..0000000 --- a/Sources/DFUI/old/contract/DFApiCall.swift +++ /dev/null @@ -1,16 +0,0 @@ -public class ApiCallConext { - let method: String - let param: Codable - public var options = [String: Any]() - - public init(method: String, param: Codable) { - self.method = method - self.param = param - } -} - -/// api调用 -public protocol DFApiCall { - /// 提供异步调用 - func callAsFunction( _ context: ApiCallConext) async throws -> Any -} diff --git a/Sources/DFUI/old/contract/DFApplication.swift b/Sources/DFUI/old/contract/DFApplication.swift deleted file mode 100644 index 68999bc..0000000 --- a/Sources/DFUI/old/contract/DFApplication.swift +++ /dev/null @@ -1,11 +0,0 @@ -import SwiftUI - -/// 应用协议 -public protocol DFApplication: AnyObject { - /// 应用默认注册的服务提供者 - var providerType: [ServiceProvider.Type] { get } - /// 已注册的服务提供者 - var loadProviders: [ServiceProvider] { get set } - - subscript(service: Service.Type, tag: String) -> Service.Value { get set } -} diff --git a/Sources/DFUI/old/contract/DFHandler.swift b/Sources/DFUI/old/contract/DFHandler.swift deleted file mode 100644 index b9283c3..0000000 --- a/Sources/DFUI/old/contract/DFHandler.swift +++ /dev/null @@ -1,32 +0,0 @@ -public protocol DFHandler { - associatedtype Input - associatedtype Output = Void - - func handleSync(_ input: Input) throws -> Output - func handle(_ input: Input) async throws-> Output -} - -public extension DFHandler { - func handle(_ input: Input) async throws -> Output { - return try self.handleSync(input) - } -} - - -public struct AnyHandler: DFHandler { - public func handleSync(_ input: Input) throws -> Output { - return try _handlerSync(input) - } - public func handle(_ input: Input) async throws -> Output { - return try await _handler(input) - } - - private let _handlerSync:(Input) throws -> Output - private let _handler:(Input) async throws -> Output - public init(_ handler: T) where T.Input == Input, T.Output == Output { - self._handler = handler.handle(_:) - self._handlerSync = handler.handleSync(_:) - } -} - - diff --git a/Sources/DFUI/old/contract/DFServiceKey.swift b/Sources/DFUI/old/contract/DFServiceKey.swift deleted file mode 100644 index df07b34..0000000 --- a/Sources/DFUI/old/contract/DFServiceKey.swift +++ /dev/null @@ -1,5 +0,0 @@ -import SwiftUI -public protocol DFServiceKey { - associatedtype Value - static var defaultValue: Self.Value { get } -} diff --git a/Sources/DFUI/old/core/FactoryKey.swift b/Sources/DFUI/old/core/FactoryKey.swift deleted file mode 100644 index 884fbb9..0000000 --- a/Sources/DFUI/old/core/FactoryKey.swift +++ /dev/null @@ -1,26 +0,0 @@ -struct FactoryKey: Hashable { - @usableFromInline let type: Any.Type - @usableFromInline let tag: String - @usableFromInline let identifier: ObjectIdentifier - - @inlinable - @inline(__always) - init(type: Any.Type, tag: String = "") { - self.type = type - self.tag = tag - self.identifier = ObjectIdentifier(type) - } - - @inlinable - @inline(__always) - public func hash(into hasher: inout Hasher) { - hasher.combine(self.identifier) - hasher.combine(self.tag) - } - - @inlinable - public static func == (lhs: Self, rhs: Self) -> Bool { - return lhs.identifier == rhs.identifier && lhs.tag == rhs.tag - } - -} diff --git a/Sources/DFUI/old/core/ServiceName.swift b/Sources/DFUI/old/core/ServiceName.swift deleted file mode 100644 index e21910c..0000000 --- a/Sources/DFUI/old/core/ServiceName.swift +++ /dev/null @@ -1,26 +0,0 @@ -public struct ServiceName: RawRepresentable, Equatable, Hashable { - public let rawValue: String - - public init(rawValue: String) { - self.rawValue = rawValue - } - public init(_ value: String) { - self.rawValue = value - } - - - public static let logger = ServiceName("df.logger") - public static let router = ServiceName("df.router") -} - - -extension ServiceName: DFApiCall { - @discardableResult - public func callAsFunction(_ context: ApiCallConext) async throws -> Any { - - guard let value = Application.shared.findBy(self) else { - throw CommonError.unImplemented() - } - return try await value.callAsFunction(context) - } -} diff --git a/Sources/DFUI/old/core/ServiceProvider.swift b/Sources/DFUI/old/core/ServiceProvider.swift deleted file mode 100644 index 14fab05..0000000 --- a/Sources/DFUI/old/core/ServiceProvider.swift +++ /dev/null @@ -1,79 +0,0 @@ -import Foundation -/// 应用内服务提供者 -/// 在应用不同时机启动服务 -open class ServiceProvider { - public let app: Application - /// 服务是否启动 - public internal(set) var isBooted: Bool = false - public required init(_ app: Application) { - self.app = app - } - /// 注册服务 - open func register() {} - /// 模拟异步启动逻辑 - open func performAsyncStartup() async throws { - // 重写此方法以实现实际的异步启动逻辑 -// try await Task.sleep(nanoseconds: 1_000_000_000)// 模拟1秒的异步启动 - } - - /// 模拟异步关闭逻辑 - open func performAsyncShutdown() async { - // 重写此方法以实现实际的异步关闭逻辑 -// try await Task.sleep(nanoseconds: 1_000_000_000) // 模拟1秒的异步关闭 - } - open var when: ProviderWhen { - return .splash - } - - open var sortIndex: Int { - return 1_000 - } - - var name: String { - return Self.name - } -} - - -extension ServiceProvider: Equatable { - public static var name: String { - return String(reflecting: self.self) - } - public static func == (lhs: ServiceProvider, rhs: ServiceProvider) -> Bool { - return lhs.name == rhs.name - } -} - -extension ServiceProvider: Comparable { - public static func < (lhs: ServiceProvider, rhs: ServiceProvider) -> Bool { - if lhs.when != rhs.when { - return lhs.when.rawValue < rhs.when.rawValue - } - return lhs.sortIndex < rhs.sortIndex - } - -} - -extension ServiceProvider { - /// 启动时机 - public struct ProviderWhen: RawRepresentable, Comparable { - public static func < (lhs: ProviderWhen, rhs: ProviderWhen) -> Bool { - return lhs.rawValue < rhs.rawValue - } - - public init(rawValue: Int) { - self.rawValue = rawValue - } - public let rawValue: Int - /// 默认启动 - public static let eager = ProviderWhen(rawValue: 0) - /// 窗口创建后启动 - public static let window = ProviderWhen(rawValue: 4) - /// 主窗口创建的第一个页面 - public static let splash = ProviderWhen(rawValue: 8) - - public static func + (lhs: ProviderWhen, rhs: Int) -> ProviderWhen { - return ProviderWhen(rawValue: lhs.rawValue + rhs) - } - } -} diff --git a/Sources/DFUI/old/exported.swift b/Sources/DFUI/old/exported.swift deleted file mode 100644 index 1024311..0000000 --- a/Sources/DFUI/old/exported.swift +++ /dev/null @@ -1,54 +0,0 @@ -@_exported import SwiftUI - - -#if canImport(UIKit) -import UIKit -public typealias PlatformView = UIView -public typealias PlatformController = UIViewController - -public protocol PlatformRepresentable: UIViewRepresentable { - associatedtype PlatformView = UIViewType - - func makeView(context: Context) -> PlatformView -} - -public extension PlatformRepresentable { - func makeUIView(context: Context) -> PlatformView { - return makeView(context: context) - } - - func updateUIView(_ uiView: PlatformView, context: Context) {} -} - -public typealias RouterNavigationController = UINavigationController -#elseif canImport(AppKit) -import AppKit - -public typealias PlatformView = NSView -public typealias PlatformController = NSViewController - -public protocol PlatformRepresentable: NSViewRepresentable { - associatedtype PlatformView = NSViewType - - func makeView(context: Context) -> PlatformView -} - -public extension PlatformRepresentable { - func makeNSView(context: Context) -> PlatformView { - makeView(context: context) - } - - func updateNSView(_ nsView: PlatformView, context: Context) { - - } -} - -public class RouterNavigationController { - -} -#else - -public class RouterNavigationController { - -} -#endif diff --git a/Sources/DFUI/old/extension/app.bool.swift b/Sources/DFUI/old/extension/app.bool.swift deleted file mode 100644 index e0d7b40..0000000 --- a/Sources/DFUI/old/extension/app.bool.swift +++ /dev/null @@ -1,20 +0,0 @@ -extension Bool: AppCompatible {} - -public extension Space where Base == Bool { - /// os ios - static var iOS: Bool { -#if os(iOS) - return true -#else - return false -#endif - } - /// UIKit - static var uikit: Bool { -#if canImport(UIKit) - return true -#else - return false -#endif - } -} diff --git a/Sources/DFUI/old/extension/app.bundle.swift b/Sources/DFUI/old/extension/app.bundle.swift deleted file mode 100644 index 72689d9..0000000 --- a/Sources/DFUI/old/extension/app.bundle.swift +++ /dev/null @@ -1,47 +0,0 @@ -import Foundation - -extension Space where Base == Bundle { - /// 应用名 egg: Example - public static var name: String { - Bundle.main.app.getInfo("CFBundleName") ?? "unkown" - } - /// 应用名 egg: com.github.example - public static var id: String { - Bundle.main.app.getInfo("CFBundleIdentifier") ?? "unkown" - } - /// 版本 egg: 1.0.0 - public static var version: String { - Bundle.main.app.getInfo("CFBundleShortVersionString") ?? "0.0.0" - } - - /// build版本 egg: 1 - public static var buildVersion: String { - Bundle.main.app.getInfo("CFBundleVersion") ?? "0.0" - } - - /// 应用信息 - public func getInfo(_ key: String) -> T? { - guard let value = base.infoDictionary?[key] else { - return nil - } - return BoxValue(value: value).optional() - } - /// 加载类 - public func loadClass(ofType type: T.Type, - named name: String? = nil) throws -> T.Type { - var name = name ?? String(reflecting: type.self) - if name.components(separatedBy: ".").count == 1, - let namespace: String = base.infoDictionary?["CFBundleExecutable"] as? String { - name = namespace.replacingOccurrences(of: " ", with: "_") + "." + name - } - guard name.components(separatedBy: ".").count > 1 else { - throw CommonError.notFound("module") - } - guard let loadedClass = base.classNamed(name) else { throw CommonError.notFound(type) } - guard let castedClass = loadedClass as? T.Type else { - throw CommonError.convert(from: String(describing: loadedClass), to: name) - } - - return castedClass - } -} diff --git a/Sources/DFUI/old/extension/app.chain.swift b/Sources/DFUI/old/extension/app.chain.swift deleted file mode 100644 index cb93a92..0000000 --- a/Sources/DFUI/old/extension/app.chain.swift +++ /dev/null @@ -1,14 +0,0 @@ -public extension Space where Base: AnyObject { - /// 链式操作 - @discardableResult - func then(_ block: (Base) throws -> Void) rethrows -> Base { - try block(self.base) - return self.base - } - /// 链式语法调用函数 - @discardableResult - func chain(_ block: (Base) throws -> Void) rethrows -> Space { - try block(base) - return self - } -} diff --git a/Sources/DFUI/old/extension/app.string.swift b/Sources/DFUI/old/extension/app.string.swift deleted file mode 100644 index a206c36..0000000 --- a/Sources/DFUI/old/extension/app.string.swift +++ /dev/null @@ -1,12 +0,0 @@ -extension String: AppCompatible {} - -public extension Space where Base == String { - var url: URL? { - if let url = URL(string: base) { - return url - } else if let str = base.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: str) { - return url - } - return nil - } -} diff --git a/Sources/DFUI/old/extension/app.thread.swift b/Sources/DFUI/old/extension/app.thread.swift deleted file mode 100644 index 0c5c59c..0000000 --- a/Sources/DFUI/old/extension/app.thread.swift +++ /dev/null @@ -1,13 +0,0 @@ -import Foundation - -public extension Space where Base: Thread { - static func mainTask(_ block: () -> Void) { - if Thread.isMainThread { - block() - } else { - DispatchQueue.main.sync { - block() - } - } - } -} diff --git a/Sources/DFUI/old/extension/app.view.swift b/Sources/DFUI/old/extension/app.view.swift deleted file mode 100644 index 39b3738..0000000 --- a/Sources/DFUI/old/extension/app.view.swift +++ /dev/null @@ -1,49 +0,0 @@ -import SwiftUI - -#if canImport(UIKit) -import UIKit -extension Space: View, UIViewRepresentable where Base: UIView { - public func makeUIView(context: Context) -> Base { - return base - } - - public func updateUIView(_ uiView: Base, context: Context) { - - } - - public typealias UIViewType = Base -} -#elseif canImport(AppKit) -import AppKit - -extension Space: View, NSViewRepresentable where Base: NSView { - public func makeNSView(context: Context) -> Base { - return base - } - - public func updateNSView(_ nsView: Base, context: Context) { - - } - - public typealias NSViewType = Base -} -#else -extension Space: View where Base: View { - public var body: Base { - return base - } - - public typealias Body = Base -} -#endif - - -public extension View { - /// 链式操作 - func chain( - @ViewBuilder - transform: (Self) -> Content - ) -> some View { - transform(self) - } -} diff --git a/Sources/DFUI/old/pages/ErrorPage.swift b/Sources/DFUI/old/pages/ErrorPage.swift deleted file mode 100644 index 7650d48..0000000 --- a/Sources/DFUI/old/pages/ErrorPage.swift +++ /dev/null @@ -1,40 +0,0 @@ - - -import SwiftUI - -struct ErrorPage: View { - var body: some View { - ZStack(alignment: Alignment(horizontal: .center, vertical: .bottom)) { - - Image(asset: Asset.pageError) - .resizable() - .aspectRatio(contentMode: .fill) - .edgesIgnoringSafeArea(.all) - - VStack(alignment: .center) { - Text("页面不存在") - .font(.title) - - Button(action: { - - }) { - Text("返回".uppercased()) - .fontWeight(.semibold) - .foregroundColor(.white) - .padding(.vertical) - .padding(.horizontal, 30) - .background(Capsule().foregroundColor(.blue)) - } - - - }.padding(.bottom, 20) - - } - } -} - -struct ErrorPage_Previews: PreviewProvider { - static var previews: some View { - ErrorPage() - } -} diff --git a/Sources/DFUI/old/pages/NavigationPage.swift b/Sources/DFUI/old/pages/NavigationPage.swift deleted file mode 100644 index 70879c2..0000000 --- a/Sources/DFUI/old/pages/NavigationPage.swift +++ /dev/null @@ -1,184 +0,0 @@ -import SwiftUI - -public struct NavigationPage: View { - @StateObject - var router: Router - - public init(router: Router = .shared) { - _router = .init(wrappedValue: router) - } - public var body: some View { - if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) { - NavigationStack(path: $router.pagePath) { - HookNavigation { - RoutePage(router.rootPath) - } - .navigationDestination(for: RouteRequest.self) { arg in - RoutePage(arg) - } - - .navigationDestination(isPresented: router.sheetBind) { - getSheetView() - } - } - .environment(\.router, router) - .frame(maxWidth: .infinity, maxHeight: .infinity) - } else if Bool.app.uikit { - NavigationView { - HookNavigation { - RoutePage(router.rootPath) - } - } - .chain { view in - if #available(iOS 13, tvOS 13, *) { -#if os(macOS) - view -#else - view.navigationViewStyle(.stack) -#endif - } else { - view - } - } - .environment(\.router, router) - .frame(maxWidth: .infinity, maxHeight: .infinity) - - } else { - ZStack(alignment: .topLeading) { - HookNavigation { - RoutePage(router.rootPath) - } - .sheet(isPresented: router.sheetBind) { - getSheetView() - } - if let req = router.pagePath.last { - router.page(req) - .frame(maxWidth: .infinity, maxHeight: .infinity) - .background(Color.white) - .environment(\.routeRequest, req) - } - - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .environment(\.router, router) - } - } - - @ViewBuilder - func getSheetView() -> some View { - if let request = router.presentingSheet { -#if os(macOS) - - VStack(alignment: .center) { - RoutePage(request) - }.padding() - -#else - RoutePage(request) -#endif - } else { - EmptyView() - } - } -} - -struct HookNavigation: View { - let content: Content - var body: some View { -#if canImport(UIKit) - ZStack { - HookController() - content - } -#else - content -#endif - } - init(content builder: () -> Content) { - self.content = builder() - } -} - -#if canImport(UIKit) -import UIKit -struct HookController: UIViewControllerRepresentable { - func makeUIViewController(context: Context) -> Hook { - return Hook(environment: context.environment) - } - - func updateUIViewController(_ uiViewController: Hook, context: Context) { - uiViewController.environment = context.environment - } - - typealias UIViewControllerType = Hook - - - class Hook: UIViewController, UIGestureRecognizerDelegate { - var environment: EnvironmentValues - - init(environment: EnvironmentValues) { - self.environment = environment - super.init(nibName: nil, bundle: nil) - } - - required init?(coder: NSCoder) { - self.environment = .init() - super.init(coder: coder) - } - - override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) - - if environment.router.controller != navigationController { - bindRouter() - } - } - func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { - guard let nav = environment.router.controller else { - return false - } - return nav.viewControllers.count > 1 - } - func bindRouter() { - guard let nav = navigationController else { - return - } - - let router = environment.router - router.controller = nav -#if os(iOS) - nav.interactivePopGestureRecognizer?.delegate = self -#endif - if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) { - return - } - - router.customHandlerGo = { [weak self] req in - guard let self = self else { return } - let rootView = RoutePage(req) - .environment(\.self, self.environment) - let controller = UIHostingController(rootView: rootView) - if req.routeType == .push { - nav.pushViewController(controller, animated: true) - } else if req.routeType == .present { - nav.present(controller, animated: true) - } - } - router.customHandlerPop = { [weak nav] req in - guard let self = nav else { return } - if let presentedViewController = self.topViewController?.presentedViewController { - presentedViewController.dismiss(animated: true) - } else { - self.popViewController(animated: true) - } - } - router.customHandlerPopRoot = { [weak nav] req in - guard let self = nav else { return } - self.popToRootViewController(animated: true) - } - } - } -} - - -#endif diff --git a/Sources/DFUI/old/pages/RoutePage.swift b/Sources/DFUI/old/pages/RoutePage.swift deleted file mode 100644 index ab9eaac..0000000 --- a/Sources/DFUI/old/pages/RoutePage.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// SwiftUIView.swift -// -// -// Created by yaochenfeng on 2024/8/31. -// - -import SwiftUI - -public struct RoutePage: View { - let request: RouteRequest - public init(_ request: RouteRequest) { - self.request = request - } - @Environment(\.router) var router - public var body: some View { - router.page(request) - .environment(\.routeRequest, request) - } -} - -struct RoutePage_Previews: PreviewProvider { - static var previews: some View { - RoutePage(.init(page: .root)) - } -} diff --git a/Sources/DFUI/old/pages/WebPage.swift b/Sources/DFUI/old/pages/WebPage.swift deleted file mode 100644 index 8cd03a7..0000000 --- a/Sources/DFUI/old/pages/WebPage.swift +++ /dev/null @@ -1,48 +0,0 @@ -import SwiftUI - -public struct WebPage: View { - let request: RouteRequest - public init(_ request: RouteRequest) { - self.request = request - } - #if canImport(WebKit) - @StateObject - var controller = WebController() - - public var body: some View { - PageLayout { - ZStack(alignment: .topLeading) { - if let url = request.url { - WebView(URLRequest(url: url), controller: controller) - } - if controller.progress != 1 { - ProgressView(value: controller.progress) - .progressViewStyle(.linear) - } - } - }.pagBar { - PageBar(controller.title ?? "") - } - } - #else - - public var body: some View { - EmptyView() - } - #endif -} -public extension WebPage { - init(_ string: String) { - if let url = string.app.url { - self.init(.init(url: url)) - } else { - self.init(.init(action: .empty)) - } - } -} - -struct WebPage_Previews: PreviewProvider { - static var previews: some View { - WebPage("https://m.baidu.com") - } -} diff --git a/Sources/DFUI/old/pages/WindowRoutePage.swift b/Sources/DFUI/old/pages/WindowRoutePage.swift deleted file mode 100644 index c9e64fb..0000000 --- a/Sources/DFUI/old/pages/WindowRoutePage.swift +++ /dev/null @@ -1,117 +0,0 @@ -// -// SwiftUIView.swift -// -// -// Created by yaochenfeng on 2024/11/14. -// - -import SwiftUI - -struct WindowRoutePage: View { - @StateObject - var router: Router = .shared - var body: some View { - if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) { - NavigationStack(path: pushBind ) { - router.page(.init(page: .root)) - } - - } - } - -// lazy var pushBind = Binding { -// return router.pages.filter { item in -// return item.routeType == .push -// } -// } set: { newValue, _ in -// -// } - - var pushBind: Binding<[PageRoute]> { - return Binding { - return router.pages.filter { item in - return item.routeType == .push - } - } set: { newValue, _ in - - } - } - - var presentBind: Binding<[PageRoute]> { - return Binding { - let pages = router.pages.filter { item in - return item.routeType == .present - } - return pages - } set: { newValue, _ in - print("set newValue\(newValue)" ) - } - } - - var isPresented: Binding { - return Binding { - let result = - router.pages.contains { page in - return page.routeType == .present - } - return result - } set: { newValue, _ in - print("set newValue\(newValue)" ) - } - - } - - struct Stack: View { - let pageBind: Binding<[PageRoute]> - var body: some View { - if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) { - NavigationStack(path: pathBind) { - if let page = pageBind.wrappedValue.first { - page - .navigationDestination(for: PageRoute.self) { page in - page - } - } else { - EmptyView() - } - } - } - } - var pathBind: Binding<[PageRoute]> { - return Binding { - var pages = pageBind.wrappedValue - _ = pages.removeFirst() - return pages - } set: { newValue, _ in - - } - - } - } -} - -struct SwiftUIView_Previews: PreviewProvider { - - static var previews: some View { - let _ = Router.shared.addPage(.root) { req in - Text("req\(req.routePath.rawValue)") - DemoPage() - } - WindowRoutePage() - } -} - -struct DemoPage: View { - var body: some View { - VStack { - Button("push") { - Router.shared.go(RouteRequest(page: .init(rawValue: "push"))) - } - Button("present") { - let req = RouteRequest(page: .init(rawValue: "present")) - req.routeType = .present - Router.shared.go(req) - } - } - } -} diff --git a/Sources/DFUI/old/service/AppService.swift b/Sources/DFUI/old/service/AppService.swift deleted file mode 100644 index ad1a1d9..0000000 --- a/Sources/DFUI/old/service/AppService.swift +++ /dev/null @@ -1,3 +0,0 @@ -public struct AppService: DFServiceKey { - public static var defaultValue = Application.shared -} diff --git a/Sources/DFUI/old/service/RouteService.swift b/Sources/DFUI/old/service/RouteService.swift deleted file mode 100644 index 6f27ebf..0000000 --- a/Sources/DFUI/old/service/RouteService.swift +++ /dev/null @@ -1,43 +0,0 @@ -import SwiftUI -public struct RouteService: DFServiceKey, EnvironmentKey { - public static var defaultValue: Router { - return Value.shared - } -} - -struct CurrentRequestKey: DFServiceKey, EnvironmentKey { - public static var defaultValue: RouteRequest { - return RouteRequest.init(action: .empty) - } -} - -public extension EnvironmentValues { - var router: Router { - get { - self[RouteService.self] - } - set { - self[RouteService.self] = newValue - } - } - - var routeRequest: RouteRequest { - get { - self[CurrentRequestKey.self] - } - set { - self[CurrentRequestKey.self] = newValue - } - } -} - -public extension Application { - var router: Router { - get { - self[RouteService.self] - } - set { - self[RouteService.self] = newValue - } - } -} diff --git a/Sources/DFUI/old/service/RuntimeService.swift b/Sources/DFUI/old/service/RuntimeService.swift deleted file mode 100644 index 50c0aa5..0000000 --- a/Sources/DFUI/old/service/RuntimeService.swift +++ /dev/null @@ -1,51 +0,0 @@ -#if canImport(UIKit) -import UIKit -#endif -public struct RuntimeService: DFServiceKey { - public static var defaultValue: Value = Value() - - public struct Value {} - - private static var uuid: String? -} - -public extension RuntimeService.Value { - var isPreview: Bool { - return ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" - } - var isRunningInTests: Bool { - #if canImport(XCTest) - return true - #else - return false - #endif - } - - var deviceName: String { - #if canImport(UIKit) - return UIDevice.current.model - #else - return "unkown" - #endif - } - /// 设备id - var genDeviceId: String { - if let value = RuntimeService.uuid { - return value - } -#if canImport(UIKit) - let value = UIDevice.current.identifierForVendor?.uuidString ?? UUID().uuidString -#else - let value = UUID().uuidString -#endif - RuntimeService.uuid = value - return value - - } -} - -public extension Application { - var runtime: RuntimeService.Value { - return self[RuntimeService.self] - } -} diff --git a/Sources/DFUI/old/service/impl/MockApiServiceImpl.swift b/Sources/DFUI/old/service/impl/MockApiServiceImpl.swift deleted file mode 100644 index aa000e5..0000000 --- a/Sources/DFUI/old/service/impl/MockApiServiceImpl.swift +++ /dev/null @@ -1,10 +0,0 @@ -struct MockApiServiceImpl { -} - - - -extension MockApiServiceImpl: DFApiCall { - func callAsFunction(_ context: ApiCallConext) async throws -> Any { - return () - } -} diff --git a/Sources/DFUI/old/service/provider/BootstrapServiceProvider.swift b/Sources/DFUI/old/service/provider/BootstrapServiceProvider.swift deleted file mode 100644 index 14fa8ab..0000000 --- a/Sources/DFUI/old/service/provider/BootstrapServiceProvider.swift +++ /dev/null @@ -1,148 +0,0 @@ -import Foundation - -actor Bootstrap { - private weak var app: Application? - - private var current: ServiceProvider.ProviderWhen = .eager - private var target: ServiceProvider.ProviderWhen = .eager - private var isRunning = false - init(app: Application) { - self.app = app - } - - func bootstrap(_ when: ServiceProvider.ProviderWhen) async { - if(target < when) { - target = when - } - await bootIfNeed() - } - func reset(_ when: ServiceProvider.ProviderWhen) async { - guard let app = app, current > when else { - return - } - let bootProviders = app.loadProviders.filter { provider in - return provider.isBooted && provider.when > current - }.sorted() - self.isRunning = true - current = when - let logger = LogKey.get() - for provider in bootProviders { - let start_time = CFAbsoluteTimeGetCurrent() - var success = false - defer { - let end_time = CFAbsoluteTimeGetCurrent() - let cost_time = (end_time - start_time) * 1000 - - logger.debug("\(provider.name) 停止服务\(success)用时: \(cost_time)毫秒") - } - await provider.performAsyncShutdown() - provider.isBooted = false - success = true - } - self.isRunning = false - await bootIfNeed() - } - - func bootIfNeed() async { - guard let app = app else { - return - } - let currentProviders = app.loadProviders.filter { provider in - return !provider.isBooted && provider.when <= current - }.sorted() - - guard !currentProviders.isEmpty else { - if current < target { - current = current + 1 - await bootIfNeed() - } - return - } - guard !isRunning else { - return - } - self.isRunning = true - let logger = LogKey.get() - for provider in currentProviders where !provider.isBooted { - let start_time = CFAbsoluteTimeGetCurrent() - var success = false - defer { - let end_time = CFAbsoluteTimeGetCurrent() - let cost_time = (end_time - start_time) * 1000 - logger.debug("\(provider.name) 启动\(success)用时: \(cost_time)毫秒") - } - do { - try await provider.performAsyncStartup() - provider.isBooted = true - success = true - } catch { - logger.error("\(provider.name) 启动失败\(error)") - self.isRunning = false - return - } - } - self.isRunning = false - await bootIfNeed() - } -} - -class BootstrapServiceProvider: ServiceProvider { - let bootstrap: Bootstrap - required init(_ app: Application) { - bootstrap = Bootstrap(app: app) - super.init(app) - } - override func register() { - app.providerType.forEach { serviceType in - app.provider(serviceType) - } - } - func bootstrap(_ when: ProviderWhen) { - Task(priority: .userInitiated){ - await bootstrap.bootstrap(when) - } - } - - func reset(_ when: ProviderWhen) { - Task(priority: .userInitiated){ - await bootstrap.reset(when) - } - } - - override var when: ServiceProvider.ProviderWhen { - return .eager - } - - override var sortIndex: Int { - return 0 - } -} - - - -public extension Application { - @discardableResult - func provider(_ serviceType: T.Type = T.self) -> T { - - let loadProvider = loadProviders.first { loaded in - return loaded.name == serviceType.name - } - if let provider = loadProvider as? T { - return provider - } - let provider = serviceType.init(self) - loadProviders.append(provider) - provider.register() - return provider - } - - - func bootstrap(_ when: ServiceProvider.ProviderWhen) { - provider(BootstrapServiceProvider.self).bootstrap(when) - } - /// 重置启动,执行provider Shutdown - func reset(_ when: ServiceProvider.ProviderWhen) { - provider(BootstrapServiceProvider.self).reset(when) - } - -} diff --git a/Sources/DFUI/old/service/router/RouteRequest.swift b/Sources/DFUI/old/service/router/RouteRequest.swift deleted file mode 100644 index 5f85e33..0000000 --- a/Sources/DFUI/old/service/router/RouteRequest.swift +++ /dev/null @@ -1,60 +0,0 @@ - -public final class RouteRequest: ObservableObject { - public enum RouterType { - case push - case present - } - /// 路由操作 - public var routeAction: Router.RouteAction = .empty - public let url: URL? - /// 参数 - public var param: Any? - public var routeType = RouterType.push - public required init(url: URL) { - self.url = url - self.isHandle = false - } - public required init(action: Router.RouteAction, url: URL? = nil) { - self.url = url - self.routeAction = action - self.isHandle = true - } - /// 是否需要经过router handler - internal var isHandle: Bool = false -} - - -public extension RouteRequest { - /// 跳转到指定页面 - convenience init(page: Router.RoutePath, url: URL? = nil){ - self.init(action: .page(page), url: url) - } - var routePath: Router.RoutePath { - switch routeAction { - case .page(let path): - return path - default: - return .page404 - } - } - - var copy: RouteRequest { - let new = RouteRequest(action: routeAction, url: url) - new.param = param - return new - } -} -public extension Router.RoutePath { - var request: RouteRequest { - return RouteRequest(page: self) - } -} -extension RouteRequest: Hashable { - public static func == (lhs: RouteRequest, rhs: RouteRequest) -> Bool { - return lhs.routeAction == rhs.routeAction && lhs.url == rhs.url && ObjectIdentifier(lhs) == ObjectIdentifier(rhs) - } - public func hash(into hasher: inout Hasher) { - hasher.combine(routePath) - hasher.combine(routeAction) - } -} diff --git a/Sources/DFUI/old/service/router/Router.action.swift b/Sources/DFUI/old/service/router/Router.action.swift deleted file mode 100644 index 0afa8c8..0000000 --- a/Sources/DFUI/old/service/router/Router.action.swift +++ /dev/null @@ -1,67 +0,0 @@ -import SwiftUI -extension Router { - - public func handleAction(_ request: RouteRequest) { - guard let builder = self.actionBuilderMap[request.routePath] else { - return - } - builder(request) - } -} -public extension Router { - func go(_ request: RouteRequest) { - if !request.isHandle { - request.routeAction = handler(request) - request.isHandle = true - } - if request.routeAction == .page(.root) { - popToRoot() - return - } - switch request.routeAction { - case .empty: break - case .page: - handlePage(request) - case .action: - handleAction(request) - } - - if let handler = customHandlerGo { - return handler(request) - } - - } - func pop() { - _ = self.pages.popLast() - if let path = presentingSheet { - presentingSheet = nil - if let handler = customHandlerPop { - return handler(path) - } - } else if !pagePath.isEmpty { - let path = pagePath.removeLast() - if let handler = customHandlerPop { - return handler(path) - } - } - } - func popToRoot() { - if presentingSheet != nil { - presentingSheet = nil - } - pagePath.removeAll() - - if let handler = customHandlerPopRoot { - return handler(.init(page: .root)) - } - } - - func canPop() -> Bool { - if let _ = presentingSheet { - return true - } else if !pagePath.isEmpty { - return true - } - return false - } -} diff --git a/Sources/DFUI/old/service/router/Router.page.swift b/Sources/DFUI/old/service/router/Router.page.swift deleted file mode 100644 index 8e49187..0000000 --- a/Sources/DFUI/old/service/router/Router.page.swift +++ /dev/null @@ -1,45 +0,0 @@ -extension Router { - @discardableResult - public func addPage(_ path: RoutePath, - @ViewBuilder - builder: @escaping (RouteRequest) -> T) -> Router { - pageBuilderMap[path] = { req in - return PageRoute(builder: { - builder(req) - }, path: req.routePath , routeType: .push) - } - if path == .root { - Thread.app.mainTask { - self.rootPath = self.rootPath.copy - } - } - return self - } - - public func page(_ request: RouteRequest) -> PageRoute { - if(!request.isHandle) { - request.routeAction = handler(request) - request.isHandle = true - } - let pid = request.routePath - guard let builder = pageBuilderMap[pid] else { - return onGenerateRoute(pid) - } - return PageRoute(builder: { - return builder(request) - }, path: pid, - routeType: request.routeType) - } - - internal func handlePage(_ request: RouteRequest) { - var route = self.page(request) - route.routeType = request.routeType - pages.append(route) - switch request.routeType { - case .push: - pagePath.append(request) - case .present: - presentingSheet = request - } - } -} diff --git a/Sources/DFUI/old/service/router/Router.swift b/Sources/DFUI/old/service/router/Router.swift deleted file mode 100644 index 397c284..0000000 --- a/Sources/DFUI/old/service/router/Router.swift +++ /dev/null @@ -1,81 +0,0 @@ -import Foundation - -public struct RouteSetting { - let name: String? - let arguments: Any -} - -public class Router: ObservableObject { - public enum RouteAction: Equatable, Hashable { - case empty - case page(Router.RoutePath) - case action(Router.RoutePath) - } - - public struct RoutePath: RawRepresentable, Equatable, Hashable { - public static let page404 = RoutePath(rawValue: "page/404") - public static let root = RoutePath(rawValue: "page/root") - public let rawValue: String - public init(rawValue: String) { - self.rawValue = rawValue - } - } - - typealias PageBuilder = (RouteRequest) -> PageRoute - public typealias ActionBuilder = (RouteRequest) -> Void - public static let shared = Router() - /// 自定义go实现 - internal var customHandlerGo: ActionBuilder? - internal var customHandlerPop: ActionBuilder? - internal var customHandlerPopRoot: ActionBuilder? - public var handler:(RouteRequest) -> RouteAction = { _ in - return .empty - } - public var onGenerateRoute: (RoutePath) -> PageRoute = { setting in - return PageRoute( - builder: { - DemoPage() - }, - path: setting, - routeType: .push) - } - - public var page404: (RouteRequest) -> any View = { _ in - return EmptyView() - } - @Published - public var rootPath = RoutePath.root.request - @Published - public var pages = [PageRoute]() - @Published - public var pagePath = [RouteRequest]() - @Published - public var presentingSheet: RouteRequest? - - internal var pageBuilderMap = [RoutePath: PageBuilder]() - internal var actionBuilderMap = [RoutePath: ActionBuilder]() - public init() {} - - var sheetBind: Binding { - return .init { - return self.presentingSheet != nil - } set: { _ in - self.presentingSheet = nil - } - - } - - weak var controller: RouterNavigationController? - -} - -public extension Router { - @discardableResult - func addAction(_ path: RoutePath, - @ViewBuilder - builder: @escaping (RouteRequest) -> Void) -> Router { - actionBuilderMap[path] = builder - return self - } - -} diff --git a/Sources/DFUI/old/utils/ArrayBuilder.swift b/Sources/DFUI/old/utils/ArrayBuilder.swift deleted file mode 100644 index 48e42cc..0000000 --- a/Sources/DFUI/old/utils/ArrayBuilder.swift +++ /dev/null @@ -1,29 +0,0 @@ -import Foundation - -@resultBuilder -public struct ArrayBuilder { - public static func buildBlock(_ components: T...) -> [T] { - return components - } - - public static func buildOptional(_ component: [T]?) -> [T] { - return component?.compactMap {$0} ?? [] - } - - public static func buildLimitedAvailability(_ component: [T]) -> [T] { - return component - } - - public static func buildEither(first component: [T]) -> [T] { - return component - } - public static func buildEither(second component: [T]) -> [T] { - return component - } - - public static func buildBlock(_ components: [T]...) -> [T] { - return components.reduce([T]()) { partialResult, value in - return partialResult + value - } - } -} diff --git a/Sources/DFUI/old/utils/BoxValue.swift b/Sources/DFUI/old/utils/BoxValue.swift deleted file mode 100644 index a11cd21..0000000 --- a/Sources/DFUI/old/utils/BoxValue.swift +++ /dev/null @@ -1,20 +0,0 @@ -import Foundation - - -struct BoxValue { - let value: Any - - func optional() -> T? { - if let v = value as? T { - return v - } - return nil - } - - func optional() -> String? { - if let v = value as? CustomStringConvertible { - return v.description - } - return nil - } -} diff --git a/Sources/DFUI/old/views/CircularLoading.swift b/Sources/DFUI/old/views/CircularLoading.swift deleted file mode 100644 index 268cc7c..0000000 --- a/Sources/DFUI/old/views/CircularLoading.swift +++ /dev/null @@ -1,18 +0,0 @@ -import SwiftUI - -public struct CircularLoading: View { - let color: Color - public init(_ color: Color = .accentColor) { - self.color = color - } - public var body: some View { - ProgressView() - .progressViewStyle(CircularProgressViewStyle(tint: color)) - } -} - -struct CircularLoading_Previews: PreviewProvider { - static var previews: some View { - CircularLoading() - } -} diff --git a/Sources/DFUI/old/views/PageBar.swift b/Sources/DFUI/old/views/PageBar.swift deleted file mode 100644 index 0b19c9b..0000000 --- a/Sources/DFUI/old/views/PageBar.swift +++ /dev/null @@ -1,133 +0,0 @@ -// -// SwiftUIView.swift -// -// -// Created by yaochenfeng on 2024/9/26. -// - -import SwiftUI - -public struct PageBar: View { - @Environment(\.router) var router - @Environment(\.routeRequest) var request - - private var titleView: AnyView - private var backgroundView: AnyView - private var leadingView: AnyView - private var trailingView: AnyView - private var showBack: Bool = true - - - public var body: some View { - ZStack { - backgroundView - .ignoresSafeArea(edges:.top) - - HStack { - HStack { - if showBack, router.canPop() { - Button { - router.pop() - } label: { - Image(systemName: backName) - } - - } - leadingView - Spacer() - } - - HStack { - titleView - } - - HStack { - Spacer() - trailingView - } - }.padding(.horizontal) - } - .frame(height: 44) - .frame(maxWidth: .infinity) - - } - - public init( - showBack: Bool, - @ViewBuilder titleView: () -> some View, - @ViewBuilder backgroundView: () -> some View, - @ViewBuilder leadingView: () -> some View, - @ViewBuilder trailingView: () -> some View) { - self.titleView = AnyView(titleView()) - self.backgroundView = AnyView(backgroundView()) - self.leadingView = AnyView(leadingView()) - self.trailingView = AnyView(trailingView()) - self.showBack = showBack - } - - - private var backName: String { - request.routeType == .present ? "xmark.circle.fill" : "chevron.left" - } -} - -public extension PageBar { - init(_ title: String, - backgroundColor: Color = .white, showBack: Bool = true) { - self.init (showBack: showBack){ - Text(title) - .font(.title3) - .lineLimit(1) - } backgroundView: { - backgroundColor - } leadingView: { - - } trailingView: { - - } - } - - - func pageBarTitle(@ViewBuilder builder: () -> some View) -> Self { - var clone = self - clone.titleView = AnyView(builder()) - return clone - } - - func pageBarLeading(@ViewBuilder builder: () -> some View) -> Self { - var clone = self - clone.leadingView = AnyView(builder()) - return clone - } - - func pageBarTrailing(@ViewBuilder builder: () -> some View) -> Self { - var clone = self - clone.trailingView = AnyView(builder()) - return clone - } - - func pageBarBackgroud(@ViewBuilder builder: () -> some View) -> Self { - var clone = self - clone.backgroundView = AnyView(builder()) - return clone - } - func pageBar(showBack: Bool) -> Self { - var clone = self - clone.showBack = showBack - return clone - } -} - -struct PageBar_Previews: PreviewProvider { - static var previews: some View { - PageLayout { - - }.pagBar { - PageBar("adsfas地方的") - .pageBarLeading { -// Text("返回") - Text("走吧") - } - } - } -} diff --git a/Sources/DFUI/old/views/PageLayout.swift b/Sources/DFUI/old/views/PageLayout.swift deleted file mode 100644 index 0d393b9..0000000 --- a/Sources/DFUI/old/views/PageLayout.swift +++ /dev/null @@ -1,56 +0,0 @@ -import SwiftUI - -public struct PageLayout: View { - var bar: PageBar? = nil - let content: Content - public var body: some View { - VStack(alignment: .leading, spacing: 0) { - if let pageBar = bar { - pageBar - } - - content - - Spacer() - } - .chain { view in -#if os(macOS) - view -#else - view.navigationBarHidden(bar != nil) -#endif - } - - } - - public init(@ViewBuilder - content: () -> Content) { - self.content = content() - } - - public func pagBar(_ builder: () -> PageBar?) -> Self { - var clone = self - clone.bar = builder() - return clone - } - - public func pagBar(title: String, - backgroundColor: Color = .white, - showBack: Bool = true) -> Self { - var clone = self - clone.bar = PageBar(title, - backgroundColor: backgroundColor,showBack: showBack) - return clone - } -} - -struct PageLayout_Previews: PreviewProvider { - static var previews: some View { - PageLayout { - Text("hello") - }.pagBar { - return .init("标题", backgroundColor: .red) - } - - } -} diff --git a/Sources/DFUI/old/views/WebView.swift b/Sources/DFUI/old/views/WebView.swift deleted file mode 100644 index 12bbaa3..0000000 --- a/Sources/DFUI/old/views/WebView.swift +++ /dev/null @@ -1,119 +0,0 @@ - -import SwiftUI -#if canImport(WebKit) -open class WebController: ObservableObject { - public init() {} - - let config = WKWebViewConfiguration().app.then { config in - config.websiteDataStore = .default() - } - - @Published - public var progress: Double = 0 - @Published - public var title: String? = nil - @Published - public var isLoading = false - -} - - -import WebKit - -public struct WebView: PlatformRepresentable { - let controller: WebController - let request: URLRequest? - - public init(_ request: URLRequest?, - controller: WebController = WebController()) { - self.request = request - self.controller = controller - } - public func makeView(context: Context) -> WKWebView { - let web = context.coordinator.webView - if let req = request { - DispatchQueue.main.async { - web.load(req) - } - } - return web - } - public func makeCoordinator() -> Coordinator { - return Coordinator(controller) - } -} - -public extension WebView { - init(_ string: String) { - if let url = string.app.url { - self.init(URLRequest(url: url)) - } else { - self.init(nil) - } - } -} - -public extension WebView { - class Coordinator: NSObject { - let controller: WebController - let webView: WKWebView - - var logger = LogService.get() - required init(_ controller: WebController) { - self.controller = controller - self.webView = WKWebView(frame: CGRect(x: 0.0, y: 0.0, width: 0.1, height: 0.1), configuration: controller.config) - super.init() - makeObserve() - } - } -} - -extension WebView.Coordinator { - func makeObserve() { - webView.publisher(for: \.estimatedProgress) - .receive(on: DispatchQueue.main) - .assign(to: &controller.$progress) - webView.publisher(for: \.isLoading) - .receive(on: DispatchQueue.main) - .assign(to: &controller.$isLoading) - - webView.publisher(for: \.title) - .receive(on: DispatchQueue.main) - .assign(to: &controller.$title) - - webView.uiDelegate = self - webView.navigationDelegate = self - } -} - -extension WebView.Coordinator: WKUIDelegate { - public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { - logger.info(navigation.debugDescription) - } -} -extension WebView.Coordinator: WKNavigationDelegate { - public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction) async -> WKNavigationActionPolicy { - logger.info(navigationAction.debugDescription) - guard let scheme = navigationAction.request.url?.scheme else { - return .cancel - } - guard scheme.contains("http") else { - return .cancel - } - if #available(macOS 11.3, iOS 14.5, *), navigationAction.shouldPerformDownload { - return .download - } - return .allow - } - public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse) async -> WKNavigationResponsePolicy { - logger.info(navigationResponse.debugDescription) - return .allow - } -} - -struct WebView_Previews: PreviewProvider { - static var previews: some View { - WebView("https://m.baidu.com") - } -} -#endif diff --git a/Sources/old/Constant.swift b/Sources/old/Constant.swift deleted file mode 100644 index 1848e29..0000000 --- a/Sources/old/Constant.swift +++ /dev/null @@ -1,9 +0,0 @@ -import Foundation - -public struct Constant { - #if canImport(UIKit) - public static let isUIKit = true - #else - public static let isUIKit = false - #endif -} diff --git a/Sources/old/ServiceContainer.swift b/Sources/old/ServiceContainer.swift deleted file mode 100644 index ada45dc..0000000 --- a/Sources/old/ServiceContainer.swift +++ /dev/null @@ -1,9 +0,0 @@ -import Foundation -/** - * 服务容器 - */ -public final class ServiceContainer { - public static let shared = ServiceContainer() - let serviceManager = ServiceManger() - public init() {} -} diff --git a/Sources/old/ServiceError.swift b/Sources/old/ServiceError.swift deleted file mode 100644 index fe84311..0000000 --- a/Sources/old/ServiceError.swift +++ /dev/null @@ -1,15 +0,0 @@ -import Foundation - -/** - * 服务错误枚举 - */ -public enum ServiceError: Error { - /// 转换失败 - case castFailed(expectedType: Any.Type, actualValue: Any) - - /// 未实现的功能 - case notImplemented(method: String = #function) - - /// 业务逻辑错误 - case businessError(code: Int, message: String) -} diff --git a/Sources/old/ServiceHandler.swift b/Sources/old/ServiceHandler.swift deleted file mode 100644 index 17a3599..0000000 --- a/Sources/old/ServiceHandler.swift +++ /dev/null @@ -1,8 +0,0 @@ -import Foundation -import SwiftUI - -///// 定义服务实现 -public protocol ServiceHandler { - @discardableResult - func callAsFunction(method: String, args: Any...) -> ServiceResult -} diff --git a/Sources/old/ServiceKey.swift b/Sources/old/ServiceKey.swift deleted file mode 100644 index c2d5de6..0000000 --- a/Sources/old/ServiceKey.swift +++ /dev/null @@ -1,14 +0,0 @@ -import Foundation - -public protocol ServiceKey { - static var name: String { get } - static var shared: Self { get } - init() -} - -extension ServiceKey { - public static var service: Service { - let key = Self.shared - return ServiceContainer.shared.getOrMock(key) - } -} diff --git a/Sources/old/ServiceManager.swift b/Sources/old/ServiceManager.swift deleted file mode 100644 index f1c5b22..0000000 --- a/Sources/old/ServiceManager.swift +++ /dev/null @@ -1,35 +0,0 @@ -import Foundation - -class ServiceManger { - var storage: [String: ServiceHandler] = [:] -} - -extension ServiceContainer { - public subscript(name: String) -> ServiceHandler? { - get { - let key = name - return serviceManager.storage[key] - } - set { - let key = name - serviceManager.storage[key] = newValue - } - } - public func get(_ key: Key) -> Service? { - let name = Key.name - if let handler = self[name] { - return Service(key, handler: handler) - } else if let handler = key as? ServiceHandler { - return Service(key, handler: handler) - } - return nil - } - - public func getOrMock(_ key: Key) -> Service { - if let value = self.get(key) { - return value - } - let name = Key.name - return Service(Key.shared, handler: ServiceMockHandler(name: name)) - } -} diff --git a/Sources/old/framework/AnyCodable.swift b/Sources/old/framework/AnyCodable.swift deleted file mode 100644 index d2a8992..0000000 --- a/Sources/old/framework/AnyCodable.swift +++ /dev/null @@ -1,81 +0,0 @@ -import Foundation - - -public struct AnyCodable { - public let value: Any - public init(_ value: Any) { - self.value = value - } - - public func `as`() throws -> T { - if let value = value as? T { - return value - } - throw ServiceError.castFailed(expectedType: T.self, actualValue: value) - } -} - -extension AnyCodable: Decodable { - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - - if container.decodeNil() { - self.value = NSNull() - } else if let boolValue = try? container.decode(Bool.self) { - self.value = boolValue - } else if let intValue = try? container.decode(Int.self) { - self.value = intValue - } else if let doubleValue = try? container.decode(Double.self) { - self.value = doubleValue - } else if let stringValue = try? container.decode(String.self) { - self.value = stringValue - } else if let arrayValue = try? container.decode([AnyCodable].self) { - self.value = arrayValue.map { $0.value } - } else if let dictionaryValue = try? container.decode([String: AnyCodable].self) { - self.value = dictionaryValue.mapValues { $0.value } - } else { - throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unsupported type") - } - } -} - -extension AnyCodable: Encodable { - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - - switch self.value { - case is NSNull: - try container.encodeNil() - case let boolValue as Bool: - try container.encode(boolValue) - case let intValue as Int: - try container.encode(intValue) - case let doubleValue as Double: - try container.encode(doubleValue) - case let stringValue as String: - try container.encode(stringValue) - case let arrayValue as [Any]: - let encodableArray = arrayValue.map { AnyCodable($0) } - try container.encode(encodableArray) - case let dictionaryValue as [String: Any]: - let encodableDictionary = dictionaryValue.mapValues { AnyCodable($0) } - try container.encode(encodableDictionary) - case let custom as Encodable: - try container.encode(custom) - default: - throw EncodingError.invalidValue(self.value, EncodingError.Context(codingPath: container.codingPath, debugDescription: "Unsupported type")) - } - } -} - -extension AnyCodable: Equatable { - public static func == (lhs: AnyCodable, rhs: AnyCodable) -> Bool { - return lhs.value as AnyObject === rhs.value as AnyObject - } -} - -extension AnyCodable: Hashable { - public func hash(into hasher: inout Hasher) { - hasher.combine(ObjectIdentifier(value as AnyObject)) - } -} diff --git a/Sources/old/framework/provider/Service.swift b/Sources/old/framework/provider/Service.swift deleted file mode 100644 index 529fcec..0000000 --- a/Sources/old/framework/provider/Service.swift +++ /dev/null @@ -1,15 +0,0 @@ -public struct Service { - public let base: Base - private let handler: ServiceHandler - public init(_ base: Base, handler: ServiceHandler) { - self.base = base - self.handler = handler - } -} - -extension Service where Base: ServiceKey { - @discardableResult - public func callAsFunction(method: String, args: Any...) -> ServiceResult { - return handler(method: method, args: args) - } -} diff --git a/Sources/old/framework/provider/ServiceFactory.swift b/Sources/old/framework/provider/ServiceFactory.swift deleted file mode 100644 index 613b9db..0000000 --- a/Sources/old/framework/provider/ServiceFactory.swift +++ /dev/null @@ -1,40 +0,0 @@ -/// 服务提供者 -final class ServiceFactory { - public static var shared = ServiceFactory() - var storage: [String: ServiceHandler] = [:] - var interceptor: ServiceInterceptor - public init(_ interceptor: ServiceInterceptor = ServiceInterceptor()) { - self.interceptor = interceptor - } -} - - - -extension ServiceFactory { - public subscript(name: String) -> ServiceHandler { - get { - let key = name - if let value = storage[key] { - return value - } - return ServiceMockHandler(name: name) - } - set { - let key = name - storage[key] = newValue - } - } - func callAsFunction(name: String, method: String, args: Any...) -> ServiceResult { - let hander = self[name] - let arguments = Array(args) - let next = { - return hander.callAsFunction(method: method, args: args) - } - let context = ServiceInterceptor.Context(name: name, method: method, args: arguments) - guard interceptor.canHandle(context) else { - return next() - } - - return interceptor.intercept(context: context, next: next) - } -} diff --git a/Sources/old/framework/provider/ServiceInterceptor.swift b/Sources/old/framework/provider/ServiceInterceptor.swift deleted file mode 100644 index 5e38ad0..0000000 --- a/Sources/old/framework/provider/ServiceInterceptor.swift +++ /dev/null @@ -1,53 +0,0 @@ - -import Foundation - -/// 服务拦截器,暂不实现 -public struct ServiceInterceptor { - public class Context { - public let name: String - public let method: String - public let args: [Any] - public var options: [String: Any] - init(name: String, method: String, args: [Any], options: [String : Any] = [:]) { - self.name = name - self.method = method - self.args = args - self.options = options - } - } - - public init( - canHandle:((Context) -> Bool)? = nil, - before: ((Context) -> Void)? = nil, - after: ((Context, ServiceResult) -> Void)? = nil, - around: ((Context) -> ServiceResult)? = nil - ) { - self.canHandle = canHandle ?? { _ in return false } - self.beforeAdvice = before - self.afterAdvice = after - self.aroundAdvice = around - } - var canHandle: (Context) -> Bool - var beforeAdvice: ((Context) -> Void)? - var afterAdvice: ((Context, ServiceResult) -> Void)? - var aroundAdvice: ((Context) -> ServiceResult)? - public func intercept(context: Context, next: () -> ServiceResult) -> ServiceResult { - // Before advice - beforeAdvice?(context) - - // Around advice, if provided, bypasses the actual method - if let aroundAdvice = aroundAdvice { - let result = aroundAdvice(context) - afterAdvice?(context, result) - return result - } - - // Call the original method if there's no around advice - let result = next() - - // After advice - afterAdvice?(context, result) - - return result - } -} diff --git a/Sources/old/framework/provider/ServicePromise.swift b/Sources/old/framework/provider/ServicePromise.swift deleted file mode 100644 index f326700..0000000 --- a/Sources/old/framework/provider/ServicePromise.swift +++ /dev/null @@ -1,84 +0,0 @@ -import Foundation - - -public final class ServicePromise where Failure: Error { - // 存储操作结果 - private var result: Result? - // 存储回调(异步操作完成后触发) - private var callbacks: [(Result) -> Void] = [] - - // 初始化 - public init() {} - - // 完成 Promise(成功或失败) - public func fulfill(with result: Result) { - self.result = result - // 调用所有等待的回调 - callbacks.forEach { $0(result) } - callbacks.removeAll() // 清空回调 - } - - // 添加回调 - public func then(_ callback: @escaping (Result) -> Void) { - if let result = self.result { - // 如果已经完成,立即回调 - callback(result) - } else { - // 如果没有完成,保存回调 - callbacks.append(callback) - } - } - - // 异常处理 - public func `catch`(_ callback: @escaping (Failure) -> Void) { - then { result in - if case .failure(let error) = result { - callback(error) - } - } - } - - // 链式调用处理 - public func done(_ callback: @escaping (Success) -> Void) { - then { result in - if case .success(let value) = result { - callback(value) - } - } - } -} - -#if canImport(Combine) -import Combine -public extension ServicePromise { - @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - func asFuture() -> Future { - return Future { promise in - self.then { result in - switch result { - case .success(let value): - promise(.success(value)) - case .failure(let error): - promise(.failure(error)) - } - } - } - } - @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - static func from(_ future: Future) -> ServicePromise { - let promise = ServicePromise() - _ = future.sink(receiveCompletion: { completion in - switch completion { - case .finished: - break // 处理完成 - case .failure(let error): - promise.fulfill(with: .failure(error)) - } - }, receiveValue: { value in - promise.fulfill(with: .success(value)) - }) - return promise - } -} - -#endif diff --git a/Sources/old/framework/provider/ServiceResult.swift b/Sources/old/framework/provider/ServiceResult.swift deleted file mode 100644 index 6f375b4..0000000 --- a/Sources/old/framework/provider/ServiceResult.swift +++ /dev/null @@ -1,10 +0,0 @@ -import Foundation - -public enum ServiceResult where Failure : Error { - /// 同步结果 - case sync(Result) - /// 异步结果 - case promise(ServicePromise) - /// 无需返回结果 - case none -} diff --git a/Sources/old/framework/provider/service/impl/ServiceMock.swift b/Sources/old/framework/provider/service/impl/ServiceMock.swift deleted file mode 100644 index a9e75f6..0000000 --- a/Sources/old/framework/provider/service/impl/ServiceMock.swift +++ /dev/null @@ -1,15 +0,0 @@ -import Foundation - -struct ServiceMockHandler: ServiceHandler { - - func callAsFunction(method: String, args: Any...) -> ServiceResult { - print("mock: \(name) method: \(method), args:\(args)") - return .none - } - - let name: String - - init(name: String) { - self.name = name - } -} diff --git a/Sources/old/key/LogService.swift b/Sources/old/key/LogService.swift deleted file mode 100644 index 86c6d06..0000000 --- a/Sources/old/key/LogService.swift +++ /dev/null @@ -1,72 +0,0 @@ -import Foundation - -public protocol LoggerHandler { - func log( - level: LogService.Level, - message: String, - file: String, - function: String, - line: UInt - ) -} -public extension LoggerHandler { - func debug( - _ message: @autoclosure () -> String, - file: String = #fileID, - function: String = #function, - line: UInt = #line - ) { - self.log(level: .debug, message: message(), file: file, function: function, line: line) - } - func info( - _ message: @autoclosure () -> String, - file: String = #fileID, - function: String = #function, - line: UInt = #line - ) { - self.log(level: .info, message: message(), file: file, function: function, line: line) - } - - func error( - _ message: @autoclosure () -> String, - file: String = #fileID, - function: String = #function, - line: UInt = #line - ) { - self.log(level: .error, message: message(), file: file, function: function, line: line) - } -} - -public struct LogService: ServiceKey { - public static let shared = Self.init() - public static let name: String = "console.log" - var tag: String - public init() { - self.init("main") - } - public init(_ tag: String) { - self.tag = tag - } - - public enum Level: String, Codable, CaseIterable { - case trace - case debug - case info - case warn - case error - } -} - -extension Service: LoggerHandler where Base == LogService { - - - public func log( - level: LogService.Level, - message: String, - file: String = #fileID, - function: String = #function, - line: UInt = #line - ) { - self(method: "log", args: level, message, file, function, line) - } -} diff --git a/Sources/old/key/RouteService.swift b/Sources/old/key/RouteService.swift deleted file mode 100644 index 792e606..0000000 --- a/Sources/old/key/RouteService.swift +++ /dev/null @@ -1,111 +0,0 @@ -import SwiftUI - -@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) -public final class RouteService: ServiceKey, ServiceHandler, ObservableObject { - public static var name: String = "router" - - public static let shared: RouteService = RouteService() - public static var service: Service { - return Service(shared, handler: shared) - } - required public init() {} - public func callAsFunction(method: String, args: Any...) -> ServiceResult { - return .none - } - - @Published - public var initRoute = RouteSetting(name: "/", argument: ()) - - @Published - public var pages = [PageRoute]() - - internal var pageBuilderMap = [String: PageBuilder]() - public var onGenerateRoute: (RouteSetting) -> PageRoute = { setting in - return PageRoute( - builder: { - ScaffoldView { - Text("\(setting.name) 4o4") - } - }, - setting: setting) - } - - internal var navigation: iOSNavigationController = iOSNavigationController() -} - -@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) -extension RouteService { - public typealias PageBuilder = (RouteSetting) -> PageRoute - - public func contains(_ name: String) -> Bool { - return pageBuilderMap.keys.contains(name) - } - public func page(_ setting: RouteSetting) -> PageRoute { - guard let builder = pageBuilderMap[setting.name] else { - return onGenerateRoute(setting) - } - return builder(setting) - } - @discardableResult - public func addPage(_ name: String, - @ViewBuilder - builder: @escaping (RouteSetting) -> T) -> Self { - pageBuilderMap[name] = { arg in - return PageRoute(builder: { - builder(arg) - }, setting: arg) - } - return self - } - @discardableResult - @MainActor - public func push(_ setting: RouteSetting, animated: Bool = true) -> Self { - if navigation.push(setting, animated: animated) { - return self - } - let page = page(setting) - - self.pages.append(page) - return self - } - - @discardableResult - @MainActor - public func pop(_ setting: RouteSetting? = nil, animated: Bool = true) -> Self { - if navigation.pop(setting, animated: animated) { - return self - } - if let setting = setting, let idx = pages.firstIndex(where: { item in - return item.setting.name == setting.name - }) { - self.pages = Array(self.pages.prefix(idx + 1)) - } else { - _ = self.pages.popLast() - } - return self - } -} - -public struct RouteSetting { - let name: String - let argument: Any - - public init(name: String, argument: Any = ()) { - self.name = name - self.argument = argument - } -} -@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) -extension EnvironmentValues { - struct RouteKey: EnvironmentKey { - static var defaultValue = RouteService.shared - } - public var router: RouteService { - get { - return self[RouteKey.self] - } - set { - self[RouteKey.self] = newValue - } - } -} diff --git a/Sources/old/swiftui/PageRoute.swift b/Sources/old/swiftui/PageRoute.swift deleted file mode 100644 index fb2ea2f..0000000 --- a/Sources/old/swiftui/PageRoute.swift +++ /dev/null @@ -1,41 +0,0 @@ -// -// SwiftUIView.swift -// -// -// Created by yaochenfeng on 2024/11/15. -// - -import SwiftUI - -@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) -public struct PageRoute: View, Hashable { - let page: AnyView - let setting: RouteSetting - public init( - @ViewBuilder builder: () -> T, - setting: RouteSetting - ) { - self.page = AnyView(builder()) - self.setting = setting - } - public var body: some View { - GeometryReader { proxy in - page - } - } - - public static func == (lhs: PageRoute, rhs: PageRoute) -> Bool { - lhs.setting.name == rhs.setting.name - && String(describing: lhs.setting.argument) == String(describing: rhs.setting.argument) - } - public func hash(into hasher: inout Hasher) { - hasher.combine(setting.name) - } -} - -@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) -extension PageRoute: Identifiable { - public var id: String { - return setting.name - } -} diff --git a/Sources/old/swiftui/ScaffoldView.swift b/Sources/old/swiftui/ScaffoldView.swift deleted file mode 100644 index 7d23497..0000000 --- a/Sources/old/swiftui/ScaffoldView.swift +++ /dev/null @@ -1,56 +0,0 @@ -import SwiftUI -@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) -public struct ScaffoldView: View { - let content: Content - let topBar: AnyView - let bottomBar: AnyView - let backgroundColor: Color - - public init( - @ViewBuilder - content: () -> Content, - @ViewBuilder - topBar: () -> any View = { - EmptyView() - }, - @ViewBuilder - bottomBar: () -> any View = { - EmptyView() - }, - backgroundColor: Color = .white - ) { - self.content = content() - self.topBar = AnyView(topBar()) - self.bottomBar = AnyView(bottomBar()) - self.backgroundColor = backgroundColor - } - - public var body: some View { - VStack(spacing: 0) { - // Top bar - topBar - - // Main content - content - .frame(maxWidth: .infinity, maxHeight: .infinity) - .background(backgroundColor) - - // Bottom bar - bottomBar - } - .edgesIgnoringSafeArea(.all) // Ignore safe areas if necessary - } -} - -@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) -struct SwiftUIView_Previews: PreviewProvider { - static var previews: some View { - ScaffoldView(content: { - - }, topBar: { - - }, bottomBar: { - - }) - } -} diff --git a/Sources/old/swiftui/ServiceApp.swift b/Sources/old/swiftui/ServiceApp.swift deleted file mode 100644 index 4734a8f..0000000 --- a/Sources/old/swiftui/ServiceApp.swift +++ /dev/null @@ -1,14 +0,0 @@ -import SwiftUI - -@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) -public struct ServiceApp: App { - let container = ServiceContainer.shared - public init() { - LogService.service.info("应用启动") - } - public var body: some Scene { - WindowGroup { - WindowRouteContent() - } - } -} diff --git a/Sources/old/swiftui/WindowRouteContent.swift b/Sources/old/swiftui/WindowRouteContent.swift deleted file mode 100644 index 556b406..0000000 --- a/Sources/old/swiftui/WindowRouteContent.swift +++ /dev/null @@ -1,47 +0,0 @@ -// -// WindowRouteContent.swift -// -// -// Created by yaochenfeng on 2024/11/17. -// - -import SwiftUI - -@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) -public struct WindowRouteContent: View { - @StateObject - var router = RouteService.shared - public var body: some View { - if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) { - NavigationStack(path: $router.pages) { - router.page(router.initRoute) - .navigationDestination(for: PageRoute.self) { page in - page - } - } - .environment(\.router, router) - } else if Constant.isUIKit { - iOSNavigationView() - .ignoresSafeArea() - .environment(\.router, router) - } else { - NavigationView { - router.page(router.initRoute) - - ZStack { - ForEach(router.pages) { page in - page - } - } - - }.environment(\.router, router) - } - - } -} -@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) -struct WindowRouteContent_Previews: PreviewProvider { - static var previews: some View { - WindowRouteContent() - } -} diff --git a/Sources/old/swiftui/iOSNavigationView.swift b/Sources/old/swiftui/iOSNavigationView.swift deleted file mode 100644 index 13088ff..0000000 --- a/Sources/old/swiftui/iOSNavigationView.swift +++ /dev/null @@ -1,145 +0,0 @@ -// -// SwiftUIView.swift -// -// -// Created by yaochenfeng on 2024/11/17. -// - -import SwiftUI - -#if canImport(UIKit) -import UIKit -import Combine -@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) -struct iOSNavigationView: UIViewControllerRepresentable { - func makeCoordinator() -> Coordinator { - return Coordinator() - } - - func makeUIViewController(context: Context) -> iOSNavigationController { - context.coordinator.updateBinds(context: context) - return context.coordinator.router.navigation - } - - func updateUIViewController(_ uiViewController: iOSNavigationController, context: Context) { - updateViewControllers(uiViewController, context: context) - } - private func updateViewControllers(_ navigationController: UINavigationController, context: Context) { - context.coordinator.updateBinds(context: context) - } - - typealias UIViewControllerType = iOSNavigationController - - - class Coordinator: NSObject, UINavigationControllerDelegate { - var router = RouteService.shared - var cancellable: AnyCancellable? - - deinit { - cancellable?.cancel() - } - func updateBinds(context: Context) { - router = context.environment.router - let navigation = router.navigation - navigation.environment = context.environment - navigation.delegate = self - cancellable?.cancel() - cancellable = router.$initRoute - .receive(on: DispatchQueue.main) - .sink(receiveValue: { [weak self] arg in - self?.router.navigation.setRoot() - }) - } - - } - -} -@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) -struct iOSNavigationView_Previews: PreviewProvider { - static var previews: some View { - iOSNavigationView() - } -} - -#else -@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) -struct iOSNavigationView: View { - var body: some View { - EmptyView() - } -} - -#endif - -#if canImport(UIKit) - -@available(tvOS 14.0, *) -@available(macCatalyst 14.0, *) -@available(iOS 14.0, *) -class iOSNavigationController: UINavigationController { - @MainActor - public var environment = EnvironmentValues() - @MainActor - func setRoot() { - let router = environment.router - let page = router.page(router.initRoute) - let rootView = page - let controller = RouteController(setting: page.setting, rootView: rootView) - setViewControllers([controller], animated: false) - } - @MainActor - func push(_ setting: RouteSetting, animated: Bool) -> Bool { - if #available(iOS 16.0, *) { - return false - } - let router = environment.router - let page = router.page(setting) - let rootView = page.environment(\.self, environment) - let controller = RouteController(setting: setting, rootView: rootView) - self.pushViewController(controller, animated: animated) - return true - } - @MainActor - func pop(_ setting: RouteSetting? = nil, animated: Bool = true) -> Bool { - if #available(iOS 16.0, *) { - return false - } - if viewControllers.count <= 1 { - return true - } else { - for viewController in self.viewControllers { - if let routable = viewController as? RouteController, - routable.routeSetting.name == setting?.name { - self.popToViewController(viewController, animated: animated) - return true - } - } - self.popViewController(animated: animated) - } - return true - } - class RouteController: UIHostingController { - let routeSetting: RouteSetting - - init(setting: RouteSetting, rootView: Content) { - self.routeSetting = setting - super.init(rootView: AnyView(rootView)) - } - - @available(*, deprecated) - required dynamic init?(coder aDecoder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - } -} -#else -@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) -class iOSNavigationController { - func push(_ setting: RouteSetting, animated: Bool) -> Bool { - return false - } - func pop(_ setting: RouteSetting? = nil, animated: Bool = true) -> Bool { - return false - } -} -#endif