feat(react/future): add structuredStackflow API
Summary
This PR introduces the structuredStackflow API, a new way to define and manage activities hierarchically, similar to Jetpack Compose Navigation.
Motivation
As applications grow, managing a flat list of activities becomes difficult. This new API allows developers to group related activities (e.g., Auth, Settings) using defineNavigation, improving code organization and maintainability.
Features
- Hierarchical Definition: Define activities in a nested structure using defineNavigation, allowing logical grouping of related screens.
- Type Safety: Fully typed API that correctly infers parameters even from deeply nested activity structures.
- Safety Checks: Built-in runtime validation to ensure unique activity names across the entire hierarchy.
-
Plugin Integration: Includes
createRoutesFromActivitieshelper to easily integrate with plugins likehistorySyncPluginwithout manual route duplication.
Usage Example
import { defineActivity, defineNavigation, structuredStackflow, createRoutesFromActivities } from "@stackflow/react/future";
import { historySyncPlugin } from "@stackflow/plugin-history-sync";
// 1. Define Activities Hierarchically
const activities = {
// Simple top-level activity
Main: defineActivity("Main")({
component: MainPage,
route: "/"
}),
// Grouped activities (e.g., Authentication flow)
Auth: defineNavigation("Auth")({
initialActivity: "Login",
activities: {
Login: defineActivity("Login")({
component: LoginPage,
route: "/auth/login",
}),
Register: defineActivity("Register")({
component: RegisterPage,
route: "/auth/register"
}),
},
}),
};
// 2. Create Stack with DRY Routes
export const { Stack, useFlow } = structuredStackflow({
activities,
initialActivity: "Main", // Type-safe!
plugins: [
historySyncPlugin({
// Automatically extracts routes from the nested structure
routes: createRoutesFromActivities(activities),
fallbackActivity: () => "Main",
}),
],
});
// 3. Type-Safe Navigation
function MyComponent() {
const { push } = useFlow();
const handleLogin = () => {
// TypeScript knows 'Login' exists and what params it takes
push("Login", {
redirect: "/dashboard"
});
};
}
⚠️ No Changeset found
Latest commit: 69c4de629e9087a11afd40c26eb6d38bb0aa314f
Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.
This PR includes no changesets
When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types
Click here to learn what changesets are, and how to add one.
Click here if you're a maintainer who wants to add a changeset to this PR
📝 Walkthrough
Summary by CodeRabbit
-
New Features
- Introduces declarative activity and navigation definitions with full type safety.
- Adds structured stack navigation system supporting push, replace, and pop operations with transition control.
- Provides hooks and utilities for type-safe navigation actions and route generation.
✏️ Tip: You can customize this high-level summary in your review settings.
Walkthrough
Adds a typed activity/navigation DSL and a structured stack navigation implementation for React: new factories to define activities and navigations, a structuredStackflow factory that builds a stack-based navigator with typed actions, data loaders with caching, plugin integration, and route generation utilities.
Changes
| Cohort / File(s) | Summary |
|---|---|
Activity & Navigation Definitions integrations/react/src/future/defineActivity.ts |
New module: adds ActivityRoute, ActivityLoader, ActivityDefinitionInput/Output, defineActivity factory, DestinationsMap, NavigationDefinitionOutput, defineNavigation factory, and isNavigationDefinition type guard. |
Structured Stack Navigation integrations/react/src/future/structuredStackflow.tsx |
New module: implements structuredStackflow factory and related types (ActivitiesMap, AllActivityNames, GetActivityDefinition, InferActivityParamsFromMap, TypedActions, TypedStepActions, StructuredStackflowInput/Output), activity flattening, createRoutesFromActivities, loader data cache with eviction, core store initialization, plugin wiring, navigation actions (push/replace/pop and step variants), and a Stack React component with provider wiring. |
Public API Exports integrations/react/src/future/index.ts |
Re-exports added: export * from "./defineActivity" and export * from "./structuredStackflow" to expose the new APIs. |
Sequence Diagram(s)
sequenceDiagram
participant Dev as Developer
participant defineActivity as defineActivity<br/>(Factory)
participant defineNavigation as defineNavigation<br/>(Factory)
participant structuredStackflow as structuredStackflow<br/>(Factory)
participant Stack as Stack Component
participant CoreStore as CoreStore +<br/>Plugins
Dev->>defineActivity: defineActivity("screen1")
defineActivity-->>Dev: returns function
Dev->>defineActivity: pass ActivityDefinitionInput<br/>(component, route, loader, transition)
defineActivity-->>Dev: ActivityDefinitionOutput<"screen1", TParams>
Dev->>defineNavigation: defineNavigation("root")
defineNavigation-->>Dev: returns function
Dev->>defineNavigation: pass {activities, initialActivity}
defineNavigation-->>Dev: NavigationDefinitionOutput
Dev->>structuredStackflow: pass StructuredStackflowInput<br/>(activities, initialActivity, plugins)
structuredStackflow->>structuredStackflow: flattenActivities()<br/>createRoutesFromActivities()
structuredStackflow->>structuredStackflow: setup loaderDataCacheMap<br/>initialize CoreStore
structuredStackflow->>structuredStackflow: register plugins<br/>(including loader plugin)
structuredStackflow-->>Dev: StructuredStackflowOutput<br/>(Stack, actions, hooks)
Dev->>Stack: render Stack component<br/>with ConfigProvider, PluginsProvider, CoreProvider
Stack->>CoreStore: dispatch Initialized<br/>ActivityRegistered events
Stack->>Stack: render current activity<br/>via ActivityComponentMapProvider + DataLoaderProvider
Stack-->>Dev: rendered navigation UI
sequenceDiagram
participant User as User
participant TypedActions as TypedActions<br/>(actions.push/replace)
participant LoaderPlugin as Loader Plugin
participant DataCache as LoaderDataCacheMap
participant Renderer as Stack Renderer
User->>TypedActions: actions.push("nextScreen", params, options)
TypedActions->>LoaderPlugin: trigger loader plugin
LoaderPlugin->>DataCache: check cache by param equality
alt Cache Hit
DataCache-->>LoaderPlugin: cached data
else Cache Miss
LoaderPlugin->>LoaderPlugin: invoke loader(params, config)
LoaderPlugin->>DataCache: store result + timestamp
end
LoaderPlugin-->>TypedActions: data ready
TypedActions->>Renderer: dispatch state update<br/>(new activity, transition animation)
Renderer->>Renderer: render new activity component<br/>with loaded data
Renderer-->>User: activity displayed
Estimated code review effort
🎯 4 (Complex) | ⏱️ ~45–75 minutes
Areas to review closely:
- Type inference utilities and recursive generic types in
structuredStackflow.tsx(name resolution, deep nesting, collisions). - Loader cache logic: param equality, cache key correctness, eviction timing, and cleanup.
- Core store initialization and browser vs. non-browser handling (SSR/hydration implications).
- Plugin registration/wiring and lifecycle (especially loader plugin interactions).
- Activity flattening and
createRoutesFromActivitiescorrectness for nested navigations and duplicate detection. - Provider composition and context propagation in the Stack component.
Pre-merge checks and finishing touches
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | ⚠️ Warning | Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. | You can run @coderabbitai generate docstrings to improve docstring coverage. |
✅ Passed checks (2 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | ✅ Passed | The title 'feat(react/future): add structuredStackflow API' directly and clearly describes the main addition in this PR—a new structuredStackflow API for hierarchical activity management. |
| Description check | ✅ Passed | The description comprehensively explains the structuredStackflow API, its motivation, features, and includes practical usage examples that align with the code changes introduced. |
✨ Finishing touches
- [ ] 📝 Generate docstrings
🧪 Generate unit tests (beta)
- [ ] Create PR with unit tests
- [ ] Post copyable unit tests in a comment
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.