Add crayons_icon_tag helper (#15878)

This commit is contained in:
Michael Kohl 2022-01-03 09:52:05 +07:00 committed by GitHub
parent 9a4edeb0ab
commit f886c758bd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 75 additions and 0 deletions

View file

@ -0,0 +1,33 @@
module CrayonsHelper
# A wrapper for the +inline_svg_tag+ helper specifically for Crayons icons.
#
# @param name [String|Symbol] the icon name. The ".svg" file extension will
# be added automatically if missing.
# @param css_class [String] additional CSS classes, "crayons-icon" is always
# included.
# @param native [Boolean] when set to +true+ the icon will not inherit its
# parent's color.
# @param **opts additional keyword arguments to be passed through to the
# +inline_svg_tag+ helper.
# @return [String] the SVG tag.
#
# @example Simplest form
# crayons_icon_tag(:twitter)
#
# @example Disabling color inheritance
# crayons_icon_tag(:twitter, native: true)
#
# @example Specifying additional CSS classes
# crayons_icon_tag("twitter.svg", css_class: "pointer-events-none")
def crayons_icon_tag(name, css_class: nil, native: false, **opts)
name = name.to_s
icon_name = name.ends_with?(".svg") ? name : "#{name}.svg"
icon_class = [
"crayons-icon",
css_class,
("crayons-icon--default" if native),
].compact.join(" ")
inline_svg_tag(icon_name, aria: true, width: 24, height: 24, class: icon_class, **opts)
end
end

View file

@ -0,0 +1,42 @@
require "rails_helper"
RSpec.describe CrayonsHelper, type: :helper do
describe "#crayons_icon_tag" do
let(:icon_tag) { helper.crayons_icon_tag("twitter.svg") }
it "generates an SVG tag" do
expect(icon_tag).to match(%r{\A<svg.*</svg>\n\z}m)
end
it "includes the correct class" do
expect(icon_tag).to match(/class="crayons-icon"/)
end
it "allows disabling color inheritance via the native attribute" do
icon_tag = helper.crayons_icon_tag(:twitter, native: true)
expect(icon_tag).to match(/class="crayons-icon crayons-icon--default"/)
end
it "adds the correct ARIA role" do
expect(icon_tag).to match(/role="img"/)
end
it "works when the .svg suffix is omitted" do
expect(helper.crayons_icon_tag("twitter")).to eq(icon_tag)
end
it "accepts a symbol for the name parameter" do
expect(helper.crayons_icon_tag(:twitter)).to eq(icon_tag)
end
it "allows specifying additional CSS classes" do
icon_tag = helper.crayons_icon_tag("twitter", css_class: "pointer-events-none")
expect(icon_tag).to match(/class="crayons-icon pointer-events-none"/)
end
it "passes additional keyword arguments to the wrapped tag" do
icon_tag = helper.crayons_icon_tag("twitter", title: "Test")
expect(icon_tag).to match(%r{<title.*>Test</title>})
end
end
end