class DatePickerInput < SimpleForm::Inputs::StringInput include ActionView::Helpers::FormTagHelper include ActionView::Context def input input_html_options[:id] ||= date_id input_html_options.reverse_merge!( placeholder: "MM/DD/YYYY", value: date_value, :"aria-describedby" => hint_id ) content_tag(:div, class: 'uc-form-field-date') do user_agent.mobile? ? input_for_mobile : input_for_desktop end end def hint options[:hint_html] ||= {} options[:hint_html].merge!(id: hint_id, class: 'hidden') hint_text = 'Date (format: MM/DD/YYYY)' if options[:input_html]["disable-future-dates"] hint_text << '. You cannot select a future date.' end hint_text end def label_html_options options[:input_html] ||= {} options[:input_html][:id] ||= date_id super end private def user_agent @user_agent ||= UserAgent.parse(@builder.template.controller.request.user_agent) end def input_for_mobile @builder.text_field(attribute_name, input_html_options.reverse_merge( type: 'date' )) end def input_for_desktop data_presents = ['datepicker'] if input_html_options['data-presents'] data_presents << input_html_options['data-presents'] end @builder.text_field(attribute_name, input_html_options.merge( 'type' => 'text', 'data-presents' => data_presents.join(' '), )) end def hint_id "#{object.class.name.underscore}_#{object_id}_datepicker_hint" end def date_id "#{object.class.name.underscore}_#{object_id}_datepicker" end def date_value value = input_html_options.fetch(:value, @builder.object.public_send(attribute_name)) value.blank? ? value : format_date(value) end def format_date(date) value = date.is_a?(String) ? Date.parse(date) : date user_agent.mobile? ? value.iso8601 : value.to_s(:default) rescue ArgumentError date end end