Skip to content

Commit

Permalink
Allow passing :modal option to Button
Browse files Browse the repository at this point in the history
It will allow opening a modal from a button click.
  • Loading branch information
davidalejandroaguilar committed Sep 27, 2024
1 parent 3167c9f commit a4fd8ab
Showing 1 changed file with 49 additions and 2 deletions.
51 changes: 49 additions & 2 deletions lib/phlexy_ui/button.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

module PhlexyUI
class Button < Base
def initialize(*, as: :button, **)
def initialize(*, as: :button, modal: nil, **)
super(*, **)
@as = as
@modal = modal
end

def view_template(&)
Expand All @@ -14,14 +15,60 @@ def view_template(&)
base_modifiers:,
options:
).then do |classes|
if modal
# TODO: Remove this abomination once Phlex 2.0 is released.
#
# The cleanest way to do this is with a single:
#
# onclick: "#{modal}.showModal()"
#
# However, currently, Phlex does not allow you to use the "onclick"
# attribute.
#
# Once Phlex 2.0 is released, it will add a #safe method
# that will allow us to replace this with a single line:
#
# onclick: safe("#{modal}.showModal()")
#
# For now, at least this only runs once and uses event delegation
# so that it only adds a single event listener to the document.body.
#
# The downside is a bigger HTML payload.
options[:data] ||= {}
options[:data][:modal] = modal
script do
unsafe_raw(<<~JS)
(() => {
if (window.PhlexyUI && window.PhlexyUI.modalInitialized) {
return;
}
document.body.addEventListener("click", (event) => {
if (event.target.tagName === 'BUTTON' &&
event.target.dataset.modal) {
const modal = document.getElementById(event.target.dataset.modal);
if (modal) {
modal.showModal();
}
}
});
if (!window.PhlexyUI) window.PhlexyUI = {};
window.PhlexyUI.modalInitialized = true;
})();
JS
end
end

public_send(as, class: classes, **options, &)
end
end

private

attr_reader :modal

register_modifiers(
# Modifiers
# "sm:no-animation"
# "md:no-animation"
# "lg:no-animation"
Expand Down

0 comments on commit a4fd8ab

Please sign in to comment.