module Coco class Icon < Coco::Component include Concerns::AcceptsOptions ICON_CACHE = {} ALIASES = { edit: "pen-line", "edit-3": "pen-line", "git-commit": "git-commit-horizontal", grid: "grid-3x3", "user-circle": "circle-user" }.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