Skip to content
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

should force load react-components which send over turbo-stream #1620

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

theforestvn88
Copy link

@theforestvn88 theforestvn88 commented May 16, 2024

Summary

Support React On Rails w/Hotwire and Turbo Streams #1493, #1508

All turbo events (turbo:before-render, turbo:render,.. ) will not dispatch with TurboStream, except turbo:before-stream-render.
And it looks like turbo-rails did not support a after-stream-render event, i don't know why yet.

But hotwired send html, react_on_rails send script, right ?
So my solution: send a script that will trigger load react component along with it.

Pull Request checklist

  • i add a new render option: force_load which if true then the trigger load script will be concat with the component itself.

  • i not use reactOnRailsPageLoaded which will query and reload all current react-components (not effective), i introduce new method reactOnRailsComponentLoaded(react-component-dom-id) to load directly the react-component that the script be sent along with.

Other Information


This change is Reviewable

Summary by CodeRabbit

  • New Features

    • Introduced a new force_load configuration option for React components, allowing immediate loading.
    • Added Turbo Frame and Turbo Stream support, enabling dynamic updates and interactions.
    • Created a new React component HelloTurboStream for enhanced user interaction.
  • Bug Fixes

    • Ensured proper rendering and unmounting of React components based on domId.
  • Documentation

    • Updated examples and documentation to reflect new force_load and Turbo functionality.
  • Tests

    • Added tests for new Turbo Stream functionality and force_load configuration.

Copy link

coderabbitai bot commented May 16, 2024

Warning

Rate Limit Exceeded

@theforestvn88 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 32 minutes and 23 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.
Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.
Please see our FAQ for further information.

Commits Files that changed from the base of the PR and between c41e5f6 and 36c4c61.

Walkthrough

This update introduces Turbo Streams integration into the react_on_rails library, enabling enhanced interactivity and dynamic component loading. Key changes include the addition of a force_load configuration, new helper methods, and Turbo Stream templates. These modifications ensure smoother React component rendering within Rails applications, leveraging Turbo Streams for real-time updates.

Changes

Files/Paths Change Summary
Gemfile.development_dependencies Added gem "turbo-rails" to development dependencies.
lib/react_on_rails/configuration.rb Added force_load configuration option with default false. Updated Configuration class.
lib/react_on_rails/helper.rb Added conditional block for force_load to include script tag.
lib/react_on_rails/react_component/render_options.rb Added force_load method to retrieve configuration value.
node_package/src/ReactOnRails.ts Added reactOnRailsComponentLoaded function to ReactOnRails object.
node_package/src/clientStartup.ts Added reactOnRailsComponentLoaded function with context and root API support.
node_package/src/types/index.ts Added reactOnRailsComponentLoaded method to ReactOnRails interface.
spec/dummy/app/controllers/pages_controller.rb Added @app_props_hello_from_turbo_stream declaration with nested data.
spec/dummy/app/views/pages/turbo_frame_tag_hello_world.html.erb Introduced Turbo Frame tag with a button triggering Turbo Stream component.
spec/dummy/app/views/pages/turbo_stream_send_hello_world.turbo_stream.erb Introduced Turbo Stream template updating element with "HelloTurboStream" React component.
spec/dummy/client/app/packs/client-bundle.js Imported @hotwired/turbo-rails and HelloTurboStream. Set turbo: true in ReactOnRails options.
spec/dummy/client/app/startup/HelloTurboStream.jsx Added HelloTurboStream React component with propTypes and event handlers.
spec/dummy/config/routes.rb Added routes for turbo_frame_tag_hello_world and turbo_stream_send_hello_world.
spec/dummy/package.json Added @hotwired/turbo-rails dependency.
spec/dummy/spec/helpers/react_on_rails_helper_spec.rb Added contexts for "force load" affecting react_component method.
spec/dummy/spec/system/integration_spec.rb Added test for TurboStream react component loading immediately.
spec/react_on_rails/react_component/render_options_spec.rb Added force_load option to predefined options.

🐇

In the world of code, a stream does flow,
React and Rails, together they grow.
With Turbo's speed and forceful load,
Components dance, in real-time mode.

🎉✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot 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

Out of diff range and nitpick comments (1)
spec/dummy/app/controllers/pages_controller.rb (1)

Line range hint 14-14: Be cautious of potential XSS vulnerabilities.

