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

80 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-10-24 15:49:58 +02:00
import { ApplicationController } from './application_controller';
export class FileInputResetController extends ApplicationController {
2024-02-13 08:04:51 +01:00
static targets = ['fileList'];
declare fileListTarget: HTMLElement;
2023-10-24 15:49:58 +02:00
2023-10-25 12:04:12 +02:00
connect() {
2024-02-13 08:04:51 +01:00
super.connect();
this.updateFileList();
this.element.addEventListener('change', (event) => {
if (
event.target instanceof HTMLInputElement &&
event.target.type === 'file'
) {
this.updateFileList();
2023-10-25 12:04:12 +02:00
}
});
}
2024-02-13 08:04:51 +01:00
updateFileList() {
const files = this.fileInput?.files ?? [];
this.fileListTarget.innerHTML = '';
const deleteLabel =
this.element.getAttribute('data-delete-label') || 'Delete';
Array.from(files).forEach((file, index) => {
const container = document.createElement('li');
container.classList.add('flex', 'flex-gap-2', 'fr-mb-1w');
2024-02-13 08:04:51 +01:00
const deleteButton = this.createDeleteButton(deleteLabel, index);
container.appendChild(deleteButton);
const listItem = document.createElement('div');
listItem.textContent = file.name;
container.appendChild(listItem);
this.fileListTarget.appendChild(container);
});
2023-10-24 15:49:58 +02:00
}
2024-02-13 08:04:51 +01:00
createDeleteButton(deleteLabel: string, index: number) {
const button = document.createElement('button');
button.textContent = deleteLabel;
button.classList.add(
'fr-btn',
'fr-btn--tertiary',
'fr-btn--sm',
'fr-icon-delete-line'
);
button.addEventListener('click', (event) => {
event.preventDefault();
this.removeFile(index);
});
return button;
}
removeFile(index: number) {
const files = this.fileInput?.files;
if (!files) return;
const dataTransfer = new DataTransfer();
Array.from(files).forEach((file, i) => {
if (index !== i) {
dataTransfer.items.add(file);
}
});
if (this.fileInput) this.fileInput.files = dataTransfer.files;
this.updateFileList();
2023-10-24 15:49:58 +02:00
}
2023-10-25 12:04:12 +02:00
2024-02-13 08:04:51 +01:00
private get fileInput(): HTMLInputElement | null {
return this.element.querySelector(
'input[type="file"]'
) as HTMLInputElement | null;
2023-10-25 12:04:12 +02:00
}
2023-10-24 15:49:58 +02:00
}