Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat(react): support lazy activity with internal plugin#617

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
orionmiz wants to merge14 commits intomain
base:main
Choose a base branch
Loading
fromlazy-activity

Conversation

@orionmiz
Copy link
Collaborator

No description provided.

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pagesbot commentedAug 1, 2025
edited
Loading

Deploying stackflow-demo with  Cloudflare Pages  Cloudflare Pages

Latest commit:7726c76
Status: ✅  Deploy successful!
Preview URL:https://f4d7e0d0.stackflow-demo.pages.dev
Branch Preview URL:https://lazy-activity.stackflow-demo.pages.dev

View logs

@changeset-bot
Copy link

changeset-botbot commentedAug 1, 2025
edited
Loading

🦋 Changeset detected

Latest commit:7726c76

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
NameType
@stackflow/reactMinor

Not sure what this means?Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai
Copy link

coderabbitaibot commentedAug 1, 2025
edited
Loading

📝 Walkthrough

Summary by CodeRabbit

  • New Features
    • Added support for lazy-loaded activities on React 18–19; navigation now waits for components to load, improving transition reliability.
  • Bug Fixes
    • More predictable behavior when the animation option is undefined, preventing unintended animation states.
  • Chores
    • Prepared a minor release for @stackflow/react.

Walkthrough

Adds a new internal React plugin that detects React.lazy and memoized activity components, pauses navigation while unresolved lazy components load, and conditionally registers the plugin for React major versions 18–19; includes a changeset for a minor @stackflow/react release.

Changes

Cohort / File(s)Change Summary
Lazy Activity Plugin Implementation
integrations/react/src/stable/lazyActivityPlugin.ts
New file: addslazyActivityPlugin(activityComponentMap) which detects React lazy/memo components, tracks load status, pauses navigation ononBeforePush/onBeforeReplace while awaiting the component's loading promise, and resumes navigation after resolve/reject.
Plugin Registration & Setup
integrations/react/src/stable/stackflow.tsx
Modified plugin initialization: normalizes and types incoming plugins array, imports Reactversion, conditionally appendslazyActivityPlugin(activityComponentMap) when React major version is 18–19, and tightened parsing ofanimate in action options.
Changeset / Release Note
.changeset/small-rice-listen.md
New changeset added declaring a minor release for@stackflow/react documenting the lazy activity support addition.

Sequence Diagram(s)

sequenceDiagram    participant User    participant Stackflow    participant LazyPlugin as lazyActivityPlugin    participant ReactLazy as ReactLazyComponent    User->>Stackflow: request navigation (push/replace)    Stackflow->>LazyPlugin: onBeforePush/onBeforeReplace    LazyPlugin->>ReactLazy: inspect activity component (lazy/memo)    alt component is lazy and uninitialized        LazyPlugin->>Stackflow: pause navigation        LazyPlugin->>ReactLazy: start loading (invoke promise)        ReactLazy-->>LazyPlugin: promise resolves / rejects        LazyPlugin->>Stackflow: resume navigation    else not lazy or already loaded        LazyPlugin->>Stackflow: allow navigation to continue    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from theIntegrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between8823102 and7726c76.

📒 Files selected for processing (1)
  • integrations/react/src/stable/stackflow.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • integrations/react/src/stable/stackflow.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Workers Builds: stackflow-docs
  • GitHub Check: Build all packages
  • GitHub Check: Check whether the written test passes normally
  • GitHub Check: Check the TypeScript typings
  • GitHub Check: Create PR or release packages
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branchlazy-activity

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat withCodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag@coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag@coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on oursupport page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type@coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add@coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add@coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add@coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit ourStatus Page to check the current availability of CodeRabbit.
  • Visit ourDocumentation for detailed information on how to use CodeRabbit.
  • Join ourDiscord Community to get help, request features, and share feedback.
  • Follow us onX/Twitter for updates and announcements.

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pagesbot commentedAug 1, 2025
edited
Loading

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more aboutintegrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
stackflow-docs7726c76Commit Preview URLAug 20 2025, 06:45 AM

@pkg-pr-new
Copy link

pkg-pr-newbot commentedAug 1, 2025
edited
Loading

@stackflow/demo

yarn add https://pkg.pr.new/@stackflow/react@617.tgz

commit:7726c76

@orionmizorionmiz changed the titlefeat(react): add lazy activity plugin for stable versionfeat(react): support lazy activity pluginAug 4, 2025
@orionmizorionmiz changed the titlefeat(react): support lazy activity pluginfeat(react): support lazy activity with internal pluginAug 4, 2025
@orionmizorionmiz marked this pull request as ready for reviewAugust 4, 2025 03:30
Copy link

