2025-04-30 18:14:22 -04:00
|
|
|
class MenuItemComponent < ViewComponent::Base
|
|
|
|
VARIANTS = %i[link button divider].freeze
|
|
|
|
|
2025-05-23 14:31:08 -05:00
|
|
|
attr_reader :variant, :text, :icon, :href, :method, :destructive, :confirm, :frame, :opts
|
2025-04-30 18:14:22 -04:00
|
|
|
|
2025-05-23 14:31:08 -05:00
|
|
|
def initialize(variant:, text: nil, icon: nil, href: nil, method: :post, destructive: false, confirm: nil, frame: nil, **opts)
|
2025-04-30 18:14:22 -04:00
|
|
|
@variant = variant.to_sym
|
|
|
|
@text = text
|
|
|
|
@icon = icon
|
|
|
|
@href = href
|
|
|
|
@method = method.to_sym
|
|
|
|
@destructive = destructive
|
|
|
|
@confirm = confirm
|
2025-05-23 14:31:08 -05:00
|
|
|
@frame = frame
|
|
|
|
@opts = opts
|
2025-04-30 18:14:22 -04:00
|
|
|
raise ArgumentError, "Invalid variant: #{@variant}" unless VARIANTS.include?(@variant)
|
|
|
|
end
|
|
|
|
|
|
|
|
def wrapper(&block)
|
|
|
|
if variant == :button
|
2025-05-23 14:31:08 -05:00
|
|
|
button_to href, method: method, class: container_classes, **merged_opts, &block
|
2025-04-30 18:14:22 -04:00
|
|
|
elsif variant == :link
|
2025-05-23 14:31:08 -05:00
|
|
|
link_to href, class: container_classes, **merged_opts, &block
|
2025-04-30 18:14:22 -04:00
|
|
|
else
|
|
|
|
nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def text_classes
|
|
|
|
[
|
|
|
|
"text-sm",
|
|
|
|
destructive? ? "text-destructive" : "text-primary"
|
|
|
|
].join(" ")
|
|
|
|
end
|
|
|
|
|
|
|
|
def destructive?
|
|
|
|
method == :delete || destructive
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
def container_classes
|
|
|
|
[
|
|
|
|
"flex items-center gap-2 p-2 rounded-md w-full",
|
|
|
|
destructive? ? "hover:bg-red-tint-5 theme-dark:hover:bg-red-tint-10" : "hover:bg-container-hover"
|
|
|
|
].join(" ")
|
|
|
|
end
|
|
|
|
|
2025-05-23 14:31:08 -05:00
|
|
|
def merged_opts
|
2025-04-30 18:14:22 -04:00
|
|
|
merged_opts = opts.dup || {}
|
|
|
|
data = merged_opts.delete(:data) || {}
|
|
|
|
|
|
|
|
if confirm.present?
|
|
|
|
data = data.merge(turbo_confirm: confirm.to_data_attribute)
|
|
|
|
end
|
|
|
|
|
2025-05-23 14:31:08 -05:00
|
|
|
if frame.present?
|
|
|
|
data = data.merge(turbo_frame: frame)
|
|
|
|
end
|
|
|
|
|
2025-04-30 18:14:22 -04:00
|
|
|
merged_opts.merge(data: data)
|
|
|
|
end
|
|
|
|
end
|