From c746b0412602e69dca735da37278f534afc05635 Mon Sep 17 00:00:00 2001 From: iletai Date: Sun, 25 Oct 2026 21:27:10 +0700 Subject: [PATCH] docs: add comprehensive wiki, api guides, and showcase readme --- README.md | 362 +++++++++++++++++---- docs/wiki/API-BaseNavigationContainer.md | 149 +++++++++ docs/wiki/API-Modifiers-and-Helpers.md | 172 ++++++++++ docs/wiki/API-NavigationRouter.md | 185 +++++++++++ docs/wiki/Deep-Linking-and-URL-Handling.md | 116 +++++++ docs/wiki/Getting-Started.md | 106 ++++++ docs/wiki/Home.md | 42 +++ docs/wiki/Migration-Guide-v1-to-v2.md | 148 +++++++++ docs/wiki/Nested-and-Tab-Navigation.md | 110 +++++++ docs/wiki/Swift-6-Concurrency.md | 107 ++++++ docs/wiki/_Footer.md | 1 + docs/wiki/_Sidebar.md | 15 + scripts/sync-wiki.sh | 50 +++ 13 files changed, 1502 insertions(+), 61 deletions(-) create mode 100644 docs/wiki/API-BaseNavigationContainer.md create mode 100644 docs/wiki/API-Modifiers-and-Helpers.md create mode 100644 docs/wiki/API-NavigationRouter.md create mode 100644 docs/wiki/Deep-Linking-and-URL-Handling.md create mode 100644 docs/wiki/Getting-Started.md create mode 100644 docs/wiki/Home.md create mode 100644 docs/wiki/Migration-Guide-v1-to-v2.md create mode 100644 docs/wiki/Nested-and-Tab-Navigation.md create mode 100644 docs/wiki/Swift-6-Concurrency.md create mode 100644 docs/wiki/_Footer.md create mode 100644 docs/wiki/_Sidebar.md create mode 100755 scripts/sync-wiki.sh diff --git a/README.md b/README.md index e726ab7..860cea9 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,84 @@ -# BaseNavigationStack 2.0 +
-Modern, type-safe, data-driven navigation controller for SwiftUI (iOS 17+ & macOS 14+). +# BaseNavigationStack -[![Swift Version](https://img.shields.io/badge/Swift-6.0-orange.svg)](https://swift.org) -[![Platforms](https://img.shields.io/badge/Platforms-iOS%2017.0+%20%7C%20macOS%2014.0+-blue.svg)](https://developer.apple.com) -[![CI](https://github.com/iletai/BaseNavigationStack/actions/workflows/ci.yml/badge.svg)](https://github.com/iletai/BaseNavigationStack/actions) -[![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) +**Type-safe, data-driven navigation for SwiftUI. One source of truth. Zero external dependencies.** -`BaseNavigationStack` simplifies navigation in SwiftUI by centralizing Stack pushes, Sheet modals, and FullScreenCover transitions under a single `@MainActor @Observable` state manager with **zero external dependencies**. +[![Swift Version](https://img.shields.io/badge/Swift-6.0-F05138.svg?style=for-the-badge&logo=swift&logoColor=white)](https://swift.org) +[![Platforms](https://img.shields.io/badge/Platforms-iOS%2017%2B%20%7C%20macOS%2014%2B%20%7C%20tvOS%2017%2B%20%7C%20watchOS%2010%2B%20%7C%20visionOS%201%2B-007AFF.svg?style=for-the-badge&logo=apple&logoColor=white)](https://developer.apple.com) +[![Strict Concurrency](https://img.shields.io/badge/Swift%206-Strict%20Concurrency%20Complete-34C759.svg?style=for-the-badge)](https://www.swift.org/migration/documentation/swift-6-concurrency-migration-guide/) +[![Zero Dependencies](https://img.shields.io/badge/Dependencies-Zero-8E8E93.svg?style=for-the-badge)](#) +[![CI](https://img.shields.io/github/actions/workflow/status/iletai/BaseNavigationStack/ci.yml?branch=develop&style=for-the-badge&label=CI)](https://github.com/iletai/BaseNavigationStack/actions/workflows/ci.yml) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=for-the-badge)](LICENSE) ---- +[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). + +
+ +## Why BaseNavigationStack? + +SwiftUI's built-in navigation is powerful, but state tends to sprawl across views. `BaseNavigationStack` unifies **push**, **sheet**, and **full screen cover** transitions under a single, observable router — keeping navigation predictable, testable, and safe under concurrency. + +## Comparison + +| Aspect | Vanilla SwiftUI Navigation | **BaseNavigationStack 2.0** | +| --- | --- | --- | +| **State ownership** | Scattered `@State` / bindings across views | **Single Source of Truth** via `NavigationRouter` | +| **Modal + Stack** | Managed separately with easy desync | **Unified** `path`, `sheet`, `cover` in one router | +| **Type-safety** | Manual `navigationDestination` wiring, error-prone routes | **Strongly typed** `Route`, `Sheet`, `Cover` (`Hashable & Sendable`) | +| **Race conditions** | Double-taps can push duplicates | **Auto-debounce** guards against immediate duplicate pushes | +| **Deep linking / programmatic nav** | Hard to coordinate across the tree | **Centralized API**: `push`, `pop`, `popToRoot`, `present`, `dismiss`, `replacePath` | +| **Concurrency** | Easy to call from wrong isolation | **Swift 6 ready** — `@MainActor` + `send(_:)` for safe cross-actor dispatch | +| **Testability** | Often requires UI tests | **Headless-testable** — inspect pure `[Route]` arrays with no UI overhead | +| **Nested flows** | Complex and easy to leak state | **Isolated sub-routers** per sheet/tab with independent lifecycles | + +## Architecture + +```text +┌─────────────────────────────────────────────────────────────────────────────┐ +│ BaseNavigationContainer │ +│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌───────────────────┐ │ +│ │ NavigationStack│ │ navigationDestination │ │ sheet(item:) │ │ fullScreenCover │ │ +│ │ (path) │ │ (Route) │ │ (Sheet) │ │ (Cover, iOS/tvOS/ │ │ +│ └─────────────┘ └─────────────┘ └─────────────┘ │ visionOS/watchOS)│ │ +└─────────────────────────────────────────────────────────────────────────────┘ + │ injects .environment(router) + ▼ +┌─────────────────────────────────────────────────────────────────────────────┐ +│ NavigationRouter │ +│ path: [Route] │ sheet: Sheet? │ cover: Cover? │ maxDepth: Int │ +│ push / pop / popToRoot / replacePath / present / dismiss / dismissModals │ +│ send(_:) for actor-safe dispatch │ debounce + depth guard │ +└─────────────────────────────────────────────────────────────────────────────┘ + │ + ▼ + Any View via @Environment +``` + +**Flow:** `Route Push` → **Debounce/Depth Guard** → `NavigationStack` → `navigationDestination` → `Sheet` / `FullScreenCover` → **Deep Link** via central router/state. ## Features -- **Swift 6 Strict Concurrency**: Fully isolated on `@MainActor` with Sendable checks enabled. -- **Unified Control**: Manage `path`, `sheet`, and `cover` from a single router without fragmented `@State` variables. -- **Race Condition Guard**: Automatic debounce for rapid taps prevents duplicated pushes. -- **Testable**: Pure Swift arrays (`[Route]`) allow inspecting the full navigation stack in unit tests with zero UI test overhead. -- **Nested Navigation Ready**: Support isolated routers per Tab and independent sub-routers inside Sheet modals. +- **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. +- **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. +- **Backward Compatible (v1.x)** — `BaseNavigationStack` remains supported with fixes for `dismiss()`, `replaceNavigationStack(path:)`, and `@Bindable` compatibility. + +## Quickstart ---- +### 1) Add the package -## Installation +**Swift Package Manager** -Add `BaseNavigationStack` to your `Package.swift`: +Add to your `Package.swift`: ```swift dependencies: [ @@ -34,18 +89,16 @@ targets: [ ] ``` ---- - -## Usage (Modern 2.0 API) +Or in Xcode: `File > Add Package Dependencies...` and paste the repo URL. -### 1. Define Routes +### 2) Define type-safe routes ```swift import Foundation enum AppRoute: Hashable, Sendable { case detail(id: Int) - case profile + case profile(userID: String) } struct AppSheet: Identifiable, Hashable, Sendable { @@ -55,78 +108,265 @@ struct AppSheet: Identifiable, Hashable, Sendable { struct AppCover: Identifiable, Hashable, Sendable { let id: String } + +typealias AppRouter = NavigationRouter ``` -### 2. Setup Container View +### 3) Wire up the container ```swift import SwiftUI import BaseNavigationStack -typealias AppRouter = NavigationRouter - -struct RootContentView: View { +struct RootView: View { @State private var router = AppRouter() var body: some View { - NavigationStack(path: $router.path) { - HomeView() - .navigationDestination(for: AppRoute.self) { route in - switch route { - case .detail(let id): - Text("Detail \(id)") - case .profile: - Text("User Profile") - } - } - .sheet(item: $router.sheet) { sheet in - Text("Sheet: \(sheet.id)") + BaseNavigationContainer( + router: router, + content: { + HomeView() + }, + destination: { route in + switch route { + case .detail(let id): + DetailView(id: id) + case .profile(let userID): + ProfileView(userID: userID) } - .fullScreenCover(item: $router.cover) { cover in - Text("Cover: \(cover.id)") - } - } - .environment(router) + }, + sheet: { sheet in + LoginSheet(id: sheet.id) + }, + cover: { cover in + OnboardingCover(id: cover.id) + } + ) } } ``` -### 3. Navigate Programmatically +> **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 ```swift +import SwiftUI +import BaseNavigationStack + struct HomeView: View { @Environment(AppRouter.self) private var router var body: some View { VStack(spacing: 16) { - Button("Push Detail") { - router.push(.detail(id: 42)) - } - Button("Present Sheet") { - router.present(sheet: AppSheet(id: "login")) - } - Button("Pop Back") { - router.pop() + Button("Push Detail") { router.push(.detail(id: 42)) } + Button("Present Sheet") { router.present(sheet: AppSheet(id: "login")) } + Button("Present Full Screen Cover") { router.present(cover: AppCover(id: "onboarding")) } + Button("Pop") { router.pop() } + Button("Pop to Root") { router.popToRoot() } + Button("Dismiss (Sheet/Cover/Stack)") { router.dismiss() } + } + .navigationTitle("Home") + } +} +``` + +## Advanced Recipes + +### Tab Navigation with Isolated Routers + +Keep each tab's stack independent. Dismissing/modals in one tab won't affect others. + +```swift +struct TabRootView: View { + @State private var homeRouter = AppRouter() + @State private var searchRouter = AppRouter() + + var body: some View { + TabView { + BaseNavigationContainer(router: homeRouter) { + HomeView() + } destination: { HomeDestination($0) } + .tabItem { Label("Home", systemImage: "house") } + + BaseNavigationContainer(router: searchRouter) { + SearchView() + } destination: { SearchDestination($0) } + .tabItem { Label("Search", systemImage: "magnifyingglass") } + } + } +} +``` + +### Sheet with its own Sub-Router + +Perfect for multi-step flows inside a modal without polluting the parent stack. + +```swift +struct FlowSheetView: View { + @State private var subRouter = AppRouter() + @Environment(AppRouter.self) private var parentRouter + + var body: some View { + BaseNavigationContainer( + router: subRouter, + content: { SheetStartView() }, + destination: { route in + switch route { + case .detail(let id): SheetDetailView(id: id) + case .profile(let userID): SheetProfileView(userID: userID) + } } - Button("Pop to Root") { - router.popToRoot() + ) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Done") { parentRouter.dismiss() } } } } } ``` ---- +### Deep Linking / Async Navigation + +Use `send(_:)` to navigate safely from async work or background actors. + +```swift +func handleDeepLink(_ url: URL) async { + // Parse route from URL... + let route = AppRoute.detail(id: 123) + + await MainActor.run { + router.push(route) + } + + // Or from a detached task/actor: + Task.detached { + router.send { r in + r.popToRoot() + r.push(.profile(userID: "u_123")) + } + } +} +``` + +### Attach to an Existing NavigationStack + +```swift +struct CustomRootView: View { + @State private var router = AppRouter() + + var body: some View { + NavigationStack(path: $router.path) { + ContentView() + .navigationRouter( + router, + destination: { route in DestinationView(route: route) }, + sheet: { sheet in SheetView(sheet: sheet) }, + cover: { cover in CoverView(cover: cover) } + ) + } + } +} +``` + +## API Cheat Sheet + +### `NavigationRouter` + +| Method / Property | Type | Description | Complexity | +| --- | --- | --- | --- | +| `init(initialPath:initialSheet:initialCover:maxDepth:)` | Initializer | Create router with optional initial state. `maxDepth` clamped to >= 1 (default `30`). | O(1) | +| `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) | +| `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) | +| `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 | + +### `BaseNavigationContainer` + +| Initializer | Notes | +| --- | --- | +| `init(router:content:destination:sheet:cover:)` | Full container: wraps `NavigationStack`, `navigationDestination`, `.sheet`, `.fullScreenCover` (platform-aware), injects `.environment(router)`. | +| `init(router:content:destination:)` where `SheetContent == EmptyView`, `CoverContent == EmptyView` | Stack-only convenience initializer. | + +### `View.navigationRouter(_:)` + +| Overload | Notes | +| --- | --- | +| `navigationRouter(_:destination:sheet:cover:)` | Attach routing to an existing view/hierarchy. Use inside your own `NavigationStack(path:)`. Injects `.environment(router)`. | +| `navigationRouter(_:destination:)` | Stack-only convenience overload. | + +### Legacy (v1.x) — `BaseNavigationStack` + +| Method | Notes | +| --- | --- | +| `pushToView(_:)` | Debounced push with duplicate prevention. | +| `popBack()` | Safe pop via `removeLastSafe()`. | +| `navigateToRoot()` | Clears modals and stack. | +| `replaceNavigationStack(path:)` | Replaces path and clears modals. | +| `presentSheet(_:)` / `presentFullScreen(_:)` | Modal presentation. | +| `dismiss()` | Sheet → FullScreen → Stack → parent binding fallback. | +| `handleOpenURL(url:)` | Route via optional `urlHandler`. | + +## Example App + +Explore a live, interactive showcase in [`NavigationStackExample/`](NavigationStackExample/). + +**Tabs included:** + +- **Stack Explorer** — Push/pop, breadcrumb trail, depth counter, present sheet/cover, pop to root. +- **Async & Concurrency Lab** — Background async navigation via `send(_:)`, rapid-tap stress test to verify debounce/guards. + +Run it in Xcode by opening `NavigationStackExample/NavigationStackExample.xcodeproj` or via the scheme in your workspace. + +## Testing + +Run the full test suite: + +```bash +# With SwiftPM +swift test + +# With coverage +swift test --enable-code-coverage + +# iOS Simulator (example from CI) +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}") +xcodebuild test -scheme BaseNavigationStack -destination "id=$SIM_ID" CODE_SIGNING_ALLOWED=NO +``` + +**Coverage includes:** push/pop/popToRoot/replace, duplicate-debounce, dismiss ladder, stack depth guard, async `send` from background, nested sub-routers, tab isolation, container/modifier initialization. + +## Docs & Wiki + +- **Design Specs:** [`docs/superpowers/specs/`](docs/superpowers/specs/) — Container, async ergonomics, performance goals. +- **Implementation Plans:** [`docs/superpowers/plans/`](docs/superpowers/plans/) — Step-by-step rollout notes. +- **GitHub Wiki:** [BaseNavigationStack Wiki](https://github.com/iletai/BaseNavigationStack/wiki) — Extended guides, migration notes, and FAQs (if enabled). +- **Issues:** [Report bugs / request features](https://github.com/iletai/BaseNavigationStack/issues) +- **Discussions:** [Community Q&A](https://github.com/iletai/BaseNavigationStack/discussions) + +## Contributing -## Backward Compatibility (v1.x) +Contributions are welcome! -If upgrading from v1.x, `BaseNavigationStack` remains supported with all logic bugs resolved: -- `dismiss()` now correctly pops single-screen stacks. -- `replaceNavigationStack(path:)` cleanly resets active modals. -- Full compatibility with SwiftUI `@Bindable`. +1. **Fork** the repo and create a feature branch off `develop`. +2. **Follow style** — Match existing Swift style; CI runs `swiftlint --strict`. +3. **Test** — Add/update tests for behavior changes. Run `swift test` locally. +4. **Commit** — Use clear, conventional commits (`feat:`, `fix:`, `refactor:`, `test:`, `docs:`). +5. **Open a PR** — Target `develop` with a concise description and test notes. ---- +See [`.github/PULL_REQUEST_TEMPLATE.md`](.github/PULL_REQUEST_TEMPLATE.md) and [`.github/ISSUE_TEMPLATE/`](.github/ISSUE_TEMPLATE/) for details. ## License -This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. +Released under the [MIT License](LICENSE). Copyright (c) 2023 Tài Lê. diff --git a/docs/wiki/API-BaseNavigationContainer.md b/docs/wiki/API-BaseNavigationContainer.md new file mode 100644 index 0000000..c0590bc --- /dev/null +++ b/docs/wiki/API-BaseNavigationContainer.md @@ -0,0 +1,149 @@ +# API — BaseNavigationContainer + +Declarative container that wires a `NavigationRouter` into a SwiftUI `NavigationStack`, destination mapping, sheet and full screen cover. + +## Signature + +```swift +public struct BaseNavigationContainer< + Route: Hashable & Sendable, + Sheet: Identifiable & Hashable & Sendable, + Cover: Identifiable & Hashable & Sendable, + Content: View, + Destination: View, + SheetContent: View, + CoverContent: View +>: View +``` + +Generic parameters: + +| Parameter | Role | +|---|---| +| `Route` | Destination type pushed onto `NavigationStack` | +| `Sheet` | Identifiable model driving `.sheet(item:)` | +| `Cover` | Identifiable model driving `.fullScreenCover(item:)` | +| `Content` | Root view inside the stack | +| `Destination` | View built from a `Route` | +| `SheetContent` | View built from a `Sheet` | +| `CoverContent` | View built from a `Cover` | + +SwiftUI infers the five view generics from the closures — you only name the three model types on the router. + +## Full initializer + +```swift +public init( + router: NavigationRouter, + @ViewBuilder content: @escaping () -> Content, + @ViewBuilder destination: @escaping (Route) -> Destination, + @ViewBuilder sheet: @escaping (Sheet) -> SheetContent, + @ViewBuilder cover: @escaping (Cover) -> CoverContent +) +``` + +```swift +@State private var router = AppRouter() + +BaseNavigationContainer( + router: router, + content: { HomeView() }, + destination: { route in DestinationView(route: route) }, + sheet: { sheet in SheetView(sheet: sheet) }, + cover: { cover in CoverView(cover: cover) } +) +``` + +## Default initializer (no modals) + +When `SheetContent == EmptyView` and `CoverContent == EmptyView`, this convenience initializer exists: + +```swift +public init( + router: NavigationRouter, + @ViewBuilder content: @escaping () -> Content, + @ViewBuilder destination: @escaping (Route) -> Destination +) +``` + +```swift +BaseNavigationContainer( + router: router, + content: { HomeView() }, + destination: { route in DestinationView(route: route) } +) +``` + +You still declare `Sheet`/`Cover` types on the router (partial application with `EmptyView` is not possible), but they are never presented. To avoid declaring dummy types, see the `navigationRouter(_:destination:)` modifier in [[API-Modifiers-and-Helpers]] — it also requires the three types, so the practical minimal setup is small empty `Identifiable` structs: + +```swift +struct NoSheet: Identifiable, Hashable, Sendable { let id = UUID() } +struct NoCover: Identifiable, Hashable, Sendable { let id = UUID() } + +typealias AppRouter = NavigationRouter +``` + +## Conditional compilation + +`fullScreenCover` does not exist on macOS. The container branches at compile time: + +```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) } +} +.environment(router) +#else +NavigationStack(path: $router.path) { + content() + .navigationDestination(for: Route.self) { destination($0) } + .sheet(item: $router.sheet) { sheetContent($0) } +} +.environment(router) +#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. + +## Behavior notes + +- Router is stored as `@Bindable`, so `$router.path`, `$router.sheet`, `$router.cover` drive SwiftUI directly. +- `.environment(router)` is applied to the stack — every pushed destination, sheet, and cover can read it with `@Environment(AppRouter.self)`. +- Modals are attached **inside** the `NavigationStack`; a sheet presented from a pushed screen still closes when the router's `sheet` becomes `nil`. +- The container does not own the router. Create it with `@State` in the parent so it survives view re-creation. + +## Complete example + +```swift +struct RootView: View { + @State private var router = AppRouter() + + var body: some View { + BaseNavigationContainer( + router: router, + content: { HomeView() }, + destination: { route in + switch route { + case .detail(let id): DetailView(id: id) + case .profile: ProfileView() + } + }, + sheet: { sheet in + SheetView(sheet: sheet) + .presentationDetents([.medium, .large]) + }, + cover: { cover in + CoverView(cover: cover) + .ignoresSafeArea() + } + ) + } +} +``` diff --git a/docs/wiki/API-Modifiers-and-Helpers.md b/docs/wiki/API-Modifiers-and-Helpers.md new file mode 100644 index 0000000..8b6c238 --- /dev/null +++ b/docs/wiki/API-Modifiers-and-Helpers.md @@ -0,0 +1,172 @@ +# API — Modifiers & Helpers + +## `.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. + +### Full form + +```swift +public extension View { + @MainActor @ViewBuilder + func navigationRouter< + Route: Hashable & Sendable, + Sheet: Identifiable & Hashable & Sendable, + Cover: Identifiable & Hashable & Sendable, + Destination: View, + SheetContent: View, + CoverContent: View + >( + _ router: NavigationRouter, + @ViewBuilder destination: @escaping (Route) -> Destination, + @ViewBuilder sheet: @escaping (Sheet) -> SheetContent, + @ViewBuilder cover: @escaping (Cover) -> CoverContent + ) -> some View +} +``` + +Attaches, in order: `.navigationDestination(for:)`, `.sheet(item:)`, `.fullScreenCover(item:)` (iOS/tvOS/watchOS/visionOS only), and `.environment(router)`. + +```swift +struct RootView: View { + @State private var router = AppRouter() + + 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) + } + ) + } +} +``` + +### Stack-only overload + +```swift +func navigationRouter( + _ router: NavigationRouter, + @ViewBuilder destination: @escaping (Route) -> Destination +) -> 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. + +## `BaseViewProtocol` + +v1 contract: a screen model that declares its own destinations. + +```swift +public protocol BaseViewProtocol: Identifiable, Hashable, Sendable { + associatedtype PresentSheetScreenView: View + associatedtype DestinationView: View + associatedtype PresentFullScreenView: View + + @MainActor @ViewBuilder func withNavigationDestination() -> DestinationView + @MainActor @ViewBuilder func withSheetDestination() -> PresentSheetScreenView + @MainActor @ViewBuilder func withFullScreenDestination() -> PresentFullScreenView +} +``` + +Example (from the demo app): + +```swift +enum ViewNavigationTarget: BaseViewProtocol { + case splash + case list + case policy(URL) + + var id: String { /* stable identity */ } + + @MainActor func withNavigationDestination() -> some View { + switch self { + case .policy: PolicyView() + case .list: ListView() + case .splash: SplashView() + } + } + + @MainActor func withSheetDestination() -> some View { /* ... */ } + @MainActor func withFullScreenDestination() -> some View { /* ... */ } +} +``` + +New code should prefer v2 routes (`Hashable & Sendable` enum + `destination:` closures) — views are mapped once in the container instead of on every model case. See [[Migration-Guide-v1-to-v2]]. + +## Legacy v1: `BaseNavigationStack` + +```swift +@MainActor @Observable +public final class BaseNavigationStack: @unchecked Sendable + where ScreenView: BaseViewProtocol +``` + +Kept for backward compatibility. Public surface: + +| Member | Behavior | +|---|---| +| `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. | +| `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`. | +| `navigationPath` / `presentingSheet` / `presentingFullScreen` / `isPresented` | `Binding` accessors. | + +```swift +typealias BaseNavigation = BaseNavigationStack + +let nav = BaseNavigation() +nav.pushToView(.list) +nav.popBack() +nav.dismiss() +``` + +v1 fixes shipped in 2.0: `dismiss()` now pops single-screen stacks; `replaceNavigationStack(path:)` resets active modals. diff --git a/docs/wiki/API-NavigationRouter.md b/docs/wiki/API-NavigationRouter.md new file mode 100644 index 0000000..c8384af --- /dev/null +++ b/docs/wiki/API-NavigationRouter.md @@ -0,0 +1,185 @@ +# API — NavigationRouter + +```swift +@MainActor @Observable +public final class NavigationRouter< + Route: Hashable & Sendable, + Sheet: Identifiable & Hashable & Sendable, + Cover: Identifiable & Hashable & Sendable +>: @unchecked Sendable +``` + +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)`. | + +## Initializer + +```swift +public init( + initialPath: [Route] = [], + initialSheet: Sheet? = nil, + initialCover: Cover? = nil, + maxDepth: Int = 30 +) +``` + +```swift +let router = NavigationRouter() +let deepLink = NavigationRouter( + initialPath: [.profile, .detail(id: 7)] +) +let shallow = NavigationRouter(maxDepth: 5) +``` + +## Stack operations + +### `push(_:)` + +```swift +public func push(_ route: Route) +``` + +- 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. +- Equality is the route's `Hashable`/`Equatable` conformance — for enum routes with associated values, same case + same values means duplicate. + +```swift +router.push(.detail(id: 42)) // path == [.detail(id: 42)] +router.push(.detail(id: 42)) // ignored — duplicate of top +router.push(.detail(id: 43)) // pushed +``` + +Note: only the *top* is compared. Pushing A → B → A is allowed. + +### `pop()` + +```swift +public func pop() +``` + +Pops topmost screen. No-op on empty path. + +### `pop(count:)` + +```swift +public func pop(count: Int) +``` + +Pops up to `count` screens: `min(count, path.count)`. Ignores non-positive counts. Over-run empties the stack safely. + +```swift +router.pop(count: 2) // remove 2 +router.pop(count: 99) // empty the stack +``` + +### `popToRoot()` + +```swift +public func popToRoot() +``` + +Clears `path`, `sheet`, and `cover`. Full reset to root. + +### `replacePath(_:)` + +```swift +public func replacePath(_ newPath: [Route]) +``` + +Replaces the whole stack (e.g. auth switch, deep-link jump) and dismisses any active sheet/cover. Truncates to `maxDepth` via `prefix(maxDepth)`. + +```swift +router.replacePath([.profile]) // sheet/cover nil, path == [.profile] +``` + +## Modal operations + +### `present(sheet:)` + +```swift +public func present(sheet: Sheet) +``` + +Sets `sheet`. Setting a new value while one is presented replaces it. + +### `present(cover:)` + +```swift +public func present(cover: Cover) +``` + +Sets `cover`. On iOS/tvOS/watchOS/visionOS rendered as `.fullScreenCover(item:)`. + +### `dismiss()` + +```swift +public func dismiss() +``` + +Ladder, first match wins: + +1. `sheet != nil` → clear sheet. +2. `cover != nil` → clear cover. +3. else → pop one screen. +4. else → no-op. + +Use this for a generic "back/close" button that works from any context. + +### `dismissModals()` + +```swift +public func dismissModals() +``` + +Clears `sheet` and `cover` without touching `path`. + +## Background dispatch + +### `send(_:)` + +```swift +nonisolated public func send(_ action: @escaping @MainActor (NavigationRouter) -> Void) +``` + +Safe entry point from non-main actors. Wraps the mutation in `Task { @MainActor in ... }`. + +```swift +Task.detached { + let user = try await api.fetchUser() + router.send { r in + r.push(.profile(user)) + } +} +``` + +`send` itself is `nonisolated`, so it can be called from any context. The closure runs on the main actor; `self` is captured safely. + +## Threading and `maxDepth` guard + +- All mutable access is `@MainActor` isolated. There is no internal lock; correctness comes from actor isolation. +- `maxDepth` prevents runaway stacks (and SwiftUI layout warnings) from loops or repeated deep links. It applies to `push` and `replacePath`; `pop` etc. always allowed. + +## Test example + +```swift +@MainActor +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.path == [.profile, .detail(id: 1)]) + + router.pop(count: 10) + assert(router.path.isEmpty) +} +``` diff --git a/docs/wiki/Deep-Linking-and-URL-Handling.md b/docs/wiki/Deep-Linking-and-URL-Handling.md new file mode 100644 index 0000000..1c88cbb --- /dev/null +++ b/docs/wiki/Deep-Linking-and-URL-Handling.md @@ -0,0 +1,116 @@ +# Deep Linking & URL Handling + +Core idea: parse URL → `[Route]` → `replacePath(_:)`. The router is plain data, so deep linking is just constructing an array. + +## 1. Define URL scheme / universal links + +Info.plist (`CFBundleURLTypes`) for custom scheme: + +```xml +CFBundleURLTypes + + + CFBundleURLSchemes + myapp + + +``` + +For universal links, add the Associated Domains entitlement: `applinks:example.com`. + +## 2. Map URL path to `[AppRoute]` + +```swift +enum AppRoute: Hashable, Sendable { + case home + case detail(id: Int) + case profile +} + +struct AppDeepLink { + static func routes(from url: URL) -> [AppRoute] { + guard url.scheme == "myapp" || url.host == "example.com" else { + return [] + } + let parts = url.pathComponents.filter { $0 != "/" } + switch parts.first { + case "home": + return [.home] + case "detail": + guard parts.count >= 2, let id = Int(parts[1]) else { return [.home] } + return [.home, .detail(id: id)] + case "profile": + return [.home, .profile] + default: + return [] + } + } +} +``` + +`myapp://detail/42` → `[.home, .detail(id: 42)]`. + +## 3. Apply on launch and on open + +```swift +@main +struct MyApp: App { + @State private var router = AppRouter() + + var body: some Scene { + WindowGroup { + RootView(router: router) + .onOpenURL { url in + let routes = AppDeepLink.routes(from: url) + guard !routes.isEmpty else { return } + router.replacePath(routes) + } + .onAppear { + if let url = URL(string: "myapp://home") { + router.replacePath(AppDeepLink.routes(from: url)) + } + } + } + } +} +``` + +`replacePath` clears any active sheet/cover and truncates to `maxDepth` — 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). + +## 4. Redirect to a modal + +```swift +static func apply(url: URL, router: AppRouter) { + switch url.pathComponents.filter({ $0 != "/" }).first { + case "paywall": + router.present(sheet: AppSheet(id: "paywall")) + default: + router.replacePath(routes(from: url)) + } +} +``` + +## Legacy v1 `urlHandler` + +v1 `BaseNavigationStack` exposes a handler hook: + +```swift +typealias BaseNavigation = BaseNavigationStack + +let nav = BaseNavigation() +nav.urlHandler = { url in + nav.pushToView(.policy(url)) + return .handled +} + +// Somewhere in the view: +.onOpenURL { _ = nav.handleOpenURL(url: $0) } +``` + +Return `.systemAction` (default) to let SwiftUI handle the URL normally, `.handled` to consume it. + +## iOS scene phase / sceneDelegate delivery + +If your app uses `Scene` with `WindowGroup`, `onOpenURL` covers both cold and warm launches. For UIKit-forward apps, forward `application(_:open:options:)` into the same `router.replacePath(AppDeepLink.routes(from: url))` call. diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md new file mode 100644 index 0000000..a470032 --- /dev/null +++ b/docs/wiki/Getting-Started.md @@ -0,0 +1,106 @@ +# Getting Started + +## 1. Install (SPM) + +Add to your `Package.swift`: + +```swift +dependencies: [ + .package(url: "https://github.com/iletai/BaseNavigationStack.git", from: "2.0.0") +], +targets: [ + .target(name: "YourTarget", dependencies: ["BaseNavigationStack"]) +] +``` + +Or in Xcode: **File → Add Package Dependencies…** → `https://github.com/iletai/BaseNavigationStack.git`. + +Platforms: iOS 17.0+, macOS 14.0+. Swift tools 6.0. + +## 2. Define your Route enum + +```swift +import Foundation + +enum AppRoute: Hashable, Sendable { + case detail(id: Int) + case profile +} + +struct AppSheet: Identifiable, Hashable, Sendable { + let id: String +} + +struct AppCover: Identifiable, Hashable, Sendable { + let id: String +} + +typealias AppRouter = NavigationRouter +``` + +`Route` needs `Hashable & Sendable`. Sheets and covers additionally need `Identifiable` (SwiftUI `.sheet(item:)` requirement). + +## 3. Mount the container + +```swift +import SwiftUI +import BaseNavigationStack + +struct RootView: View { + @State private var router = AppRouter() + + var body: some View { + BaseNavigationContainer( + router: router, + content: { + HomeView() + }, + destination: { route in + switch route { + case .detail(let id): + Text("Detail \(id)") + case .profile: + Text("User Profile") + } + }, + sheet: { sheet in + Text("Sheet: \(sheet.id)") + }, + cover: { cover in + Text("Cover: \(cover.id)") + } + ) + } +} +``` + +No sheet/cover? Use the default initializer (see [[API-BaseNavigationContainer]]): + +```swift +BaseNavigationContainer( + router: router, + content: { HomeView() }, + destination: { route in /* ... */ } +) +``` + +## 4. Navigate from any child view + +The container injects the router via `.environment(router)`, so descendants read it with `@Environment`: + +```swift +struct HomeView: View { + @Environment(AppRouter.self) private var router + + var body: some View { + VStack(spacing: 16) { + Button("Push Detail") { router.push(.detail(id: 42)) } + Button("Present Sheet") { router.present(sheet: AppSheet(id: "login")) } + Button("Pop") { router.pop() } + Button("Pop to Root") { router.popToRoot() } + } + } +} +``` + +Full API: [[API-NavigationRouter]]. diff --git a/docs/wiki/Home.md b/docs/wiki/Home.md new file mode 100644 index 0000000..545ea1a --- /dev/null +++ b/docs/wiki/Home.md @@ -0,0 +1,42 @@ +# BaseNavigationStack 2.0 + +Modern, type-safe, data-driven navigation for SwiftUI (iOS 17+ / macOS 14+, Swift 6). + +`BaseNavigationStack` unifies Stack pushes, Sheets, and FullScreenCovers under a single `@MainActor @Observable` router — no fragmented `@State`, no external dependencies. + +## Goals + +- **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`. +- **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. +- **Nested ready** — independent routers per Tab and per modal. + +## Design philosophy + +1. Data-driven: navigation state is data, SwiftUI renders it. Programmatic navigation == mutate an array. +2. Type-safe routes: `Route: Hashable & Sendable`, no string identifiers. +3. Safe by default: `pop()` on empty stack, `pop(count:)` over-run, duplicate pushes — all no-ops instead of crashes. +4. Testable: router logic is pure Swift, exercised in `Tests/BaseNavigationStackTests`. + +## Architecture + +``` +NavigationRouter ← state (@Observable, @MainActor) + │ +BaseNavigationContainer ← declarative view (NavigationStack + destinations + modals) + │ +View.navigationRouter(...) ← modifier alternative for custom stacks +``` + +## Pages + +- [[Getting-Started]] — install + first router in 3 steps +- [[API-NavigationRouter]] — full router API +- [[API-BaseNavigationContainer]] — container view +- [[API-Modifiers-and-Helpers]] — modifiers, collection helpers, v1 layer +- [[Deep-Linking-and-URL-Handling]] +- [[Nested-and-Tab-Navigation]] +- [[Swift-6-Concurrency]] +- [[Migration-Guide-v1-to-v2]] diff --git a/docs/wiki/Migration-Guide-v1-to-v2.md b/docs/wiki/Migration-Guide-v1-to-v2.md new file mode 100644 index 0000000..870fab5 --- /dev/null +++ b/docs/wiki/Migration-Guide-v1-to-v2.md @@ -0,0 +1,148 @@ +# Migration Guide — v1 → v2 + +v1 bound navigation logic to each screen (`BaseViewProtocol`). v2 splits **state** (`NavigationRouter`) from **mapping** (container closures). v1 still compiles — migrate incrementally, screen by screen. + +## Mapping table + +| v1 | v2 | +|---|---| +| `BaseNavigationStack` | `NavigationRouter` | +| `BaseViewProtocol` screen model | plain `Hashable & Sendable` route enum | +| `withNavigationDestination()` on every case | one `destination:` closure in container | +| `withSheetDestination()` | `sheet:` closure | +| `withFullScreenDestination()` | `cover:` closure | +| `pushToView(_:)` | `push(_:)` | +| `popBack()` | `pop()` | +| `navigateToRoot()` | `popToRoot()` | +| `replaceNavigationStack(path:)` | `replacePath(_:)` | +| `presentSheet(_:)` | `present(sheet:)` | +| `presentFullScreen(_:)` | `present(cover:)` | +| `dismiss()` | `dismiss()` (same ladder) | +| `navigationPath` binding | `router.path` (`$router.path` via `@Bindable`) | +| `presentingSheet`, `presentingFullScreen` | `router.sheet`, `router.cover` | +| `urlHandler` | `onOpenURL` / `handleOpenURL` equivalent mapping to `replacePath` | + +## Before (v1) + +```swift +enum Screen: BaseViewProtocol { + case list + case policy(URL) + + var id: String { /* ... */ } + + @MainActor func withNavigationDestination() -> some View { + switch self { + case .list: ListView() + case .policy: PolicyView() + } + } + // withSheetDestination(), withFullScreenDestination() ... +} + +typealias BaseNavigation = BaseNavigationStack + +struct RootView: View { + @State private var nav = BaseNavigation() + + var body: some View { + NavigationStack(path: nav.navigationPath) { + HomeView() + .navigationDestination(for: Screen.self) { screen in + screen.withNavigationDestination() + } + .sheet(item: nav.presentingSheet) { $0.withSheetDestination() } + .fullScreenCover(item: nav.presentingFullScreen) { $0.withFullScreenDestination() } + } + .environment(nav) + } +} + +struct HomeView: View { + @Environment(BaseNavigation.self) private var nav + var body: some View { + Button("Policy") { nav.pushToView(.policy(url)) } + Button("Back") { nav.popBack() } + } +} +``` + +## After (v2) + +```swift +enum AppRoute: Hashable, Sendable { + case list + case policy(URL) +} + +struct AppSheet: Identifiable, Hashable, Sendable { let id: String } +struct AppCover: Identifiable, Hashable, Sendable { let id: String } + +typealias AppRouter = NavigationRouter + +struct RootView: View { + @State private var router = AppRouter() + + var body: some View { + BaseNavigationContainer( + router: router, + content: { HomeView() }, + destination: { route in + switch route { + case .list: ListView() + case .policy(let url): PolicyView(url: url) + } + }, + sheet: { sheet in SheetView(id: sheet.id) }, + cover: { cover in CoverView(id: cover.id) } + ) + } +} + +struct HomeView: View { + @Environment(AppRouter.self) private var router + var body: some View { + Button("Policy") { router.push(.policy(url)) } + Button("Back") { router.pop() } + } +} +``` + +## Step-by-step + +1. Extract each v1 screen case into a route enum case. Move payloads into associated values (`policy(URL)` stays `policy(URL)`); the old `id` property becomes unnecessary. +2. Replace `with*Destination()` switches with a single `destination:` closure in the container. Delete `BaseViewProtocol` conformance. +3. Rename calls: + - `pushToView(x)` → `push(x)` + - `popBack()` → `pop()` + - `navigateToRoot()` → `popToRoot()` + - `replaceNavigationStack(path:)` → `replacePath(_:)` + - `presentSheet(x)` / `presentFullScreen(x)` → `present(sheet:)` / `present(cover:)` +4. Replace `@Environment(BaseNavigation.self)` with `@Environment(AppRouter.self)`; update the typealias. +5. Replace `NavigationStack(path: nav.navigationPath)` + manual `.navigationDestination/.sheet/.fullScreenCover` chains with `BaseNavigationContainer` (or `.navigationRouter(...)`). +6. Build. The compiler flags every remaining v1 call site. + +## Behavior changes to watch + +| 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 | +| Modal types | one `ScreenView` type | independent `Sheet` and `Cover` types | +| macOS full screen cover | manual | compiled out | + +## Using v2 without migrating everything + +v1 API is still exported. You can, for example, keep `BaseNavigationStack` for a legacy feature while new features use `NavigationRouter`. Do not mount both on the same stack — each owns a different `NavigationStack`. + +## Checklist + +- [ ] Routes are `Hashable & Sendable` value types. +- [ ] `Sheet`/`Cover` are `Identifiable & Hashable & Sendable`. +- [ ] Router created with `@State`, not in `body`. +- [ ] All `pushToView`/`popBack`/… call sites renamed. +- [ ] `@Environment` type changed to the new router typealias. +- [ ] `maxDepth` reviewed for deep-flow features. +- [ ] Tests updated to `@MainActor` + direct `[Route]` assertions. diff --git a/docs/wiki/Nested-and-Tab-Navigation.md b/docs/wiki/Nested-and-Tab-Navigation.md new file mode 100644 index 0000000..ba41679 --- /dev/null +++ b/docs/wiki/Nested-and-Tab-Navigation.md @@ -0,0 +1,110 @@ +# Nested & Tab Navigation + +One router = one stack. Tabs and modals each get their own router instance; parent never sees child state. + +## Independent routers per Tab + +Each tab owns a router with `@State` in the tab host. Per-tab routes can even be different `Route` enums: + +```swift +enum HomeRoute: Hashable, Sendable { + case feed, post(id: Int) +} +enum SettingsRoute: Hashable, Sendable { + case account, notifications +} + +struct NoModal: Identifiable, Hashable, Sendable { let id = UUID() } + +typealias HomeRouter = NavigationRouter +typealias SettingsRouter = NavigationRouter + +struct RootTabView: View { + @State private var homeRouter = HomeRouter() + @State private var settingsRouter = SettingsRouter() + @State private var selection = 0 + + var body: some View { + TabView(selection: $selection) { + BaseNavigationContainer( + router: homeRouter, + content: { FeedView() }, + destination: { route in + switch route { + case .feed: Text("Feed") + case .post(let id): PostView(id: id) + } + } + ) + .tabItem { Label("Home", systemImage: "house") } + .tag(0) + + BaseNavigationContainer( + router: settingsRouter, + content: { SettingsView() }, + destination: { route in + switch route { + case .account: AccountView() + case .notifications: NotificationsView() + } + } + ) + .tabItem { Label("Settings", systemImage: "gearshape") } + .tag(1) + } + } +} +``` + +Switching tabs does not reset stacks — `@State` keeps both alive in the host view. `popToRoot()` on one router never touches the other. + +## Sheet with its own NavigationStack + +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 +enum SubModalRoute: Hashable, Sendable { + case subDetail +} + +typealias SubRouter = NavigationRouter + +struct NestedSheetContainerView: View { + let sheet: DemoSheet + @State private var subRouter = SubRouter() + @Environment(DemoRouter.self) private var parentRouter // for dismissing the sheet itself + + var body: some View { + BaseNavigationContainer( + router: subRouter, + content: { + VStack { + Text(sheet.title) + Button("Push Child Screen") { subRouter.push(.subDetail) } + Button("Dismiss Entire Sheet") { parentRouter.dismiss() } + } + }, + destination: { route in + switch route { + case .subDetail: + Button("Pop Child") { subRouter.pop() } + } + } + ) + } +} +``` + +Rules of thumb: + +- **Push/pop inside the modal** → child `subRouter`. +- **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. + +## 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]]. +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 new file mode 100644 index 0000000..b9c3aa9 --- /dev/null +++ b/docs/wiki/Swift-6-Concurrency.md @@ -0,0 +1,107 @@ +# Swift 6 Concurrency + +Package is built with `swift-tools-version: 6.0` and `.enableUpcomingFeature("StrictConcurrency")`. + +## `@MainActor` isolation + +`NavigationRouter` (and legacy `BaseNavigationStack`) are `@MainActor`: + +```swift +@MainActor +@Observable +public final class NavigationRouter: @unchecked Sendable +``` + +Consequences: + +- All mutations (`push`, `pop`, `present`, …) run on the main actor. Calling them from a background task directly is a compile error — use `send(_:)`. +- SwiftUI reads (`path`, `sheet`, `cover`) happen on the main thread anyway; no extra hops. +- Tests must be `@MainActor`: + +```swift +@MainActor +final class NavigationRouterTests: XCTestCase { + func testPushAndPop() { + let router = NavigationRouter() + router.push(.detail(id: 1)) + XCTAssertEqual(router.path, [.detail(id: 1)]) + } +} +``` + +## `send(_:)` — crossing actor boundaries + +```swift +nonisolated public func send( + _ action: @escaping @MainActor (NavigationRouter) -> Void +) { + Task { @MainActor in + action(self) + } +} +``` + +- `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. + +```swift +Task.detached { + let items = try await api.fetch() + router.send { r in + for item in items { + r.push(.detail(id: item.id)) // runs on MainActor + } + } +} +``` + +## `@Observable` runtime + +```swift +import Observation + +@Observable @MainActor +final class NavigationRouter<...> { ... } +``` + +- Observation tracks `path`/`sheet`/`cover` access during `body` evaluation; writes invalidate only dependent views — no `objectWillChange` overhead. +- `@Bindable var bindableRouter = router` inside the modifier/container produces `$router.path` bindings for `NavigationStack(path:)` and `.sheet(item:)`. +- `@Observable` + `@MainActor` is fully supported under strict concurrency; no `@Published`, no Combine. + +## Sendable constraints on generics + +| Type | Constraints | Why | +|---|---|---| +| `Route` | `Hashable & Sendable` | stored in `@MainActor` array, compared per push, may cross into `navigationDestination` | +| `Sheet` / `Cover` | `Identifiable & Hashable & Sendable` | SwiftUI `item:` APIs + may be created off-main before `send` | + +Practical impact: route enums and modal models must be value types (or otherwise correctly `Sendable`). `struct`, `enum` with associated `Sendable` values — fine. Non-Sendable classes as routes — compiler error, use `id` payloads instead: + +```swift +// Bad: class payload +case user(UserClass) + +// Good: stable identifier +case user(id: UUID) +``` + +## Data-race safety guarantees + +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. +4. Runaway stack: `maxDepth` caps depth at push time. +5. Empty-stack ops: `pop()`, `pop(count:)`, `removeLastSafe()` are no-ops, never traps. + +## Build flags reference + +`Package.swift`: + +```swift +swiftSettings: [ + .enableUpcomingFeature("StrictConcurrency") +] +``` + +App targets using Swift 6 language mode should set `SWIFT_STRICT_CONCURRENCY = complete` in build settings to match. diff --git a/docs/wiki/_Footer.md b/docs/wiki/_Footer.md new file mode 100644 index 0000000..d517b02 --- /dev/null +++ b/docs/wiki/_Footer.md @@ -0,0 +1 @@ +BaseNavigationStack 2.0 · MIT License · [iletai/BaseNavigationStack](https://github.com/iletai/BaseNavigationStack) · Swift 6 · iOS 17+ / macOS 14+ diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md new file mode 100644 index 0000000..0640fcc --- /dev/null +++ b/docs/wiki/_Sidebar.md @@ -0,0 +1,15 @@ +**BaseNavigationStack 2.0** + +- [[Home]] +- [[Getting-Started]] +- **API** + - [[API-NavigationRouter]] + - [[API-BaseNavigationContainer]] + - [[API-Modifiers-and-Helpers]] +- **Guides** + - [[Deep-Linking-and-URL-Handling]] + - [[Nested-and-Tab-Navigation]] + - [[Swift-6-Concurrency]] + - [[Migration-Guide-v1-to-v2]] +- [Repository](https://github.com/iletai/BaseNavigationStack) +- [Issues](https://github.com/iletai/BaseNavigationStack/issues) diff --git a/scripts/sync-wiki.sh b/scripts/sync-wiki.sh new file mode 100755 index 0000000..049feca --- /dev/null +++ b/scripts/sync-wiki.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# +# scripts/sync-wiki.sh +# Push docs/wiki/ to https://github.com/iletai/BaseNavigationStack.wiki.git +# +# Requires: +# 1. Wiki enabled on GitHub repo settings (create at least one page first so .wiki.git exists). +# 2. Push rights (SSH key or gh auth). + +set -euo pipefail + +REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +WIKI_DIR="${REPO_DIR}/docs/wiki" +REMOTE_URL="${WIKI_REMOTE:-https://github.com/iletai/BaseNavigationStack.wiki.git}" +TMP_DIR="$(mktemp -d -t bnswiki.XXXXXX)" + +trap 'rm -rf "${TMP_DIR}"' EXIT + +if [ ! -d "${WIKI_DIR}" ]; then + echo "Error: ${WIKI_DIR} not found" >&2 + exit 1 +fi + +echo "Cloning wiki repo into temp dir..." +if ! git clone "${REMOTE_URL}" "${TMP_DIR}" 2>/dev/null; then + echo "Wiki repo not found remotely. Initializing fresh repo..." + git -C "${TMP_DIR}" init -b master + git -C "${TMP_DIR}" remote add origin "${REMOTE_URL}" +fi + +echo "Syncing wiki files..." +# Clear tracked files, replace with fresh contents +find "${TMP_DIR}" -maxdepth 1 -not -name '.git' -not -name '.' -exec rm -rf {} + +cp -R "${WIKI_DIR}/"* "${TMP_DIR}/" + +cd "${TMP_DIR}" +git add -A + +if git diff --cached --quiet; then + echo "No wiki changes to commit." + exit 0 +fi + +COMMIT_MSG="docs(wiki): sync wiki pages $(date -u '+%Y-%m-%d %H:%M:%SZ')" +git commit -m "${COMMIT_MSG}" + +echo "Pushing to ${REMOTE_URL}..." +git push origin HEAD + +echo "Wiki sync completed successfully."