2024-04-29 00:17:15 +02:00
# frozen_string_literal: true
2022-12-15 13:08:20 +01:00
class Dsfr :: InputComponent < ApplicationComponent
2023-05-05 09:13:05 +02:00
include Dsfr :: InputErrorable
2022-12-20 17:51:36 +01:00
delegate :object , to : :@form
delegate :errors , to : :object
2024-10-07 18:10:37 +02:00
attr_reader :attribute
2022-12-20 17:51:36 +01:00
# use it to indicate detailed about the inputs, ex: https://www.systeme-de-design.gouv.fr/elements-d-interface/modeles-et-blocs-fonctionnels/demande-de-mot-de-passe
# it uses aria-describedby on input and link it to yielded content
renders_one :describedby
2023-08-30 18:11:19 +02:00
renders_one :label
2022-12-20 17:51:36 +01:00
2024-03-07 12:06:00 +01:00
def initialize ( form : , attribute : , input_type : :text_field , opts : { } , required : true , autoresize : true )
2022-12-15 13:08:20 +01:00
@form = form
@attribute = attribute
@input_type = input_type
@opts = opts
@required = required
2024-03-07 12:06:00 +01:00
@autoresize = autoresize
2022-12-15 13:08:20 +01:00
end
2023-08-21 16:18:31 +02:00
def dsfr_champ_container
:div
end
2022-12-20 17:51:36 +01:00
# add invalid class on input when input is invalid
# and and valid on input only if another input is invalid
def input_group_opts
opts = {
2023-05-05 09:13:05 +02:00
class : class_names ( {
'fr-input-group' : true ,
'fr-password' : password?
} . merge ( input_group_error_class_names ) )
2022-12-20 17:51:36 +01:00
}
if email?
2024-06-07 10:06:40 +02:00
opts [ :data ] = { controller : 'email-input' , email_input_url_value : show_email_suggestions_path }
2022-12-20 17:51:36 +01:00
end
opts
end
def label_opts
{ class : class_names ( 'fr-label' : true , 'fr-password__label' : password? ) }
end
# errors helpers
def error_messages
errors . full_messages_for ( attribute_or_rich_body )
2022-12-15 13:08:20 +01:00
end
2023-02-15 11:33:42 +01:00
def describedby_id
dom_id ( object , " #{ @attribute } -messages " )
end
2022-12-20 17:51:36 +01:00
# i18n lookups
def label
2023-08-30 18:11:19 +02:00
get_slot ( :label ) . presence || default_label
2022-12-15 13:08:20 +01:00
end
2023-08-21 16:18:31 +02:00
def dsfr_input_classname
'fr-input'
end
2022-12-20 17:51:36 +01:00
# kind of input helpers
def password?
@input_type == :password_field
end
def email?
@input_type == :email_field
2022-12-15 13:08:20 +01:00
end
2024-03-07 12:06:00 +01:00
def autoresize?
@input_type == :text_area && @autoresize
end
2023-10-02 15:31:32 +02:00
def required?
@required
end
2023-02-07 18:06:38 +01:00
def show_password_id
dom_id ( object , " #{ @attribute } _show_password " )
end
2022-12-15 13:08:20 +01:00
private
2023-08-30 18:11:19 +02:00
def default_label
object . class . human_attribute_name ( @attribute )
end
2022-12-15 13:08:20 +01:00
end