Sha256: 61a6de843a6506dbcfdb2683a69111698205e846dfc67630721957b8e9a23020

Contents?: true

Size: 1.52 KB

Versions: 2

Compression:

Stored size: 1.52 KB

Contents

module Coco
  class Icon < Coco::Component
    include Concerns::AcceptsOptions

    ICON_CACHE = {}

    ALIASES = {
      edit: "pen-line",
      "edit-3": "pen-line",
      grid: "grid-3x3"
    }.freeze

    InvalidIconError = Class.new(StandardError)

    accepts_option :size, from: %i[xs sm md lg xl xxl full]
    accepts_option :spin, from: [true, false]
    accepts_option :style, from: [:line, :fill, :custom]

    before_render do
      if name
        set_tag_data_attr(:icon, name)
        set_option_value(:style, :custom) if icon_data[:custom]
      end
    end

    def initialize(name: nil, **kwargs)
      @icon_name = name&.to_s&.tr("_", "-")
    end

    def name
      ALIASES.fetch(@icon_name.to_sym, @icon_name) if @icon_name
    end

    def svg
      content || icon_data[:svg]
    end

    def icon_data
      ICON_CACHE[name] ||= {
        custom: custom?,
        svg: read_svg
      }
    end

    def custom?
      @_custom ||= File.exist?(custom_icon_path)
    end

    def read_svg
      if custom?
        File.read(custom_icon_path).html_safe
      elsif File.exist?(icon_path)
        File.read(icon_path).html_safe
      elsif Rails.env.development? || Rails.env.test?
        raise InvalidIconError, "`#{name}` is not a valid icon name"
      end
    end

    def icon_path
      @_icon_path ||= Coco::Engine.root.join("app/assets/build/coco/icons/#{name}.svg")
    end

    def custom_icon_path
      @_custom_icon_path ||= Coco::Engine.root.join("app/assets/build/coco/icons/custom/#{name}.svg")
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
coveragebook_components-0.8.2 app/components/coco/base/icon/icon.rb
coveragebook_components-0.8.1 app/components/coco/base/icon/icon.rb