Ensure that the data being merged into xss_payload is properly sanitized to prevent XSS attacks.

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 1295ce9 and 4f44915.
Files selected for processing (17)
  • Gemfile.development_dependencies (1 hunks)
  • lib/react_on_rails/configuration.rb (3 hunks)
  • lib/react_on_rails/helper.rb (1 hunks)
  • lib/react_on_rails/react_component/render_options.rb (1 hunks)
  • node_package/src/ReactOnRails.ts (1 hunks)
  • node_package/src/clientStartup.ts (1 hunks)
  • node_package/src/types/index.ts (1 hunks)
  • spec/dummy/app/controllers/pages_controller.rb (1 hunks)
  • spec/dummy/app/views/pages/turbo_frame_tag_hello_world.html.erb (1 hunks)
  • spec/dummy/app/views/pages/turbo_stream_send_hello_world.turbo_stream.erb (1 hunks)
  • spec/dummy/client/app/packs/client-bundle.js (1 hunks)
  • spec/dummy/client/app/startup/HelloTurboStream.jsx (1 hunks)
  • spec/dummy/config/routes.rb (1 hunks)
  • spec/dummy/package.json (1 hunks)
  • spec/dummy/spec/helpers/react_on_rails_helper_spec.rb (1 hunks)
  • spec/dummy/spec/system/integration_spec.rb (1 hunks)
  • spec/react_on_rails/react_component/render_options_spec.rb (1 hunks)
Files not reviewed due to errors (2)
  • node_package/src/clientStartup.ts (no review received)
  • lib/react_on_rails/helper.rb (no review received)
Files skipped from review due to trivial changes (7)
  • Gemfile.development_dependencies
  • spec/dummy/app/views/pages/turbo_frame_tag_hello_world.html.erb
  • spec/dummy/app/views/pages/turbo_stream_send_hello_world.turbo_stream.erb
  • spec/dummy/client/app/packs/client-bundle.js
  • spec/dummy/config/routes.rb
  • spec/dummy/package.json
  • spec/react_on_rails/react_component/render_options_spec.rb
Additional comments not posted (9)
spec/dummy/client/app/startup/HelloTurboStream.jsx (1)

8-13: Prop types validation looks good.

spec/dummy/app/controllers/pages_controller.rb (1)

39-43: LGTM! The addition of @app_props_hello_from_turbo_stream is well-structured.

lib/react_on_rails/react_component/render_options.rb (1)

94-96: LGTM! The force_load method correctly retrieves the configuration value.

node_package/src/types/index.ts (1)

129-129: LGTM! The reactOnRailsComponentLoaded method is correctly defined in the ReactOnRails interface.

node_package/src/ReactOnRails.ts (1)

136-138: LGTM! The method reactOnRailsComponentLoaded correctly delegates to ClientStartup.reactOnRailsComponentLoaded.

spec/dummy/spec/system/integration_spec.rb (1)

100-107: The new test case for TurboStream looks good and follows the existing pattern. It ensures that the TurboStream component is loaded and the expected text is present.

spec/dummy/spec/helpers/react_on_rails_helper_spec.rb (1)

292-309: The new context for force load correctly tests the force_load option by checking if the force load script is included or not based on the option.

lib/react_on_rails/configuration.rb (2)

42-43: LGTM! The addition of force_load to the configuration method is consistent with the existing pattern.


57-58: LGTM! The addition of force_load to the attr_accessor list is correct and necessary for the new functionality.

@@ -68,7 +70,7 @@ def initialize(node_modules_location: nil, server_bundle_js_file: nil, prerender
same_bundle_for_client_and_server: nil,
i18n_dir: nil, i18n_yml_dir: nil, i18n_output_format: nil,
random_dom_id: nil, server_render_method: nil, rendering_props_extension: nil,
components_subdirectory: nil, auto_load_bundle: nil)
components_subdirectory: nil, auto_load_bundle: nil, force_load: nil)
Copy link

@coderabbitai coderabbitai bot May 16, 2024

Choose a reason for hiding this comment

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

Consider adding a comment explaining the purpose of force_load for better maintainability.

-                   components_subdirectory: nil, auto_load_bundle: nil, force_load: nil)
+                   components_subdirectory: nil, auto_load_bundle: nil, force_load: nil) # force_load: Forces the loading of React components

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.

Suggested change
components_subdirectory: nil, auto_load_bundle: nil, force_load: nil)
components_subdirectory: nil, auto_load_bundle: nil, force_load: nil) # force_load: Forces the loading of React components

Copy link
Author

Choose a reason for hiding this comment

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

Fixed, but add comment on line 43

Copy link

Choose a reason for hiding this comment

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

The line 43 in the provided content of lib/react_on_rails/configuration.rb is part of the initialize method of the Configuration class. Specifically, it is where the force_load attribute is initialized. This attribute is crucial for the new functionality introduced in this pull request, which forces the loading of React components.

Here's the specific line from the file:

self.force_load = force_load

Given the context and the purpose of the force_load attribute, a suitable comment would explain that this line is setting the default behavior for the force_load configuration, which is used to control whether React components are loaded immediately.

@theforestvn88, here's a suggested comment for line 43 in lib/react_on_rails/configuration.rb:

self.force_load = force_load  # Sets the default behavior for force loading React components

