Sha256: 5f4b750c200bdfd450d74b832d4070540969bd081927fedb889359c22ea63e98

Contents?: true

Size: 1.36 KB

Versions: 13

Compression:

Stored size: 1.36 KB

Contents

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

    ICON_CACHE = {}

    InvalidIconError = Class.new(StandardError)

    accepts_option :size, from: %i[xs sm md lg xl xxl]
    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
      @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

13 entries across 13 versions & 1 rubygems

Version Path
coveragebook_components-0.7.9 app/components/coco/base/icon/icon.rb
coveragebook_components-0.7.8 app/components/coco/base/icon/icon.rb
coveragebook_components-0.7.7 app/components/coco/base/icon/icon.rb
coveragebook_components-0.7.6 app/components/coco/base/icon/icon.rb
coveragebook_components-0.7.5 app/components/coco/base/icon/icon.rb
coveragebook_components-0.7.4 app/components/coco/base/icon/icon.rb
coveragebook_components-0.7.3 app/components/coco/base/icon/icon.rb
coveragebook_components-0.7.2 app/components/coco/base/icon/icon.rb
coveragebook_components-0.7.1 app/components/coco/base/icon/icon.rb
coveragebook_components-0.7.0 app/components/coco/base/icon/icon.rb
coveragebook_components-0.6.5 app/components/coco/base/icon/icon.rb
coveragebook_components-0.6.4 app/components/coco/base/icon/icon.rb
coveragebook_components-0.6.3 app/components/coco/base/icon/icon.rb