diff --git a/app/components/editable_champ/champ_label_content_component/champ_label_content_component.html.haml b/app/components/editable_champ/champ_label_content_component/champ_label_content_component.html.haml index 713fd100d..932d82668 100644 --- a/app/components/editable_champ/champ_label_content_component/champ_label_content_component.html.haml +++ b/app/components/editable_champ/champ_label_content_component/champ_label_content_component.html.haml @@ -18,7 +18,7 @@ = t('.check_content_rebased') - if hint? - %span.fr-hint-text= hint + %span.fr-hint-text{ data: { controller: 'date-input-hint' } }= hint - if @champ.description.present? %span.fr-hint-text{ id: @champ.describedby_id }= render SimpleFormatComponent.new(@champ.description, allow_a: true) diff --git a/app/components/editable_champ/date_component/date_component.html.haml b/app/components/editable_champ/date_component/date_component.html.haml index e6d6b332c..97a4be017 100644 --- a/app/components/editable_champ/date_component/date_component.html.haml +++ b/app/components/editable_champ/date_component/date_component.html.haml @@ -3,4 +3,4 @@ aria: { describedby: @champ.describedby_id }, value: @champ.value, required: @champ.required?, - placeholder: 'aaaa-mm-jj', class: "width-33-desktop") + class: "width-33-desktop") diff --git a/app/javascript/controllers/date_input_hint_controller.ts b/app/javascript/controllers/date_input_hint_controller.ts new file mode 100644 index 000000000..8eacd6d53 --- /dev/null +++ b/app/javascript/controllers/date_input_hint_controller.ts @@ -0,0 +1,49 @@ +import { ApplicationController } from './application_controller'; + +const DATE_PLACEHOLDER_REGEXP = /[jJmMdD]{2}\/[jJmMdD]{2}\/[aAyY]{4}/; +const DATE_EXAMPLE_REGEXP = /\d{1,2}\/\d{1,2}\/\d{4}/; +const PARTS = { + fr: { + '15': 'JJ', + '10': 'MM', + '2022': 'AAAA' + }, + en: { + '15': 'dd', + '10': 'mm', + '2022': 'yyyy' + } +}; + +export class DateInputHintController extends ApplicationController { + connect() { + this.fixDateFormat(this.element); + } + + private fixDateFormat(input: Element) { + const text = input.textContent ?? ''; + const match = text.match(DATE_PLACEHOLDER_REGEXP); + + if (match) { + const [placeholder, example] = this.translatePlaceholder(); + // This component behaviour can be had to test and debug. We keep a (debug) log here to help. + console.debug(`Replace ${match[0]} with ${placeholder} and ${example}`); + input.textContent = text + .replace(DATE_PLACEHOLDER_REGEXP, placeholder) + .replace(DATE_EXAMPLE_REGEXP, example); + } + } + + private translatePlaceholder() { + const locale = document.documentElement.lang as 'fr' | 'en'; + const parts = PARTS[locale]; + const example = new Date(2022, 9, 15).toLocaleDateString(); + return [ + Object.entries(parts).reduce( + (text, [part, str]) => text.replace(part, str), + example + ), + example + ]; + } +}