This comment clarifies that the line is responsible for setting the default state of the force_load attribute, which is central to the new functionality introduced in your pull request. If this aligns with your expectations, you can add it to the code.

@@ -0,0 +1,44 @@
import PropTypes from 'prop-types';
import React from 'react';
import RailsContext from '../components/RailsContext';
Copy link

@coderabbitai coderabbitai bot May 16, 2024

Choose a reason for hiding this comment

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

Remove the unnecessary import.

- import RailsContext from '../components/RailsContext';

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.

Suggested change
import RailsContext from '../components/RailsContext';

Copy link
Author

Choose a reason for hiding this comment

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

Not Fix, it's be used later.

Copy link

Choose a reason for hiding this comment

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

@theforestvn88, thank you for the clarification regarding the use of RailsContext. I'll remember this for future reviews to ensure more accurate suggestions.


New Learnings Added
User: theforestvn88
PR: shakacode/react_on_rails#1620
File: spec/dummy/client/app/startup/HelloTurboStream.jsx:3-3
Timestamp: 2024-05-22T09:15:02.548Z
Learning: The `RailsContext` import in `spec/dummy/client/app/startup/HelloTurboStream.jsx` is used later in the project, as clarified by the user theforestvn88.

Note: Learnings are effective only in the context of specific code segments. To apply general coding guidelines, please configure review instructions.

Comment on lines 7 to 42
class HelloTurboStream extends React.Component {
static propTypes = {
helloTurboStreamData: PropTypes.shape({
name: PropTypes.string,
}).isRequired,
railsContext: PropTypes.object,
};

constructor(props) {
super(props);
this.state = props.helloTurboStreamData;
this.setNameDomRef = this.setNameDomRef.bind(this);
this.handleChange = this.handleChange.bind(this);
}

setNameDomRef(nameDomNode) {
this.nameDomRef = nameDomNode;
}

handleChange() {
const name = this.nameDomRef.value;
this.setState({ name });
}

render() {
const { name } = this.state;
const { railsContext } = this.props;

return (
<div>
<h3 className={css.brightColor}>Hello, {name}!</h3>
{railsContext && <RailsContext {...{ railsContext }} />}
</div>
);
}
}
Copy link

Choose a reason for hiding this comment

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

Consider using functional components and hooks for better readability and performance.

- class HelloTurboStream extends React.Component {
-   static propTypes = {
-     helloTurboStreamData: PropTypes.shape({
-       name: PropTypes.string,
-     }).isRequired,
-     railsContext: PropTypes.object,
-   };
- 
-   constructor(props) {
-     super(props);
-     this.state = props.helloTurboStreamData;
-     this.setNameDomRef = this.setNameDomRef.bind(this);
-     this.handleChange = this.handleChange.bind(this);
-   }
- 
-   setNameDomRef(nameDomNode) {
-     this.nameDomRef = nameDomNode;
-   }
- 
-   handleChange() {
-     const name = this.nameDomRef.value;
-     this.setState({ name });
-   }
- 
-   render() {
-     const { name } = this.state;
-     const { railsContext } = this.props;
- 
-     return (
-       <div>
-         <h3 className={css.brightColor}>Hello, {name}!</h3>
-         {railsContext && <RailsContext {...{ railsContext }} />}
-       </div>
-     );
-   }
- }
+ const HelloTurboStream = ({ helloTurboStreamData, railsContext }) => {
+   const [name, setName] = useState(helloTurboStreamData.name);
+   const nameDomRef = useRef(null);
+ 
+   const handleChange = () => {
+     setName(nameDomRef.current.value);
+   };
+ 
+   return (
+     <div>
+       <h3 className={css.brightColor}>Hello, {name}!</h3>
+       {railsContext && <RailsContext {...{ railsContext }} />}
+     </div>
+   );
+ };
+ 
+ HelloTurboStream.propTypes = {
+   helloTurboStreamData: PropTypes.shape({
+     name: PropTypes.string,
+   }).isRequired,
+   railsContext: PropTypes.object,
+ };

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.

Suggested change
class HelloTurboStream extends React.Component {
static propTypes = {
helloTurboStreamData: PropTypes.shape({
name: PropTypes.string,
}).isRequired,
railsContext: PropTypes.object,
};
constructor(props) {
super(props);
this.state = props.helloTurboStreamData;
this.setNameDomRef = this.setNameDomRef.bind(this);
this.handleChange = this.handleChange.bind(this);
}
setNameDomRef(nameDomNode) {
this.nameDomRef = nameDomNode;
}
handleChange() {
const name = this.nameDomRef.value;
this.setState({ name });
}
render() {
const { name } = this.state;
const { railsContext } = this.props;
return (
<div>
<h3 className={css.brightColor}>Hello, {name}!</h3>
{railsContext && <RailsContext {...{ railsContext }} />}
</div>
);
}
}
const HelloTurboStream = ({ helloTurboStreamData, railsContext }) => {
const [name, setName] = useState(helloTurboStreamData.name);
const nameDomRef = useRef(null);
const handleChange = () => {
setName(nameDomRef.current.value);
};
return (
<div>
<h3 className={css.brightColor}>Hello, {name}!</h3>
{railsContext && <RailsContext {...{ railsContext }} />}
</div>
);
};
HelloTurboStream.propTypes = {
helloTurboStreamData: PropTypes.shape({
name: PropTypes.string,
}).isRequired,
railsContext: PropTypes.object,
};

