2023-10-26 16:01:15 +02:00
|
|
|
import { isButtonElement } from '@coldwired/utils';
|
2022-10-11 11:33:09 +02:00
|
|
|
|
|
|
|
import { ApplicationController } from './application_controller';
|
|
|
|
|
|
|
|
export class AutosaveSubmitController extends ApplicationController {
|
|
|
|
#isSaving = false;
|
2023-10-26 16:02:23 +02:00
|
|
|
#shouldSubmit = false;
|
2022-10-11 11:33:09 +02:00
|
|
|
#buttonText?: string;
|
|
|
|
|
|
|
|
connect(): void {
|
2023-10-10 18:14:09 +02:00
|
|
|
this.onGlobal('autosave:input', () => this.didInput());
|
2022-10-11 11:33:09 +02:00
|
|
|
this.onGlobal('autosave:end', () => this.didSucceed());
|
|
|
|
this.onGlobal('autosave:error', () => this.didFail());
|
|
|
|
this.on('click', (event) => this.onClick(event));
|
|
|
|
}
|
|
|
|
|
|
|
|
// Intercept form submit if autosave is still in progress
|
|
|
|
private onClick(event: Event) {
|
|
|
|
if (this.#isSaving) {
|
|
|
|
this.#shouldSubmit = true;
|
|
|
|
this.disableButton();
|
|
|
|
event.preventDefault();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-10 18:14:09 +02:00
|
|
|
private didInput() {
|
2022-10-11 11:33:09 +02:00
|
|
|
this.#isSaving = true;
|
|
|
|
this.#shouldSubmit = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If submit was previously requested, send it, now that autosave have finished
|
|
|
|
private didSucceed() {
|
|
|
|
if (this.#shouldSubmit && isButtonElement(this.element)) {
|
|
|
|
this.element.form?.requestSubmit(this.element);
|
|
|
|
}
|
|
|
|
this.#isSaving = false;
|
|
|
|
this.#shouldSubmit = false;
|
|
|
|
this.enableButton();
|
|
|
|
}
|
|
|
|
|
|
|
|
private didFail() {
|
|
|
|
this.#isSaving = false;
|
|
|
|
this.#shouldSubmit = false;
|
|
|
|
this.enableButton();
|
|
|
|
}
|
|
|
|
|
|
|
|
private disableButton() {
|
|
|
|
if (isButtonElement(this.element)) {
|
2023-10-26 16:02:23 +02:00
|
|
|
const disableWith = this.element.dataset.disableWith ?? '';
|
|
|
|
if (disableWith) {
|
|
|
|
this.#buttonText = this.element.textContent ?? undefined;
|
|
|
|
this.element.textContent = disableWith;
|
|
|
|
}
|
2022-10-11 11:33:09 +02:00
|
|
|
this.element.disabled = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private enableButton() {
|
2023-10-26 16:02:23 +02:00
|
|
|
if (isButtonElement(this.element)) {
|
|
|
|
if (this.#buttonText) {
|
|
|
|
this.element.textContent = this.#buttonText;
|
|
|
|
}
|
2022-10-11 11:33:09 +02:00
|
|
|
this.element.disabled = false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|