CommunityCoding & Developmentgithub.com

jayvijaygohil/compose-multiplatform-navigation-state

Implement and debug Compose Multiplatform Lifecycle, Multiplatform ViewModel, Navigation 2, Navigation 3, web browser routing, cross-platform deep links, and Compose UI or localization tests across Android, iOS, Desktop, and Web. Use when wiring LifecycleOwner or ViewModel in commonMain, scoping ViewModels to Navigation 3 entries, choosing between Navigation 2 and Navigation 3, setting up polymorphic NavKey serialization, binding NavController to browser history, handling external deep link URIs, or writing runComposeUiTest and locale tests.

What is compose-multiplatform-navigation-state?

compose-multiplatform-navigation-state is a Claude Code agent skill that implement and debug Compose Multiplatform Lifecycle, Multiplatform ViewModel, Navigation 2, Navigation 3, web browser routing, cross-platform deep links, and Compose UI or localization tests across Android, iOS, Desktop, and Web. Use when wiring LifecycleOwner or ViewModel in commonMain, scoping ViewModels to Navigation 3 entries, choosing between Navigation 2 and Navigation 3, setting up polymorphic NavKey serialization, binding NavController to browser history, handling external deep link URIs, or writing runComposeUiTest and locale tests.

Works with~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/jayvijaygohil/kmp-agent-skills/tree/HEAD/skills/compose-multiplatform-navigation-state

Installed? Explore more Coding & Development skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Ask in your favorite AI

Open a new chat with this agent skill pre-loaded.

Documentation

Compose Multiplatform Navigation, State & Testing

Use this skill to design, implement, and test navigation, lifecycle, ViewModel state management, deep links, and UI/localization tests in Compose Multiplatform projects targeting Android, iOS, Desktop (JVM), and Web (Wasm/JS).

Core Cross-Platform Rules

  1. No reflection on non-JVM targets (iOS, Web):
    • ViewModel: Never call viewModel() with zero arguments in commonMain. Always supply an initializer lambda (viewModel { MyViewModel() }) or explicit factory.
    • Navigation 3: Never use the reflection-based rememberNavBackStack(RouteA) overload in cross-platform code. Always pass a SavedStateConfiguration with a SerializersModule (or use rememberSerializable with a sealed interface : NavKey).
  2. Desktop Dispatchers.Main.immediate requirement:
    • Both Lifecycle.coroutineScope and ViewModel.viewModelScope rely on Dispatchers.Main.immediate. Whenever targeting Desktop (jvmMain), add org.jetbrains.kotlinx:kotlinx-coroutines-swing to jvmMain.dependencies.
  3. Navigation 3 does not auto-scope ViewModels:
    • Pass both rememberSaveableStateHolderNavEntryDecorator() and rememberViewModelStoreNavEntryDecorator() to NavDisplay(entryDecorators = ...) so ViewModels and Compose state are scoped per navigation entry rather than leaking to the root Activity/owner.
  4. Pass minimal route data:
    • Pass only IDs, URIs, or primitive keys in route arguments. Never pass domain objects, bitmaps, app state, or ViewModel instances; load full data from the data layer at the destination.
  5. Web URLs must stay in # fragments (by default):
    • When customizing browser URLs in bindToBrowserNavigation { ... }, prefix every returned route string with # and parse window.location.hash before calling bindToBrowserNavigation(). On Kotlin/JS (jsMain), wrap ComposeViewport inside onWasmReady {}.
  6. Treat external deep link URIs as untrusted input:
    • Validate and sanitize all parsed deep link arguments. Cache incoming URIs in a commonMain singleton (ExternalUriHandler) so cold-start URIs arriving before composition are not dropped.
  7. Common UI tests use runComposeUiTest, not JUnit TestRule:
    • Put shared tests in commonTest using androidx.compose.ui.test.v2.runComposeUiTest and run Android UI tests via ./gradlew :<module>:connectedAndroidTest (local Android unit-test gutter icons do not work).

Workflow Decision Trees

1. Choosing a Navigation Approach

Need navigation in Compose Multiplatform?
├─ Compose Multiplatform >= 1.10 AND want user-owned SnapshotStateList back stack,
│  low-level Compose building blocks, or Material 3 Adaptive multi-pane layouts?
│  └─ Use Navigation 3 (`org.jetbrains.androidx.navigation3:navigation3-ui`)
│     ├─ Single module -> `sealed interface Route : NavKey` + `subclassesOfSealed<Route>()`
│     ├─ Multi-module (feature sealed types) -> aggregate `subclassesOfSealed<FeatureX>()` in app module
│     └─ Multi-module (decoupled routes) -> combine per-module `SerializersModule` with `+`
│     -> Read references/navigation-3.md
├─ Need mature deep linking, NavHost/NavController, or built-in experimental Web browser history?
│  └─ Use Navigation 2 (`org.jetbrains.androidx.navigation:navigation-compose`)
│     ├─ Standard routing, arguments, back stack, iOS/Desktop back gestures -> Read references/navigation-2.md
│     └─ Web `bindToBrowserNavigation()` & custom `#` URL mapping -> Read references/navigation-routing-web.md
└─ Need native iOS Liquid Glass navigation chrome or specialized third-party architecture?
   └─ Keep Compose for screen content + native SwiftUI navigation, OR evaluate Voyager/Decompose/Circuit/Appyx/PreCompose
      -> Read references/navigation-2.md

2. Wiring Lifecycle & ViewModel

