diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dd1b039..d71f577 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,56 +10,105 @@ concurrency: group: ci-${{ github.ref }} cancel-in-progress: true +env: + SWIFTLINT_VERSION: 0.65.1 + jobs: lint: name: SwiftLint - runs-on: macos-15 + runs-on: macos-26 steps: - name: Checkout Repository uses: actions/checkout@v4 - - name: Install SwiftLint + - name: Install SwiftLint ${{ env.SWIFTLINT_VERSION }} run: | - brew update - brew install swiftlint + curl -sSL -o swiftlint.zip "https://github.com/realm/SwiftLint/releases/download/${SWIFTLINT_VERSION}/portable_swiftlint.zip" + unzip -q swiftlint.zip -d "$RUNNER_TEMP/swiftlint" + echo "$RUNNER_TEMP/swiftlint" >> "$GITHUB_PATH" - name: Run SwiftLint run: swiftlint --strict --quiet test-macos: - name: macOS Tests (Swift ${{ matrix.swift }}) - runs-on: macos-15 - strategy: - fail-fast: false - matrix: - swift: ['6.0'] + name: macOS Tests + runs-on: macos-26 steps: - name: Checkout Repository uses: actions/checkout@v4 + - name: Select Xcode + uses: maxim-lobanov/setup-xcode@v1 + with: + xcode-version: latest-stable + - name: Run Tests - run: swift test --enable-code-coverage -v + run: swift test --enable-code-coverage test-ios: name: iOS Simulator Tests - runs-on: macos-15 + runs-on: macos-26 steps: - name: Checkout Repository uses: actions/checkout@v4 + - name: Select Xcode + uses: maxim-lobanov/setup-xcode@v1 + with: + xcode-version: latest-stable + - name: Run iOS Simulator Tests run: | SIM_ID=$(xcrun simctl list devices available | grep -E "iPhone" | head -1 | grep -o -E "[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}") - echo "Selected simulator ID: $SIM_ID" - if [ -n "$SIM_ID" ]; then - xcodebuild test \ - -scheme BaseNavigationStack \ - -destination "id=$SIM_ID" \ - CODE_SIGNING_ALLOWED=NO - else - echo "No iPhone simulator found, testing with generic platform" - xcodebuild build \ - -scheme BaseNavigationStack \ - -destination 'generic/platform=iOS' \ - CODE_SIGNING_ALLOWED=NO + if [ -z "$SIM_ID" ]; then + echo "::error::No iPhone simulator available" + exit 1 fi + echo "Selected simulator ID: $SIM_ID" + xcodebuild test \ + -scheme BaseNavigationStack \ + -destination "id=$SIM_ID" \ + CODE_SIGNING_ALLOWED=NO + + build-platforms: + name: Build (${{ matrix.platform }}) + runs-on: macos-26 + strategy: + fail-fast: false + matrix: + platform: [tvOS, watchOS, visionOS] + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + + - name: Select Xcode + uses: maxim-lobanov/setup-xcode@v1 + with: + xcode-version: latest-stable + + - name: Build Package + run: | + xcodebuild build \ + -scheme BaseNavigationStack \ + -destination "generic/platform=${{ matrix.platform }}" \ + CODE_SIGNING_ALLOWED=NO + + build-example: + name: Build Example App + runs-on: macos-26 + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + + - name: Select Xcode + uses: maxim-lobanov/setup-xcode@v1 + with: + xcode-version: latest-stable + + - name: Build Example + run: | + xcodebuild build \ + -project NavigationStackExample/NavigationStackExample.xcodeproj \ + -scheme NavigationStackExample \ + -destination 'generic/platform=iOS Simulator' \ + CODE_SIGNING_ALLOWED=NO diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a7d5c97..fa33469 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,7 +3,8 @@ name: Release on: push: tags: - - 'v*.*.*' + - 'v[0-9]+.[0-9]+.[0-9]+*' + - '[0-9]+.[0-9]+.[0-9]+*' permissions: contents: write @@ -11,11 +12,19 @@ permissions: jobs: release: name: GitHub Release - runs-on: macos-15 + runs-on: macos-26 steps: - name: Checkout Repository uses: actions/checkout@v4 + - name: Select Xcode + uses: maxim-lobanov/setup-xcode@v1 + with: + xcode-version: latest-stable + + - name: Run Tests + run: swift test + - name: Build Package for Release run: swift build -c release diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..254623d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,31 @@ +# Changelog + +All notable changes to this project are documented here. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow [SemVer](https://semver.org). + +## [2.0.0] - Unreleased + +### Added +- `NavigationRouter`: one `@MainActor @Observable` router for stack, sheet, and cover. +- `BaseNavigationContainer` and `View.navigationRouter(...)`. +- `maxDepth` stack cap (default 30) and duplicate-top push guard. +- `push`, `replacePath`, `present(sheet:)`, `present(cover:)` return `Bool` (`@discardableResult`) and log rejections via `os.Logger`. +- `send(_:)` returns its `Task` so callers can await the main-actor mutation. +- tvOS 17, watchOS 10, and visionOS 1 declared in `Package.swift`. + +### Changed +- **Breaking:** `swift-tools-version` 6.0 (Xcode 16+), Swift 6 language mode; minimums iOS 17 / macOS 14. +- Because `push`/`present`/`replacePath` now return `Bool`, generic single-expression closures such as `MainActor.run { router.push(x) }` infer `Bool` and warn about an unused result. Call `await router.push(x)` directly, or write `_ = router.push(x)`. +- macOS presents covers as sheets instead of ignoring them. +- A sheet and a cover can no longer be presented at the same time through the router API. +- `maxDepth` is clamped to `>= 1` on every assignment (assigning a negative value previously crashed `replacePath`); `initialPath` is truncated to `maxDepth`. + +### Removed +- **Breaking:** public `Collection.subscript(safe:)` and `Array.removeLastSafe()`. +- Redundant `@unchecked Sendable` on `@MainActor` classes. + +### Fixed +- v1 `BaseNavigationStack.dismiss()` pops a single-screen stack; `replaceNavigationStack(path:)` clears active modals. + +## [1.0.3] - 2023-12-24 + +Last 1.x release (`BaseNavigationStack` + `BaseViewProtocol`). diff --git a/NavigationStackExample/NavigationStackExample.xcodeproj/project.pbxproj b/NavigationStackExample/NavigationStackExample.xcodeproj/project.pbxproj index b8ee5c7..a528775 100644 --- a/NavigationStackExample/NavigationStackExample.xcodeproj/project.pbxproj +++ b/NavigationStackExample/NavigationStackExample.xcodeproj/project.pbxproj @@ -12,11 +12,6 @@ 3E7A81C72B2B06C70003D5A3 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 3E7A81C62B2B06C70003D5A3 /* Assets.xcassets */; }; 3E7A81CA2B2B06C70003D5A3 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 3E7A81C92B2B06C70003D5A3 /* Preview Assets.xcassets */; }; 3E7A81D52B2B07C50003D5A3 /* BaseNavigationStack in Frameworks */ = {isa = PBXBuildFile; productRef = 3E7A81D42B2B07C50003D5A3 /* BaseNavigationStack */; }; - 3E7A81D72B2B0F1A0003D5A3 /* ViewNavigationTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E7A81D62B2B0F1A0003D5A3 /* ViewNavigationTarget.swift */; }; - 3E7A81DC2B2B0FA90003D5A3 /* View+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E7A81DB2B2B0FA90003D5A3 /* View+Extension.swift */; }; - 3E7A81E02B2B0FE50003D5A3 /* ListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E7A81DF2B2B0FE50003D5A3 /* ListView.swift */; }; - 3E7A81E22B2B10040003D5A3 /* BaseView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E7A81E12B2B10040003D5A3 /* BaseView.swift */; }; - 3E7A81E42B2C50A80003D5A3 /* PolicyView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E7A81E32B2C50A80003D5A3 /* PolicyView.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -25,11 +20,6 @@ 3E7A81C42B2B06C60003D5A3 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; 3E7A81C62B2B06C70003D5A3 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 3E7A81C92B2B06C70003D5A3 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; }; - 3E7A81D62B2B0F1A0003D5A3 /* ViewNavigationTarget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewNavigationTarget.swift; sourceTree = ""; }; - 3E7A81DB2B2B0FA90003D5A3 /* View+Extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "View+Extension.swift"; sourceTree = ""; }; - 3E7A81DF2B2B0FE50003D5A3 /* ListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ListView.swift; sourceTree = ""; }; - 3E7A81E12B2B10040003D5A3 /* BaseView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BaseView.swift; sourceTree = ""; }; - 3E7A81E32B2C50A80003D5A3 /* PolicyView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PolicyView.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -63,9 +53,6 @@ 3E7A81C12B2B06C60003D5A3 /* NavigationStackExample */ = { isa = PBXGroup; children = ( - 3E7A81DE2B2B0FD90003D5A3 /* View */, - 3E7A81DD2B2B0FBE0003D5A3 /* BaseDefineTarget */, - 3E7A81DA2B2B0F4D0003D5A3 /* Utils */, 3E7A81C22B2B06C60003D5A3 /* NavigationStackExampleApp.swift */, 3E7A81C42B2B06C60003D5A3 /* ContentView.swift */, 3E7A81C62B2B06C70003D5A3 /* Assets.xcassets */, @@ -82,32 +69,6 @@ path = "Preview Content"; sourceTree = ""; }; - 3E7A81DA2B2B0F4D0003D5A3 /* Utils */ = { - isa = PBXGroup; - children = ( - 3E7A81DB2B2B0FA90003D5A3 /* View+Extension.swift */, - ); - path = Utils; - sourceTree = ""; - }; - 3E7A81DD2B2B0FBE0003D5A3 /* BaseDefineTarget */ = { - isa = PBXGroup; - children = ( - 3E7A81D62B2B0F1A0003D5A3 /* ViewNavigationTarget.swift */, - ); - path = BaseDefineTarget; - sourceTree = ""; - }; - 3E7A81DE2B2B0FD90003D5A3 /* View */ = { - isa = PBXGroup; - children = ( - 3E7A81DF2B2B0FE50003D5A3 /* ListView.swift */, - 3E7A81E12B2B10040003D5A3 /* BaseView.swift */, - 3E7A81E32B2C50A80003D5A3 /* PolicyView.swift */, - ); - path = View; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -185,12 +146,7 @@ buildActionMask = 2147483647; files = ( 3E7A81C52B2B06C60003D5A3 /* ContentView.swift in Sources */, - 3E7A81D72B2B0F1A0003D5A3 /* ViewNavigationTarget.swift in Sources */, - 3E7A81E02B2B0FE50003D5A3 /* ListView.swift in Sources */, - 3E7A81DC2B2B0FA90003D5A3 /* View+Extension.swift in Sources */, - 3E7A81E22B2B10040003D5A3 /* BaseView.swift in Sources */, 3E7A81C32B2B06C60003D5A3 /* NavigationStackExampleApp.swift in Sources */, - 3E7A81E42B2C50A80003D5A3 /* PolicyView.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -340,7 +296,7 @@ PRODUCT_BUNDLE_IDENTIFIER = com.baseNavigationStack.NavigationStackExample; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = YES; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; @@ -369,7 +325,7 @@ PRODUCT_BUNDLE_IDENTIFIER = com.baseNavigationStack.NavigationStackExample; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = YES; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Release; diff --git a/NavigationStackExample/NavigationStackExample/BaseDefineTarget/ViewNavigationTarget.swift b/NavigationStackExample/NavigationStackExample/BaseDefineTarget/ViewNavigationTarget.swift deleted file mode 100644 index a846958..0000000 --- a/NavigationStackExample/NavigationStackExample/BaseDefineTarget/ViewNavigationTarget.swift +++ /dev/null @@ -1,96 +0,0 @@ -// -// ViewNavigationTarget.swift -// NavigationStackExample -// -// Created by iletai on 14/12/2023. -// - -import Foundation -import BaseNavigationStack -import SwiftUI - -/// Legacy v1 router alias used by the original demo views (ListView, PolicyView, BaseView). -public typealias BaseNavigation = BaseNavigationStack - -public enum ViewNavigationTarget: BaseViewProtocol { - case splash - case main - case list - case policy(URL) - case updateProfile(userID: String) - - public var id: String { - switch self { - case .policy(let url): - return "policy-\(url.absoluteString)" - case .updateProfile(let id): - return "updateProfile-\(id)" - case .splash: - return "splash" - case .main: - return "main" - case .list: - return "list" - } - } - - public static func == (lhs: ViewNavigationTarget, rhs: ViewNavigationTarget) -> Bool { - lhs.id == rhs.id - } - - public func hash(into hasher: inout Hasher) { - hasher.combine(id) - } - - @MainActor - public func withNavigationDestination() -> some View { - switch self { - case .policy(_): - PolicyView() - case .list: - ListView() - case .splash: - SplashView() - default: - EmptyView() - } - } - - @MainActor - public func withSheetDestination() -> some View { - switch self { - case .policy(_): - PolicyView() - .presentationDetents(self.detent) - case .list: - ListView() - .presentationDetents(self.detent) - case .splash: - SplashView() - .presentationDetents(self.detent) - default: - EmptyView() - } - } - - @MainActor - public func withFullScreenDestination() -> some View { - switch self { - case .policy(_): - PolicyView() - case .list: - ListView() - case .splash: - SplashView() - default: - EmptyView() - } - } - - public var detent: Set { - switch self { - case .splash, .main, .list, .policy, .updateProfile: - return [.large] - } - } -} diff --git a/NavigationStackExample/NavigationStackExample/ContentView.swift b/NavigationStackExample/NavigationStackExample/ContentView.swift index 80a2ba4..6285d2b 100644 --- a/NavigationStackExample/NavigationStackExample/ContentView.swift +++ b/NavigationStackExample/NavigationStackExample/ContentView.swift @@ -258,9 +258,10 @@ struct AsyncLabView: View { Button("Simulate Background Async Push") { isLoading = true + let router = labRouter Task.detached { try? await Task.sleep(nanoseconds: 1_000_000_000) - labRouter.send { r in + router.send { r in isLoading = false r.push(.detail(title: "Loaded from Network Actor")) } diff --git a/NavigationStackExample/NavigationStackExample/Utils/View+Extension.swift b/NavigationStackExample/NavigationStackExample/Utils/View+Extension.swift deleted file mode 100644 index b93fe2b..0000000 --- a/NavigationStackExample/NavigationStackExample/Utils/View+Extension.swift +++ /dev/null @@ -1,55 +0,0 @@ -// -// View+Extension.swift -// NavigationStackExample -// -// Created by iletai on 14/12/2023. -// - -import Foundation -import SwiftUI - -@MainActor -extension View { - func withNavigationRouter() -> some View { - navigationDestination(for: ViewNavigationTarget.self) { pushTo in - switch pushTo { - case .list: - ListView() - case .splash: - SplashView() - default: - EmptyView() - } - - } - } - - func withSheetRouter(sheetDestination: Binding) -> some View { - sheet(item: sheetDestination) { toSheet in - switch toSheet { - case .policy(_): - PolicyView() - case .list: - ListView() - case .splash: - SplashView() - default: - EmptyView() - } - } - } - - @MainActor - func withFullScreenRouter(_ presentFullView: Binding) -> some View { - fullScreenCover(item: presentFullView) { fullView in - switch fullView { - case .list: - ListView() - case .splash: - SplashView() - default: - EmptyView() - } - } - } -} diff --git a/NavigationStackExample/NavigationStackExample/View/BaseView.swift b/NavigationStackExample/NavigationStackExample/View/BaseView.swift deleted file mode 100644 index 2a11391..0000000 --- a/NavigationStackExample/NavigationStackExample/View/BaseView.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// BaseView.swift -// NavigationStackExample -// -// Created by iletai on 14/12/2023. -// - -import Foundation -import SwiftUI -import BaseNavigationStack - -struct BaseView: View { - @Environment(BaseNavigation.self) - var navigationRouter - - var body: some View { - VStack { - Text("Base View") - .font(.title) - .fontWeight(.bold) - HStack { - Button { - navigationRouter.pushToView(.list) - } label: { - Text("Push View") - } - Button { - navigationRouter.presentSheet(.policy(URL(string: "https://google.com")!)) - } label: { - Text("Present View") - } - Button { - navigationRouter.presentFullScreen(.list) - } label: { - Text("Present Full View") - } - } - .buttonStyle(.bordered) - Spacer() - } - .navigationTitle("BaseView") - .navigationBarTitleDisplayMode(.inline) - } -} - diff --git a/NavigationStackExample/NavigationStackExample/View/ListView.swift b/NavigationStackExample/NavigationStackExample/View/ListView.swift deleted file mode 100644 index 9f3481d..0000000 --- a/NavigationStackExample/NavigationStackExample/View/ListView.swift +++ /dev/null @@ -1,114 +0,0 @@ -// -// ListView.swift -// NavigationStackExample -// -// Created by iletai on 14/12/2023. -// - -import Foundation -import SwiftUI -import BaseNavigationStack - -struct ListView: View { - @Environment(BaseNavigation.self) var navigationRouter - @Environment(\.dismiss) var dimiss - var body: some View { - VStack { - Text("List View") - .font(.title) - .fontWeight(.bold) - HStack { - Button { - dimiss() - navigationRouter.dismiss() - } label: { - Text("Dis") - } - } - HStack { - Button { - navigationRouter.presentSheet(.policy(URL(string: "https://google.com")!)) - } label: { - Text("Present View") - } - Button { - navigationRouter.pushToView(.splash) - } label: { - Text("Splash") - } - Button { - navigationRouter.popBack() - } label: { - Text("PopBack") - } - Button { - navigationRouter.navigateToRoot() - } label: { - Text("PopRoot") - } - Button { - navigationRouter.presentFullScreen(.list) - } label: { - Text("FullView") - } - Button { - navigationRouter.presentFullScreen(.splash) - } label: { - Text("SplashView") - } - } - .buttonStyle(.bordered) - Spacer() - } - .navigationTitle("ListView") - .navigationBarTitleDisplayMode(.inline) - } -} - -struct SplashView: View { - @Environment(BaseNavigation.self) - var navigationRouter - - @Environment(\.dismiss) var dimiss - - var body: some View { - VStack { - Text("SplashView") - .font(.title) - .fontWeight(.bold) - HStack { - Button { - dimiss() - navigationRouter.dismiss() - } label: { - Text("Dis") - } - Button { - navigationRouter.pushToView(.list) - } label: { - Text("List") - } - Button { - navigationRouter.popBack() - } label: { - Text("PopBack") - } - Button { - navigationRouter.navigateToRoot() - } label: { - Text("PopRoot") - } - Button { - navigationRouter.presentFullScreen(.list) - } label: { - Text("FullView") - } - } - .buttonStyle(.bordered) - Spacer() - } - .navigationTitle("Splash") - .navigationBarTitleDisplayMode(.inline) - } -} - diff --git a/NavigationStackExample/NavigationStackExample/View/PolicyView.swift b/NavigationStackExample/NavigationStackExample/View/PolicyView.swift deleted file mode 100644 index 8c84198..0000000 --- a/NavigationStackExample/NavigationStackExample/View/PolicyView.swift +++ /dev/null @@ -1,65 +0,0 @@ -// -// PolicyView.swift -// NavigationStackExample -// -// Created by iletai on 15/12/2023. -// - -import Foundation -import SwiftUI -import BaseNavigationStack - -struct PolicyView: View { - @Environment(BaseNavigation.self) var navigationRouter - @Environment(\.dismiss) var dimiss - var body: some View { - VStack { - Text("Policy") - .font(.title) - .fontWeight(.bold) - HStack { - Button { - dimiss() - navigationRouter.dismiss() - } label: { - Text("Dis") - } - Button { - navigationRouter.presentSheet(.splash) - } label: { - Text("PresentSplas") - } - } - HStack { - Button { - navigationRouter.pushToView(.list) - } label: { - Text("List") - } - Button { - navigationRouter.presentSheet(.list) - } label: { - Text("Present List") - } - Button { - navigationRouter.popBack() - } label: { - Text("Pop Back") - } - Button { - navigationRouter.navigateToRoot() - } label: { - Text("Pop To Root") - } - Button { - navigationRouter.presentFullScreen(.list) - } label: { - Text("Present Full View") - } - } - .buttonStyle(.bordered) - Spacer() - } - .navigationTitle("Policy") - } -} diff --git a/Package.swift b/Package.swift index 25f7a6b..c295287 100644 --- a/Package.swift +++ b/Package.swift @@ -6,7 +6,7 @@ import PackageDescription let package = Package( name: "BaseNavigationStack", platforms: [ - .macOS(.v14), .iOS(.v17) + .macOS(.v14), .iOS(.v17), .tvOS(.v17), .watchOS(.v10), .visionOS(.v1) ], products: [ .library( @@ -16,10 +16,7 @@ let package = Package( ], targets: [ .target( - name: "BaseNavigationStack", - swiftSettings: [ - .enableUpcomingFeature("StrictConcurrency") - ] + name: "BaseNavigationStack" ), .testTarget( name: "BaseNavigationStackTests", diff --git a/README.md b/README.md index 860cea9..2db3d43 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ [Features](#features) • [Quickstart](#quickstart) • [Architecture](#architecture) • [API Cheat Sheet](#api-cheat-sheet) • [Advanced Recipes](#advanced-recipes) • [Example App](#example-app) • [Docs & Wiki](#docs--wiki) • [Contributing](#contributing) • [License](#license) -Minimums declared in `Package.swift`: iOS 17+, macOS 14+. tvOS / watchOS / visionOS compile via conditional code paths (full screen cover applied only where supported). +Minimums declared in `Package.swift`: iOS 17+, macOS 14+, tvOS 17+, watchOS 10+, visionOS 1+. macOS has no full screen cover, so covers are presented as sheets there. @@ -64,12 +64,12 @@ SwiftUI's built-in navigation is powerful, but state tends to sprawl across view - **Swift 6 Strict Concurrency** — Fully `@MainActor`, `Sendable`-compliant, ready for complete concurrency checking. - **Zero External Dependencies** — Built on native SwiftUI, `Observation`, and Foundation only. - **Unified Multi-Modal Routing** — Manage stack, sheet, and full screen cover from one `@Observable` router. -- **Auto-Debounce Rapid Taps** — Prevents duplicate pushes when the same route hits back-to-back. -- **Stack Depth Protection** — `maxDepth` guard (default `30`) helps avoid layout recursion/memory pressure. +- **Duplicate-Top Guard** — Ignores a push equal to the current top route (double taps). `push` returns `false` when it rejects. +- **Stack Depth Protection** — `maxDepth` guard (default `30`, always `>= 1`) helps avoid layout recursion/memory pressure. Rejections are reported via return value and `os.Logger`. - **Actor-Safe Navigation** — `send(_:)` lets you dispatch navigation safely from `Task.detached`, background actors, or async callbacks. - **Nested & Tabbed Navigation** — Spin up isolated routers per tab or inside sheets for independent flows. - **Headless Unit-Testable** — Mutate router state directly in tests; assert on `[Route]`, modals, and transitions. -- **Cross-Platform Aware** — Works across iOS 17+, macOS 14+, tvOS 17+, watchOS 10+, visionOS 1+. Full-screen covers are applied on platforms that support them. +- **Cross-Platform Aware** — Works across iOS 17+, macOS 14+, tvOS 17+, watchOS 10+, visionOS 1+. On macOS, covers fall back to sheets. - **Backward Compatible (v1.x)** — `BaseNavigationStack` remains supported with fixes for `dismiss()`, `replaceNavigationStack(path:)`, and `@Bindable` compatibility. ## Quickstart @@ -146,6 +146,8 @@ struct RootView: View { } ``` +> Own the router with `@State` (or a long-lived model). Creating `NavigationRouter()` inline in `body` recreates it on every render and loses the stack. + > **Already have a `NavigationStack`?** Use the modifier instead: `.navigationRouter(router, destination:sheet:cover:)` to attach routing to your existing hierarchy. See [Advanced Recipes](#advanced-recipes). ### 4) Navigate from anywhere @@ -210,7 +212,15 @@ struct FlowSheetView: View { var body: some View { BaseNavigationContainer( router: subRouter, - content: { SheetStartView() }, + content: { + // Toolbar must live inside the stack's content to show up + SheetStartView() + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Done") { parentRouter.dismiss() } + } + } + }, destination: { route in switch route { case .detail(let id): SheetDetailView(id: id) @@ -218,34 +228,31 @@ struct FlowSheetView: View { } } ) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button("Done") { parentRouter.dismiss() } - } - } } } ``` +> `parentRouter` is read *outside* the container on purpose: inside it, `@Environment(AppRouter.self)` resolves to `subRouter` because both share the same type. + ### Deep Linking / Async Navigation Use `send(_:)` to navigate safely from async work or background actors. ```swift -func handleDeepLink(_ url: URL) async { +func handleDeepLink(_ url: URL, router: AppRouter) async { // Parse route from URL... let route = AppRoute.detail(id: 123) - await MainActor.run { - router.push(route) - } + // Router is @MainActor: awaiting the call hops to the main actor + await router.push(route) // Or from a detached task/actor: Task.detached { - router.send { r in + // `send` is asynchronous; await the returned task when ordering matters + await router.send { r in r.popToRoot() r.push(.profile(userID: "u_123")) - } + }.value } } ``` @@ -266,6 +273,8 @@ struct CustomRootView: View { cover: { cover in CoverView(cover: cover) } ) } + // Also inject on the stack so pushed destinations can read the router + .environment(router) } } ``` @@ -280,17 +289,17 @@ struct CustomRootView: View { | `path` | `[Route]` | Active navigation stack. Bind to `NavigationStack(path:)`. | O(1) access | | `sheet` | `Sheet?` | Currently presented sheet. | O(1) | | `cover` | `Cover?` | Currently presented full screen cover. | O(1) | -| `maxDepth` | `Int` | Maximum allowed stack depth. `push` is a no-op if `path.count >= maxDepth`. | O(1) | -| `push(_:)` | `func(Route)` | Push route if different from last and under `maxDepth` (auto-debounce). | O(1) | +| `maxDepth` | `Int` | Maximum allowed stack depth, clamped to `>= 1` on every assignment. `push` is rejected if `path.count >= maxDepth`. | O(1) | +| `push(_:)` | `func(Route) -> Bool` | Push route if different from last and under `maxDepth`. Returns `false` (and logs) when rejected. | O(1) | | `pop()` | `func()` | Pop top route if exists. | O(1) | | `pop(count:)` | `func(Int)` | Safely pop up to `count` routes. | O(k), k = removed | | `popToRoot()` | `func()` | Clear path and dismiss all modals. | O(n) path clear | -| `replacePath(_:)` | `func([Route])` | Replace stack with new path (truncated to `maxDepth`), clears modals. | O(n) | -| `present(sheet:)` | `func(Sheet)` | Present a sheet. | O(1) | -| `present(cover:)` | `func(Cover)` | Present a full screen cover. | O(1) | +| `replacePath(_:)` | `func([Route]) -> Bool` | Replace stack with new path, clears modals. Returns `false` if truncated to `maxDepth`. | O(n) | +| `present(sheet:)` | `func(Sheet) -> Bool` | Present a sheet. Rejected (`false`) while a cover is presented. | O(1) | +| `present(cover:)` | `func(Cover) -> Bool` | Present a full screen cover (sheet on macOS). Rejected (`false`) while a sheet is presented. | O(1) | | `dismiss()` | `func()` | Dismiss ladder: sheet → cover → pop top route. No-op on empty stack. | O(1) | | `dismissModals()` | `func()` | Clear sheet/cover without touching stack. | O(1) | -| `send(_:)` | `nonisolated func(@MainActor (NavigationRouter) -> Void)` | Dispatch navigation from any actor/context via `Task { @MainActor in ... }`. | O(1) dispatch | +| `send(_:)` | `nonisolated func(@MainActor (NavigationRouter) -> Void) -> Task` | Dispatch navigation from any actor/context. Runs asynchronously; await the returned task for ordering. | O(1) dispatch | ### `BaseNavigationContainer` @@ -311,7 +320,7 @@ struct CustomRootView: View { | Method | Notes | | --- | --- | | `pushToView(_:)` | Debounced push with duplicate prevention. | -| `popBack()` | Safe pop via `removeLastSafe()`. | +| `popBack()` | Safe pop; no-op on empty stack. | | `navigateToRoot()` | Clears modals and stack. | | `replaceNavigationStack(path:)` | Replaces path and clears modals. | | `presentSheet(_:)` / `presentFullScreen(_:)` | Modal presentation. | diff --git a/Sources/BaseNavigationStack/BaseNavigationStack.swift b/Sources/BaseNavigationStack/BaseNavigationStack.swift index 77c4590..f31d9f5 100644 --- a/Sources/BaseNavigationStack/BaseNavigationStack.swift +++ b/Sources/BaseNavigationStack/BaseNavigationStack.swift @@ -1,6 +1,3 @@ -// The Swift Programming Language -// https://docs.swift.org/swift-book - import SwiftUI import Foundation import Observation @@ -8,8 +5,10 @@ import Observation @MainActor @Observable /// Base Navigation Stack With Generic Type. -public final class BaseNavigationStack: @unchecked Sendable where ScreenView: BaseViewProtocol { +public final class BaseNavigationStack where ScreenView: BaseViewProtocol { private(set) var state: RootingState + /// Stored strongly; capture owners with `[weak self]` to avoid a retain cycle. + @ObservationIgnored public var urlHandler: (@MainActor (URL) -> OpenURLAction.Result)? public init(isPresented: Binding = .constant(nil)) { @@ -35,7 +34,7 @@ public extension BaseNavigationStack { /// Pop To Back Previous View In Navigation Stack @MainActor func popBack() { - state.navigationPath.removeLastSafe() + _ = state.navigationPath.popLast() } /// Pop To Root View Init In Navigation Stack diff --git a/Sources/BaseNavigationStack/Interface/BaseViewProtocol.swift b/Sources/BaseNavigationStack/Interface/BaseViewProtocol.swift index 514a088..96d4427 100644 --- a/Sources/BaseNavigationStack/Interface/BaseViewProtocol.swift +++ b/Sources/BaseNavigationStack/Interface/BaseViewProtocol.swift @@ -1,5 +1,5 @@ // -// PresentViewProtocol.swift +// BaseViewProtocol.swift // // // Created by iletai on 18/12/2023. diff --git a/Sources/BaseNavigationStack/Modifiers/NavigationRouterModifier.swift b/Sources/BaseNavigationStack/Modifiers/NavigationRouterModifier.swift index 9e7c2c8..2409994 100644 --- a/Sources/BaseNavigationStack/Modifiers/NavigationRouterModifier.swift +++ b/Sources/BaseNavigationStack/Modifiers/NavigationRouterModifier.swift @@ -8,9 +8,12 @@ import SwiftUI public extension View { - /// Binds a `NavigationRouter` to the current view hierarchy for Stack, Sheet, and Cover handling. + /// Attaches a `NavigationRouter`'s destinations, sheet, and cover to this view, and injects the router + /// into the environment. + /// + /// Apply it to the root content *inside* a `NavigationStack(path: $router.path)`; this modifier does not + /// bind `path` itself. Use `BaseNavigationContainer` to get the stack and binding for free. @MainActor - @ViewBuilder func navigationRouter< Route: Hashable & Sendable, Sheet: Identifiable & Hashable & Sendable, @@ -25,28 +28,17 @@ public extension View { @ViewBuilder cover: @escaping (Cover) -> CoverContent ) -> some View { @Bindable var bindableRouter = router - #if os(iOS) || os(tvOS) || os(watchOS) || os(visionOS) - self + return self .navigationDestination(for: Route.self) { route in destination(route) } .sheet(item: $bindableRouter.sheet) { sheetTarget in sheet(sheetTarget) } - .fullScreenCover(item: $bindableRouter.cover) { coverTarget in + .coverPresentation(item: $bindableRouter.cover) { coverTarget in cover(coverTarget) } .environment(router) - #else - self - .navigationDestination(for: Route.self) { route in - destination(route) - } - .sheet(item: $bindableRouter.sheet) { sheetTarget in - sheet(sheetTarget) - } - .environment(router) - #endif } /// Convenience modifier for Stack-only routing. @@ -68,3 +60,18 @@ public extension View { ) } } + +extension View { + /// `fullScreenCover` where available; macOS has no full screen cover, so it falls back to a sheet. + @ViewBuilder + func coverPresentation( + item: Binding, + @ViewBuilder content: @escaping (Item) -> Content + ) -> some View { + #if os(macOS) + sheet(item: item, content: content) + #else + fullScreenCover(item: item, content: content) + #endif + } +} diff --git a/Sources/BaseNavigationStack/NavigationRouter.swift b/Sources/BaseNavigationStack/NavigationRouter.swift index 2333d26..e2159d3 100644 --- a/Sources/BaseNavigationStack/NavigationRouter.swift +++ b/Sources/BaseNavigationStack/NavigationRouter.swift @@ -7,19 +7,29 @@ import SwiftUI import Observation +import os /// Modern 2.0 Router for SwiftUI Data-Driven Navigation. /// Unifies Stack navigation, Sheet presentation, and FullScreenCover in a single point of truth. +/// +/// Own the router with `@State` (or a long-lived model). Creating it inline inside `body` +/// recreates it on every render and loses the stack. @MainActor @Observable -public final class NavigationRouter: @unchecked Sendable { +public final class NavigationRouter { + /// Current stack. Bound to `NavigationStack(path:)`. Writing it directly bypasses + /// the `push` duplicate and `maxDepth` guards. public var path: [Route] = [] + /// Active sheet. Only one of `sheet` / `cover` is presented at a time. public var sheet: Sheet? + /// Active full screen cover. Presented as a sheet on macOS. public var cover: Cover? /// Maximum stack depth allowed to prevent memory bloating and SwiftUI layout warnings. - /// Default is 30. - public var maxDepth: Int + /// Default is 30. Always clamped to `>= 1`. + public var maxDepth: Int { + didSet { if maxDepth < 1 { maxDepth = 1 } } + } public init( initialPath: [Route] = [], @@ -27,20 +37,28 @@ public final class NavigationRouter Bool { + guard path.count < maxDepth else { + Self.logger.warning("push rejected: stack reached maxDepth (\(self.maxDepth))") + return false } + guard path.last != route else { + Self.logger.debug("push ignored: route equals current top") + return false + } + path.append(route) + return true } /// Pops the topmost screen from the navigation stack. @@ -63,20 +81,42 @@ public final class NavigationRouter Bool { sheet = nil cover = nil path = Array(newPath.prefix(maxDepth)) + guard newPath.count <= maxDepth else { + Self.logger.warning("replacePath truncated \(newPath.count) routes to maxDepth (\(self.maxDepth))") + return false + } + return true } - /// Presents a modal sheet. - public func present(sheet: Sheet) { + /// Presents a modal sheet. Rejected while a cover is presented, because SwiftUI cannot + /// present both from the same view. Present from the cover's own router instead. + /// - Returns: `false` if the presentation was rejected. + @discardableResult + public func present(sheet: Sheet) -> Bool { + guard cover == nil else { + Self.logger.warning("present(sheet:) rejected: a cover is already presented") + return false + } self.sheet = sheet + return true } - /// Presents a full screen cover. - public func present(cover: Cover) { + /// Presents a full screen cover. Rejected while a sheet is presented. + /// - Returns: `false` if the presentation was rejected. + @discardableResult + public func present(cover: Cover) -> Bool { + guard sheet == nil else { + Self.logger.warning("present(cover:) rejected: a sheet is already presented") + return false + } self.cover = cover + return true } /// Dismisses active sheet/cover if any, otherwise pops top screen from navigation stack. @@ -96,10 +136,16 @@ public final class NavigationRouter Void) { + /// Dispatches a navigation mutation onto the main actor from any background Task or actor. + /// The mutation runs asynchronously; `await` the returned task if ordering matters. + @discardableResult + nonisolated public func send(_ action: @escaping @MainActor (NavigationRouter) -> Void) -> Task { Task { @MainActor in action(self) } } + + private static var logger: Logger { + Logger(subsystem: "BaseNavigationStack", category: "NavigationRouter") + } } diff --git a/Sources/BaseNavigationStack/StackObject/BaseNavigationStack+ViewObject.swift b/Sources/BaseNavigationStack/StackObject/BaseNavigationStack+ViewObject.swift index 384b6fa..68b78d2 100644 --- a/Sources/BaseNavigationStack/StackObject/BaseNavigationStack+ViewObject.swift +++ b/Sources/BaseNavigationStack/StackObject/BaseNavigationStack+ViewObject.swift @@ -23,10 +23,6 @@ extension BaseNavigationStack { /// Status Is Presenting A View var isPresented: Binding - var isPresenting: Bool { - return presentingSheet != nil || presentingFullScreen != nil - } - /// Initial /// - Parameter isPresented: With Router Stack Init View. init(isPresented: Binding) { diff --git a/Sources/BaseNavigationStack/Utils/Collection+Extension.swift b/Sources/BaseNavigationStack/Utils/Collection+Extension.swift deleted file mode 100644 index 858df56..0000000 --- a/Sources/BaseNavigationStack/Utils/Collection+Extension.swift +++ /dev/null @@ -1,21 +0,0 @@ -// -// Collection+Extension.swift -// -// -// Created by Lê Quang Trọng Tài on 12/17/23. -// - -import Foundation - -extension Collection { - public subscript (safe index: Index) -> Element? { - indices.contains(index) ? self[index] : nil - } -} - -extension Array { - public mutating func removeLastSafe() { - guard !isEmpty else { return } - removeLast() - } -} diff --git a/Sources/BaseNavigationStack/Views/BaseNavigationContainer.swift b/Sources/BaseNavigationStack/Views/BaseNavigationContainer.swift index cb46019..ec7a02a 100644 --- a/Sources/BaseNavigationStack/Views/BaseNavigationContainer.swift +++ b/Sources/BaseNavigationStack/Views/BaseNavigationContainer.swift @@ -38,32 +38,11 @@ public struct BaseNavigationContainer< } public var body: some View { - #if os(iOS) || os(tvOS) || os(watchOS) || os(visionOS) NavigationStack(path: $router.path) { content() - .navigationDestination(for: Route.self) { route in - destination(route) - } - .sheet(item: $router.sheet) { sheet in - sheetContent(sheet) - } - .fullScreenCover(item: $router.cover) { cover in - coverContent(cover) - } + .navigationRouter(router, destination: destination, sheet: sheetContent, cover: coverContent) } .environment(router) - #else - NavigationStack(path: $router.path) { - content() - .navigationDestination(for: Route.self) { route in - destination(route) - } - .sheet(item: $router.sheet) { sheet in - sheetContent(sheet) - } - } - .environment(router) - #endif } } diff --git a/Tests/BaseNavigationStackTests/BaseNavigationStackTests.swift b/Tests/BaseNavigationStackTests/BaseNavigationStackTests.swift deleted file mode 100644 index 5447e60..0000000 --- a/Tests/BaseNavigationStackTests/BaseNavigationStackTests.swift +++ /dev/null @@ -1,12 +0,0 @@ -import XCTest -@testable import BaseNavigationStack - -final class BaseNavigationStackTests: XCTestCase { - func testExample() throws { - // XCTest Documentation - // https://developer.apple.com/documentation/xctest - - // Defining Test Cases and Test Methods - // https://developer.apple.com/documentation/xctest/defining_test_cases_and_test_methods - } -} diff --git a/Tests/BaseNavigationStackTests/BaseNavigationStackV1Tests.swift b/Tests/BaseNavigationStackTests/BaseNavigationStackV1Tests.swift index 330a9ca..85857ff 100644 --- a/Tests/BaseNavigationStackTests/BaseNavigationStackV1Tests.swift +++ b/Tests/BaseNavigationStackTests/BaseNavigationStackV1Tests.swift @@ -39,4 +39,45 @@ final class BaseNavigationStackV1Tests: XCTestCase { XCTAssertNil(stack.presentingFullScreen.wrappedValue) XCTAssertEqual(stack.navigationPath.wrappedValue, [.second]) } + + func testLegacyPopAndRoot() { + let stack = BaseNavigationStack() + stack.pushToView(.first) + stack.pushToView(.first) + stack.pushToView(.second) + XCTAssertEqual(stack.navigationPath.wrappedValue, [.first, .second]) + + stack.popBack() + XCTAssertEqual(stack.navigationPath.wrappedValue, [.first]) + + stack.presentSheet(.second) + stack.navigateToRoot() + XCTAssertTrue(stack.navigationPath.wrappedValue.isEmpty) + XCTAssertNil(stack.presentingSheet.wrappedValue) + + // Empty stack pop is a no-op + stack.popBack() + XCTAssertTrue(stack.navigationPath.wrappedValue.isEmpty) + } + + func testLegacyDismissFallsBackToParentBinding() { + var parentPresented: LegacyTarget? = .first + let binding = Binding(get: { parentPresented }, set: { parentPresented = $0 }) + let stack = BaseNavigationStack(isPresented: binding) + + stack.dismiss() + XCTAssertNil(parentPresented, "Dismiss on empty stack must clear parent presentation") + } + + func testLegacyURLHandler() { + let stack = BaseNavigationStack() + let url = URL(string: "myapp://x")! + var received: URL? + stack.urlHandler = { url in + received = url + return .handled + } + _ = stack.handleOpenURL(url: url) + XCTAssertEqual(received, url) + } } diff --git a/Tests/BaseNavigationStackTests/ContainerViewTests.swift b/Tests/BaseNavigationStackTests/ContainerViewTests.swift index c8fedd3..1edcea6 100644 --- a/Tests/BaseNavigationStackTests/ContainerViewTests.swift +++ b/Tests/BaseNavigationStackTests/ContainerViewTests.swift @@ -24,18 +24,17 @@ final class ContainerViewTests: XCTestCase { cover: { cover in Text("Cover: \(cover.id)") } ) - XCTAssertNotNil(container.body) + // Smoke test: body must build on every platform branch without trapping + _ = container.body } func testModifierApplication() { let router = NavigationRouter() - let view = Text("Hello") + _ = Text("Hello") .navigationRouter( router, destination: { _ in Text("Dest") } ) - - XCTAssertNotNil(view) } } diff --git a/Tests/BaseNavigationStackTests/NavigationRouterTests.swift b/Tests/BaseNavigationStackTests/NavigationRouterTests.swift index efe8390..e438011 100644 --- a/Tests/BaseNavigationStackTests/NavigationRouterTests.swift +++ b/Tests/BaseNavigationStackTests/NavigationRouterTests.swift @@ -58,8 +58,8 @@ final class NavigationRouterTests: XCTestCase { func testDuplicatePushDebounce() { let router = NavigationRouter() - router.push(.home) - router.push(.home) // Repeated immediate push + XCTAssertTrue(router.push(.home)) + XCTAssertFalse(router.push(.home), "Repeated immediate push must report rejection") XCTAssertEqual(router.path.count, 1) router.push(.detail(id: 1)) @@ -94,9 +94,8 @@ final class NavigationRouterTests: XCTestCase { let router = NavigationRouter() router.push(.home) router.present(sheet: TestSheet(id: "s1")) - router.present(cover: TestCover(id: "c1")) - router.replacePath([.detail(id: 99)]) + XCTAssertTrue(router.replacePath([.detail(id: 99)])) XCTAssertNil(router.sheet) XCTAssertNil(router.cover) XCTAssertEqual(router.path, [.detail(id: 99)]) @@ -113,4 +112,37 @@ final class NavigationRouterTests: XCTestCase { XCTAssertNil(router.sheet) XCTAssertNil(router.cover) } + + func testSheetAndCoverAreMutuallyExclusive() { + let router = NavigationRouter() + + XCTAssertTrue(router.present(sheet: TestSheet(id: "s1"))) + XCTAssertFalse(router.present(cover: TestCover(id: "c1"))) + XCTAssertNil(router.cover) + + // Swapping one sheet for another is allowed + XCTAssertTrue(router.present(sheet: TestSheet(id: "s2"))) + XCTAssertEqual(router.sheet?.id, "s2") + + router.dismiss() + XCTAssertTrue(router.present(cover: TestCover(id: "c1"))) + XCTAssertFalse(router.present(sheet: TestSheet(id: "s3"))) + XCTAssertNil(router.sheet) + } + + func testInitKeepsOnlyOneModal() { + let router = NavigationRouter( + initialSheet: TestSheet(id: "s1"), + initialCover: TestCover(id: "c1") + ) + XCTAssertNotNil(router.sheet) + XCTAssertNil(router.cover) + } + + func testPopNonPositiveCountIsNoOp() { + let router = NavigationRouter(initialPath: [.home, .profile]) + router.pop(count: 0) + router.pop(count: -3) + XCTAssertEqual(router.path, [.home, .profile]) + } } diff --git a/Tests/BaseNavigationStackTests/PerformanceAndAsyncTests.swift b/Tests/BaseNavigationStackTests/PerformanceAndAsyncTests.swift index 09de680..986f496 100644 --- a/Tests/BaseNavigationStackTests/PerformanceAndAsyncTests.swift +++ b/Tests/BaseNavigationStackTests/PerformanceAndAsyncTests.swift @@ -16,34 +16,51 @@ final class PerformanceAndAsyncTests: XCTestCase { func testStackMaxDepthGuard() { let router = NavigationRouter(maxDepth: 5) - for stepIndex in 1...10 { - router.push(.step(stepIndex)) + for stepIndex in 1...5 { + XCTAssertTrue(router.push(.step(stepIndex))) } + XCTAssertFalse(router.push(.step(6)), "push at maxDepth must report rejection") XCTAssertEqual(router.path.count, 5, "Stack must strictly not exceed maxDepth (5)") XCTAssertEqual(router.path.last, .step(5)) // Replace path must also respect maxDepth let overflowList = (1...20).map { AsyncRoute.step($0) } - router.replacePath(overflowList) + XCTAssertFalse(router.replacePath(overflowList), "truncation must be reported") XCTAssertEqual(router.path.count, 5, "replacePath must clamp to maxDepth") } func testAsyncSendFromBackgroundThread() async { let router = NavigationRouter() - // Dispatch action from detached background Task - await Task.detached { - // Perform simulated heavy work - try? await Task.sleep(nanoseconds: 10_000_000) + // Dispatch action from detached background Task and await the main-actor mutation itself + let mutation = await Task.detached { router.send { targetRouter in targetRouter.push(.step(100)) } }.value - - // Allow runloop to process MainActor task - try? await Task.sleep(nanoseconds: 50_000_000) + await mutation.value XCTAssertEqual(router.path, [.step(100)], "send() should safely mutate router on MainActor from background task") } + + func testMaxDepthClampedOnAssignment() { + let router = NavigationRouter(maxDepth: 0) + XCTAssertEqual(router.maxDepth, 1) + + router.maxDepth = -1 + XCTAssertEqual(router.maxDepth, 1) + // Previously crashed with prefix(-1) + XCTAssertFalse(router.replacePath([.step(1), .step(2)])) + XCTAssertEqual(router.path, [.step(1)]) + } + + func testInitialPathClampedToMaxDepth() { + let router = NavigationRouter( + initialPath: (1...5).map { AsyncRoute.step($0) }, + maxDepth: 3 + ) + XCTAssertEqual(router.path, [.step(1), .step(2), .step(3)]) + } + } diff --git a/docs/wiki/API-BaseNavigationContainer.md b/docs/wiki/API-BaseNavigationContainer.md index c0590bc..3741556 100644 --- a/docs/wiki/API-BaseNavigationContainer.md +++ b/docs/wiki/API-BaseNavigationContainer.md @@ -83,34 +83,26 @@ struct NoCover: Identifiable, Hashable, Sendable { let id = UUID() } typealias AppRouter = NavigationRouter ``` -## Conditional compilation +## Platform behavior -`fullScreenCover` does not exist on macOS. The container branches at compile time: +`fullScreenCover` does not exist on macOS. The container (and the `.navigationRouter` modifier it uses) presents the cover through a single internal helper: ```swift -#if os(iOS) || os(tvOS) || os(watchOS) || os(visionOS) NavigationStack(path: $router.path) { content() - .navigationDestination(for: Route.self) { destination($0) } - .sheet(item: $router.sheet) { sheetContent($0) } - .fullScreenCover(item: $router.cover) { coverContent($0) } + .navigationRouter(router, destination: destination, sheet: sheetContent, cover: coverContent) } .environment(router) + +// inside .navigationRouter: +#if os(macOS) +sheet(item: $router.cover, content: coverContent) #else -NavigationStack(path: $router.path) { - content() - .navigationDestination(for: Route.self) { destination($0) } - .sheet(item: $router.sheet) { sheetContent($0) } -} -.environment(router) +fullScreenCover(item: $router.cover, content: coverContent) #endif ``` -On macOS: - -- `cover` state is still tracked by the router but never rendered. Guard UI that assumes a cover is visible. -- `.sheet(item:)` exists on macOS and works normally. -- Your `cover:` closure still compiles; keep it platform-neutral. +On macOS the `cover:` closure is shown as a sheet, so `present(cover:)` is always visible and `dismiss()` closes what the user sees. ## Behavior notes diff --git a/docs/wiki/API-Modifiers-and-Helpers.md b/docs/wiki/API-Modifiers-and-Helpers.md index 8b6c238..7070994 100644 --- a/docs/wiki/API-Modifiers-and-Helpers.md +++ b/docs/wiki/API-Modifiers-and-Helpers.md @@ -2,13 +2,13 @@ ## `.navigationRouter(...)` View modifier -Binds a `NavigationRouter` to an existing `NavigationStack` (or any view hierarchy) instead of using `BaseNavigationContainer`. Use it when you already build the `NavigationStack` yourself. +Attaches a `NavigationRouter`'s destinations and modals to the root content of a `NavigationStack` you build yourself, instead of using `BaseNavigationContainer`. It does **not** bind `path`: you must pass `$router.path` to `NavigationStack(path:)`. ### Full form ```swift public extension View { - @MainActor @ViewBuilder + @MainActor func navigationRouter< Route: Hashable & Sendable, Sheet: Identifiable & Hashable & Sendable, @@ -25,7 +25,9 @@ public extension View { } ``` -Attaches, in order: `.navigationDestination(for:)`, `.sheet(item:)`, `.fullScreenCover(item:)` (iOS/tvOS/watchOS/visionOS only), and `.environment(router)`. +Attaches, in order: `.navigationDestination(for:)`, `.sheet(item:)`, `.fullScreenCover(item:)` (a second `.sheet` on macOS), and `.environment(router)`. + +Apply it to the content **inside** the stack — `navigationDestination` must be declared within the `NavigationStack`, not on the stack itself. ```swift struct RootView: View { @@ -34,22 +36,24 @@ struct RootView: View { var body: some View { NavigationStack(path: $router.path) { HomeView() + .navigationRouter( + router, + destination: { route in + switch route { + case .detail(let id): DetailView(id: id) + case .profile: ProfileView() + } + }, + sheet: { sheet in + SheetView(sheet: sheet) + }, + cover: { cover in + CoverView(cover: cover) + } + ) } - .navigationRouter( - router, - destination: { route in - switch route { - case .detail(let id): DetailView(id: id) - case .profile: ProfileView() - } - }, - sheet: { sheet in - SheetView(sheet: sheet) - }, - cover: { cover in - CoverView(cover: cover) - } - ) + // Also inject on the stack so pushed destinations can read the router + .environment(router) } } ``` @@ -63,39 +67,7 @@ func navigationRouter( ) -> some View ``` -Passes `EmptyView` for sheet and cover internally. On macOS the `fullScreenCover` branch is compiled out (same `#if` as the container). - -## Collection helpers - -`Sources/BaseNavigationStack/Utils/Collection+Extension.swift`: - -```swift -extension Collection { - /// Returns nil instead of trapping when out of bounds. - public subscript(safe index: Index) -> Element? { - indices.contains(index) ? self[index] : nil - } -} - -extension Array { - /// removeLast() that is a no-op on empty arrays. - public mutating func removeLastSafe() { - guard !isEmpty else { return } - removeLast() - } -} -``` - -```swift -let stack = ["a", "b"] -let first = stack[safe: 5] // nil, no crash -let mid = stack[safe: 0] // Optional("a") - -var path = [Route]() -path.removeLastSafe() // no crash on empty path -``` - -These are public and used by the v1 `BaseNavigationStack` compatibility layer. +Passes `EmptyView` for sheet and cover internally. On macOS the cover is presented as a sheet (same behavior as the container). ## `BaseViewProtocol` @@ -113,7 +85,7 @@ public protocol BaseViewProtocol: Identifiable, Hashable, Sendable { } ``` -Example (from the demo app): +Example (a v1-style screen model; the demo app now uses v2 only): ```swift enum ViewNavigationTarget: BaseViewProtocol { @@ -142,7 +114,7 @@ New code should prefer v2 routes (`Hashable & Sendable` enum + `destination:` cl ```swift @MainActor @Observable -public final class BaseNavigationStack: @unchecked Sendable +public final class BaseNavigationStack where ScreenView: BaseViewProtocol ``` @@ -152,12 +124,12 @@ Kept for backward compatibility. Public surface: |---|---| | `init(isPresented: Binding = .constant(nil))` | Root binding for modal-presentation ownership. | | `pushToView(_:)` | Append with duplicate-top debounce (no `maxDepth` cap in v1). | -| `popBack()` | `removeLastSafe()` — safe on empty. | +| `popBack()` | Pops the top screen; no-op on empty. | | `navigateToRoot()` | Clear path + sheet + cover. | | `replaceNavigationStack(path:)` | Clear modals, replace path. | | `presentSheet(_:)` / `presentFullScreen(_:)` | Set modal state. | -| `dismiss()` | sheet → cover → pop → `isPresented = nil` ladder. | -| `urlHandler` | `(@MainActor (URL) -> OpenURLAction.Result)?` hook; `handleOpenURL(url:)` invokes it, defaults `.systemAction`. | +| `dismiss()` | sheet → cover → pop → `isPresented = nil` ladder. With the default `.constant(nil)` binding the last step is a no-op. | +| `urlHandler` | `(@MainActor (URL) -> OpenURLAction.Result)?` hook; `handleOpenURL(url:)` invokes it, defaults `.systemAction`. Stored strongly — capture owners with `[weak ...]`. | | `navigationPath` / `presentingSheet` / `presentingFullScreen` / `isPresented` | `Binding` accessors. | ```swift diff --git a/docs/wiki/API-NavigationRouter.md b/docs/wiki/API-NavigationRouter.md index c8384af..c60ef1d 100644 --- a/docs/wiki/API-NavigationRouter.md +++ b/docs/wiki/API-NavigationRouter.md @@ -6,19 +6,23 @@ public final class NavigationRouter< Route: Hashable & Sendable, Sheet: Identifiable & Hashable & Sendable, Cover: Identifiable & Hashable & Sendable ->: @unchecked Sendable +> ``` +`@MainActor` classes are implicitly `Sendable`, so the router can be captured from any context (see `send(_:)`). + +Own the router with `@State` (or a long-lived model). Creating it inline in `body` recreates it on every render and loses the stack. + Single point of truth for stack, sheet, and cover state. ## State | Property | Type | Meaning | |---|---|---| -| `path` | `[Route]` | Navigation stack, root-first. Bind directly with `$router.path`. | -| `sheet` | `Sheet?` | Active sheet; drives `.sheet(item:)`. | -| `cover` | `Cover?` | Active full screen cover; drives `.fullScreenCover(item:)`. | -| `maxDepth` | `Int` | Stack cap. Default `30`. Initializer clamps to `max(1, maxDepth)`. | +| `path` | `[Route]` | Navigation stack, root-first. Bind directly with `$router.path`. Writing it directly bypasses the `push` guards. | +| `sheet` | `Sheet?` | Active sheet; drives `.sheet(item:)`. At most one of `sheet` / `cover` is set through the router API. | +| `cover` | `Cover?` | Active full screen cover; drives `.fullScreenCover(item:)` (a sheet on macOS). | +| `maxDepth` | `Int` | Stack cap. Default `30`. Clamped to `>= 1` in the initializer and on every assignment. Lowering it does not trim an existing `path`. | ## Initializer @@ -34,7 +38,7 @@ public init( ```swift let router = NavigationRouter() let deepLink = NavigationRouter( - initialPath: [.profile, .detail(id: 7)] + initialPath: [.profile, .detail(id: 7)] // truncated to maxDepth ) let shallow = NavigationRouter(maxDepth: 5) ``` @@ -44,11 +48,14 @@ let shallow = NavigationRouter(maxDepth: 5) ### `push(_:)` ```swift -public func push(_ route: Route) +@discardableResult +public func push(_ route: Route) -> Bool ``` -- Guards `path.count < maxDepth`; silently drops when at cap. -- **Debounce**: if `path.last == route`, the push is ignored. Protects against double taps / repeated async dispatches producing duplicated screens. +Returns `false` when the push is rejected, and logs the reason through `os.Logger` (subsystem `BaseNavigationStack`). + +- Rejected when `path.count >= maxDepth`. +- **Duplicate-top guard**: if `path.last == route`, the push is ignored. Protects against double taps / repeated async dispatches producing duplicated screens. It is not time-based: a flow that legitimately pushes the same value twice in a row needs distinct values (e.g. include a step index). - Equality is the route's `Hashable`/`Equatable` conformance — for enum routes with associated values, same case + same values means duplicate. ```swift @@ -91,10 +98,11 @@ Clears `path`, `sheet`, and `cover`. Full reset to root. ### `replacePath(_:)` ```swift -public func replacePath(_ newPath: [Route]) +@discardableResult +public func replacePath(_ newPath: [Route]) -> Bool ``` -Replaces the whole stack (e.g. auth switch, deep-link jump) and dismisses any active sheet/cover. Truncates to `maxDepth` via `prefix(maxDepth)`. +Replaces the whole stack (e.g. auth switch, deep-link jump) and dismisses any active sheet/cover. Keeps the first `maxDepth` routes and returns `false` when it had to truncate, so a deep link longer than `maxDepth` does not land on its final screen — check the result or raise `maxDepth`. ```swift router.replacePath([.profile]) // sheet/cover nil, path == [.profile] @@ -105,18 +113,20 @@ router.replacePath([.profile]) // sheet/cover nil, path == [.profile] ### `present(sheet:)` ```swift -public func present(sheet: Sheet) +@discardableResult +public func present(sheet: Sheet) -> Bool ``` -Sets `sheet`. Setting a new value while one is presented replaces it. +Sets `sheet`. Setting a new value while one is presented replaces it. Rejected (`false`) while a cover is presented: SwiftUI cannot present both from the same view. To show a sheet on top of a cover, give the cover its own router (see [[Nested-and-Tab-Navigation]]). ### `present(cover:)` ```swift -public func present(cover: Cover) +@discardableResult +public func present(cover: Cover) -> Bool ``` -Sets `cover`. On iOS/tvOS/watchOS/visionOS rendered as `.fullScreenCover(item:)`. +Sets `cover`. On iOS/tvOS/watchOS/visionOS rendered as `.fullScreenCover(item:)`; on macOS as a sheet. Rejected (`false`) while a sheet is presented. ### `dismiss()` @@ -146,16 +156,17 @@ Clears `sheet` and `cover` without touching `path`. ### `send(_:)` ```swift -nonisolated public func send(_ action: @escaping @MainActor (NavigationRouter) -> Void) +@discardableResult +nonisolated public func send(_ action: @escaping @MainActor (NavigationRouter) -> Void) -> Task ``` -Safe entry point from non-main actors. Wraps the mutation in `Task { @MainActor in ... }`. +Safe entry point from non-main actors. Wraps the mutation in `Task { @MainActor in ... }` and returns that task. The mutation runs asynchronously, so separate `send` calls are not guaranteed to run in call order — `await` the returned task (`await router.send { ... }.value`) when ordering matters. From code already on the main actor, call the methods directly. ```swift Task.detached { let user = try await api.fetchUser() router.send { r in - r.push(.profile(user)) + r.push(.detail(id: user.id)) } } ``` @@ -174,9 +185,9 @@ Task.detached { func testCapAndDebounce() { let router = NavigationRouter(maxDepth: 2) router.push(.profile) - router.push(.profile) // debounced - router.push(.detail(id: 1)) // depth 2 - router.push(.detail(id: 2)) // rejected by maxDepth + assert(router.push(.profile) == false) // duplicate of top + router.push(.detail(id: 1)) // depth 2 + assert(router.push(.detail(id: 2)) == false) // rejected by maxDepth assert(router.path == [.profile, .detail(id: 1)]) router.pop(count: 10) diff --git a/docs/wiki/Deep-Linking-and-URL-Handling.md b/docs/wiki/Deep-Linking-and-URL-Handling.md index 1c88cbb..773245a 100644 --- a/docs/wiki/Deep-Linking-and-URL-Handling.md +++ b/docs/wiki/Deep-Linking-and-URL-Handling.md @@ -28,11 +28,21 @@ enum AppRoute: Hashable, Sendable { } struct AppDeepLink { - static func routes(from url: URL) -> [AppRoute] { - guard url.scheme == "myapp" || url.host == "example.com" else { + /// Path segments for both `myapp://detail/42` (first segment is the URL host) + /// and `https://example.com/detail/42`. + static func segments(from url: URL) -> [String] { + switch url.scheme { + case "myapp": + return ([url.host].compactMap { $0 } + url.pathComponents).filter { $0 != "/" && !$0.isEmpty } + case "https" where url.host == "example.com": + return url.pathComponents.filter { $0 != "/" } + default: return [] } - let parts = url.pathComponents.filter { $0 != "/" } + } + + static func routes(from url: URL) -> [AppRoute] { + let parts = segments(from: url) switch parts.first { case "home": return [.home] @@ -48,7 +58,9 @@ struct AppDeepLink { } ``` -`myapp://detail/42` → `[.home, .detail(id: 42)]`. +`myapp://detail/42`, `myapp:///detail/42` and `https://example.com/detail/42` → `[.home, .detail(id: 42)]`. + +> With a custom scheme, `myapp://detail/42` puts `detail` in `url.host`, not in `pathComponents`. Parsing only `pathComponents` silently returns `[]`. ## 3. Apply on launch and on open @@ -59,6 +71,7 @@ struct MyApp: App { var body: some Scene { WindowGroup { + // This RootView receives the router instead of owning it with @State RootView(router: router) .onOpenURL { url in let routes = AppDeepLink.routes(from: url) @@ -75,7 +88,7 @@ struct MyApp: App { } ``` -`replacePath` clears any active sheet/cover and truncates to `maxDepth` — the correct semantic for "jump to this destination". +`replacePath` clears any active sheet/cover and truncates to `maxDepth` (returning `false` when it truncates) — the correct semantic for "jump to this destination". Prefer **pushing incrementally** (`push` per segment) when intermediate screens must appear in the back stack history; both work — `replacePath` is all-or-nothing, repeated `push` builds the history (watch duplicate-top debounce when a segment repeats). @@ -83,7 +96,7 @@ Prefer **pushing incrementally** (`push` per segment) when intermediate screens ```swift static func apply(url: URL, router: AppRouter) { - switch url.pathComponents.filter({ $0 != "/" }).first { + switch segments(from: url).first { case "paywall": router.present(sheet: AppSheet(id: "paywall")) default: @@ -97,11 +110,13 @@ static func apply(url: URL, router: AppRouter) { v1 `BaseNavigationStack` exposes a handler hook: ```swift -typealias BaseNavigation = BaseNavigationStack +// `AppScreen` is your own type conforming to `BaseViewProtocol` +typealias BaseNavigation = BaseNavigationStack let nav = BaseNavigation() -nav.urlHandler = { url in - nav.pushToView(.policy(url)) +// `urlHandler` is stored strongly: capture the owner weakly to avoid a retain cycle +nav.urlHandler = { [weak nav] url in + nav?.pushToView(.policy(url)) return .handled } diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md index a470032..60cc9cc 100644 --- a/docs/wiki/Getting-Started.md +++ b/docs/wiki/Getting-Started.md @@ -15,7 +15,7 @@ targets: [ Or in Xcode: **File → Add Package Dependencies…** → `https://github.com/iletai/BaseNavigationStack.git`. -Platforms: iOS 17.0+, macOS 14.0+. Swift tools 6.0. +Platforms: iOS 17.0+, macOS 14.0+, tvOS 17.0+, watchOS 10.0+, visionOS 1.0+. Swift tools 6.0 (Xcode 16+). ## 2. Define your Route enum diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md index 545ea1a..4f83c76 100644 --- a/docs/wiki/Home.md +++ b/docs/wiki/Home.md @@ -1,6 +1,6 @@ # BaseNavigationStack 2.0 -Modern, type-safe, data-driven navigation for SwiftUI (iOS 17+ / macOS 14+, Swift 6). +Modern, type-safe, data-driven navigation for SwiftUI (iOS 17+ / macOS 14+ / tvOS 17+ / watchOS 10+ / visionOS 1+, Swift 6). `BaseNavigationStack` unifies Stack pushes, Sheets, and FullScreenCovers under a single `@MainActor @Observable` router — no fragmented `@State`, no external dependencies. @@ -8,9 +8,9 @@ Modern, type-safe, data-driven navigation for SwiftUI (iOS 17+ / macOS 14+, Swif - **Single source of truth** — one router owns `path`, `sheet`, `cover`. - **Zero dependencies** — pure SwiftUI + Observation, nothing else in `Package.swift`. -- **Strict Concurrency** — Swift 6 with `StrictConcurrency` upcoming feature; router is `@MainActor` isolated and `Sendable`. +- **Strict Concurrency** — Swift 6 language mode; router is `@MainActor` isolated (and therefore `Sendable`). - **O(1)-style mutations** — stack state is a plain `[Route]` array; duplicate push is one equality check against `path.last`, pops are bounded with `min(count, path.count)`. Unit-testable with zero UI test overhead. -- **Race-condition guard** — rapid identical taps collapse into one push (debounce), `maxDepth` caps stack growth. +- **Race-condition guard** — rapid identical taps collapse into one push, `maxDepth` caps stack growth; rejected operations return `false` and log. - **Nested ready** — independent routers per Tab and per modal. ## Design philosophy diff --git a/docs/wiki/Migration-Guide-v1-to-v2.md b/docs/wiki/Migration-Guide-v1-to-v2.md index 870fab5..34a05fc 100644 --- a/docs/wiki/Migration-Guide-v1-to-v2.md +++ b/docs/wiki/Migration-Guide-v1-to-v2.md @@ -17,10 +17,10 @@ v1 bound navigation logic to each screen (`BaseViewProtocol`). v2 splits **state | `replaceNavigationStack(path:)` | `replacePath(_:)` | | `presentSheet(_:)` | `present(sheet:)` | | `presentFullScreen(_:)` | `present(cover:)` | -| `dismiss()` | `dismiss()` (same ladder) | +| `dismiss()` | `dismiss()` — same sheet → cover → pop ladder, without v1's final `isPresented = nil` step. Close a presented flow from the parent router instead. | | `navigationPath` binding | `router.path` (`$router.path` via `@Bindable`) | | `presentingSheet`, `presentingFullScreen` | `router.sheet`, `router.cover` | -| `urlHandler` | `onOpenURL` / `handleOpenURL` equivalent mapping to `replacePath` | +| `urlHandler` / `handleOpenURL(url:)` | No router hook in v2: parse the URL yourself in `.onOpenURL` and call `replacePath(_:)`. See [[Deep-Linking-and-URL-Handling]]. | ## Before (v1) @@ -126,12 +126,19 @@ struct HomeView: View { | Behavior | v1 | v2 | |---|---|---| -| `dismiss()` on a 1-item stack | buggy/none in old builds | pops it | -| Duplicate push | debounced | debounced (same) | -| Stack cap | none | `maxDepth = 30` by default | -| `replacePath` | did not clear modals in old builds | clears sheet + cover | +| `dismiss()` on a 1-item stack | no-op in 1.0.x (required 2+ items) | pops it | +| Duplicate push | ignored silently | ignored; `push` returns `false` | +| Stack cap | none | `maxDepth = 30` by default; rejected pushes return `false` | +| `replacePath` | did not clear modals in 1.0.x | clears sheet + cover | | Modal types | one `ScreenView` type | independent `Sheet` and `Cover` types | -| macOS full screen cover | manual | compiled out | +| macOS full screen cover | manual | presented as a sheet | +| Sheet while a cover is up | allowed (SwiftUI cannot show both) | `present(sheet:)` rejected, returns `false` (and vice versa) | + +## Breaking changes in 2.0 (even if you stay on v1 APIs) + +- `swift-tools-version: 6.0` — requires Xcode 16+. +- Minimum platforms raised to iOS 17 / macOS 14 / tvOS 17 / watchOS 10 / visionOS 1 (needed for `@Observable`). +- Public `Collection.subscript(safe:)` and `Array.removeLastSafe()` removed. Use `indices.contains(i) ? c[i] : nil` and `popLast()`. ## Using v2 without migrating everything diff --git a/docs/wiki/Nested-and-Tab-Navigation.md b/docs/wiki/Nested-and-Tab-Navigation.md index ba41679..f10b71a 100644 --- a/docs/wiki/Nested-and-Tab-Navigation.md +++ b/docs/wiki/Nested-and-Tab-Navigation.md @@ -63,6 +63,16 @@ Switching tabs does not reset stacks — `@State` keeps both alive in the host v A modal can host a fully isolated sub-stack. The child router lives inside the sheet view; the parent only knows "sheet is open": ```swift +// Parent router types +struct DemoSheet: Identifiable, Hashable, Sendable { + let id: String + let title: String +} +struct DemoCover: Identifiable, Hashable, Sendable { let id: String } +enum DemoRoute: Hashable, Sendable { case detail(id: Int) } +typealias DemoRouter = NavigationRouter + +// Child router types enum SubModalRoute: Hashable, Sendable { case subDetail } @@ -101,10 +111,12 @@ Rules of thumb: - **Close the modal** → parent `parentRouter.dismiss()`. - Parent stack is untouched while the child stack grows — `dismissModals()` on the parent closes the sheet and discards child state. - Child routes must not reference parent routes; keep enums separate. +- If the child router has the **same type** as the parent, `@Environment(ParentRouter.self)` inside the child container resolves to the child. Read the parent router outside the child container (as above), or give the child its own route types. +- A presented cover blocks `present(sheet:)` on the same router (it returns `false`). To show a sheet from inside a cover, give the cover its own router. ## Common pitfalls 1. **Creating the router inside `body`** — `let r = AppRouter()` re-instantiates every render, stack resets. Always `@State private var router = AppRouter()`. 2. **Sharing one router across tabs** — `popToRoot` in tab A nukes tab B. One router per stack. -3. **Presenting a cover on macOS** — compiled out of the container; see [[API-BaseNavigationContainer]]. +3. **Presenting a cover on macOS** — presented as a sheet, since macOS has no full screen cover; see [[API-BaseNavigationContainer]]. 4. **Nested `NavigationStack` on iOS 17** — legal inside `.sheet`, but never nest two stacks in the *same* column; give each its own modal boundary. diff --git a/docs/wiki/Swift-6-Concurrency.md b/docs/wiki/Swift-6-Concurrency.md index b9c3aa9..51ac857 100644 --- a/docs/wiki/Swift-6-Concurrency.md +++ b/docs/wiki/Swift-6-Concurrency.md @@ -1,6 +1,6 @@ # Swift 6 Concurrency -Package is built with `swift-tools-version: 6.0` and `.enableUpcomingFeature("StrictConcurrency")`. +Package is built with `swift-tools-version: 6.0`, which compiles in the Swift 6 language mode (complete strict concurrency checking) by default. No extra flags are needed. ## `@MainActor` isolation @@ -9,7 +9,7 @@ Package is built with `swift-tools-version: 6.0` and `.enableUpcomingFeature("St ```swift @MainActor @Observable -public final class NavigationRouter: @unchecked Sendable +public final class NavigationRouter ``` Consequences: @@ -32,9 +32,10 @@ final class NavigationRouterTests: XCTestCase { ## `send(_:)` — crossing actor boundaries ```swift +@discardableResult nonisolated public func send( _ action: @escaping @MainActor (NavigationRouter) -> Void -) { +) -> Task { Task { @MainActor in action(self) } @@ -43,7 +44,8 @@ nonisolated public func send( - `send` is `nonisolated` → callable from any actor/Task. - The closure is `@MainActor`-typed → runs isolated on main after the hop. -- The class declares `@unchecked Sendable`: safety relies on main-actor isolation of all stored state (the standard `@MainActor` class pattern). Do not add non-isolated mutable storage. +- `@MainActor` classes are implicitly `Sendable`, so capturing `router` in a detached task is checked by the compiler — no `@unchecked` escape hatch. +- The mutation runs asynchronously. Separate `send` calls are not guaranteed to run in call order; `await router.send { ... }.value` when ordering matters. ```swift Task.detached { @@ -90,18 +92,13 @@ case user(id: UUID) 1. Single writer domain: main actor only; no locks, no queues. 2. Rapid-tap race: `push` compares `path.last` — duplicate collapses (debounce). -3. Background dispatch race: `send` serializes onto main actor. +3. Background dispatch race: `send` hops onto the main actor; await the returned task to order calls. 4. Runaway stack: `maxDepth` caps depth at push time. -5. Empty-stack ops: `pop()`, `pop(count:)`, `removeLastSafe()` are no-ops, never traps. +5. Empty-stack ops: `pop()`, `pop(count:)`, `dismiss()` are no-ops, never traps. +6. Invalid configuration: `maxDepth` is clamped to `>= 1` on every assignment. ## Build flags reference -`Package.swift`: +`Package.swift` uses `swift-tools-version: 6.0` with no extra `swiftSettings`; the Swift 6 language mode already enables complete concurrency checking. -```swift -swiftSettings: [ - .enableUpcomingFeature("StrictConcurrency") -] -``` - -App targets using Swift 6 language mode should set `SWIFT_STRICT_CONCURRENCY = complete` in build settings to match. +App targets should set `SWIFT_VERSION = 6.0` (the example app does). Apps still on Swift 5 mode can use the package, but get weaker checking in their own code. diff --git a/docs/wiki/_Footer.md b/docs/wiki/_Footer.md index d517b02..843f2d9 100644 --- a/docs/wiki/_Footer.md +++ b/docs/wiki/_Footer.md @@ -1 +1 @@ -BaseNavigationStack 2.0 · MIT License · [iletai/BaseNavigationStack](https://github.com/iletai/BaseNavigationStack) · Swift 6 · iOS 17+ / macOS 14+ +BaseNavigationStack 2.0 · MIT License · [iletai/BaseNavigationStack](https://github.com/iletai/BaseNavigationStack) · Swift 6 · iOS 17+ / macOS 14+ / tvOS 17+ / watchOS 10+ / visionOS 1+