Class: ERBLint::Linters::ArgumentMappers::Button

Inherits:
Object
  • Object
show all
Defined in:
lib/primer/view_components/linters/argument_mappers/button.rb

Overview

Maps classes in a button element to arguments for the Button component.

Constant Summary collapse

SCHEME_MAPPINGS =
{
  "btn-primary" => ":primary",
  "btn-danger" => ":danger",
  "btn-outline" => ":outline",
  "btn-invisible" => ":invisible",
  "btn-link" => ":link"
}.freeze
VARIANT_MAPPINGS =
{
  "btn-sm" => ":small",
  "btn-large" => ":large"
}.freeze
TYPE_OPTIONS =
%w[button reset submit].freeze

Instance Method Summary collapse

Constructor Details

#initialize(tag) ⇒ Button

Returns a new instance of Button.



26
27
28
# File 'lib/primer/view_components/linters/argument_mappers/button.rb', line 26

def initialize(tag)
  @tag = tag
end

Instance Method Details

#classes_to_args(classes) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/primer/view_components/linters/argument_mappers/button.rb', line 62

def classes_to_args(classes)
  classes.value.split(" ").each_with_object({}) do |class_name, acc|
    next if class_name == "btn"

    if SCHEME_MAPPINGS[class_name] && acc[:scheme].nil?
      acc[:scheme] = SCHEME_MAPPINGS[class_name]
    elsif VARIANT_MAPPINGS[class_name] && acc[:variant].nil?
      acc[:variant] = VARIANT_MAPPINGS[class_name]
    elsif class_name == "btn-block"
      acc[:block] = true
    elsif class_name == "BtnGroup-item"
      acc[:group_item] = true
    else
      raise ConversionError, "Cannot convert class \"#{class_name}\""
    end
  end
end

#to_argsObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/primer/view_components/linters/argument_mappers/button.rb', line 34

def to_args
  args = {}

  args[:tag] = ":#{@tag.name}" unless @tag.name == "button"

  @tag.attributes.each do |attribute|
    attr_name = attribute.name

    if attr_name == "class"
      args = args.merge(classes_to_args(attribute))
    elsif attr_name == "disabled"
      args[:disabled] = true
    elsif attr_name == "type"
      # button is the default type, so we don't need to do anything.
      next if attribute.value == "button"

      raise ConversionError, "Button component does not support type \"#{attribute.value}\"" unless TYPE_OPTIONS.include?(attribute.value)

      args[:type] = ":#{attribute.value}"
    else
      # Assume the attribute is a system argument.
      args.merge!(SystemArguments.new(attribute).to_args)
    end
  end

  args
end

#to_sObject



30
31
32
# File 'lib/primer/view_components/linters/argument_mappers/button.rb', line 30

def to_s
  to_args.map { |k, v| "#{k}: #{v}" }.join(", ")
end