Manage client-side js with turbo_stream actions

This commit is contained in:
cryptogopher 2024-01-22 02:14:01 +01:00
parent 0e8bc18620
commit a7f80a575c
6 changed files with 30 additions and 17 deletions

View File

@ -102,6 +102,10 @@ module ApplicationHelper
tag.tr tag.td t('.no_items'), colspan: 10, class: 'hint'
end
def turbo_stream_handler(partial)
"Turbo.renderStreamMessage('#{j(render partial: partial)}'); return false;"
end
private
def image_element_to(type, name, image = nil, options = nil, html_options = {})

View File

@ -23,3 +23,7 @@ Turbo.StreamActions.enable = function() {
e.removeAttribute("tabindex")
})
}
Turbo.StreamActions.focus = function() {
this.targetElements[0].focus({focusVisible: true})
}

View File

@ -17,9 +17,9 @@
</td>
<td class="actions">
<%= form.submit form: :unit_form, onclick: 'focusAddLink(event)' %>
<%= form.submit form: :unit_form %>
<%= image_link_to t(:cancel), "close-circle-outline", units_path, class: 'dangerous',
onclick: 'closeForm(event); return false;' %>
onclick: turbo_stream_handler('form_close'), name: :cancel %>
</td>
</tr>
<!-- TODO: display error_messages_for unit -->

View File

@ -0,0 +1,4 @@
<%= turbo_stream.remove @unit %>
<%= turbo_stream.enable_all 'td.actions .button' %>
<%= turbo_stream.enable :add_unit %>
<%= turbo_stream.focus :add_unit %>

View File

@ -2,7 +2,7 @@
<% if current_user.at_least(:active) %>
<%= turbo_frame_tag do %>
<%= image_link_to t('.add_unit'), 'plus-outline', new_unit_path, id: :add_unit,
onclick: 'this.blur(); this.style.visibility = "hidden";', data: {turbo_stream: true} %>
onclick: 'this.blur();', data: {turbo_stream: true} %>
<% end %>
<% end %>
</div>
@ -26,20 +26,9 @@
</table>
<%= javascript_tag do %>
function closeForm(event) {
event.target.closest("tr").remove();
focusAddLink(event);
}
function focusAddLink(event) {
var add_unit_link = document.querySelector("a#add_unit");
add_unit_link.style.visibility = "visible";
add_unit_link.focus({ focusVisible: true });
}
function processKey(event) {
if (event.key == "Escape") {
closeForm(event);
event.target.closest("tr").querySelector("a[name=cancel]").click();
}
}
<% end %>

View File

@ -1,9 +1,21 @@
ActiveSupport.on_load :turbo_streams_tag_builder do
def disable(target)
action :disable, target
action :disable, target, allow_inferred_rendering: false
end
def disable_all(targets)
action_all :disable, targets
action_all :disable, targets, allow_inferred_rendering: false
end
def enable(target)
action :enable, target, allow_inferred_rendering: false
end
def enable_all(targets)
action_all :enable, targets, allow_inferred_rendering: false
end
def focus(target)
action :focus, target, allow_inferred_rendering: false
end
end