module Turbo::Streams::ActionHelper

def convert_to_turbo_stream_dom_id(target, include_selector: false)

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

def turbo_stream_action_tag(action, target: nil, targets: nil, template: nil)

# =>
turbo_stream_action_tag "replace", targets: "message_1", template: %(
Hello!
)

# =>
turbo_stream_action_tag "replace", target: "message_1", template: %(
Hello!
)

# =>
turbo_stream_action_tag "remove", target: "message_1"

Creates a `turbo-stream` tag according to the passed parameters. Examples:
def turbo_stream_action_tag(action, target: nil, targets: nil, template: nil)
  template = action.to_sym == :remove ? "" : "<template>#{template}</template>"
  if target = convert_to_turbo_stream_dom_id(target)
    %(<turbo-stream action="#{action}" target="#{target}">#{template}</turbo-stream>).html_safe
  elsif targets = convert_to_turbo_stream_dom_id(targets, include_selector: true)
    %(<turbo-stream action="#{action}" targets="#{targets}">#{template}</turbo-stream>).html_safe
  else
    raise ArgumentError, "target or targets must be supplied"
  end
end