demarches-normaliennes/app/helpers/turbo_stream_helper.rb

75 lines
2.2 KiB
Ruby
Raw Normal View History

2022-04-14 20:46:28 +02:00
module TurboStreamHelper
def turbo_stream
TagBuilder.new(self)
end
class TagBuilder < Turbo::Streams::TagBuilder
include ActionView::Helpers::TagHelper
2022-04-14 20:46:28 +02:00
def show(target, delay: nil)
turbo_stream_simple_action_tag :show, target: target, delay: delay
2022-04-14 20:46:28 +02:00
end
def show_all(targets, delay: nil)
turbo_stream_simple_action_tag :show, targets: targets, delay: delay
2022-04-14 20:46:28 +02:00
end
def hide(target, delay: nil)
turbo_stream_simple_action_tag :hide, target: target, delay: delay
2022-04-14 20:46:28 +02:00
end
def hide_all(targets, delay: nil)
turbo_stream_simple_action_tag :hide, targets: targets, delay: delay
2022-04-14 20:46:28 +02:00
end
def focus(target)
turbo_stream_simple_action_tag :focus, target: target
2022-04-14 20:46:28 +02:00
end
def focus_all(targets)
turbo_stream_simple_action_tag :focus, targets: targets
end
def enable(target)
turbo_stream_simple_action_tag :enable, target: target
end
def enable_all(targets)
turbo_stream_simple_action_tag :enable, targets: targets
2022-04-14 20:46:28 +02:00
end
def disable(target)
turbo_stream_simple_action_tag :disable, target: target
end
def disable_all(targets)
turbo_stream_simple_action_tag :disable, targets: targets
end
2022-05-09 18:48:52 +02:00
def morph(target, content = nil, **rendering, &block)
action :morph, target, content, **rendering, &block
2022-05-09 18:48:52 +02:00
end
def morph_all(targets, content = nil, **rendering, &block)
action_all :morph, targets, content, **rendering, &block
end
def dispatch(type, detail = nil)
content = detail.present? ? tag.script(cdata_section(detail.to_json), type: 'application/json') : nil
action_all :append, 'head', tag.dispatch_event(content, type:)
end
private
def turbo_stream_simple_action_tag(action, target: nil, targets: nil, **attributes)
if (target = convert_to_turbo_stream_dom_id(target))
tag.turbo_stream('', **attributes.merge(action: action, target: target))
elsif (targets = convert_to_turbo_stream_dom_id(targets, include_selector: true))
tag.turbo_stream('', **attributes.merge(action: action, targets: targets))
else
tag.turbo_stream('', **attributes.merge(action: action))
end
2022-05-09 18:48:52 +02:00
end
2022-04-14 20:46:28 +02:00
end
end