refactor to use event delegation

This commit is contained in:
Paul Chavard 2023-10-25 12:04:12 +02:00
parent 00e3d33ba4
commit c60494c975
4 changed files with 27 additions and 6 deletions

View file

@ -2,18 +2,36 @@ import { ApplicationController } from './application_controller';
import { hide, show } from '@utils';
export class FileInputResetController extends ApplicationController {
static targets = ['input', 'reset'];
static targets = ['reset'];
declare readonly inputTarget: HTMLInputElement;
declare readonly resetTarget: HTMLElement;
connect() {
this.on('change', (event) => {
if (event.target == this.fileInput) {
this.showResetButton();
}
});
}
reset(event: Event) {
event.preventDefault();
this.inputTarget.value = '';
this.fileInput.value = '';
hide(this.resetTarget);
}
showResetButton() {
show(this.resetTarget);
}
private get fileInput() {
const inputs =
this.element.querySelectorAll<HTMLInputElement>('input[type="file"]');
if (inputs.length == 0) {
throw new Error('No file input found');
} else if (inputs.length > 1) {
throw new Error('Multiple file inputs found');
}
return inputs[0];
}
}

View file

@ -9,8 +9,9 @@
= render Dsfr::InputComponent.new(form: f, attribute: :body, input_type: :text_area, opts: { rows: 5, placeholder: placeholder, title: placeholder, class: 'fr-input message-textarea'})
.fr-mt-3w{ data: { controller: "file-input-reset" } }
%button.hidden.fr-btn.fr-btn--tertiary.fr-btn--sm.fr-icon-delete-line.fr-mr-1w{ 'aria-label': t('views.shared.messages.remove_file'), data: { 'file-input-reset-target': 'reset', action: 'file-input-reset#reset' } }
= f.file_field :piece_jointe, direct_upload: true, data: { 'file-input-reset-target': 'input', action: 'change->file-input-reset#showResetButton' }
= render Attachment::EditComponent.new(attached_file: commentaire.piece_jointe)
%button.hidden.fr-btn.fr-btn--tertiary-no-outline.fr-btn--icon-left.fr-icon-delete-line{ data: { 'file-input-reset-target': 'reset', action: 'file-input-reset#reset' } }
= t('views.shared.messages.remove_file')
.fr-mt-3w
= f.submit t('views.shared.dossiers.messages.form.send_message'), class: 'fr-btn', data: { disable: true }

View file

@ -21,3 +21,5 @@ en:
already_user: "I already have an account"
create: 'Create an account'
signin: 'Sign in'
messages:
remove_file: 'Remove file'

View file

@ -22,4 +22,4 @@ fr:
create: 'Créer un compte'
signin: 'Se connecter'
messages:
remove_file: 'Supprime le fichier'
remove_file: 'Supprimer le fichier'