2019-05-02 17:17:27 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2015-01-23 14:02:25 -06:00
|
|
|
module CategoryBadge
|
2015-05-17 11:38:43 -05:00
|
|
|
def self.html_for(category, opts = nil)
|
2015-01-23 14:02:25 -06:00
|
|
|
opts = opts || {}
|
|
|
|
|
|
|
|
# If there is no category, bail
|
|
|
|
return "" if category.blank?
|
|
|
|
|
|
|
|
# By default hide uncategorized
|
|
|
|
return "" if category.uncategorized? && !opts[:show_uncategorized]
|
|
|
|
|
2023-11-13 09:46:15 -06:00
|
|
|
extra_classes = "#{opts[:extra_classes]}"
|
2015-01-23 14:02:25 -06:00
|
|
|
|
2023-01-09 06:10:19 -06:00
|
|
|
result = +""
|
2015-01-23 14:02:25 -06:00
|
|
|
|
2023-11-13 09:46:15 -06:00
|
|
|
# parent class
|
|
|
|
parent_category =
|
|
|
|
Category.find_by(id: category.parent_category_id) unless category.parent_category_id.nil?
|
|
|
|
has_parent_class = parent_category ? "--has-parent" : ""
|
2015-01-23 14:02:25 -06:00
|
|
|
|
2015-05-17 11:38:43 -05:00
|
|
|
# category name
|
2023-11-13 09:46:15 -06:00
|
|
|
class_names = "badge-category #{has_parent_class}"
|
2023-01-09 06:10:19 -06:00
|
|
|
description = category.description_text ? "title='#{category.description_text}'" : ""
|
|
|
|
category_url =
|
|
|
|
opts[:absolute_url] ? "#{Discourse.base_url_no_prefix}#{category.url}" : category.url
|
2015-01-23 14:02:25 -06:00
|
|
|
|
2023-12-06 11:49:19 -06:00
|
|
|
# styles
|
|
|
|
styles = {
|
|
|
|
"--category-badge-color": "##{category.color}",
|
|
|
|
"--category-badge-text-color": "##{category.text_color}",
|
|
|
|
}
|
|
|
|
styles["--parent-category-badge-color"] = "##{parent_category.color}" if parent_category
|
|
|
|
style_value = styles.map { |k, v| "#{k}: #{ERB::Util.html_escape(v)};" }.join(" ")
|
|
|
|
|
2023-11-13 09:46:15 -06:00
|
|
|
# category badge structure
|
|
|
|
result << "<span data-category-id='#{category.id}'"
|
2023-12-06 11:49:19 -06:00
|
|
|
result << " style='#{style_value}'"
|
2023-11-13 09:46:15 -06:00
|
|
|
result << " data-parent-category-id='#{parent_category.id}'" if parent_category
|
|
|
|
result << " data-drop-close='true' class='#{class_names}' #{description}>"
|
|
|
|
result << "<span class='badge-category__name'>"
|
|
|
|
result << ERB::Util.html_escape(category.name)
|
|
|
|
result << "</span></span>"
|
2018-06-28 03:14:55 -05:00
|
|
|
|
2023-11-13 09:46:15 -06:00
|
|
|
# wrapping link
|
2023-01-09 06:10:19 -06:00
|
|
|
result =
|
2023-11-13 09:46:15 -06:00
|
|
|
"<a class='badge-category__wrapper #{extra_classes}' href='#{category_url}'>#{result}</a>"
|
2018-06-28 03:14:55 -05:00
|
|
|
|
|
|
|
result.html_safe
|
2015-05-13 06:25:27 -05:00
|
|
|
end
|
2015-01-23 14:02:25 -06:00
|
|
|
end
|