Copy link

@coderabbitai coderabbitai bot 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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 4f44915 and d2e0e27.
Files selected for processing (1)
  • Gemfile.development_dependencies (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • Gemfile.development_dependencies

@justin808
Copy link
Member

@theforestvn88 Please

  1. Check the coderabitai suggestions
  2. fix the CI failure on liniting
  3. Rebase on master, and check CI failures.

@Judahmeek did you see anything requiring changes?

@justin808
Copy link
Member

@theforestvn88 can you check if your PR solves the problem in #1508 (comment)?

Copy link

@coderabbitai coderabbitai bot 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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between d2e0e27 and 7bfde72.
Files selected for processing (6)
  • lib/react_on_rails/configuration.rb (4 hunks)
  • lib/react_on_rails/helper.rb (1 hunks)
  • spec/dummy/app/views/pages/turbo_frame_tag_hello_world.html.erb (1 hunks)
  • spec/dummy/app/views/pages/turbo_stream_send_hello_world.turbo_stream.erb (1 hunks)
  • spec/dummy/spec/helpers/react_on_rails_helper_spec.rb (1 hunks)
  • spec/dummy/spec/system/integration_spec.rb (1 hunks)
Files skipped from review as they are similar to previous changes (6)
  • lib/react_on_rails/configuration.rb
  • lib/react_on_rails/helper.rb
  • spec/dummy/app/views/pages/turbo_frame_tag_hello_world.html.erb
  • spec/dummy/app/views/pages/turbo_stream_send_hello_world.turbo_stream.erb
  • spec/dummy/spec/helpers/react_on_rails_helper_spec.rb
  • spec/dummy/spec/system/integration_spec.rb

Copy link

@coderabbitai coderabbitai bot 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

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 7bfde72 and c41e5f6.
Files selected for processing (17)
  • Gemfile.development_dependencies (1 hunks)
  • lib/react_on_rails/configuration.rb (4 hunks)
  • lib/react_on_rails/helper.rb (1 hunks)
  • lib/react_on_rails/react_component/render_options.rb (1 hunks)
  • node_package/src/ReactOnRails.ts (1 hunks)
  • node_package/src/clientStartup.ts (1 hunks)
  • node_package/src/types/index.ts (1 hunks)
  • spec/dummy/app/controllers/pages_controller.rb (1 hunks)
  • spec/dummy/app/views/pages/turbo_frame_tag_hello_world.html.erb (1 hunks)
  • spec/dummy/app/views/pages/turbo_stream_send_hello_world.turbo_stream.erb (1 hunks)
  • spec/dummy/client/app/packs/client-bundle.js (1 hunks)
  • spec/dummy/client/app/startup/HelloTurboStream.jsx (1 hunks)
  • spec/dummy/config/routes.rb (1 hunks)
  • spec/dummy/package.json (1 hunks)
  • spec/dummy/spec/helpers/react_on_rails_helper_spec.rb (1 hunks)
  • spec/dummy/spec/system/integration_spec.rb (1 hunks)
  • spec/react_on_rails/react_component/render_options_spec.rb (1 hunks)
Files skipped from review as they are similar to previous changes (17)
  • Gemfile.development_dependencies
  • lib/react_on_rails/configuration.rb
  • lib/react_on_rails/helper.rb
  • lib/react_on_rails/react_component/render_options.rb
  • node_package/src/ReactOnRails.ts
  • node_package/src/clientStartup.ts
  • node_package/src/types/index.ts
  • spec/dummy/app/controllers/pages_controller.rb
  • spec/dummy/app/views/pages/turbo_frame_tag_hello_world.html.erb
  • spec/dummy/app/views/pages/turbo_stream_send_hello_world.turbo_stream.erb
  • spec/dummy/client/app/packs/client-bundle.js
  • spec/dummy/client/app/startup/HelloTurboStream.jsx
  • spec/dummy/config/routes.rb
  • spec/dummy/package.json
  • spec/dummy/spec/helpers/react_on_rails_helper_spec.rb
  • spec/dummy/spec/system/integration_spec.rb
  • spec/react_on_rails/react_component/render_options_spec.rb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants