demarches-normaliennes/app/javascript/controllers/file_input_reset_controller.ts

38 lines
891 B
TypeScript
Raw Normal View History

2023-10-24 15:49:58 +02:00
import { ApplicationController } from './application_controller';
import { hide, show } from '@utils';
export class FileInputResetController extends ApplicationController {
2023-10-25 12:04:12 +02:00
static targets = ['reset'];
2023-10-24 15:49:58 +02:00
declare readonly resetTarget: HTMLElement;
2023-10-25 12:04:12 +02:00
connect() {
this.on('change', (event) => {
if (event.target == this.fileInput) {
this.showResetButton();
}
});
}
2023-10-24 15:49:58 +02:00
reset(event: Event) {
event.preventDefault();
2023-10-25 12:04:12 +02:00
this.fileInput.value = '';
2023-10-24 15:49:58 +02:00
hide(this.resetTarget);
}
showResetButton() {
show(this.resetTarget);
}
2023-10-25 12:04:12 +02:00
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];
}
2023-10-24 15:49:58 +02:00
}