2022-11-21 16:32:17 +01:00
|
|
|
import { ApplicationController } from './application_controller';
|
2023-01-04 18:29:44 +01:00
|
|
|
import { disable, enable } from '@utils';
|
2023-01-06 20:07:53 +01:00
|
|
|
import invariant from 'tiny-invariant';
|
2022-11-21 16:32:17 +01:00
|
|
|
|
|
|
|
export class BatchOperationController extends ApplicationController {
|
2023-01-06 20:07:53 +01:00
|
|
|
static targets = ['menu', 'input'];
|
2022-11-21 16:32:17 +01:00
|
|
|
|
2023-01-06 20:07:53 +01:00
|
|
|
declare readonly menuTarget: HTMLButtonElement;
|
|
|
|
declare readonly hasMenuTarget: boolean;
|
2022-11-21 16:32:17 +01:00
|
|
|
declare readonly inputTargets: HTMLInputElement[];
|
|
|
|
|
2023-01-04 18:29:44 +01:00
|
|
|
onCheckOne() {
|
2022-11-21 16:32:17 +01:00
|
|
|
this.toggleSubmitButtonWhenNeeded();
|
|
|
|
}
|
|
|
|
|
|
|
|
onCheckAll(event: Event) {
|
2022-12-02 17:16:29 +01:00
|
|
|
const target = event.target as HTMLInputElement;
|
|
|
|
|
|
|
|
this.inputTargets.forEach((e) => (e.checked = target.checked));
|
2022-11-21 16:32:17 +01:00
|
|
|
this.toggleSubmitButtonWhenNeeded();
|
|
|
|
}
|
|
|
|
|
|
|
|
toggleSubmitButtonWhenNeeded() {
|
2023-01-06 20:07:53 +01:00
|
|
|
const buttons = [
|
|
|
|
...this.element.querySelectorAll<HTMLButtonElement>('[data-operation]')
|
|
|
|
];
|
|
|
|
const checked = this.inputTargets.filter((input) => input.checked);
|
|
|
|
if (checked.length) {
|
|
|
|
const available = buttons.filter((button) => {
|
|
|
|
const operation = button.dataset.operation;
|
|
|
|
invariant(operation, 'data-operation is required');
|
|
|
|
const available = checked.every(isInputForOperation(operation));
|
|
|
|
switchButton(button, available);
|
|
|
|
return available;
|
|
|
|
});
|
|
|
|
if (this.hasMenuTarget) {
|
|
|
|
if (available.length) {
|
|
|
|
enable(this.menuTarget);
|
|
|
|
} else {
|
|
|
|
disable(this.menuTarget);
|
|
|
|
}
|
2022-12-15 17:35:50 +01:00
|
|
|
}
|
2023-01-06 20:07:53 +01:00
|
|
|
} else if (this.hasMenuTarget) {
|
|
|
|
disable(this.menuTarget);
|
2022-11-21 16:32:17 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-01-06 20:07:53 +01:00
|
|
|
|
|
|
|
function isInputForOperation(operation: string) {
|
|
|
|
return (input: HTMLInputElement) =>
|
|
|
|
(input.dataset.operations?.split(',') ?? []).includes(operation);
|
|
|
|
}
|
|
|
|
|
|
|
|
function switchButton(button: HTMLButtonElement, flag: boolean) {
|
|
|
|
if (flag) {
|
|
|
|
enable(button);
|
|
|
|
button.querySelectorAll('button').forEach((button) => enable(button));
|
|
|
|
} else {
|
|
|
|
disable(button);
|
|
|
|
button.querySelectorAll('button').forEach((button) => disable(button));
|
|
|
|
}
|
|
|
|
}
|