hotwire_react 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 94a67c7d39f7bd4321fa153ad690442940e9691e47ff4bda0c7451614377b766
4
+ data.tar.gz: 16c15c83a00301fd0279485b3e3a9c6733f6aa99f0b9abf72b378c3578199b6b
5
+ SHA512:
6
+ metadata.gz: 10bc6be8594332fff0b57d8549c2dfd6c9258b57fdee42c5ff4ed4d99bd06b8557852446ebd4805255291ee6d4729e7e50dc25aee1a9d4a25deda5d051f6b4a9
7
+ data.tar.gz: e362627e89542acbf3d325568a3176770acbd4428edf9a48b7bcdd05cfe7ace20a402146a32df5a0f7ca8a6c0b64db58faa9298b208d2f4bd7e54e94835b32a5
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,8 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.0
3
+
4
+ Style/StringLiterals:
5
+ EnforcedStyle: double_quotes
6
+
7
+ Style/StringLiteralsInInterpolation:
8
+ EnforcedStyle: double_quotes
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Carl Dawson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,152 @@
1
+ # HotwireReact
2
+
3
+ HotwireReact is a Ruby gem that seamlessly integrates React into Rails 7 projects using esbuild.
4
+
5
+ It allows you to create React components in the app/javascript/components directory and include them in your Rails views with a <%= component "ComponentName" %> helper.
6
+
7
+ This gem is designed to work alongside Hotwire, providing a useTurboFetch hook to allow React components to send JSON to Rails controllers and receive back and render TurboStreams.
8
+
9
+ ## Features
10
+
11
+ - **Easy Integration**: Add React components to your Rails views effortlessly.
12
+ - **Hotwire/ Compatibility**: Use the useTurboFetch hook for seamless integration with TurboStreams.
13
+ - **JavaScript and TypeScript Support**: Write your components in either JavaScript or TypeScript.
14
+ - **Automatic Setup**: Installs react and react-dom (and types and TypeScript, if using) and sets up your project with necessary files.
15
+
16
+
17
+ ## Installation
18
+
19
+ Create a new Rails 7 project using esbuild:
20
+
21
+ ```
22
+ rails new my_app -j esbuild
23
+ ```
24
+
25
+ Add this line to your application's Gemfile:
26
+
27
+ ```
28
+ gem 'hotwire_react'
29
+ ```
30
+
31
+ And then execute:
32
+
33
+ ```
34
+ bundle install
35
+ ```
36
+
37
+ Next, run the install generator:
38
+
39
+ ```
40
+ rails generate hotwire_react:install:js # for JavaScript
41
+ rails generate hotwire_react:install:ts # for TypeScript
42
+ ```
43
+
44
+ This will install the necessary JavaScript dependencies and copy the required files into your app/javascript directory.
45
+
46
+ ## Usage
47
+
48
+ ### Creating React Components
49
+
50
+ Create a React component in app/javascript/components, an example component is already created for you:
51
+
52
+ ```tsx
53
+ import React from "react";
54
+
55
+ type HelloProps = {
56
+ name: String
57
+ }
58
+
59
+ const Hello = ({ name }: HelloProps) => {
60
+ if (name === undefined) {
61
+ return (
62
+ <h1>Hello from HotwireReact!</h1>
63
+ )
64
+ }
65
+
66
+ return (
67
+ <h1>Hello, { name }!</h1>
68
+ )
69
+ }
70
+
71
+ export default Hello
72
+ ```
73
+
74
+ Make sure you add this component to the components/index.ts:
75
+
76
+ ```ts
77
+ import Hello from "./Hello";
78
+
79
+ interface Components {
80
+ [key: string]: ({}: any) => React.JSX.Element;
81
+ }
82
+
83
+ const components: Components = {
84
+ Hello,
85
+ // Add other components here
86
+ };
87
+
88
+ export default components;
89
+ ```
90
+
91
+ ### Including Components in Rails Views
92
+
93
+ Now you can use the component in a Rails view:
94
+
95
+ ```rb
96
+ <%= component "Hello" %>
97
+ ```
98
+
99
+ ### Components with Props
100
+
101
+ You can pass props (if required by your components) as follows:
102
+
103
+ ```rb
104
+ <%= component "Hello", { name: @name } %>
105
+ ```
106
+
107
+ ### The useTurboFetch hook
108
+
109
+ With the useTurboFetch hook you can continue to use TurboStreams to update page content as you would in a standard Rails application. Create a React form that uses the hook like so:
110
+
111
+ ```tsx
112
+ import React, { useState, FormEvent, ChangeEvent } from "react";
113
+ import useTurboFetch from "../hooks/useTurboFetch";
114
+
115
+ const MessageForm = () => {
116
+ const [content, setContent] = useState('');
117
+ const { turboFetch } = useTurboFetch();
118
+
119
+ const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
120
+ event.preventDefault();
121
+ turboFetch(event.currentTarget.action, "POST", { message: { content } });
122
+ setContent('');
123
+ }
124
+
125
+ const handleMessageChange = (event: ChangeEvent<HTMLInputElement>) => {
126
+ setContent(event.target.value);
127
+ }
128
+
129
+ return (
130
+ <form action="/messages" onSubmit={handleSubmit}>
131
+ <input type="text" value={content} onChange={handleMessageChange}/>
132
+ <button type="submit">Submit</button>
133
+ </form>
134
+ )
135
+ }
136
+
137
+ export default MessageForm
138
+ ```
139
+
140
+ Here turboFetch replaces the standard fetch call.
141
+
142
+ ## Configuration
143
+
144
+ By default, HotwireReact will automatically configure your Rails application. If you need to customize the setup, you can modify the generated files in the app/javascript directory.
145
+
146
+ ## Contributing
147
+
148
+ Bug reports and pull requests are welcome on GitHub at https://github.com/carldaws/hotwire_react.
149
+
150
+ ## License
151
+
152
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,34 @@
1
+ module HotwireReact
2
+ module Generators
3
+ module Install
4
+ class JsGenerator < Rails::Generators::Base
5
+ source_root File.expand_path('templates', __dir__)
6
+
7
+ def copy_setup_script
8
+ copy_file "setup_hotwire_react.sh", "bin/setup_hotwire_react.sh"
9
+ chmod "bin/setup_hotwire_react.sh", 0755
10
+ end
11
+
12
+ def copy_react_controller
13
+ copy_file "controllers/react_controller.js", "app/javascript/controllers/react_controller.js"
14
+ end
15
+
16
+ def copy_turbo_hook
17
+ copy_file "hooks/useTurboFetch.jsx", "app/javascript/hooks/useTurboFetch.jsx"
18
+ end
19
+
20
+ def copy_example_component
21
+ copy_file "components/Hello.jsx", "app/javascript/components/Hello.jsx"
22
+ end
23
+
24
+ def copy_components_index
25
+ copy_file "components/index.js", "app/javascript/components/index.js"
26
+ end
27
+
28
+ def add_yarn_dependencies
29
+ run "bin/setup_hotwire_react.sh"
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,9 @@
1
+ import React from "react";
2
+
3
+ const Hello = () => {
4
+ return (
5
+ <h1>Hello from HotwireReact!</h1>
6
+ )
7
+ }
8
+
9
+ export default Hello
@@ -0,0 +1,8 @@
1
+ import Hello from "./Hello";
2
+
3
+ const components = {
4
+ Hello
5
+ // add more components here
6
+ }
7
+
8
+ export default components
@@ -0,0 +1,24 @@
1
+ import { Controller } from "@hotwired/stimulus";
2
+ import React from "react";
3
+ import ReactDOM from "react-dom/client";
4
+ import components from "../components";
5
+
6
+ // Connects to data-controller="react"
7
+ export default class extends Controller {
8
+ static values = {
9
+ component: String,
10
+ props: Object
11
+ }
12
+
13
+ connect() {
14
+ const componentName = this.componentValue;
15
+ const root = ReactDOM.createRoot(this.element);
16
+
17
+ const component = components[componentName];
18
+ if (component) {
19
+ root.render(React.createElement(component, this.propsValue, null));
20
+ } else {
21
+ console.error(`Component ${componentName} not found`)
22
+ }
23
+ }
24
+ }
@@ -0,0 +1,47 @@
1
+ import React, { useState, useEffect } from "react";
2
+ import { Turbo } from "@hotwired/turbo-rails";
3
+
4
+ const useTurboFetch = () => {
5
+ const [token, setToken] = useState(null);
6
+
7
+ useEffect(() => {
8
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
9
+ setToken(csrfToken);
10
+ }, []);
11
+
12
+ const turboFetch = async (url, method, body) => {
13
+ if (!token) {
14
+ console.error("CSRF token is not set");
15
+ return;
16
+ }
17
+
18
+ try {
19
+ const response = await fetch(url, {
20
+ method: method,
21
+ headers: {
22
+ Accept: "text/vnd.turbo-stream.html",
23
+ "X-CSRF-Token": token,
24
+ "Content-Type": "application/json"
25
+ },
26
+ body: JSON.stringify(body)
27
+ });
28
+
29
+ if (!response.ok) {
30
+ throw new Error("Network response failed");
31
+ }
32
+
33
+ const responseText = await response.text();
34
+ Turbo.renderStreamMessage(responseText);
35
+ } catch (error) {
36
+ if (error instanceof Error) {
37
+ console.log(error.message);
38
+ } else {
39
+ console.log("An unknown error occurred");
40
+ }
41
+ }
42
+ };
43
+
44
+ return { turboFetch };
45
+ }
46
+
47
+ export default useTurboFetch;
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env bash
2
+ yarn add react react-dom
3
+ ./bin/rails stimulus:manifest:update
@@ -0,0 +1,19 @@
1
+ import React from "react";
2
+
3
+ type HelloProps = {
4
+ name: String
5
+ }
6
+
7
+ const Hello = ({ name }: HelloProps) => {
8
+ if (name === undefined) {
9
+ return (
10
+ <h1>Hello from HotwireReact!</h1>
11
+ )
12
+ }
13
+
14
+ return (
15
+ <h1>Hello, { name }!</h1>
16
+ )
17
+ }
18
+
19
+ export default Hello
@@ -0,0 +1,12 @@
1
+ import Hello from "./Hello";
2
+
3
+ interface Components {
4
+ [key: string]: ({}: any) => React.JSX.Element;
5
+ }
6
+
7
+ const components: Components = {
8
+ Hello,
9
+ // Add other components here
10
+ };
11
+
12
+ export default components;
@@ -0,0 +1,27 @@
1
+ import { Controller } from "@hotwired/stimulus";
2
+ import React from "react";
3
+ import ReactDOM from "react-dom/client";
4
+ import components from "../components";
5
+
6
+ // Connects to data-controller="react"
7
+ export default class extends Controller {
8
+ static values = {
9
+ component: String,
10
+ props: Object
11
+ }
12
+
13
+ declare componentValue: string;
14
+ declare propsValue: Object;
15
+
16
+ connect() {
17
+ const componentName = this.componentValue;
18
+ const root = ReactDOM.createRoot(this.element);
19
+
20
+ const component = components[componentName];
21
+ if (component) {
22
+ root.render(React.createElement(component, this.propsValue, null));
23
+ } else {
24
+ console.error(`Component ${componentName} not found`)
25
+ }
26
+ }
27
+ }
@@ -0,0 +1,47 @@
1
+ import React, { useState, useEffect } from "react";
2
+ import { Turbo } from "@hotwired/turbo-rails";
3
+
4
+ const useTurboFetch = () => {
5
+ const [token, setToken] = useState<string | null | undefined>(null);
6
+
7
+ useEffect(() => {
8
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
9
+ setToken(csrfToken);
10
+ }, []);
11
+
12
+ const turboFetch = async (url: string, method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE", body: Object) => {
13
+ if (!token) {
14
+ console.error("CSRF token is not set");
15
+ return;
16
+ }
17
+
18
+ try {
19
+ const response = await fetch(url, {
20
+ method: method,
21
+ headers: {
22
+ Accept: "text/vnd.turbo-stream.html",
23
+ "X-CSRF-Token": token,
24
+ "Content-Type": "application/json"
25
+ },
26
+ body: JSON.stringify(body)
27
+ });
28
+
29
+ if (!response.ok) {
30
+ throw new Error("Network response failed");
31
+ }
32
+
33
+ const responseText = await response.text();
34
+ Turbo.renderStreamMessage(responseText);
35
+ } catch (error) {
36
+ if (error instanceof Error) {
37
+ console.log(error.message);
38
+ } else {
39
+ console.log("An unknown error occurred");
40
+ }
41
+ }
42
+ };
43
+
44
+ return { turboFetch };
45
+ }
46
+
47
+ export default useTurboFetch;
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env bash
2
+ yarn add react react-dom @types/react @types/react-dom typescript
3
+ ./bin/rails stimulus:manifest:update
@@ -0,0 +1,11 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "commonjs",
4
+ "esModuleInterop": true,
5
+ "forceConsistentCasingInFileNames": true,
6
+ "strict": true,
7
+ "skipLibCheck": true,
8
+ "jsx": "react",
9
+ "target": "ES2015"
10
+ }
11
+ }
@@ -0,0 +1,6 @@
1
+ declare module "@hotwired/turbo-rails" {
2
+ export namespace Turbo {
3
+ function renderStreamMessage(message: string): void;
4
+ // Add other methods and properties as needed
5
+ }
6
+ }
@@ -0,0 +1,42 @@
1
+ module HotwireReact
2
+ module Generators
3
+ module Install
4
+ class TsGenerator < Rails::Generators::Base
5
+ source_root File.expand_path('templates', __dir__)
6
+
7
+ def copy_setup_script
8
+ copy_file "setup_hotwire_react.sh", "bin/setup_hotwire_react.sh"
9
+ chmod "bin/setup_hotwire_react.sh", 0755
10
+ end
11
+
12
+ def copy_ts_config
13
+ copy_file "tsconfig.json", "tsconfig.json"
14
+ end
15
+
16
+ def copy_react_controller
17
+ copy_file "controllers/react_controller.ts", "app/javascript/controllers/react_controller.ts"
18
+ end
19
+
20
+ def copy_turbo_hook
21
+ copy_file "hooks/useTurboFetch.tsx", "app/javascript/hooks/useTurboFetch.tsx"
22
+ end
23
+
24
+ def copy_turbo_types
25
+ copy_file "types/turbo.d.ts", "app/javascript/types/turbo.d.ts"
26
+ end
27
+
28
+ def copy_example_component
29
+ copy_file "components/Hello.tsx", "app/javascript/components/Hello.tsx"
30
+ end
31
+
32
+ def copy_components_index
33
+ copy_file "components/index.ts", "app/javascript/components/index.ts"
34
+ end
35
+
36
+ def add_yarn_dependencies
37
+ run "bin/setup_hotwire_react.sh"
38
+ end
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,7 @@
1
+ module HotwireReact
2
+ module ReactHelper
3
+ def component(name, props = {})
4
+ content_tag(:div, nil, data: { controller: 'react', react_component_value: name, react_props_value: props.to_json })
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module HotwireReact
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "hotwire_react/version"
4
+ require_relative "hotwire_react/react_helper"
5
+
6
+ module HotwireReact
7
+ class Railtie < Rails::Railtie
8
+ initializer "hotwire_react.view_helpers" do
9
+ ActionView::Base.send :include, ReactHelper
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,4 @@
1
+ module HotwireReact
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,69 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: hotwire_react
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Carl Dawson
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-06-04 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: HotwireReact integrates React into Rails 7 apps and allows you to combine
14
+ the power of Hotwire with React.
15
+ email:
16
+ - carldawson@hey.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - ".rspec"
22
+ - ".rubocop.yml"
23
+ - LICENSE.txt
24
+ - README.md
25
+ - Rakefile
26
+ - lib/generators/hotwire_react/install/js/js_generator.rb
27
+ - lib/generators/hotwire_react/install/js/templates/components/Hello.jsx
28
+ - lib/generators/hotwire_react/install/js/templates/components/index.js
29
+ - lib/generators/hotwire_react/install/js/templates/controllers/react_controller.js
30
+ - lib/generators/hotwire_react/install/js/templates/hooks/useTurboFetch.jsx
31
+ - lib/generators/hotwire_react/install/js/templates/setup_hotwire_react.sh
32
+ - lib/generators/hotwire_react/install/ts/templates/components/Hello.tsx
33
+ - lib/generators/hotwire_react/install/ts/templates/components/index.ts
34
+ - lib/generators/hotwire_react/install/ts/templates/controllers/react_controller.ts
35
+ - lib/generators/hotwire_react/install/ts/templates/hooks/useTurboFetch.tsx
36
+ - lib/generators/hotwire_react/install/ts/templates/setup_hotwire_react.sh
37
+ - lib/generators/hotwire_react/install/ts/templates/tsconfig.json
38
+ - lib/generators/hotwire_react/install/ts/templates/types/turbo.d.ts
39
+ - lib/generators/hotwire_react/install/ts/ts_generator.rb
40
+ - lib/hotwire_react.rb
41
+ - lib/hotwire_react/react_helper.rb
42
+ - lib/hotwire_react/version.rb
43
+ - sig/turbo_react.rbs
44
+ homepage: https://github.com/carldaws/hotwire_react
45
+ licenses:
46
+ - MIT
47
+ metadata:
48
+ allowed_push_host: https://rubygems.org
49
+ homepage_uri: https://github.com/carldaws/hotwire_react
50
+ post_install_message:
51
+ rdoc_options: []
52
+ require_paths:
53
+ - lib
54
+ required_ruby_version: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - ">="
57
+ - !ruby/object:Gem::Version
58
+ version: 3.0.0
59
+ required_rubygems_version: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: '0'
64
+ requirements: []
65
+ rubygems_version: 3.5.7
66
+ signing_key:
67
+ specification_version: 4
68
+ summary: Adds React to Rails 7 apps which use jsbundling.
69
+ test_files: []