|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module Flowbite |
| 4 | + class Sidebar |
| 5 | + # Renders a sidebar navigation item. |
| 6 | + # |
| 7 | + # Each item renders as a list item containing a link. Optionally, an icon |
| 8 | + # can be provided using the +icon+ slot, which will be displayed before the |
| 9 | + # label text. |
| 10 | + # |
| 11 | + # @example Basic item |
| 12 | + # <%= render Flowbite::Sidebar::Item.new(href: "/dashboard") { "Dashboard" } %> |
| 13 | + # |
| 14 | + # @example Item with icon |
| 15 | + # <%= render(Flowbite::Sidebar::Item.new(href: "/dashboard")) do |item| %> |
| 16 | + # <% item.with_icon do %> |
| 17 | + # <svg class="w-5 h-5" ...>...</svg> |
| 18 | + # <% end %> |
| 19 | + # Dashboard |
| 20 | + # <% end %> |
| 21 | + # |
| 22 | + # @viewcomponent_slot icon An optional icon displayed before the label text. |
| 23 | + class Item < ViewComponent::Base |
| 24 | + renders_one :icon |
| 25 | + |
| 26 | + attr_reader :href, :options |
| 27 | + |
| 28 | + class << self |
| 29 | + def classes |
| 30 | + [ |
| 31 | + "flex", "items-center", "px-2", "py-1.5", "text-body", |
| 32 | + "rounded-base", "hover:bg-neutral-tertiary", "hover:text-fg-brand", "group" |
| 33 | + ] |
| 34 | + end |
| 35 | + end |
| 36 | + |
| 37 | + # @param class [Array<String>] Additional CSS classes for the link element. |
| 38 | + # @param href [String] The URL for the navigation link. |
| 39 | + # @param options [Hash] Additional HTML attributes for the link element. |
| 40 | + def initialize(href:, class: nil, **options) |
| 41 | + super() |
| 42 | + @class = Array.wrap(binding.local_variable_get(:class)) |
| 43 | + @href = href |
| 44 | + @options = options |
| 45 | + end |
| 46 | + |
| 47 | + def call |
| 48 | + content_tag(:li) do |
| 49 | + link_options = {class: link_classes}.merge(options) |
| 50 | + content_tag(:a, href: href, **link_options) do |
| 51 | + concat(icon) if icon? |
| 52 | + concat(content_tag(:span, content, class: label_classes)) |
| 53 | + end |
| 54 | + end |
| 55 | + end |
| 56 | + |
| 57 | + private |
| 58 | + |
| 59 | + def label_classes |
| 60 | + "ms-3" if icon? |
| 61 | + end |
| 62 | + |
| 63 | + def link_classes |
| 64 | + self.class.classes + @class |
| 65 | + end |
| 66 | + end |
| 67 | + end |
| 68 | +end |
0 commit comments