Sha256: 9ff5ee53aa5f636db0225767338604b41ff07837c1907ce5dbc8b29bdffc92ec

Contents?: true

Size: 1.59 KB

Versions: 3

Compression:

Stored size: 1.59 KB

Contents

module Turbo::Streams::ActionHelper
  include ActionView::Helpers::TagHelper

  # Creates a `turbo-stream` tag according to the passed parameters. Examples:
  #
  #   turbo_stream_action_tag "remove", target: "message_1"
  #   # => <turbo-stream action="remove" target="message_1"></turbo-stream>
  #
  #   turbo_stream_action_tag "replace", target: "message_1", template: %(<div id="message_1">Hello!</div>)
  #   # => <turbo-stream action="replace" target="message_1"><template><div id="message_1">Hello!</div></template></turbo-stream>
  #
  #   turbo_stream_action_tag "replace", targets: "message_1", template: %(<div id="message_1">Hello!</div>)
  #   # => <turbo-stream action="replace" targets="message_1"><template><div id="message_1">Hello!</div></template></turbo-stream>
  def turbo_stream_action_tag(action, target: nil, targets: nil, template: nil, **attributes)
    template = action.to_sym == :remove ? "" : tag.template(template.to_s.html_safe)

    if target = convert_to_turbo_stream_dom_id(target)
      tag.turbo_stream(template, **attributes.merge(action: action, target: target))
    elsif targets = convert_to_turbo_stream_dom_id(targets, include_selector: true)
      tag.turbo_stream(template, **attributes.merge(action: action, targets: targets))
    else
      tag.turbo_stream(template, **attributes.merge(action: action))
    end
  end

  private
    def convert_to_turbo_stream_dom_id(target, include_selector: false)
      if target.respond_to?(:to_key)
        [ ("#" if include_selector), ActionView::RecordIdentifier.dom_id(target) ].compact.join
      else
        target
      end
    end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
turbo-rails-1.3.2 app/helpers/turbo/streams/action_helper.rb
turbo-rails-1.3.1 app/helpers/turbo/streams/action_helper.rb
turbo-rails-1.3.0 app/helpers/turbo/streams/action_helper.rb