From ff37b7c3f7076e6d2e8bda25e22aba6755bb17ea Mon Sep 17 00:00:00 2001 From: iletai Date: Mon, 2 Nov 2026 22:46:44 +0700 Subject: [PATCH] fix(modifier): inject router into pushed destinations; add UI tests and size budget - navigationRouter on a hand-built NavigationStack crashed pushed screens reading @Environment for the router (environment was applied inside the stack) - example app: cover, sheet-rejected-while-cover, maxDepth deep link, modifier tab - NavigationStackExampleUITests: 9 normal/boundary cases with screenshots - scripts/check-binary-size.sh: fail when the library adds > 80 KB to a release app - CI: Example UI Tests (newest iOS simulator, xcresult artifact) and Binary Size jobs --- .github/workflows/ci.yml | 58 ++++++ CHANGELOG.md | 6 + CONTRIBUTING.md | 4 +- .../project.pbxproj | 138 +++++++++++++ .../xcschemes/NavigationStackExample.xcscheme | 111 +++++++++++ .../NavigationStackExample/ContentView.swift | 127 +++++++++++- .../NavigationFlowUITests.swift | 185 ++++++++++++++++++ README.md | 2 - .../Modifiers/NavigationRouterModifier.swift | 7 +- docs/wiki/API-Modifiers-and-Helpers.md | 4 +- scripts/check-binary-size.sh | 98 ++++++++++ 11 files changed, 722 insertions(+), 18 deletions(-) create mode 100644 NavigationStackExample/NavigationStackExample.xcodeproj/xcshareddata/xcschemes/NavigationStackExample.xcscheme create mode 100644 NavigationStackExample/NavigationStackExampleUITests/NavigationFlowUITests.swift create mode 100755 scripts/check-binary-size.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4839e07..6183cfb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -112,3 +112,61 @@ jobs: -scheme NavigationStackExample \ -destination 'generic/platform=iOS Simulator' \ CODE_SIGNING_ALLOWED=NO + + ui-tests-example: + name: Example UI Tests + runs-on: macos-26 + steps: + - name: Checkout Repository + uses: actions/checkout@v7 + + - name: Select Xcode + uses: maxim-lobanov/setup-xcode@v1 + with: + xcode-version: latest-stable + + - name: Run UI Tests On Newest iOS Simulator + run: | + SIM_ID=$(xcrun simctl list devices available -j | python3 -c ' + import json, sys + devices = json.load(sys.stdin)["devices"] + runtimes = sorted((k for k in devices if ".iOS-" in k), key=lambda k: [int(x) for x in k.split(".iOS-")[1].split("-")]) + for runtime in reversed(runtimes): + phones = [d["udid"] for d in devices[runtime] if d["name"].startswith("iPhone")] + if phones: + print(phones[0]) + break + ') + if [ -z "$SIM_ID" ]; then + echo "::error::No iPhone simulator available" + exit 1 + fi + xcodebuild test \ + -project NavigationStackExample/NavigationStackExample.xcodeproj \ + -scheme NavigationStackExample \ + -destination "id=$SIM_ID" \ + -resultBundlePath UITests.xcresult \ + CODE_SIGNING_ALLOWED=NO + + - name: Upload Result Bundle (screenshots) + if: always() + uses: actions/upload-artifact@v4 + with: + name: example-ui-tests-xcresult + path: UITests.xcresult + if-no-files-found: ignore + + binary-size: + name: Binary Size + runs-on: macos-26 + steps: + - name: Checkout Repository + uses: actions/checkout@v7 + + - name: Select Xcode + uses: maxim-lobanov/setup-xcode@v1 + with: + xcode-version: latest-stable + + - name: Check Library Binary Size Budget + run: scripts/check-binary-size.sh 80000 diff --git a/CHANGELOG.md b/CHANGELOG.md index 06cd04f..2233943 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to this project are documented here. Format follows [Keep a ## [Unreleased] +### Fixed +- `View.navigationRouter(...)` on a hand-built `NavigationStack`: pushed destinations crashed when reading the router from `@Environment`, because `.environment(router)` was applied inside the stack. The router is now injected into every pushed destination (sheets and covers already inherited it). `BaseNavigationContainer` was not affected. + +### Added +- Example app UI tests (`NavigationStackExampleUITests`) covering push/pop, nested sheet stack, full screen cover, background `send`, the modifier recipe (pushed screen and sheet), duplicate-push guard, `maxDepth` truncation, and sheet rejection while a cover is shown. CI runs them and attaches screenshots to the result bundle. + ## [2.0.0] - 2026-11-02 ### Added diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c4eed53..caf369c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -23,8 +23,10 @@ The project uses Git Flow: ```bash swift test swiftlint --strict + scripts/check-binary-size.sh # library must add < 80 KB to a release app ``` -5. CI must pass (macOS, iOS Simulator, tvOS, watchOS, visionOS, example app, SwiftLint). + Changes that affect rendering should also pass the example UI tests (scheme `NavigationStackExample`, target `NavigationStackExampleUITests`); each step attaches a screenshot to the result bundle. +5. CI must pass (macOS, iOS Simulator, tvOS, watchOS, visionOS, example app build and UI tests, binary size, SwiftLint). ## Versioning diff --git a/NavigationStackExample/NavigationStackExample.xcodeproj/project.pbxproj b/NavigationStackExample/NavigationStackExample.xcodeproj/project.pbxproj index a528775..9bbc171 100644 --- a/NavigationStackExample/NavigationStackExample.xcodeproj/project.pbxproj +++ b/NavigationStackExample/NavigationStackExample.xcodeproj/project.pbxproj @@ -7,22 +7,45 @@ objects = { /* Begin PBXBuildFile section */ + 2F415C30082A237CE9040EB5 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8947B5544ECAFE722A93B6CC /* Foundation.framework */; }; 3E7A81C32B2B06C60003D5A3 /* NavigationStackExampleApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E7A81C22B2B06C60003D5A3 /* NavigationStackExampleApp.swift */; }; 3E7A81C52B2B06C60003D5A3 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E7A81C42B2B06C60003D5A3 /* ContentView.swift */; }; 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 */; }; + AC7418F0D4DFC75CE7265C5A /* NavigationFlowUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CCBA617EF856AC0741BA0D65 /* NavigationFlowUITests.swift */; }; /* End PBXBuildFile section */ +/* Begin PBXContainerItemProxy section */ + 32DFD30F4FA9EE8EA0E8F8AA /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 3E7A81B72B2B06C50003D5A3 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 3E7A81BE2B2B06C60003D5A3; + remoteInfo = NavigationStackExample; + }; +/* End PBXContainerItemProxy section */ + /* Begin PBXFileReference section */ 3E7A81BF2B2B06C60003D5A3 /* NavigationStackExample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = NavigationStackExample.app; sourceTree = BUILT_PRODUCTS_DIR; }; 3E7A81C22B2B06C60003D5A3 /* NavigationStackExampleApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NavigationStackExampleApp.swift; sourceTree = ""; }; 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 = ""; }; + 6E3B2544D9A08AC0C04E7D89 /* NavigationStackExampleUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = NavigationStackExampleUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 8947B5544ECAFE722A93B6CC /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS26.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + CCBA617EF856AC0741BA0D65 /* NavigationFlowUITests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NavigationFlowUITests.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ + 104829D03CBC760B8A6278F1 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2F415C30082A237CE9040EB5 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 3E7A81BC2B2B06C60003D5A3 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; @@ -39,6 +62,8 @@ children = ( 3E7A81C12B2B06C60003D5A3 /* NavigationStackExample */, 3E7A81C02B2B06C60003D5A3 /* Products */, + 5F599B154D6A3E05F3E95133 /* Frameworks */, + 806789F8DAA2C52F51E0F308 /* NavigationStackExampleUITests */, ); sourceTree = ""; }; @@ -46,6 +71,7 @@ isa = PBXGroup; children = ( 3E7A81BF2B2B06C60003D5A3 /* NavigationStackExample.app */, + 6E3B2544D9A08AC0C04E7D89 /* NavigationStackExampleUITests.xctest */, ); name = Products; sourceTree = ""; @@ -69,9 +95,52 @@ path = "Preview Content"; sourceTree = ""; }; + 5F599B154D6A3E05F3E95133 /* Frameworks */ = { + isa = PBXGroup; + children = ( + BC6690ABD9CC6A44B9BFC02E /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 806789F8DAA2C52F51E0F308 /* NavigationStackExampleUITests */ = { + isa = PBXGroup; + children = ( + CCBA617EF856AC0741BA0D65 /* NavigationFlowUITests.swift */, + ); + name = NavigationStackExampleUITests; + path = NavigationStackExampleUITests; + sourceTree = ""; + }; + BC6690ABD9CC6A44B9BFC02E /* iOS */ = { + isa = PBXGroup; + children = ( + 8947B5544ECAFE722A93B6CC /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ + 03412AC37194981B7A5118EA /* NavigationStackExampleUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 636323033ED8E83B3F78E2AD /* Build configuration list for PBXNativeTarget "NavigationStackExampleUITests" */; + buildPhases = ( + 28195A8B9D26B02A521FB54C /* Sources */, + 104829D03CBC760B8A6278F1 /* Frameworks */, + B02A721A51B055B6254F85B7 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 9D466A08BE0EC8E47BAE9B1F /* PBXTargetDependency */, + ); + name = NavigationStackExampleUITests; + productName = NavigationStackExampleUITests; + productReference = 6E3B2544D9A08AC0C04E7D89 /* NavigationStackExampleUITests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; + }; 3E7A81BE2B2B06C60003D5A3 /* NavigationStackExample */ = { isa = PBXNativeTarget; buildConfigurationList = 3E7A81CD2B2B06C70003D5A3 /* Build configuration list for PBXNativeTarget "NavigationStackExample" */; @@ -124,6 +193,7 @@ projectRoot = ""; targets = ( 3E7A81BE2B2B06C60003D5A3 /* NavigationStackExample */, + 03412AC37194981B7A5118EA /* NavigationStackExampleUITests */, ); }; /* End PBXProject section */ @@ -138,9 +208,24 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + B02A721A51B055B6254F85B7 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ + 28195A8B9D26B02A521FB54C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + AC7418F0D4DFC75CE7265C5A /* NavigationFlowUITests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 3E7A81BB2B2B06C60003D5A3 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -152,6 +237,15 @@ }; /* End PBXSourcesBuildPhase section */ +/* Begin PBXTargetDependency section */ + 9D466A08BE0EC8E47BAE9B1F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = NavigationStackExample; + target = 3E7A81BE2B2B06C60003D5A3 /* NavigationStackExample */; + targetProxy = 32DFD30F4FA9EE8EA0E8F8AA /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + /* Begin XCBuildConfiguration section */ 3E7A81CB2B2B06C70003D5A3 /* Debug */ = { isa = XCBuildConfiguration; @@ -330,6 +424,41 @@ }; name = Release; }; + 7EBFF36BD61EC1EBC3921615 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = AP58YLHQ2S; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + PRODUCT_BUNDLE_IDENTIFIER = com.baseNavigationStack.NavigationStackExampleUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = NavigationStackExample; + }; + name = Debug; + }; + FDE56473E18DA50FBF2A25AC /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = AP58YLHQ2S; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + PRODUCT_BUNDLE_IDENTIFIER = com.baseNavigationStack.NavigationStackExampleUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = NavigationStackExample; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ @@ -351,6 +480,15 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + 636323033ED8E83B3F78E2AD /* Build configuration list for PBXNativeTarget "NavigationStackExampleUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FDE56473E18DA50FBF2A25AC /* Release */, + 7EBFF36BD61EC1EBC3921615 /* Debug */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; /* End XCConfigurationList section */ /* Begin XCLocalSwiftPackageReference section */ diff --git a/NavigationStackExample/NavigationStackExample.xcodeproj/xcshareddata/xcschemes/NavigationStackExample.xcscheme b/NavigationStackExample/NavigationStackExample.xcodeproj/xcshareddata/xcschemes/NavigationStackExample.xcscheme new file mode 100644 index 0000000..797f161 --- /dev/null +++ b/NavigationStackExample/NavigationStackExample.xcodeproj/xcshareddata/xcschemes/NavigationStackExample.xcscheme @@ -0,0 +1,111 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/NavigationStackExample/NavigationStackExample/ContentView.swift b/NavigationStackExample/NavigationStackExample/ContentView.swift index 6285d2b..e6ffb92 100644 --- a/NavigationStackExample/NavigationStackExample/ContentView.swift +++ b/NavigationStackExample/NavigationStackExample/ContentView.swift @@ -59,15 +59,7 @@ struct ContentView: View { NestedSheetContainerView(sheet: sheet) }, cover: { cover in - VStack(spacing: 20) { - Text("Full Screen Cover: \(cover.id)") - .font(.largeTitle) - Button("Dismiss Cover") { - router.dismiss() - } - .buttonStyle(.borderedProminent) - } - .padding() + CoverView(cover: cover) } ) .tabItem { @@ -81,6 +73,13 @@ struct ContentView: View { Label("Async Lab", systemImage: "bolt.horizontal") } .tag(1) + + // Tab 3: `.navigationRouter` modifier on a hand-built NavigationStack + ModifierRecipeView() + .tabItem { + Label("Modifier", systemImage: "wand.and.stars") + } + .tag(2) } } } @@ -89,6 +88,7 @@ struct ContentView: View { struct StackExplorerView: View { @Environment(DemoRouter.self) private var router + @State private var lastResult = "none" var body: some View { VStack(spacing: 20) { @@ -97,6 +97,10 @@ struct StackExplorerView: View { Text("Current Stack Depth: \(router.path.count) / \(router.maxDepth)") .font(.subheadline) .foregroundStyle(.secondary) + .accessibilityIdentifier("depthLabel") + Text("Last result: \(lastResult)") + .font(.caption) + .accessibilityIdentifier("lastResult") // Breadcrumb Trail ScrollView(.horizontal, showsIndicators: false) { @@ -125,10 +129,21 @@ struct StackExplorerView: View { VStack(spacing: 12) { Button("Push Next Step") { - router.push(.step(router.path.count + 1)) + lastResult = router.push(.step(router.path.count + 1)) ? "push accepted" : "push rejected" } .buttonStyle(.borderedProminent) + Button("Present Full Screen Cover") { + router.present(cover: DemoCover(id: "cover-1")) + } + .buttonStyle(.bordered) + + Button("Deep Link 35 Screens") { + let routes = (1...35).map { DemoRoute.step($0) } + lastResult = router.replacePath(routes) ? "deep link full" : "deep link truncated" + } + .buttonStyle(.bordered) + Button("Present Modal Sheet") { router.present(sheet: DemoSheet(id: "modal-1", title: "Nested Flow Sheet")) } @@ -185,6 +200,97 @@ struct StepDetailView: View { } } +// MARK: - Full Screen Cover + +struct CoverView: View { + let cover: DemoCover + @Environment(DemoRouter.self) private var router + @State private var sheetAttempt = "none" + + var body: some View { + VStack(spacing: 20) { + Text("Full Screen Cover: \(cover.id)") + .font(.largeTitle) + Text("Sheet attempt: \(sheetAttempt)") + .accessibilityIdentifier("sheetAttempt") + Button("Try Present Sheet From Same Router") { + sheetAttempt = router.present(sheet: DemoSheet(id: "blocked", title: "Blocked")) ? "presented" : "rejected" + } + .buttonStyle(.bordered) + Button("Dismiss Cover") { + router.dismiss() + } + .buttonStyle(.borderedProminent) + } + .padding() + } +} + +// MARK: - Modifier Recipe + +/// Uses only `.navigationRouter` inside a hand-built stack, without injecting the router +/// on the stack itself, to check that pushed destinations still receive it. +struct ModifierRecipeView: View { + @State private var modifierRouter = DemoRouter() + + var body: some View { + NavigationStack(path: $modifierRouter.path) { + VStack(spacing: 16) { + Button("Push Via Modifier") { + modifierRouter.push(.step(1)) + } + .buttonStyle(.borderedProminent) + + Button("Present Sheet Via Modifier") { + modifierRouter.present(sheet: DemoSheet(id: "modifier-sheet", title: "Modifier Sheet")) + } + .buttonStyle(.bordered) + } + .navigationTitle("Modifier") + .navigationRouter( + modifierRouter, + destination: { route in ModifierDestinationView(route: route) }, + sheet: { _ in ModifierSheetView() }, + cover: { _ in EmptyView() } + ) + } + } +} + +struct ModifierDestinationView: View { + let route: DemoRoute + @Environment(DemoRouter.self) private var router + + var body: some View { + VStack(spacing: 16) { + Text("Env router depth: \(router.path.count)") + .accessibilityIdentifier("modifierEnvDepth") + Button("Push Another Via Env") { + if case .step(let index) = route { + router.push(.step(index + 1)) + } + } + .buttonStyle(.borderedProminent) + } + .navigationTitle("Modifier Detail") + } +} + +struct ModifierSheetView: View { + @Environment(DemoRouter.self) private var router + + var body: some View { + VStack(spacing: 16) { + Text("Modifier sheet has router: \(router.sheet?.id ?? "none")") + .accessibilityIdentifier("modifierSheetEnv") + Button("Close Modifier Sheet") { + router.dismiss() + } + .buttonStyle(.borderedProminent) + } + } +} + // MARK: - Nested Modal Sub-Router View enum SubModalRoute: Hashable, Sendable { @@ -280,6 +386,7 @@ struct AsyncLabView: View { Text("Stack items: \(labRouter.path.count)") .font(.caption) .foregroundStyle(.secondary) + .accessibilityIdentifier("labStackCount") Spacer() } diff --git a/NavigationStackExample/NavigationStackExampleUITests/NavigationFlowUITests.swift b/NavigationStackExample/NavigationStackExampleUITests/NavigationFlowUITests.swift new file mode 100644 index 0000000..8854eb3 --- /dev/null +++ b/NavigationStackExample/NavigationStackExampleUITests/NavigationFlowUITests.swift @@ -0,0 +1,185 @@ +// +// NavigationFlowUITests.swift +// NavigationStackExampleUITests +// +// Drives the example app to verify the router against real SwiftUI rendering. +// Every step attaches a screenshot to the test result bundle. +// + +import XCTest + +final class NavigationFlowUITests: XCTestCase { + + override func setUp() { + continueAfterFailure = false + } + + // MARK: - Normal cases + + @MainActor + func testPushPopAndPopToRoot() { + let app = launch() + tap(app, "Push Next Step") + assertVisible(app, "Step Screen #1") + tap(app, "Push Step #2") + assertVisible(app, "Step Screen #2") + snapshot(app, "stack-depth-2") + + tap(app, "Pop Back") + assertVisible(app, "Step Screen #1") + tap(app, "Pop to Root") + XCTAssertEqual(text(app, "depthLabel"), "Current Stack Depth: 0 / 30") + snapshot(app, "stack-back-at-root") + } + + @MainActor + func testSheetHostsIndependentChildStack() { + let app = launch() + tap(app, "Present Modal Sheet") + assertVisible(app, "Nested Flow Sheet") + tap(app, "Push Child Stack Screen") + assertVisible(app, "Child Stack Detail") + snapshot(app, "sheet-child-pushed") + + tap(app, "Pop Child Screen") + assertVisible(app, "Nested Flow Sheet") + tap(app, "Dismiss Entire Sheet") + XCTAssertTrue(app.staticTexts["depthLabel"].waitForExistence(timeout: 5)) + XCTAssertEqual(text(app, "depthLabel"), "Current Stack Depth: 0 / 30", "Parent stack must be untouched") + snapshot(app, "sheet-dismissed") + } + + @MainActor + func testFullScreenCoverPresentsAndDismisses() { + let app = launch() + tap(app, "Present Full Screen Cover") + assertVisible(app, "Full Screen Cover: cover-1") + snapshot(app, "cover-presented") + + tap(app, "Dismiss Cover") + XCTAssertTrue(app.staticTexts["depthLabel"].waitForExistence(timeout: 5)) + snapshot(app, "cover-dismissed") + } + + @MainActor + func testBackgroundSendPushesOnMainActor() { + let app = launch() + tap(app, "Async Lab") + tap(app, "Simulate Background Async Push") + assertVisible(app, "Loaded from Network Actor", timeout: 8) + snapshot(app, "async-send-pushed") + } + + @MainActor + func testModifierRecipePropagatesRouterToPushedScreens() { + let app = launch() + tap(app, "Modifier") + tap(app, "Push Via Modifier") + XCTAssertTrue(app.staticTexts["modifierEnvDepth"].waitForExistence(timeout: 5), + "Pushed destination did not render (router missing from environment?)") + XCTAssertEqual(text(app, "modifierEnvDepth"), "Env router depth: 1") + + tap(app, "Push Another Via Env") + XCTAssertTrue(app.staticTexts["Env router depth: 2"].waitForExistence(timeout: 5)) + snapshot(app, "modifier-env-depth-2") + } + + @MainActor + func testModifierRecipePropagatesRouterToSheet() { + let app = launch() + tap(app, "Modifier") + tap(app, "Present Sheet Via Modifier") + XCTAssertTrue(app.staticTexts["modifierSheetEnv"].waitForExistence(timeout: 5), + "Sheet content did not render (router missing from environment?)") + XCTAssertEqual(text(app, "modifierSheetEnv"), "Modifier sheet has router: modifier-sheet") + snapshot(app, "modifier-sheet-env") + + tap(app, "Close Modifier Sheet") + XCTAssertTrue(app.buttons["Present Sheet Via Modifier"].waitForExistence(timeout: 5)) + } + + // MARK: - Boundary cases + + @MainActor + func testRapidDuplicatePushesCollapseToOne() { + let app = launch() + tap(app, "Async Lab") + tap(app, "Rapid Tap Stress Test (10x in 100ms)") + assertVisible(app, "Stress step 999") + snapshot(app, "rapid-tap-single-screen") + + // One back tap must return to the root: only one screen was pushed + app.navigationBars.buttons.element(boundBy: 0).tap() + XCTAssertTrue(app.staticTexts["labStackCount"].waitForExistence(timeout: 5)) + XCTAssertEqual(text(app, "labStackCount"), "Stack items: 0") + } + + @MainActor + func testDeepLinkBeyondMaxDepthIsTruncatedAndFurtherPushRejected() { + let app = launch() + tap(app, "Deep Link 35 Screens") + assertVisible(app, "Step Screen #30") + snapshot(app, "deep-link-truncated-at-30") + + // At maxDepth the push is rejected: still on step 30 + tap(app, "Push Step #31") + XCTAssertFalse(app.staticTexts["Step Screen #31"].waitForExistence(timeout: 2)) + XCTAssertTrue(app.staticTexts["Step Screen #30"].exists) + + tap(app, "Pop to Root") + XCTAssertTrue(app.staticTexts["lastResult"].waitForExistence(timeout: 5)) + XCTAssertEqual(text(app, "lastResult"), "Last result: deep link truncated") + XCTAssertEqual(text(app, "depthLabel"), "Current Stack Depth: 0 / 30") + } + + @MainActor + func testSheetIsRejectedWhileCoverIsPresented() { + let app = launch() + tap(app, "Present Full Screen Cover") + assertVisible(app, "Full Screen Cover: cover-1") + + tap(app, "Try Present Sheet From Same Router") + XCTAssertTrue(app.staticTexts["Sheet attempt: rejected"].waitForExistence(timeout: 5)) + XCTAssertFalse(app.staticTexts["Blocked"].waitForExistence(timeout: 2), "No sheet may appear over the cover") + XCTAssertTrue(app.staticTexts["Full Screen Cover: cover-1"].exists, "Cover must stay presented") + snapshot(app, "cover-rejects-sheet") + + tap(app, "Dismiss Cover") + XCTAssertTrue(app.staticTexts["depthLabel"].waitForExistence(timeout: 5)) + } + + // MARK: - Helpers + + @MainActor + private func launch() -> XCUIApplication { + let app = XCUIApplication() + app.launch() + return app + } + + @MainActor + private func tap(_ app: XCUIApplication, _ title: String, file: StaticString = #filePath, line: UInt = #line) { + let button = app.buttons[title].firstMatch + XCTAssertTrue(button.waitForExistence(timeout: 5), "Button '\(title)' not found", file: file, line: line) + button.tap() + } + + @MainActor + private func assertVisible(_ app: XCUIApplication, _ label: String, timeout: TimeInterval = 5, + file: StaticString = #filePath, line: UInt = #line) { + XCTAssertTrue(app.staticTexts[label].waitForExistence(timeout: timeout), "'\(label)' not shown", file: file, line: line) + } + + @MainActor + private func text(_ app: XCUIApplication, _ identifier: String) -> String { + app.staticTexts[identifier].label + } + + @MainActor + private func snapshot(_ app: XCUIApplication, _ name: String) { + let attachment = XCTAttachment(screenshot: app.screenshot()) + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + } +} diff --git a/README.md b/README.md index 7747637..5029e83 100644 --- a/README.md +++ b/README.md @@ -273,8 +273,6 @@ struct CustomRootView: View { cover: { cover in CoverView(cover: cover) } ) } - // Also inject on the stack so pushed destinations can read the router - .environment(router) } } ``` diff --git a/Sources/BaseNavigationStack/Modifiers/NavigationRouterModifier.swift b/Sources/BaseNavigationStack/Modifiers/NavigationRouterModifier.swift index 2409994..1eafa7b 100644 --- a/Sources/BaseNavigationStack/Modifiers/NavigationRouterModifier.swift +++ b/Sources/BaseNavigationStack/Modifiers/NavigationRouterModifier.swift @@ -12,7 +12,8 @@ public extension View { /// 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. + /// bind `path` itself. Pushed destinations, sheets, and covers all receive the router through the + /// environment. Use `BaseNavigationContainer` to get the stack and binding for free. @MainActor func navigationRouter< Route: Hashable & Sendable, @@ -28,9 +29,11 @@ public extension View { @ViewBuilder cover: @escaping (Cover) -> CoverContent ) -> some View { @Bindable var bindableRouter = router + // Pushed destinations take their environment from the NavigationStack, not from this view, + // so the router is injected into each destination. Sheets and covers inherit it from this view. return self .navigationDestination(for: Route.self) { route in - destination(route) + destination(route).environment(router) } .sheet(item: $bindableRouter.sheet) { sheetTarget in sheet(sheetTarget) diff --git a/docs/wiki/API-Modifiers-and-Helpers.md b/docs/wiki/API-Modifiers-and-Helpers.md index 7070994..7bf8b59 100644 --- a/docs/wiki/API-Modifiers-and-Helpers.md +++ b/docs/wiki/API-Modifiers-and-Helpers.md @@ -25,7 +25,7 @@ public extension View { } ``` -Attaches, in order: `.navigationDestination(for:)`, `.sheet(item:)`, `.fullScreenCover(item:)` (a second `.sheet` on macOS), and `.environment(router)`. +Attaches, in order: `.navigationDestination(for:)`, `.sheet(item:)`, `.fullScreenCover(item:)` (a second `.sheet` on macOS), and `.environment(router)`. The router is also injected into every pushed destination: pushed screens take their environment from the `NavigationStack`, not from the view that declares `navigationDestination`, so without this they could not read `@Environment(AppRouter.self)`. Sheets and covers inherit it from the presenting view. Apply it to the content **inside** the stack — `navigationDestination` must be declared within the `NavigationStack`, not on the stack itself. @@ -52,8 +52,6 @@ struct RootView: View { } ) } - // Also inject on the stack so pushed destinations can read the router - .environment(router) } } ``` diff --git a/scripts/check-binary-size.sh b/scripts/check-binary-size.sh new file mode 100755 index 0000000..69e2960 --- /dev/null +++ b/scripts/check-binary-size.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# +# scripts/check-binary-size.sh +# Measures how much BaseNavigationStack adds to a release app binary and fails above a budget. +# +# Builds two tiny macOS SwiftUI apps with -Osize and dead stripping: +# baseline: plain NavigationStack + sheet +# withlib: BaseNavigationContainer with the same routes +# and compares their stripped binary sizes. +# +# Usage: scripts/check-binary-size.sh [budget-bytes] (default 80000) + +set -euo pipefail + +BUDGET="${1:-80000}" +REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +WORK="$(mktemp -d -t bnssize.XXXXXX)" +trap 'rm -rf "${WORK}"' EXIT + +write_package() { + local dir="$1" deps="$2" target_deps="$3" + mkdir -p "${dir}/Sources/Probe" + cat > "${dir}/Package.swift" < "${WORK}/baseline/Sources/Probe/main.swift" <<'SWIFT' +import SwiftUI +enum Route: Hashable, Sendable { case a, b(Int) } +struct Item: Identifiable, Hashable, Sendable { let id: Int } +@MainActor @Observable final class Model { var path: [Route] = []; var sheet: Item?; var cover: Item? } +struct Root: View { + @State private var model = Model() + var body: some View { + NavigationStack(path: $model.path) { + Button("Go") { model.path.append(.a) } + .navigationDestination(for: Route.self) { Text(String(describing: $0)) } + .sheet(item: $model.sheet) { Text("\($0.id)") } + } + } +} +@main struct ProbeApp: App { var body: some Scene { WindowGroup { Root() } } } +SWIFT + +write_package "${WORK}/withlib" ".package(path: \"${REPO_DIR}\")" "\"BaseNavigationStack\"" +cat > "${WORK}/withlib/Sources/Probe/main.swift" <<'SWIFT' +import SwiftUI +import BaseNavigationStack +enum Route: Hashable, Sendable { case a, b(Int) } +struct Item: Identifiable, Hashable, Sendable { let id: Int } +struct Root: View { + @State private var router = NavigationRouter() + var body: some View { + BaseNavigationContainer(router: router) { + Button("Go") { router.push(.a) } + } destination: { Text(String(describing: $0)) } sheet: { Text("\($0.id)") } cover: { Text("\($0.id)") } + } +} +@main struct ProbeApp: App { var body: some Scene { WindowGroup { Root() } } } +SWIFT + +size_of() { + (cd "${WORK}/$1" && swift build -c release 2>&1 | grep -E "error|warning: " >&2 || true) + cp "${WORK}/$1/.build/release/Probe" "${WORK}/$1.bin" + strip -x "${WORK}/$1.bin" + stat -f %z "${WORK}/$1.bin" +} + +BASE=$(size_of baseline) +WITH=$(size_of withlib) +DELTA=$((WITH - BASE)) + +REPORT="Binary size cost of BaseNavigationStack (release, -Osize, dead-stripped, stripped): ${DELTA} bytes (baseline ${BASE}, with library ${WITH}, budget ${BUDGET})" +echo "${REPORT}" +if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then + echo "${REPORT}" >> "${GITHUB_STEP_SUMMARY}" +fi + +if [ "${DELTA}" -gt "${BUDGET}" ]; then + echo "::error::Library adds ${DELTA} bytes, over the ${BUDGET}-byte budget" + exit 1 +fi