What are you sharing across platforms?
├─ Shared ViewModel + Shared Compose UI
│  ├─ Add `org.jetbrains.androidx.lifecycle:lifecycle-viewmodel-compose` (+ `lifecycle-runtime-compose` for Lifecycle)
│  ├─ Add `kotlinx-coroutines-swing` in `jvmMain` if targeting Desktop
│  ├─ Instantiate via `viewModel { MyViewModel() }`, `koinViewModel()` (Koin), or `metroViewModel()` (Metro)
│  └─ If using Navigation 3, add `lifecycle-viewmodel-navigation3` and entry decorators on `NavDisplay`
│     -> Read references/viewmodel.md and references/lifecycle.md
├─ Shared ViewModel + Native Platform UI (Jetpack Compose / SwiftUI)
│  ├─ Expose `androidx.lifecycle:lifecycle-viewmodel` via `api(...)` and `export(...)` to iOS framework
│  └─ On iOS, bridge to SwiftUI with `KMP-ObservableViewModel` (`@NativeCoroutinesState` + `@StateViewModel`)
│     -> Read references/viewmodel.md
└─ Shared Repository / Data Layer Only
   └─ Keep data/repos in `commonMain`; use native Android `ViewModel` + Hilt and Swift `ObservableObject` + `@StateObject`
      -> Read references/viewmodel.md

Lifecycle platform quirks to watch:

  • Web (Wasm/JS) skips CREATED and never reaches DESTROYED (tab close terminates the page).
  • iOS maps UIViewController & app active/background notifications to ON_START/ON_RESUME/ON_PAUSE/ON_STOP/ON_DESTROY.
  • Desktop maps Swing window focus/iconify/dispose callbacks.
  • See full mapping tables in references/lifecycle.md.

3. Implementing Cross-Platform Deep Links

Follow this 3-step sequence (details and full code in references/deep-links.md):

  1. Register URI scheme per OS:
    • Android: AndroidManifest.xml <intent-filter> (or App Links)
    • iOS / macOS: Info.plist CFBundleURLTypes (or Universal Links)
    • Windows: Registry / package manifest URI activation (avoid reserved schemes)
    • Linux: .desktop file
  2. Attach deepLinks to composable<Route>:
    • Prefer type-safe navDeepLink<Route>(basePath = ...) (required fields → path params; default-value & collection fields → query params) or explicit navDeepLink { uriPattern = ... }.
    • Ensure URI patterns do not overlap across destinations.
    • For Web, place parameters in URL fragments (localhost:8080/#dlscreen%2F{name}).
  3. Bridge OS URI callbacks to NavController:
    • Create ExternalUriHandler singleton in commonMain with cold-start caching.
    • Forward Desktop (Desktop.getDesktop().setOpenURIHandler on macOS, CLI args on Windows/Linux) and iOS (application(_:open:options:)) URIs to ExternalUriHandler.onNewUri(...).
    • Bind ExternalUriHandler.listener = { navController.navigate(NavUri(it)) } inside DisposableEffect(Unit) in the root composable.

4. Setting Up UI & Localization Tests

What are you testing?
├─ Shared Compose UI interactions / state / navigation
│  ├─ Add `org.jetbrains.compose.ui:ui-test` to `commonTest` and `compose.desktop.currentOs` to `jvmTest`
│  ├─ For Android emulator tests, wire `androidLibrary { withDeviceTestBuilder { sourceSetTreeName = "test" } }`,
│  │  `AndroidJUnitRunner`, `ui-test-junit4-android` + `ui-test-manifest`, and `androidDeviceTest/AndroidManifest.xml`
│  └─ Write `@Test fun ...() = runComposeUiTest { setContent { ... } }`
│     -> Read references/ui-testing.md
└─ Multi-locale strings, fallback resources, RTL/LTR, regional dates/numbers, multi-script (zh-Hans/zh-Hant)
   ├─ Android: `adb -e shell` `setprop persist.sys.locale ...;stop;sleep 5;start` or Espresso `LocaleTestRule()`
   ├─ iOS: XCUITest `app.launchArguments = ["-AppleLanguages", "(es)", "-AppleLocale", "es_ES"]`
   ├─ Desktop: `java.util.Locale.setDefault(...)` before UI init
   └─ Web: browser prefs, Selenium/Puppeteer, or custom `window.navigator.languages`
      -> Read references/localization-testing.md

Reference Files

Read only the reference file(s) relevant to the current task:

ReferenceWhen to read
references/lifecycle.mdConfiguring lifecycle-runtime-compose, LifecycleOwner, desktop coroutines, or checking iOS/Web/Desktop lifecycle state mappings.
references/viewmodel.mdWiring ViewModel in commonMain, Navigation 3 ViewModel decorators, Koin/Metro DI, or iOS SwiftUI KMP-ObservableViewModel integration.
references/navigation-2.mdSetting up NavHost/NavController, type-safe @Serializable routes, back stack ops, iOS/Desktop back gestures, or evaluating alternatives.
references/navigation-3.mdSetting up Navigation 3 (navigation3-ui), NavDisplay, adaptive navigation, and non-JVM polymorphic NavKey serialization patterns.
references/navigation-routing-web.mdBinding NavController to browser history (bindToBrowserNavigation), @SerialName URLs, custom # fragments, and reverse URL parsing in Wasm/JS.
references/deep-links.mdRegistering OS URI schemes, configuring navDeepLink patterns, Web fragment deep links, and implementing ExternalUriHandler for iOS/Desktop.
references/ui-testing.mdConfiguring ui-test dependencies, Android androidDeviceTest manifest/runner, writing runComposeUiTest tests, and target Gradle test commands.
references/localization-testing.mdSwitching locales on Android/iOS/Desktop/Web and validating fallback resources, regional formats, RTL/LTR, and multi-script locales.

Individual skills in this repo

This repo contains 1 individual skill — each has its own dedicated page.

Related Skills