Class: Blacklight::System::DropdownComponent

Inherits:
Component
  • Object
show all
Defined in:
app/components/blacklight/system/dropdown_component.rb

Constant Summary

Constants inherited from Component

Component::EXCLUDE_VARIABLES

Instance Method Summary collapse

Methods inherited from Component

compiler, config, #inspect

Constructor Details

#initialize(param:, choices:, search_state:, id: nil, classes: [], default: nil, selected: nil, interpolation: :field) ⇒ DropdownComponent

rubocop:disable Metrics/ParameterLists



16
17
18
19
20
21
22
23
24
# File 'app/components/blacklight/system/dropdown_component.rb', line 16

def initialize(param:, choices:, search_state:, id: nil, classes: [], default: nil, selected: nil, interpolation: :field)
  @param = param
  @choices = choices
  @search_state = search_state
  @id = id
  @classes = classes.concat(['btn-group', "#{param.to_s.parameterize}-dropdown"])
  @selected = selected || default || option_text_and_value(@choices.first)&.first
  @interpolation = interpolation
end

Instance Method Details

#before_renderObject



31
32
33
34
35
36
37
38
39
40
# File 'app/components/blacklight/system/dropdown_component.rb', line 31

def before_render
  with_button(classes: 'btn btn-outline-secondary dropdown-toggle', label: button_label) unless button

  return if options.any?

  with_options(@choices.map do |option|
    text, value = option_text_and_value(option)
    { text: text, url: helpers.url_for(@search_state.params_for_search(@param => value)), selected: @selected == value }
  end)
end

#button_labelObject

rubocop:enable Metrics/ParameterLists



27
28
29
# File 'app/components/blacklight/system/dropdown_component.rb', line 27

def button_label
  t(:button_label_html, default: :label_html, scope: "blacklight.search.#{@param}", @interpolation => label_for_value(@selected))
end

#label_for_value(value) ⇒ Object

rubocop:enable Style/CaseEquality



59
60
61
62
63
# File 'app/components/blacklight/system/dropdown_component.rb', line 59

def label_for_value(value)
  choice = @choices.find { |option| option_text_and_value(option).last == value }

  choice && option_text_and_value(choice).first
end

#option_text_and_value(option) ⇒ Object

rubocop:disable Style/CaseEquality This method is from Rails to mirror how it handles native dropdowns



48
49
50
51
52
53
54
55
56
# File 'app/components/blacklight/system/dropdown_component.rb', line 48

def option_text_and_value(option)
  # Options are [text, value] pairs or strings used for both.
  if !option.is_a?(String) && option.respond_to?(:first) && option.respond_to?(:last)
    option = option.reject { |e| Hash === e } if Array === option
    [option.first, option.last]
  else
    [option, option]
  end
end

#render?Boolean

Returns:

  • (Boolean)


42
43
44
# File 'app/components/blacklight/system/dropdown_component.rb', line 42

def render?
  @choices.many?
end