You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.7 KiB

  1. # Font Awesome Helper
  2. module FaIconHelper
  3. LOGGER = SemanticLogger[Module.nesting[0]]
  4. ##
  5. # mandatory:
  6. # name: without 'fa-' prefix
  7. # might be a symbol, automatic conversion of undashed symbol
  8. # for instance symbol :magnify_lens is converted to string 'magnify-lens'
  9. # optional:
  10. # style: [:solid|:regular|:brands] solid as default value
  11. # size: [2, 3, ..., 10 ]
  12. # class: extra classes, any tailwind keyword...
  13. # aria-hidden: true as default value
  14. #
  15. # example:
  16. # fa_icon(:user)
  17. # fa_icon(:user, style: :regular)
  18. # fa_icon(:user, size: 2)
  19. # fa_icon(:user, class: 'text-blue-500')
  20. ##
  21. def fa_icon(name, html_options = {})
  22. warn_useless_options html_options
  23. fa_icon = "fa-#{to_dash(name)}"
  24. fa_style = "fa-#{to_dash(html_options[:style] || :solid)}"
  25. fa_size = to_fa_size(html_options[:size])
  26. content_class = [fa_icon, fa_style, fa_size, html_options[:class]].compact.join(' ')
  27. tag.i(class: content_class, 'aria-hidden': html_options['aria-hidden'] || true)
  28. end
  29. private
  30. def to_dash(symbol) = symbol.to_s.dasherize
  31. def to_fa_size(value)
  32. return unless value
  33. size = value.to_i
  34. unless (1..10).include? size
  35. LOGGER.warn "unparseable size <#{value}>, should be an integer from a range of 1 to 10!",
  36. Rails.backtrace_cleaner.clean(caller[1..])&.first
  37. return
  38. end
  39. return if size == 1
  40. "fa-#{size}x"
  41. end
  42. def warn_useless_options(hash)
  43. hash.except(:style, :size, :class, 'aria-hidden').each_key do |key|
  44. LOGGER.warn "useless option <#{key}>, please consider removal for safety reason!",
  45. Rails.backtrace_cleaner.clean(caller[3..])&.first
  46. end
  47. end
  48. end