### Install Basic Renderer Plugin
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-renderer-basic.en.mdx
Install the @stackflow/plugin-renderer-basic package using npm or yarn.
```bash
npm install @stackflow/plugin-renderer-basic
```
--------------------------------
### Install @stackflow/plugin-renderer-web
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-renderer-web.en.mdx
Install the web renderer plugin using npm or yarn.
```bash
npm install @stackflow/plugin-renderer-web
```
--------------------------------
### Install Basic UI Plugin
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-basic-ui.en.mdx
Install the @stackflow/plugin-basic-ui package using npm or yarn.
```bash
npm install @stackflow/plugin-basic-ui
```
--------------------------------
### Start Demo Project
Source: https://github.com/daangn/stackflow/blob/main/CONTRIBUTING.md
Starts the demo project located in the \/demo folder. This is useful for testing features and changes in an integrated environment.
```bash
$ yarn workspace @stackflow/demo dev:app
```
--------------------------------
### Install @stackflow/config
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/migration-v2.en.mdx
Install the necessary configuration package for Stackflow v2.
```sh
npm install @stackflow/config
```
--------------------------------
### Install Basic UI Plugins
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/get-started/installation.en.mdx
Install the basic renderer and UI plugins to enable default rendering and styling for Stackflow.
```sh
npm install @stackflow/plugin-renderer-basic @stackflow/plugin-basic-ui
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/daangn/stackflow/blob/main/CONTRIBUTING.md
Installs all project dependencies using Yarn. Ensure you have Yarn 4 installed.
```bash
$ yarn
```
--------------------------------
### Run Development Server
Source: https://github.com/daangn/stackflow/blob/main/demo/README.md
Use these commands to start the development server for the Stackflow demo application.
```bash
$ yarn dev
# or
$ yarn dev:app
```
--------------------------------
### Install History Sync Plugin
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-history-sync.en.mdx
Install the history sync plugin using npm or yarn.
```bash
npm install @stackflow/plugin-history-sync
```
--------------------------------
### Install @stackflow/plugin-devtools
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-devtools.en.mdx
Install the devtools plugin using npm or yarn.
```bash
npm install @stackflow/plugin-devtools
```
--------------------------------
### Install Stackflow Packages
Source: https://github.com/daangn/stackflow/blob/main/README.md
Install the necessary Stackflow packages using Yarn.
```bash
$ yarn add @stackflow/config @stackflow/core @stackflow/react
```
--------------------------------
### Install Stackflow Core Packages
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/get-started/installation.en.mdx
Install the necessary Stackflow packages for configuration, core functionality, and React integration.
```sh
npm install @stackflow/config @stackflow/core @stackflow/react
```
--------------------------------
### Install Google Analytics 4 Plugin
Source: https://github.com/daangn/stackflow/blob/main/extensions/plugin-google-analytics-4/README.md
Install the plugin using yarn.
```bash
yarn add @stackflow/plugin-google-analytics-4
```
--------------------------------
### Install @stackflow/plugin-stack-depth-change
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-stack-depth-change.en.mdx
Install the stack depth change plugin using npm or yarn.
```bash
npm install @stackflow/plugin-stack-depth-change
```
--------------------------------
### Basic Stackflow React Setup
Source: https://github.com/daangn/stackflow/blob/main/README.md
Set up a basic Stackflow application using React. This involves configuring activities, defining the initial activity, and rendering the Stack component.
```tsx
import ReactDOM from "react-dom";
import { defineConfig } from "@stackflow/config";
import { stackflow } from "@stackflow/react";
import MyActivity from "./MyActivity";
const config = defineConfig({
activities: [
{
name: "MyActivity",
},
],
initialActivity: () => "MyActivity",
transitionDuration: 350,
});
const { Stack } = stackflow({
config,
components: {
MyActivity,
},
plugins: [],
});
const App = () => {
return (
);
};
ReactDOM.render(, ...)
```
--------------------------------
### Install Google Analytics 4 Plugin
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-google-analytics-4.en.mdx
Install the GA4 plugin using npm or yarn.
```bash
npm install @stackflow/plugin-google-analytics-4
```
--------------------------------
### Initialize Stackflow with Devtools Plugin
Source: https://github.com/daangn/stackflow/blob/main/extensions/plugin-devtools/README.md
Integrate the devtools plugin into your Stackflow application setup. Ensure the Stackflow Chrome extension is installed.
```typescript
import { stackflow } from "@stackflow/react";
import { devtoolsPlugin } from "@stackflow/plugin-devtools";
import { config } from "./stackflow.config";
import { MyHome } from "./MyHome";
import { MyArticle } from "./MyArticle";
const { Stack } = stackflow({
config,
components: {
MyHome,
MyArticle,
},
plugins: [
devtoolsPlugin(),
// ...
],
});
```
--------------------------------
### Configure Stackflow with Basic UI Plugin
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-basic-ui.en.mdx
Integrate the basicUIPlugin into your Stackflow configuration. This example shows how to set up activities and include the plugin with a 'cupertino' theme.
```typescript
import { defineConfig } from "@stackflow/config";
export const config = defineConfig({
activities: [
{
name: "MyHome",
route: "/",
},
{
name: "MyArticle",
route: "/articles/:articleId",
},
],
});
```
```typescript
import { stackflow } from "@stackflow/react";
import { basicUIPlugin } from "@stackflow/plugin-basic-ui";
import { config } from "./stackflow.config";
import { MyHome } from "./MyHome";
import { MyArticle } from "./MyArticle";
const { Stack } = stackflow({
config,
components: {
MyHome,
MyArticle,
},
plugins: [
// ...
basicUIPlugin({
theme: "cupertino",
}),
],
});
```
--------------------------------
### Install @stackflow/link
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/link.en.mdx
Install the @stackflow/link package using npm or yarn. This package is required for using the Link component.
```bash
npm install @stackflow/link
```
--------------------------------
### Stackflow Configuration with Activity Loader
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/advanced/structured-activity.en.mdx
Configure Stackflow activities, including defining routes and associating loader functions. This example shows how to set up the 'Article' activity with its loader.
```ts
import { defineConfig } from "@stackflow/config";
import { articleLoader } from "./Article.loader";
export const config = defineConfig({
activities: [
{
name: "Article",
route: "/articles/:articleId",
loader: articleLoader,
},
],
transitionDuration: 350,
});
```
--------------------------------
### pop() Function Usage Examples
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/get-started/navigating-activities.en.mdx
Demonstrates various ways to use the pop() function, including popping a single activity, multiple activities, and with additional options. The first parameter can be a number of activities or an options object.
```ts
pop(); // pop a single activity
pop(3); // pop multiple activities
pop({
/* additional option */
}); // pop a single activity with additional options
pop(3, {
/* additional option */
}); // pop multiple activities with additional options
```
--------------------------------
### Build All Packages
Source: https://github.com/daangn/stackflow/blob/main/CONTRIBUTING.md
Builds all packages within the Stackflow project. This command is used after installing dependencies or making changes to package code.
```bash
$ yarn build
```
--------------------------------
### Basic Structured Activity Definition
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/advanced/structured-activity.en.mdx
Define a structured activity component, specifying its content and loading component. This is the fundamental setup for an activity.
```tsx
import { structuredActivityComponent } from "@stackflow/react";
import ArticleLoading from "./Article.loading";
export const Article = structuredActivityComponent<"Article">({
content: () => import("./Article.content"),
loading: ArticleLoading,
});
```
--------------------------------
### Extract Activity Declarations to Config
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/migration-v2.en.mdx
Move activity declarations from the main stackflow setup to a dedicated configuration file.
```typescript
import { stackflow } from "@stackflow/react";
export const { Stack, useFlow } = stackflow({
transitionDuration: 350,
activities: {
HomeActivity,
MyProfileActivity,
},
plugins: [],
});
```
```typescript
import { defineConfig } from "@stackflow/config";
export const config = defineConfig({
activities: [
{ name: "HomeActivity" },
{ name: "MyProfileActivity" },
],
transitionDuration: 350,
});
```
```typescript
import { stackflow } from "@stackflow/react";
import { config } from "./stackflow.config";
export const { Stack } = stackflow({
config,
components: {
HomeActivity,
MyProfileActivity,
},
plugins: [],
});
```
--------------------------------
### Stackflow Configuration with Lifecycle Plugin
Source: https://github.com/daangn/stackflow/blob/main/extensions/plugin-lifecycle/README.md
Configure your Stackflow application to include the lifecycle plugin. This is typically done in the main stackflow setup.
```typescript
import { defineConfig } from "@stackflow/config";
export const config = defineConfig({
activities: [
{
name: "MyHome",
},
{
name: "MyArticle",
},
],
transitionDuration: 350,
});
```
```typescript
import { stackflow } from "@stackflow/react";
import { lifecyclePlugin } from "@stackflow/plugin-lifecycle";
import { config } from "./stackflow.config";
import { MyHome } from "./MyHome";
import { MyArticle } from "./MyArticle";
const { Stack } = stackflow({
config,
components: {
MyHome,
MyArticle,
},
plugins: [
lifecyclePlugin(),
// ... other plugins
],
});
```
--------------------------------
### Configure Stackflow with Devtools Plugin
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-devtools.en.mdx
Integrate the devtoolsPlugin into your Stackflow setup by importing and including it in the plugins array of your stackflow configuration.
```typescript
import { defineConfig } from "@stackflow/config";
export const config = defineConfig({
activities: [
{
name: "MyHome",
route: "/",
},
{
name: "MyArticle",
route: "/articles/:articleId",
},
],
});
```
```typescript
import { stackflow } from "@stackflow/react";
import { devtoolsPlugin } from "@stackflow/plugin-devtools";
import { config } from "./stackflow.config";
import { MyHome } from "./MyHome";
import { MyArticle } from "./MyArticle";
const { Stack } = stackflow({
config,
components: {
MyHome,
MyArticle,
},
plugins: [
devtoolsPlugin(),
// ...
],
});
```
--------------------------------
### Code Splitting Setup for Activities
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/advanced/code-splitting.en.mdx
When splitting code by activity, ensure you import `lazy` from `@stackflow/react` and use it to define your components. This approach pauses stack state mutation during asset fetching and resumes it upon completion.
```tsx
import { lazy } from "react";
import { stackflow } from "@stackflow/react";
stackflow({
// ...
components: {
MyActivity: lazy(() => import("./activities/MyActivity")),
},
});
// to-be:
import { stackflow, lazy } from "@stackflow/react";
stackflow({
// ...
components: {
// replace `lazy()` from `@stackflow/react`
MyActivity: lazy(() => import("./activities/MyActivity")),
},
});
```
--------------------------------
### Structured Activity with Layout and Loading
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/advanced/structured-activity.en.mdx
Define a structured activity component that includes both a layout and a loading component. This setup ensures a complete and consistent user experience during content fetching.
```tsx
import { structuredActivityComponent } from "@stackflow/react";
import ArticleLayout from "./Article.layout";
import ArticleLoading from "./Article.loading";
export const Article = structuredActivityComponent<"Article">({
content: () => import("./Article.content"),
layout: ArticleLayout,
loading: ArticleLoading,
});
```
--------------------------------
### Structured Activity Content with Loader Data
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/advanced/structured-activity.en.mdx
Implement the content component for a structured activity, using the useLoaderData hook to access preloaded data. This example demonstrates accessing article data and parameters.
```tsx
import { content, useLoaderData } from "@stackflow/react";
import type { articleLoader } from "./Article.loader";
const ArticleContent = content<"Article">(({ params: { title } }) => {
const { data } = useLoaderData();
return (
{title}
{/* use data */}
);
});
export default ArticleContent;
```
--------------------------------
### Defining a Stackflow Activity
Source: https://github.com/daangn/stackflow/blob/main/CLAUDE.md
Defines a custom activity component for Stackflow navigation. This example shows how to declare activity parameters and use the 'useFlow' hook to navigate to another activity.
```tsx
import type { ActivityComponentType } from "@stackflow/react";
import { useFlow } from "@stackflow/react";
declare module "@stackflow/config" {
interface Register {
MyActivity: {
title: string;
};
}
}
const MyActivity: ActivityComponentType<"MyActivity"> = () => {
const { push } = useFlow();
const onClick = () => {
push("Article", {
title: "Hello",
});
};
return (
My Activity
);
};
```
--------------------------------
### Accessing Activity State with useActivity Hook
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/get-started/getting-state.en.mdx
Use the `useActivity` hook to get the current activity's state, including its transition state. This example logs the transition state to the console on mount. Ensure you have imported `useActivity` from `@stackflow/react`.
```tsx
import { useEffect } from "react";
import { useActivity, useFlow, type ActivityComponentType } from "@stackflow/react";
import { AppScreen } from "@stackflow/plugin-basic-ui";
declare module "@stackflow/config" {
interface Register {
MyActivity: {
// activity has no parameters
};
Article: {
title: string;
};
}
}
const MyActivity: ActivityComponentType<"MyActivity"> = () => {
const activity = useActivity();
const { replace } = useFlow();
const onClick = () => {
replace("Article", {
title: "Hello",
});
};
useEffect(() => {
console.log("Transition State of Current Activity:", activity.transitionState);
}, [activity]);
return (
My Activity
);
};
export default MyActivity;
```
--------------------------------
### Setting Up Stackflow Navigation
Source: https://github.com/daangn/stackflow/blob/main/AGENTS.md
Initializes Stackflow with configuration, activities, and plugins. Requires importing necessary functions and components.
```typescript
import { stackflow } from "@stackflow/react";
export const { Stack, actions } = stackflow({
config,
components: {
Main,
Article,
},
plugins: [
basicRendererPlugin(),
basicUIPlugin({
theme: "cupertino",
}),
historySyncPlugin({
config,
fallbackActivity: () => "Main",
}),
],
});
```
--------------------------------
### Initialize Stackflow with Plugins and Components
Source: https://github.com/daangn/stackflow/blob/main/extensions/link/README.md
Set up the core Stackflow instance, including necessary plugins like historySyncPlugin and defining your application's components. Ensure the config and fallbackActivity are correctly provided.
```typescript
/**
* stackflow.ts
*/
import { stackflow } from "@stackflow/react";
import { historySyncPlugin } from "@stackflow/plugin-history-sync";
import { config } from "./stackflow.config";
import { MyActivity } from "./MyActivity";
const { Stack } = stackflow({
config,
components: {
MyActivity,
},
plugins: [
historySyncPlugin({
config,
fallbackActivity: () => "MyActivity",
}),
// ...
],
});
```
--------------------------------
### Setting Up Stackflow Navigation
Source: https://github.com/daangn/stackflow/blob/main/CLAUDE.md
Initializes the Stackflow navigation with configuration, components, and plugins. Ensure 'config' is defined and necessary plugins like 'basicRendererPlugin', 'basicUIPlugin', and 'historySyncPlugin' are imported.
```typescript
import {
stackflow,
basicRendererPlugin,
basicUIPlugin,
historySyncPlugin,
} from "@stackflow/react";
// Assume 'config' is defined elsewhere
// Assume 'Main' and 'Article' components are defined elsewhere
export const { Stack, actions } = stackflow({
config,
components: {
Main,
Article,
},
plugins: [
basicRendererPlugin(),
basicUIPlugin({
theme: "cupertino",
}),
historySyncPlugin({
config,
fallbackActivity: () => "Main",
}),
],
});
```
--------------------------------
### Enable Development Mode
Source: https://github.com/daangn/stackflow/blob/main/CONTRIBUTING.md
Runs the project in development mode, allowing you to view changes in the \/demo project while editing other packages. This facilitates rapid testing and iteration.
```bash
$ yarn dev
```
--------------------------------
### Stacking a New Activity with useFlow
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/get-started/navigating-activities.en.mdx
Use the `push()` function from `useFlow` to stack a new activity. The first parameter is the activity name, the second is its parameters, and the third is optional additional options like animation.
```tsx
import type { ActivityComponentType } from "@stackflow/react";
import { useFlow } from "@stackflow/react";
import { AppScreen } from "@stackflow/plugin-basic-ui";
declare module "@stackflow/config" {
interface Register {
MyActivity: {
// activity has no parameters
};
Article: {
title: string;
};
}
}
const MyActivity: ActivityComponentType<"MyActivity"> = () => {
const { push } = useFlow();
const onClick = () => {
push("Article", {
title: "Hello",
});
};
return (
My Activity
);
};
export default MyActivity;
```
--------------------------------
### Register History Sync Plugin
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/advanced/history-sync.en.mdx
Register the historySyncPlugin in your stackflow setup, providing the configuration and a fallback activity for initial navigation.
```tsx
import { stackflow } from "@stackflow/react";
import { basicRendererPlugin } from "@stackflow/plugin-renderer-basic";
import { basicUIPlugin } from "@stackflow/plugin-basic-ui";
import { historySyncPlugin } from "@stackflow/plugin-history-sync";
import { config } from "./stackflow.config";
import MyActivity from "./MyActivity";
import Article from "./Article";
const { Stack } = stackflow({
config,
components: {
MyActivity,
Article,
},
plugins: [
basicRendererPlugin(),
basicUIPlugin({
theme: "cupertino",
}),
historySyncPlugin({
config,
fallbackActivity: () => "MyActivity",
}),
],
});
```
--------------------------------
### Initialize Stackflow with Basic UI Plugin
Source: https://github.com/daangn/stackflow/blob/main/extensions/plugin-basic-ui/README.md
Initialize Stackflow with your configuration, components, and plugins, including the basic UI plugin with a specified theme.
```typescript
/**
* stackflow.ts
*/
import { stackflow } from "@stackflow/react";
import { basicUIPlugin } from "@stackflow/plugin-basic-ui";
import { config } from "./stackflow.config";
import { MyHome } from "./MyHome";
import { MyArticle } from "./MyArticle";
const { Stack } = stackflow({
config,
components: {
MyHome,
MyArticle,
},
plugins: [
// ...
basicUIPlugin({
theme: "cupertino",
}),
],
});
```
--------------------------------
### Implement API Pipelining in Entry File
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/advanced/api-pipelining.en.mdx
This code snippet shows how to implement API pipelining in the entry file. It iterates through activities, parses the route, requests API data without awaiting, downloads the React app, and then renders the app with the initial loader data. Use this to optimize initial rendering.
```tsx
import { makeTemplate } from "@stackflow/plugin-history-sync";
import { config } from "./stackflow/stackflow.config";
async function main() {
let initialLoaderData: unknown | null = null;
for (const activity of config.activities) {
const t = makeTemplate({ path: activity.route });
const match = t.parse(location.pathname + location.search);
if (!match) {
continue;
}
// 1. Request API data (do not await)
initialLoaderData = activity.loader({ params: match as any });
break;
}
// 2. Download the React app simultaneously.
const { renderApp } = await import("./renderApp");
// 3. Combine them.
renderApp({ initialLoaderData });
}
main();
```
--------------------------------
### Initialize Stackflow with Basic UI Plugins
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/get-started/installation.en.mdx
Integrate the basic renderer and UI plugins into the stackflow initialization to enable UI features and theming.
```typescript
import { stackflow } from "@stackflow/react";
import { basicRendererPlugin } from "@stackflow/plugin-renderer-basic";
import { basicUIPlugin } from "@stackflow/plugin-basic-ui";
import { config } from "./stackflow.config";
import MyActivity from "./MyActivity";
export const { Stack } = stackflow({
config,
components: {
MyActivity,
},
plugins: [
basicRendererPlugin(),
basicUIPlugin({
theme: "cupertino",
}),
],
});
```
--------------------------------
### Basic Plugin with Inline Function
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/advanced/write-plugin.en.mdx
A minimal plugin defined as an inline function, returning a unique key. This is the starting point for developing custom plugins.
```typescript
import { basicRendererPlugin } from "@stackflow/plugin-renderer-basic";
import { stackflow } from "@stackflow/react";
stackflow({
// ...
plugins: [
basicRendererPlugin(),
basicUIPlugin({
theme: "cupertino",
}),
() => {
return {
key: "my-plugin",
};
},
],
});
```
--------------------------------
### Initialize Stackflow with History Sync Plugin
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-history-sync.en.mdx
Initialize Stackflow, including the history sync plugin and defining fallback behavior for unmatched URLs.
```typescript
import {
stackflow
} from "@stackflow/react";
import {
historySyncPlugin
} from "@stackflow/plugin-history-sync";
import {
config
} from "./stackflow.config";
import {
MyHome
} from "./MyHome";
import {
MyArticle
} from "./MyArticle";
import {
NotFoundPage
} from "./NotFoundPage";
const {
Stack
} = stackflow({
config,
components: {
MyHome,
MyArticle,
NotFoundPage,
},
plugins: [
// ...
historySyncPlugin({
config,
/**
* If a URL that does not correspond to the URL template is given, it moves to the `fallbackActivity`.
*/
fallbackActivity: ({ initialContext }) => "NotFoundPage",
/**
* Uses the hash portion of the URL (i.e. window.location.hash)
*/
useHash: false,
}),
],
});
```
--------------------------------
### Initialize Stackflow with Web Renderer
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-renderer-web.en.mdx
Initialize Stackflow with your configuration, components, and the web renderer plugin for web applications.
```typescript
import {
stackflow
} from "@stackflow/react";
import {
webRendererPlugin
} from "@stackflow/plugin-renderer-web";
import {
config
} from "./stackflow.config";
import {
MyHome
} from "./MyHome";
import {
MyArticle
} from "./MyArticle";
const {
Stack
} = stackflow({
config,
components: {
MyHome,
MyArticle,
},
plugins: [
webRendererPlugin()
],
});
```
--------------------------------
### Recommended File Structure for Structured Activity
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/advanced/structured-activity.en.mdx
This file structure organizes components by activity, co-locating related files for better navigation. It includes the main component definition, content, layout, loading states, and loader files.
```tree
activities/
└── Article/
├── Article.tsx # structuredActivityComponent definition
├── Article.content.tsx # content()
├── Article.layout.tsx # layout()
├── Article.loading.tsx # loading()
└── Article.loader.ts # loader
```
--------------------------------
### Initialize Stackflow with Basic Renderer Plugin
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-renderer-basic.en.mdx
Initialize Stackflow in stackflow.ts, importing necessary components and plugins, including the basic renderer plugin.
```typescript
import { stackflow } from "@stackflow/react";
import { basicRendererPlugin } from "@stackflow/plugin-renderer-basic";
import { config } from "./stackflow.config";
import { MyHome } from "./MyHome";
import { MyArticle } from "./MyArticle";
const { Stack } = stackflow({
config,
components: {
MyHome,
MyArticle,
},
plugins: [basicRendererPlugin()],
});
```
--------------------------------
### Update Import Paths
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/migration-v2.en.mdx
Replace old entry points like `@stackflow/react/future` and `@stackflow/link/future` with their v2 equivalents: `@stackflow/react` and `@stackflow/link` respectively.
```plaintext
@stackflow/react/future
```
```plaintext
@stackflow/react
```
```plaintext
@stackflow/link/future
```
```plaintext
@stackflow/link
```
--------------------------------
### Define Activity with Parameters
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/get-started/activity.en.mdx
Create an activity component that accepts parameters. Declare the parameter types using module augmentation and access them via the `params` prop.
```tsx
import type { ActivityComponentType } from "@stackflow/react";
import { AppScreen } from "@stackflow/plugin-basic-ui";
declare module "@stackflow/config" {
interface Register {
Article: {
title: string;
};
}
}
const Article: ActivityComponentType<"Article"> = ({ params }) => {
return (
{params.title}
);
};
export default Article;
```
--------------------------------
### Initialize Stackflow with Activities
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/get-started/installation.en.mdx
Initialize the stackflow function with your configuration and activity components. Export the Stack component for rendering.
```typescript
import { stackflow } from "@stackflow/react";
import { config } from "./stackflow.config";
import MyActivity from "./MyActivity";
export const { Stack } = stackflow({
config,
components: {
MyActivity,
},
plugins: [],
});
```
--------------------------------
### Initialize Theme Detection
Source: https://github.com/daangn/stackflow/blob/main/demo/index.html
This script detects the user's preferred color scheme (light or dark) and applies a 'data-seed-scale-color' attribute to the document element. It uses event listeners to update the attribute if the user's preference changes.
```javascript
(() => {
var e = document.documentElement;
e.dataset.seed = "";
var pd = window.matchMedia("(prefers-color-scheme: dark)");
var a = () => {
e.dataset.seedScaleColor = pd.matches ? "dark" : "light";
};
"addEventListener" in pd ? pd.addEventListener("change", a) : "addListener" in pd && pd.addListener(a),
a();
})();
```
--------------------------------
### v1 to v2 API Mapping: Step Navigation Methods
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/migration-v2.en.mdx
Provides the new naming convention for step navigation methods in v2, replacing the v1 `stepPush/stepReplace/stepPop`.
```text
stepPush/stepReplace/stepPop
pushStep/replaceStep/popStep
```
--------------------------------
### v1 to v2 API Mapping: Link Component
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/migration-v2.en.mdx
Shows the migration from `createLinkComponent` in v1 to importing `Link` directly from the `@stackflow/link` package in v2.
```text
createLinkComponent()
import { Link } from "@stackflow/link"
```
--------------------------------
### Creating a Custom Stackflow Plugin
Source: https://github.com/daangn/stackflow/blob/main/AGENTS.md
Illustrates how to create a custom plugin for Stackflow by defining lifecycle hooks like `onPushed`. Plugins can access actions and effects.
```typescript
stackflow({
// ...
plugins: [
() => {
return {
key: "my-plugin",
onPushed(actions, effect) {
// actions.getStack()
// actions.dispatchEvent(...)
console.log("Pushed!");
console.log("Effect:", effect);
},
};
},
],
});
```
--------------------------------
### Configure Stackflow with Activities
Source: https://github.com/daangn/stackflow/blob/main/extensions/link/README.md
Define your application's activities and their routes using defineConfig. This configuration is essential for setting up Stackflow.
```typescript
/**
* stackflow.config.ts
*/
import { defineConfig } from "@stackflow/config";
export const config = defineConfig({
activities: [
{
name: "MyActivity",
route: "/my-activity",
},
],
transitionDuration: 350,
});
```
--------------------------------
### Initialize Stackflow with GA4 Plugin
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-google-analytics-4.en.mdx
Configure Stackflow with the Google Analytics 4 plugin, providing your tracking ID and optional user information.
```typescript
import { defineConfig } from "@stackflow/config";
export const config = defineConfig({
activities: [
{
name: "MyHome",
route: "/",
},
{
name: "MyArticle",
route: "/articles/:articleId",
},
],
});
```
```typescript
import { stackflow } from "@stackflow/react";
import { googleAnalyticsPlugin } from "@stackflow/plugin-google-analytics-4";
import { config } from "./stackflow.config";
import { MyHome } from "./MyHome";
import { MyArticle } from "./MyArticle";
const { Stack } = stackflow({
config,
components: {
MyHome,
MyArticle,
},
plugins: [
googleAnalyticsPlugin({
trackingId: "G-XXXXXXXXXX", // Required. Your Google Analytics 4 Tracking ID
userInfo: {
// optional
userId: "test123", // Your own user distinguishable id. (https://bit.ly/3VGu04K)
userProperties: {
// ...
// You can add additional event parameters. This value will collected as a user properties of "Custom Dimension" in GA.
// https://bit.ly/3uQbriR
},
},
useTitle: true, // Optional. If true, the title of the current screen will be sent to GA. if false, ActivityName will be sent to GA.(default false).
}),
],
});
```
--------------------------------
### Create a Stackflow Preset Plugin
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/advanced/write-plugin.en.mdx
Combine multiple plugins into a single preset by grouping them in an array. This is the easiest way to publish a Stackflow plugin.
```typescript
import { basicRendererPlugin } from "@stackflow/plugin-renderer-basic";
import { historySyncPlugin } from "@stackflow/plugin-history-sync";
import { stackflow } from "@stackflow/react";
const myPlugin = ({ ... }) => [
basicRendererPlugin(),
historySyncPlugin({ ... }),
];
stackflow({
// ...
plugins: [myPlugin()],
});
```
--------------------------------
### Replace API Usage
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/get-started/navigating-activities.en.mdx
Demonstrates the basic and extended API usage for the `replace()` function, showing how to navigate to another activity with or without additional options.
```typescript
replace("activity_name", {
/* activity parameters */
});
```
```typescript
replace(
"activity_name",
{
/* activity parameters */
},
{
/* additional options */
},
);
```
--------------------------------
### Basic Link Usage
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/link.en.mdx
Import and use the Link component to navigate to a specific activity. Provide the activity name and any necessary parameters.
```tsx
import { Link } from "@stackflow/link";
const MyComponent = () => {
return (
{/* ... */}
)
}
```
--------------------------------
### push() Function Signature
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/get-started/navigating-activities.en.mdx
Demonstrates the different ways to call the `push()` function, with and without additional options.
```ts
push("activity_name", {
/* activity parameters */
});
// or
push(
"activity_name",
{
/* activity parameters */
},
{
/* additional options */
},
);
```
--------------------------------
### Import Global Styles and Configure App Component
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/_app.mdx
This snippet shows the necessary imports for global styles and the root `_app.js` component configuration for a Nextra-based Stackflow application. Ensure all required CSS files are imported before defining the `Nextra` component.
```javascript
import "nextra-theme-docs/style.css";
import "@stackflow/demo/style.css";
import "@stackflow/plugin-basic-ui/index.css";
import "@seed-design/stylesheet/global.css";
import "react-lazy-load-image-component/src/effects/opacity.css";
import "simple-reveal/index.css";
import "../styles/global.css";
export default function Nextra({ Component, pageProps }) {
return ;
}
```
--------------------------------
### Stackflow Configuration
Source: https://github.com/daangn/stackflow/blob/main/extensions/plugin-devtools/README.md
Define your Stackflow activities and transition duration. This is a prerequisite for setting up the devtools plugin.
```typescript
import { defineConfig } from "@stackflow/config";
export const config = defineConfig({
activities: [
{
name: "MyHome",
},
{
name: "MyArticle",
},
],
transitionDuration: 350,
});
```
--------------------------------
### Initialize Sentry with Stackflow Browser Tracing
Source: https://github.com/daangn/stackflow/blob/main/extensions/plugin-sentry/README.md
Initialize Sentry in your browser application and include the `stackflowBrowserTracingIntegration` to enable automatic tracing of Stackflow activities.
```typescript
import * as Sentry from "@sentry/browser";
import { stackflowBrowserTracingIntegration } from "@stackflow/plugin-sentry";
Sentry.init({
dsn: "https://xxx.ingest.us.sentry.io/xxx",
integrations: [
stackflowBrowserTracingIntegration(),
// ... other integrations
],
});
```
--------------------------------
### Creating a Custom Stackflow Plugin
Source: https://github.com/daangn/stackflow/blob/main/CLAUDE.md
Illustrates how to create a custom plugin for Stackflow by defining a factory function that returns a plugin object. The plugin can hook into lifecycle events like 'onPushed'.
```typescript
stackflow({
// ... other configurations
plugins: [
() => {
return {
key: "my-plugin",
onPushed(actions, effect) {
// Example usage of actions and effect
// console.log(actions.getStack());
// console.log(actions.dispatchEvent(...));
console.log("Pushed!");
console.log("Effect:", effect);
},
};
},
],
});
```
--------------------------------
### v1 to v2 API Mapping: Activity Component Type
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/migration-v2.en.mdx
Illustrates the change in how activity component types are defined, moving from generic parameters to specific activity names.
```text
ActivityComponentType
ActivityComponentType<"ActivityName">
```
--------------------------------
### Define a Basic Activity Component
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/get-started/activity.en.mdx
Create a React component for your activity using `ActivityComponentType`. This component will be rendered as a screen in your application.
```tsx
import type { ActivityComponentType } from "@stackflow/react";
import { AppScreen } from "@stackflow/plugin-basic-ui";
const MyActivity: ActivityComponentType<"MyActivity"> = () => {
return (
My Activity
);
};
export default MyActivity;
```
--------------------------------
### v1 to v2 API Mapping: History Sync Plugin
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/migration-v2.en.mdx
Illustrates the changes in the `historySyncPlugin` configuration, specifically the removal of the `routes` parameter and the renaming of the configuration object.
```text
historySyncPlugin({ routes, fallbackActivity })
historySyncPlugin({ config, fallbackActivity })
```
--------------------------------
### Initialize Stackflow with Google Analytics 4 Plugin
Source: https://github.com/daangn/stackflow/blob/main/extensions/plugin-google-analytics-4/README.md
Initialize Stackflow with the googleAnalyticsPlugin, providing your GA4 tracking ID and optional user information. The `useTitle` option determines whether screen titles or activity names are sent to GA.
```typescript
import { stackflow } from "@stackflow/react";
import { googleAnalyticsPlugin } from "@stackflow/plugin-google-analytics-4";
import { config } from "./stackflow.config";
import { MyHome } from "./MyHome";
import { MyArticle } from "./MyArticle";
const { Stack } = stackflow({
config,
components: {
MyHome,
MyArticle,
},
plugins: [
googleAnalyticsPlugin({
trackingId: "G-XXXXXXXXXX", // Required. Your Google Analytics 4 Tracking ID
userInfo: {
// optional
userId: "test123", // Your own user distinguishable id. (https://bit.ly/3VGu04K)
userProperties: {
// ...
// You can add additional event parameters. This value will collected as a user properties of "Custom Dimension" in GA.
// https://bit.ly/3uQbriR
},
},
useTitle: true, // Optional. If true, the title of the current screen will be sent to GA. if false, ActivityName will be sent to GA.(default false).
}),
],
});
```
--------------------------------
### v1 to v2 API Mapping: Preload Plugin
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/migration-v2.en.mdx
Indicates that the `preloadPlugin` functionality from v1 is now integrated into the built-in Loader API in v2.
```text
preloadPlugin(...)
Built-in Loader API
```
--------------------------------
### v1 to v2 API Mapping: Core Function
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/migration-v2.en.mdx
Maps the v1 `stackflow` function signature to its v2 equivalent, showing changes in configuration and component parameters.
```text
stackflow({ transitionDuration, activities, plugins })
stackflow({ config, components, plugins })
```
--------------------------------
### Configure Stackflow Activities
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-renderer-basic.en.mdx
Define activities and their routes in the stackflow.config.ts file.
```typescript
import { defineConfig } from "@stackflow/config";
export const config = defineConfig({
activities: [
{
name: "MyHome",
route: "/",
},
{
name: "MyArticle",
route: "/articles/:articleId",
},
],
});
```
--------------------------------
### Configure Stackflow Activities
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-renderer-web.en.mdx
Define the activities and their corresponding routes in your stackflow configuration file.
```typescript
import {
defineConfig
} from "@stackflow/config";
export const config = defineConfig({
activities: [
{
name: "MyHome",
route: "/",
},
{
name: "MyArticle",
route: "/articles/:articleId",
},
],
});
```
--------------------------------
### Set Initial Activity in stackflow.config.ts
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/get-started/activity.en.mdx
Define the `initialActivity` option in `defineConfig()` to specify which activity should be rendered when the application first loads.
```ts
import { defineConfig } from "@stackflow/config";
export const config = defineConfig({
activities: [
{
name: "MyActivity",
},
],
initialActivity: () => "MyActivity",
transitionDuration: 350,
});
```
--------------------------------
### Include Basic UI CSS
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/get-started/installation.en.mdx
Import the CSS file provided by the basic UI plugin to apply default styling to your Stackflow application.
```typescript
import "@stackflow/plugin-basic-ui/index.css";
```
--------------------------------
### Stackflow Project Structure
Source: https://github.com/daangn/stackflow/blob/main/CLAUDE.md
Overview of the monorepo project structure, detailing the purpose of each directory.
```text
/
├── core/ # Core library
├── integrations/ # Framework integrations
│ └── react/ # React integration
├── extensions/ # Official plugins and extensions
│ ├── link/ # Link component
│ ├── plugin-basic-ui/ # Basic UI components
│ ├── plugin-devtools/ # Development tools
│ ├── plugin-history-sync/ # Browser history sync
│ └── ...
├── demo/ # Demo application
├── docs/ # Documentation site (Next.js)
└── config/ # Configuration package
```
--------------------------------
### historySyncPlugin Configuration
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-history-sync.en.mdx
Configuration options for the `historySyncPlugin` to synchronize Stackflow navigation with browser history.
```APIDOC
## `historySyncPlugin` Options
### Description
This plugin synchronizes the stack state with the browser's history, enabling features like back/forward navigation and URL updates.
### Parameters
#### `config`
- **Type**: `object`
- **Description**: The config object created with `defineConfig()`. Routes are read from the `route` field of each activity definition.
#### `fallbackActivity`
- **Type**: `(args: { initialContext: any }) => K`
- **Description**: Determines which activity to navigate to if there is no matching URL when first entering. Typically, you create a 404 page and assign it here.
#### `useHash`
- **Type**: `boolean` (optional)
- **Description**: Determines if hash-based routing should be used. Defaults to false.
#### `history`
- **Type**: `History` (optional)
- **Description**: A custom history object used for managing navigation state. Defaults to browser or memory history.
#### `urlPatternOptions`
- **Type**: `UrlPatternOptions` (optional)
- **Description**: Options for URL pattern matching and generation, affecting how URLs are constructed and parsed.
```
--------------------------------
### Receive Data in Activity with @stackflow/compat-await-push
Source: https://github.com/daangn/stackflow/blob/main/extensions/compat-await-push/README.md
Use `receive` to wait for data pushed from another activity. Ensure `push` is called on the sending activity.
```typescript
import { receive } from "@stackflow/compat-await-push";
const MyActivity = () => {
const { push } = useFlow();
const onClick = async () => {
const data = await receive(
push("NextActivity", {
// ...
}),
);
console.log(data);
};
};
```
--------------------------------
### Configure Stackflow with Stack Depth Change Plugin
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/api-references/plugins/plugin-stack-depth-change.en.mdx
Integrate the stack depth change plugin into your Stackflow configuration. Use the `onInit` and `onDepthChanged` callbacks to monitor stack depth and activities.
```typescript
import {
defineConfig
} from "@stackflow/config";
export const config = defineConfig({
activities: [
{
name: "MyHome",
route: "/",
},
{
name: "MyArticle",
route: "/articles/:articleId",
},
],
});
```
```typescript
import {
stackflow
} from "@stackflow/react";
import {
stackDepthChangePlugin
} from "@stackflow/plugin-stack-depth-change";
import {
config
} from "./stackflow.config";
import {
MyHome
} from "./MyHome";
import {
MyArticle
} from "./MyArticle";
const {
Stack
} = stackflow({
config,
components: {
MyHome,
MyArticle,
},
plugins: [
// ...
stackDepthChangePlugin({
onInit: ({ depth, activities, activeActivities }) => {},
onDepthChanged: ({ depth, activities, activeActivities }) => {},
}),
],
});
```
--------------------------------
### Build Individual Packages
Source: https://github.com/daangn/stackflow/blob/main/CONTRIBUTING.md
Builds a specific package using Yarn workspace. Useful for testing changes in a single package.
```bash
# Build @stackflow/core
$ yarn workspace @stackflow/core build
# Build @stackflow/react
$ yarn workspace @stackflow/react build
```
--------------------------------
### v1 to v2 API Mapping: Actions Hook
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/migration-v2.en.mdx
Shows the renaming of the `useActions` hook in v1 to `useFlow` in v2, with an updated import path.
```text
useActions()
useFlow() from "@stackflow/react"
```
--------------------------------
### Plugin with Initialization Hook
Source: https://github.com/daangn/stackflow/blob/main/docs/pages/docs/advanced/write-plugin.en.mdx
Utilizes the `onInit` hook to execute logic when the `` component is first initialized. Be aware of potential double invocation in React 18 Strict Mode.
```typescript
stackflow({
// ...
plugins: [
() => {
return {
key: "my-plugin",
onInit() {
console.log("Initialized!");
},
};
},
],
});
```