@coderabbitaicoderabbitaibot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
integrations/react/src/stable/lazyActivityPlugin.ts (2)

43-46:Consider using an enum for status constants

The status constants would be more maintainable and type-safe as an enum:

-const Uninitialized = -1;-const Pending = 0;-const Resolved = 1;-const Rejected = 2;+enum LazyStatus {+  Uninitialized = -1,+  Pending = 0,+  Resolved = 1,+  Rejected = 2,+}

Then update the type definitions to use the enum:

-type UninitializedPayload<T> = {-  _status: -1;+type UninitializedPayload<T> = {+  _status: LazyStatus.Uninitialized;

126-133:Add error logging for failed lazy loading

When lazy loading fails, the navigation is resumed but the error is silently swallowed. This could make debugging difficult.

       Activity._payload._result().then(         () => {           actions.resume();         },-        () => {+        (error) => {+          console.error(`Failed to load lazy activity "${actionParams.activityName}":`, error);           actions.resume();         },       );
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between7db7958 and6b8fa40.

📒 Files selected for processing (3)
  • .changeset/small-rice-listen.md (1 hunks)
  • integrations/react/src/stable/lazyActivityPlugin.ts (1 hunks)
  • integrations/react/src/stable/stackflow.tsx (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Workers Builds: stackflow-docs
🔇 Additional comments (4)
integrations/react/src/stable/lazyActivityPlugin.ts (1)

137-146:Well-structured plugin implementation

Good use of the factory pattern and code reuse by extracting the common logic tohandleLazyActivity.

integrations/react/src/stable/stackflow.tsx (2)

23-23:Import statement looks good


144-149:Strategic plugin placement ensures compatibility

Placing thelazyActivityPlugin at the end of the plugins array is a good design choice. This ensures user plugins execute first and can potentially modify the activity map before lazy loading logic runs.

.changeset/small-rice-listen.md (1)

1-5:Appropriate changeset documentation

The minor version bump is correct for this new feature addition, and the description clearly communicates the change.

Comment on lines +4 to +6
// https://github.com/facebook/react/blob/v19.1.1/packages/shared/ReactSymbols.js#L32
constREACT_LAZY_TYPE:symbol=Symbol.for("react.lazy");
constREACT_MEMO_TYPE:symbol=Symbol.for("react.memo");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

⚠️ Potential issue

Consider the risks of using React internals

Using React's internal symbols (react.lazy andreact.memo) makes this implementation fragile. These symbols are not part of React's public API and could change in future versions without notice, potentially breaking this plugin.

Consider adding:

  1. Version checks or feature detection
  2. Fallback behavior if symbols are undefined
  3. Documentation about supported React versions
🤖 Prompt for AI Agents
In integrations/react/src/stable/lazyActivityPlugin.ts around lines 4 to 6, thecode uses React internal symbols react.lazy and react.memo which are not part ofthe public API and may change unexpectedly. To fix this, add runtime checks toverify these symbols exist before using them, implement fallback behavior ifthey are undefined, and document the React versions supported by this plugin toinform users of compatibility constraints.

Copy link

@coderabbitaicoderabbitaibot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
integrations/react/src/stable/stackflow.tsx (1)

146-151:Normalize plugin flattening (DRY) and avoid Infinity-as-0 hack scattered inline

Current inline flatten/cast is duplicated (also used in addPlugin) and relies on a TS hack. Centralize into a helper to improve readability and reduce mistakes.

Apply this diff here:

-  const plugins: StackflowReactPlugin[] = [-    ...(options.plugins ?? [])-      .flat(Number.POSITIVE_INFINITY as 0)-      .map((p) => p as StackflowReactPlugin),-  ];+  const plugins: StackflowReactPlugin[] = normalizePlugins(options.plugins);

Add this helper (can be placed near the top ofstackflow() or file-level):

functionnormalizePlugins<TextendsBaseActivities>(entries:Array<StackflowPluginsEntry<T>>|undefined,):StackflowReactPlugin[]{return(entries??[]).flat(Number.POSITIVE_INFINITYas0).map((p)=>pasStackflowReactPlugin);}

Optionally, reuse the same helper inaddPlugin() to remove duplication.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and betweena488fe9 andeebe0c6.

📒 Files selected for processing (1)
  • integrations/react/src/stable/stackflow.tsx (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Workers Builds: stackflow-docs
  • GitHub Check: Create PR or release packages
  • GitHub Check: Check whether the written test passes normally
  • GitHub Check: Check the TypeScript typings
  • GitHub Check: Build all packages
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (2)
integrations/react/src/stable/stackflow.tsx (2)

23-23:Import of internal plugin looks good

Import path and locality are appropriate for stable internals.


158-160:Verify plugin ordering relative to user plugins

Appending places the lazy plugin last. If other plugins hook onBeforePush/Replace, they may run before the lazy pause logic. Prepending ensures lazy-load pausing happens earliest.

If you keep append semantics, please confirm behavior with commonly used plugins (e.g., history sync) to ensure no regressions. Otherwise, switch to unshift as suggested above.

Comment on lines +152 to +161
constmajorReactVersion=Number.parseInt(version);

/**
* TODO: This plugin depends on internal APIs of React.
* A proper solution (e.g. Suspense integration) should be implemented in the next major version.
*/
if(majorReactVersion>=18&&majorReactVersion<=19){
plugins.push(lazyActivityPlugin(activityComponentMap));
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

⚠️ Potential issue

Tighten React version gate to 18.x and prepend plugin; add radix to parseInt

The plugin relies on React internals; enabling it for 19.x is risky. Also, to ensure it pauses navigation before other plugins, it should run first. Pass radix 10 to parseInt for robustness.

Apply this diff:

-  const majorReactVersion = Number.parseInt(version);+  const majorReactVersion = Number.parseInt(version, 10);@@-  if (majorReactVersion >= 18 && majorReactVersion <= 19) {-    plugins.push(lazyActivityPlugin(activityComponentMap));+  if (majorReactVersion >= 18 && majorReactVersion < 19) {+    // Prepend so it can pause navigation early+    plugins.unshift(lazyActivityPlugin(activityComponentMap));   }

If you prefer extra safety, also log a dev-only warning when outside the supported range to aid debugging. I can provide a snippet.

📝 Committable suggestion

‼️IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
constmajorReactVersion=Number.parseInt(version);
/**
*TODO:ThisplugindependsoninternalAPIsofReact.
*Apropersolution(e.g.Suspenseintegration)shouldbeimplementedinthenextmajorversion.
*/
if(majorReactVersion>=18&&majorReactVersion<=19){
plugins.push(lazyActivityPlugin(activityComponentMap));
}
constmajorReactVersion=Number.parseInt(version,10);
/**
*TODO:ThisplugindependsoninternalAPIsofReact.
*Apropersolution(e.g.Suspenseintegration)shouldbeimplementedinthenextmajorversion.
*/
if(majorReactVersion>=18&&majorReactVersion<19){
// Prepend so it can pause navigation early
plugins.unshift(lazyActivityPlugin(activityComponentMap));
}
🤖 Prompt for AI Agents
integrations/react/src/stable/stackflow.tsx around lines 152 to 161: tighten theReact version gate to only allow 18.x (e.g., check majorReactVersion === 18 ormajorReactVersion >= 18 && majorReactVersion < 19), pass radix 10 intoNumber.parseInt(version, 10), and prepend the plugin to the plugins arrayinstead of pushing it (use unshift) so it runs before other plugins; optionallyadd a dev-only warning (guarded by NODE_ENV !== 'production') when the Reactversion is outside the supported range to aid debugging.

@orionmiz
Copy link
CollaboratorAuthor

/oc summarize

@opencode-agent
Copy link

opencode-agentbot commentedAug 11, 2025
edited
Loading

This PR adds support for lazy-loaded React components in Stackflow by implementing an internal plugin that handles React.lazy and React.memo components.

Key Changes

New lazy activity plugin (integrations/react/src/stable/lazyActivityPlugin.ts):

  • Detects React.lazy and React.memo components using internal React symbols
  • Pauses navigation during lazy component loading to prevent flicker/errors
  • Handles bothonBeforePush andonBeforeReplace events
  • Automatically resumes navigation after component loads (success or failure)

Plugin integration (integrations/react/src/stable/stackflow.tsx):

  • Conditionally registers the plugin only for React 18.x
  • Appends plugin to existing plugin array
  • Uses React version detection to ensure compatibility

Changeset (.changeset/small-rice-listen.md):

  • Documents this as a minor version bump for@stackflow/react
  • No breaking changes to public APIs

Technical Implementation

The plugin works by:

  1. Inspecting activity components for lazy/memo wrappers
  2. Extracting loading promises from React's internal_payload structure
  3. Pausing navigation until promises resolve/reject
  4. Automatically resuming navigation afterward

This is backward-compatible and requires no configuration - it's automatically applied for supported React versions.

Implementing%20lazy%20activity%20support%20for%20Stackflow%20R
opencode session  |  github run

Copy link

@coderabbitaicoderabbitaibot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
integrations/react/src/stable/stackflow.tsx (1)

29-29:Tighten React gating to 18.x, prepend the plugin, and add radix to parseInt (optional dev warning)

Given the plugin depends on React internals, be conservative: only enable on 18.x, run it before user plugins (so pause executes early), and parse React version with radix 10. Optional: warn in dev when disabled.

- import { version } from "react";+ import { version as reactVersion } from "react";@@- const majorReactVersion = Number.parseInt(version);+ const majorReactVersion = Number.parseInt(reactVersion, 10);@@- /**-  * TODO: This plugin depends on internal APIs of React.-  * A proper solution (e.g. Suspense integration) should be implemented in the next major version.-  */- if (majorReactVersion >= 18 && majorReactVersion <= 19) {-   plugins.push(lazyActivityPlugin(activityComponentMap));- }+ /**+  * TODO: This plugin depends on internal React internals.+  * A proper solution (e.g., Suspense integration) should be implemented in the next major version.+  */+ if (majorReactVersion >= 18 && majorReactVersion < 19) {+   // Prepend so it can pause navigation before other plugins+   plugins.unshift(lazyActivityPlugin(activityComponentMap));+ } else if (process.env.NODE_ENV !== "production") {+   console.warn(+     `@stackflow/react: lazyActivityPlugin disabled (React ${reactVersion} not in supported range 18.x).`,+   );+ }

Also applies to: 152-161

🧹 Nitpick comments (1)
integrations/react/src/stable/stackflow.tsx (1)

146-151:Simplify flattening and preserve generic typing for better type-safety

Theflat(Number.POSITIVE_INFINITY as 0) trick works but is a bit opaque and drops the generic parameter. Consider simplifying and keeping the generic to help TS catch mismatches.

-  const plugins: StackflowReactPlugin[] = [-    ...(options.plugins ?? [])-      .flat(Number.POSITIVE_INFINITY as 0)-      .map((p) => p as StackflowReactPlugin),-  ];+  const plugins: StackflowReactPlugin<NoInfer<T>>[] = [];+  (options.plugins ?? [])+    .flat(Infinity)+    .forEach((p) => {+      plugins.push(p as StackflowReactPlugin<NoInfer<T>>);+    });

Alternatively, extract a tiny helper for clarity:

functionnormalizePlugins<TextendsBaseActivities>(entries:Array<StackflowPluginsEntry<T>>,):StackflowReactPlugin<T>[]{return(entries.flat(Infinity)asunknownasStackflowReactPlugin<T>[]);}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and betweeneebe0c6 and8823102.

📒 Files selected for processing (1)
  • integrations/react/src/stable/stackflow.tsx (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
integrations/react/src/stable/stackflow.tsx (2)
integrations/react/src/__internal__/StackflowReactPlugin.ts (1)
  • StackflowReactPlugin (4-41)
integrations/react/src/stable/lazyActivityPlugin.ts (1)
  • lazyActivityPlugin (105-147)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Workers Builds: stackflow-docs
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (1)
integrations/react/src/stable/stackflow.tsx (1)

23-23:Import looks good

Brings in the internal plugin cleanly for use below. No issues.

@daangndaangn deleted a comment fromopencode-agentbotAug 20, 2025
@orionmiz
Copy link
CollaboratorAuthor

/oc could you review this PR line-by-line via gh api command with gh cli?

@opencode-agent
Copy link

opencode-agentbot commentedAug 20, 2025
edited
Loading

undefined is not an object (evaluating '(await client.session.chat({
path: session,
body: {
providerID,
modelID,
agent: "build",
parts: [
{
type: "text",
text
},
...files.flatMap((f) => [
{
type: "file",
mime: f.mime,
url:data:${f.mime};base64,${f.content},
filename: f.filename,
source: {
type: "file",
text: {
value: f.replacement,
start: f.start,
end: f.end
},
path: f.filename
}
}
])
]
}
})).data.parts')

opencode session  |  github run

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

@coderabbitaicoderabbitai[bot]coderabbitai[bot] left review comments

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

2 participants

@orionmiz

[8]ページ先頭

©2009-2025 Movatter.jp