roda-turbo 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: f601487ee4ee48f12acd104f8d38f2c074fce692beebb1e6dce0520ab73d6548
4
+ data.tar.gz: d29eec5784ca8d7e36bc0fff46fa38060d65e3f47fa341983fa8039cac0e3693
5
+ SHA512:
6
+ metadata.gz: 63226f9a9c9ea269d0b2a33d722cccf44bfae5db63b1b0a9ecb5e06cff4c334baa01d199130c80bb94afff0b2cc20fbea810546d01120fd2e9a8098312e304b5
7
+ data.tar.gz: 67db6aefd648d2e6316429f57d5a908c55f602fd4062c0e43fefaf1f12d8a0d368a99f13f25b7af4fe3e7b7a62647baaa0a54fe6b145ad55d93426f4aa9314ca
data/.rubocop.yml ADDED
@@ -0,0 +1,48 @@
1
+ AllCops:
2
+ NewCops: enable
3
+ TargetRubyVersion: 2.7
4
+
5
+ Metrics/MethodLength:
6
+ Max: 20
7
+ Exclude:
8
+ - test/**/*.rb
9
+
10
+ Naming/FileName:
11
+ Exclude:
12
+ - lib/roda-turbo.rb
13
+
14
+ Style/ClassVars:
15
+ Exclude:
16
+ - test/**/*.rb
17
+
18
+ Style/ClassAndModuleChildren:
19
+ Enabled: false
20
+
21
+ Style/Documentation:
22
+ Enabled: false
23
+
24
+ Style/EmptyCaseCondition:
25
+ Enabled: false
26
+
27
+ Style/Lambda:
28
+ Enabled: false
29
+
30
+ Style/LambdaCall:
31
+ Enabled: false
32
+
33
+ Style/ParallelAssignment:
34
+ Enabled: false
35
+
36
+ Style/StringLiterals:
37
+ Enabled: true
38
+ EnforcedStyle: double_quotes
39
+
40
+ Style/StringLiteralsInInterpolation:
41
+ Enabled: true
42
+ EnforcedStyle: double_quotes
43
+
44
+ Layout/LineLength:
45
+ Max: 120
46
+ Exclude:
47
+ - lib/roda/plugins/turbo-streams/**/*.rb
48
+ - test/**/*.rb
data/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## [Unreleased]
4
+
5
+ ## [1.0.0] - 2022-10-02
6
+
7
+ - Official 1.0 release to use with Roda and Bridgetown 1.2.
8
+
9
+ ## [0.1.0] - 2022-05-27
10
+
11
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at jared@jaredwhite.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in roda-turbo.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "minitest", "~> 5.0"
11
+
12
+ gem "rubocop", "~> 1.21"
13
+
14
+ gem "rack-test"
15
+
16
+ gem "rubocop-minitest", "~> 0.19.1"
17
+
18
+ gem "rubocop-rake", "~> 0.6.0"
19
+
20
+ gem "tilt", "~> 2.0"
data/Gemfile.lock ADDED
@@ -0,0 +1,58 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ roda-turbo (1.0.0)
5
+ roda (~> 3.50)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ ast (2.4.2)
11
+ minitest (5.15.0)
12
+ parallel (1.22.1)
13
+ parser (3.1.2.0)
14
+ ast (~> 2.4.1)
15
+ rack (2.2.3.1)
16
+ rack-test (1.1.0)
17
+ rack (>= 1.0, < 3)
18
+ rainbow (3.1.1)
19
+ rake (13.0.6)
20
+ regexp_parser (2.5.0)
21
+ rexml (3.2.5)
22
+ roda (3.58.0)
23
+ rack
24
+ rubocop (1.30.0)
25
+ parallel (~> 1.10)
26
+ parser (>= 3.1.0.0)
27
+ rainbow (>= 2.2.2, < 4.0)
28
+ regexp_parser (>= 1.8, < 3.0)
29
+ rexml (>= 3.2.5, < 4.0)
30
+ rubocop-ast (>= 1.18.0, < 2.0)
31
+ ruby-progressbar (~> 1.7)
32
+ unicode-display_width (>= 1.4.0, < 3.0)
33
+ rubocop-ast (1.18.0)
34
+ parser (>= 3.1.1.0)
35
+ rubocop-minitest (0.19.1)
36
+ rubocop (>= 0.90, < 2.0)
37
+ rubocop-rake (0.6.0)
38
+ rubocop (~> 1.0)
39
+ ruby-progressbar (1.11.0)
40
+ tilt (2.0.10)
41
+ unicode-display_width (2.1.0)
42
+
43
+ PLATFORMS
44
+ arm64-darwin-21
45
+ x86_64-linux
46
+
47
+ DEPENDENCIES
48
+ minitest (~> 5.0)
49
+ rack-test
50
+ rake (~> 13.0)
51
+ roda-turbo!
52
+ rubocop (~> 1.21)
53
+ rubocop-minitest (~> 0.19.1)
54
+ rubocop-rake (~> 0.6.0)
55
+ tilt (~> 2.0)
56
+
57
+ BUNDLED WITH
58
+ 2.3.3
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Jared White, portions (c) 2020 Basecamp
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,163 @@
1
+ # roda-turbo
2
+
3
+ This plugin adds [Turbo Streams](https://turbo.hotwired.dev/handbook/streams) support for the [Roda web toolkit](http://roda.jeremyevans.net/). It works in a standard Roda context as well as in [Bridgetown](https://www.bridgetownrb.com).
4
+
5
+ **NOTE:** This does not add support for async streaming (aka via Websockets, etc.). It simply adds support for stream tags in HTML responses, such as when forms are submitted via Turbo. See [issue #2](https://github.com/bridgetownrb/roda-turbo/issues/2) to track a future implementation. Turbo Frame tag helpers are [also planned](https://github.com/bridgetownrb/roda-turbo/issues/1).
6
+
7
+ ## Installation
8
+
9
+ This README assumes you know how to install [Turbo's JavaScript library](https://turbo.hotwired.dev/handbook/installing) in your Roda project. The easiest way might be to use the Skypack CDN in your main JavaScript file.
10
+
11
+ ```js
12
+ import * as Turbo from "https://cdn.skypack.dev/@hotwired/turbo"
13
+ ```
14
+
15
+ If you're using Bridgetown, you can simply run the [Turbo bundled configuration](https://www.bridgetownrb.com/docs/bundled-configurations#turbo).
16
+
17
+ Once the Turbo frontend is installed, you can run this command to add the roda-turbo gem to your `Gemfile`:
18
+
19
+ ```sh
20
+ $ bundle add roda-turbo
21
+ ```
22
+
23
+ Then add the plugin to your Roda app:
24
+
25
+ ```rb
26
+ class App < Roda
27
+ plugin :turbo
28
+ end
29
+ ```
30
+
31
+ ## Usage
32
+
33
+ Now you can use the `turbo_stream` helper in a route, and the `turbo_stream?` request method to determine if the incoming request was triggered by a Turbo form submission:
34
+
35
+ ```rb
36
+ r.post "stream_this" do
37
+ if r.turbo_stream?
38
+ turbo_stream.append "element-id", "<p>Hello from Turbo!</p>"
39
+ else
40
+ "<p>Just a regular HTML request.</p>"
41
+ end
42
+ end
43
+ ```
44
+
45
+ If you'd like to return multiple stream actions, just define them within an array:
46
+
47
+ ```rb
48
+ r.post do
49
+ [
50
+ turbo_stream.append_all(".content", "<p>Content goes here.</p>"),
51
+ turbo_stream.replace_all("header", "<h1>Header Title</h1>")
52
+ ]
53
+ end
54
+ ```
55
+
56
+ You can also use the `turbo_stream` helper in Roda views, along with `render` parameters.
57
+
58
+ ```erb
59
+ <%= turbo_stream.update "#el", template: "content_partial", locals: { foo: "bar" } %>
60
+ ```
61
+
62
+ If for some reason you need to set the response content type to Turbo Streams programmatically (`text/vnd.turbo-stream.html`), you can call the `r.respond_with_turbo_stream` method.
63
+
64
+ ### Bridgetown Setup
65
+
66
+ Add the initializer to your configure block:
67
+
68
+ ```rb
69
+ # config/initializers.rb
70
+
71
+ Bridgetown.configure do
72
+ # configurations…
73
+
74
+ init :"roda-turbo"
75
+
76
+ # configurations…
77
+ end
78
+ ```
79
+
80
+ The `turbo_stream` helper will available within routes inside your Bridgetown project as well as Ruby-based templates.
81
+
82
+ Render parameters (such as in the above example) will be passed to the underlying template engine's `partial` method. You can also inline render components and pass the output to the initial string argument.
83
+
84
+ ```rb
85
+ turbo_stream.update "#navbar", render(Public::Navbar.new metadata: bridgetown_site.metadata, resource: resource)
86
+ ```
87
+
88
+ ## Custom Actions
89
+
90
+ Turbo 7.2+ supports the ability to add custom actions so that you're no longer restricted only to `append`, `replace`, etc. There's a two-step process to adding custom actions. First, you'll want to add the action as a new method available through the `turbo_stream` helper. Next, you'll want to provide the action function to Turbo's JS on the frontend.
91
+
92
+ Let's add a `redirect_to` action so that it's easy to use Turbo's `visit` feature from a stream. We'll start first with the pure Roda example, then show an alternate approach for Bridgetown.
93
+
94
+ Define this above your Roda application, or in a separate file:
95
+
96
+ ```ruby
97
+ require "json"
98
+
99
+ module CustomActions
100
+ def redirect_to(url, delay: nil)
101
+ action "redirect_to", "", { url: url, delay: delay }.to_json
102
+ end
103
+ end
104
+ ```
105
+
106
+ Next, right below the `plugin :turbo` statement, add the following:
107
+
108
+ ```ruby
109
+ Turbo::Streams::TagBuilder.include CustomActions
110
+ ```
111
+
112
+ Then, below where you `import * from Turbo`, add the following:
113
+
114
+ ```js
115
+ const redirectTo = function() {
116
+ const payload = JSON.parse(this.templateContent.textContent)
117
+ setTimeout(() => {
118
+ Turbo.visit(payload.url)
119
+ }, payload.delay || 0)
120
+ }
121
+
122
+ Turbo.StreamActions.redirect_to = redirectTo
123
+ ```
124
+
125
+ If you have a lot of custom actions, you could relocate them all to a separate file.
126
+
127
+ And that's it! Now you can call `turbo_stream.redirect_to("/my-url", delay: 2500)` in a response and it will use this custom action.
128
+
129
+ For Bridgetown users, configuration is easy. Just define a `config/roda-turbo.rb` file and include the following:
130
+
131
+ ```ruby
132
+ module CustomActions
133
+ def redirect_to(url, delay: nil)
134
+ action "redirect_to", "", { url:, delay: }.to_json
135
+ end
136
+ end
137
+
138
+ Bridgetown.initializer :"roda-turbo" do
139
+ Turbo::Streams::TagBuilder.include CustomActions
140
+ end
141
+ ```
142
+
143
+ And there you go!
144
+
145
+ **Note:** third-party gem makers can build their own custom actions which could be used by Rails, Roda, and/or Bridgetown. As long as they provide a module that's easily included in `Turbo::Streams::TagBuilder` and doesn't require Rails as a hard dependency, then that will allow Turbo to flourish as a cross-Ruby-platform framework.
146
+
147
+ ## Development
148
+
149
+ After checking out this repo, run `bin/setup` to install dependencies. Then, run `bin/rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
150
+
151
+ To install this gem onto your local machine, run `bin/rake install`. To release a new version, update the version number in `roda-turbo.gemspec`, and then run `bin/rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
152
+
153
+ ## Contributing
154
+
155
+ Bug reports and pull requests are welcome on GitHub at https://github.com/bridgetownrb/roda-turbo. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/bridgetownrb/roda-turbo/blob/main/CODE_OF_CONDUCT.md).
156
+
157
+ ## License
158
+
159
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
160
+
161
+ ## Code of Conduct
162
+
163
+ Everyone interacting in the roda-turbo project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/bridgetownrb/roda-turbo/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ require "rubocop/rake_task"
13
+
14
+ RuboCop::RakeTask.new
15
+
16
+ task default: %i[test rubocop]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "roda/turbo"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/rake ADDED
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ #
5
+ # This file was generated by Bundler.
6
+ #
7
+ # The application 'rake' is installed as part of a gem, and
8
+ # this file is here to facilitate running it.
9
+ #
10
+
11
+ require "pathname"
12
+ ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
13
+ Pathname.new(__FILE__).realpath)
14
+
15
+ bundle_binstub = File.expand_path("bundle", __dir__)
16
+
17
+ if File.file?(bundle_binstub)
18
+ if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
19
+ load(bundle_binstub)
20
+ else
21
+ abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
22
+ Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
23
+ end
24
+ end
25
+
26
+ require "rubygems"
27
+ require "bundler/setup"
28
+
29
+ load Gem.bin_path("rake", "rake")
data/bin/rubocop ADDED
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ #
5
+ # This file was generated by Bundler.
6
+ #
7
+ # The application 'rubocop' is installed as part of a gem, and
8
+ # this file is here to facilitate running it.
9
+ #
10
+
11
+ require "pathname"
12
+ ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
13
+ Pathname.new(__FILE__).realpath)
14
+
15
+ bundle_binstub = File.expand_path("bundle", __dir__)
16
+
17
+ if File.file?(bundle_binstub)
18
+ if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
19
+ load(bundle_binstub)
20
+ else
21
+ abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
22
+ Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
23
+ end
24
+ end
25
+
26
+ require "rubygems"
27
+ require "bundler/setup"
28
+
29
+ load Gem.bin_path("rubocop", "rubocop")
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "turbo/streams/tag_builder"
4
+
5
+ class Roda
6
+ module RodaPlugins
7
+ module Turbo
8
+ def self.configure(app, opts = OPTS)
9
+ app.opts[:turbo_stream_content_type] = opts[:content_type] || "text/vnd.turbo-stream.html"
10
+ end
11
+
12
+ module RequestMethods
13
+ def turbo_stream?
14
+ (env["HTTP_ACCEPT"] || []).include?(roda_class.opts[:turbo_stream_content_type])
15
+ end
16
+
17
+ def respond_with_turbo_stream
18
+ response["Content-Type"] = roda_class.opts[:turbo_stream_content_type] if turbo_stream?
19
+ end
20
+
21
+ private
22
+
23
+ def block_result_body(result)
24
+ if result.is_a?(Array) && response["Content-Type"] == roda_class.opts[:turbo_stream_content_type]
25
+ result.join
26
+ else
27
+ super
28
+ end
29
+ end
30
+ end
31
+
32
+ module InstanceMethods
33
+ def turbo_stream
34
+ @turbo_stream ||= begin
35
+ request.respond_with_turbo_stream
36
+ ::Turbo::Streams::TagBuilder.new(self)
37
+ end
38
+ end
39
+ end
40
+ end
41
+
42
+ register_plugin :turbo, Turbo
43
+ end
44
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ Bridgetown.initializer :"roda-turbo" do |config|
4
+ require "turbo/streams/tag_builder"
5
+
6
+ # Add the Turbo plugin to the Roda app
7
+ config.roda do |app|
8
+ app.plugin :turbo
9
+ end
10
+
11
+ # Add a turbo_stream helper to Bridgetown views
12
+ config.builder :RodaTurboBuilder do
13
+ def build
14
+ helper :turbo_stream do
15
+ Turbo::Streams::TagBuilder.new(helpers.view, render_method: :partial)
16
+ end
17
+ end
18
+ end
19
+ end
data/lib/roda-turbo.rb ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ if defined?(Bridgetown)
4
+ # Check compatibility
5
+ raise "The Roda Turbo plugin support for Bridgetown requires v1.2 or newer" if Bridgetown::VERSION.to_f < 1.2
6
+
7
+ require "roda-turbo/bridgetown_helpers"
8
+ end
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Turbo
4
+ module Streams
5
+ module ActionHelper
6
+ def turbo_stream_action_tag(action, target: nil, targets: nil, template: nil)
7
+ template = action.to_sym == :remove ? "" : "<template>#{template}</template>"
8
+
9
+ safe_if_required = ->(str) do
10
+ str.respond_to?(:html_safe) ? str.html_safe : str
11
+ end
12
+
13
+ if target
14
+ safe_if_required.(%(<turbo-stream action="#{action}" target="#{target}">#{template}</turbo-stream>))
15
+ elsif targets
16
+ safe_if_required.(%(<turbo-stream action="#{action}" targets="#{targets}">#{template}</turbo-stream>))
17
+ else
18
+ raise ArgumentError, "target or targets must be supplied"
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
24
+
25
+ # NOTE: this is a slightly modified version of what's available in turbo-rails.
26
+ # URL: https://github.com/hotwired/turbo-rails
27
+ # We will endeavor to keep this version in-sync with upstream changes.
28
+ class Turbo::Streams::TagBuilder
29
+ include Turbo::Streams::ActionHelper
30
+
31
+ # @param view_context [Object] the context in which templates are rendered
32
+ # @param render_method [Symbol] the method name to use when rendering a partial
33
+ def initialize(view_context, render_method: :render)
34
+ @view_context, @render_method = view_context, render_method
35
+ end
36
+
37
+ def remove(target)
38
+ action :remove, target, allow_inferred_rendering: false
39
+ end
40
+
41
+ def remove_all(targets)
42
+ action_all :remove, targets, allow_inferred_rendering: false
43
+ end
44
+
45
+ def replace(target, content = nil, **rendering, &block)
46
+ action :replace, target, content, **rendering, &block
47
+ end
48
+
49
+ def replace_all(targets, content = nil, **rendering, &block)
50
+ action_all :replace, targets, content, **rendering, &block
51
+ end
52
+
53
+ def before(target, content = nil, **rendering, &block)
54
+ action :before, target, content, **rendering, &block
55
+ end
56
+
57
+ def before_all(targets, content = nil, **rendering, &block)
58
+ action_all :before, targets, content, **rendering, &block
59
+ end
60
+
61
+ def after(target, content = nil, **rendering, &block)
62
+ action :after, target, content, **rendering, &block
63
+ end
64
+
65
+ def after_all(targets, content = nil, **rendering, &block)
66
+ action_all :after, targets, content, **rendering, &block
67
+ end
68
+
69
+ def update(target, content = nil, **rendering, &block)
70
+ action :update, target, content, **rendering, &block
71
+ end
72
+
73
+ def update_all(targets, content = nil, **rendering, &block)
74
+ action_all :update, targets, content, **rendering, &block
75
+ end
76
+
77
+ def append(target, content = nil, **rendering, &block)
78
+ action :append, target, content, **rendering, &block
79
+ end
80
+
81
+ def append_all(targets, content = nil, **rendering, &block)
82
+ action_all :append, targets, content, **rendering, &block
83
+ end
84
+
85
+ def prepend(target, content = nil, **rendering, &block)
86
+ action :prepend, target, content, **rendering, &block
87
+ end
88
+
89
+ def prepend_all(targets, content = nil, **rendering, &block)
90
+ action_all :prepend, targets, content, **rendering, &block
91
+ end
92
+
93
+ def action(name, target, content = nil, allow_inferred_rendering: true, **rendering, &block)
94
+ template = render_template(target, content, allow_inferred_rendering: allow_inferred_rendering, **rendering, &block)
95
+
96
+ turbo_stream_action_tag name, target: target, template: template
97
+ end
98
+
99
+ def action_all(name, targets, content = nil, allow_inferred_rendering: true, **rendering, &block)
100
+ template = render_template(
101
+ targets, content, allow_inferred_rendering: allow_inferred_rendering, **rendering, &block
102
+ )
103
+
104
+ turbo_stream_action_tag name, targets: targets, template: template
105
+ end
106
+
107
+ private
108
+
109
+ def render_template(target, content = nil, allow_inferred_rendering: true, **rendering, &block)
110
+ case
111
+ when content
112
+ allow_inferred_rendering ? (render_record(content) || content) : content
113
+ when block_given?
114
+ @view_context.capture(&block)
115
+ when rendering.any?
116
+ @view_context.send(@render_method, **rendering)
117
+ else
118
+ render_record(target) if allow_inferred_rendering
119
+ end
120
+ end
121
+
122
+ def render_record(possible_record)
123
+ return unless possible_record.respond_to?(:to_partial_path)
124
+
125
+ record_path = possible_record.to_partial_path
126
+ @view_context.send(@render_method, template: record_path)
127
+ end
128
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "roda-turbo"
5
+ spec.version = "1.0.0"
6
+ spec.authors = ["Jared White"]
7
+ spec.email = ["jared@whitefusion.studio"]
8
+
9
+ spec.summary = "Turbo Frames & Streams support for Roda"
10
+ spec.homepage = "https://github.com/bridgetownrb/roda-turbo"
11
+ spec.license = "MIT"
12
+ spec.required_ruby_version = ">= 2.7"
13
+ spec.metadata["rubygems_mfa_required"] = "true"
14
+
15
+ # Specify which files should be added to the gem when it is released.
16
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
17
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
18
+ `git ls-files -z`.split("\x0").reject do |f|
19
+ (f == __FILE__) || f.match(%r{\A(?:(?:test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
20
+ end
21
+ end
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_dependency "roda", "~> 3.50"
25
+ end
metadata ADDED
@@ -0,0 +1,75 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: roda-turbo
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Jared White
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2022-10-03 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: roda
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '3.50'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '3.50'
27
+ description:
28
+ email:
29
+ - jared@whitefusion.studio
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".rubocop.yml"
35
+ - CHANGELOG.md
36
+ - CODE_OF_CONDUCT.md
37
+ - Gemfile
38
+ - Gemfile.lock
39
+ - LICENSE.txt
40
+ - README.md
41
+ - Rakefile
42
+ - bin/console
43
+ - bin/rake
44
+ - bin/rubocop
45
+ - bin/setup
46
+ - lib/roda-turbo.rb
47
+ - lib/roda-turbo/bridgetown_helpers.rb
48
+ - lib/roda/plugins/turbo.rb
49
+ - lib/turbo/streams/tag_builder.rb
50
+ - roda-turbo.gemspec
51
+ homepage: https://github.com/bridgetownrb/roda-turbo
52
+ licenses:
53
+ - MIT
54
+ metadata:
55
+ rubygems_mfa_required: 'true'
56
+ post_install_message:
57
+ rdoc_options: []
58
+ require_paths:
59
+ - lib
60
+ required_ruby_version: !ruby/object:Gem::Requirement
61
+ requirements:
62
+ - - ">="
63
+ - !ruby/object:Gem::Version
64
+ version: '2.7'
65
+ required_rubygems_version: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - ">="
68
+ - !ruby/object:Gem::Version
69
+ version: '0'
70
+ requirements: []
71
+ rubygems_version: 3.3.3
72
+ signing_key:
73
+ specification_version: 4
74
+ summary: Turbo Frames & Streams support for Roda
75
+ test_files: []