|
// retoor <retoor@molodetz.nl>
|
|
|
|
import { Http } from "./Http.js";
|
|
import { Toast } from "./Toast.js";
|
|
|
|
export class OptimisticAction {
|
|
async submit(url, params, errorTarget, render, button = null) {
|
|
if (button) {
|
|
button.disabled = true;
|
|
button.classList.add("is-loading");
|
|
}
|
|
try {
|
|
const result = await Http.sendForm(url, params, { silent: true });
|
|
if (render) render(result);
|
|
return result;
|
|
} catch (error) {
|
|
console.error("optimistic action failed", error);
|
|
if (errorTarget) Toast.flash(errorTarget, "Error", 1500);
|
|
return null;
|
|
} finally {
|
|
if (button) {
|
|
button.disabled = false;
|
|
button.classList.remove("is-loading");
|
|
}
|
|
}
|
|
}
|
|
|
|
async submitOptimistic(url, params, errorTarget, apply, revert, reconcile, button = null) {
|
|
if (button) {
|
|
button.disabled = true;
|
|
button.classList.add("is-loading");
|
|
}
|
|
apply();
|
|
try {
|
|
const result = await Http.sendForm(url, params, { silent: true });
|
|
if (reconcile) reconcile(result);
|
|
return result;
|
|
} catch (error) {
|
|
console.error("optimistic action failed", error);
|
|
revert();
|
|
if (errorTarget) Toast.flash(errorTarget, "Error", 1500);
|
|
return null;
|
|
} finally {
|
|
if (button) {
|
|
button.disabled = false;
|
|
button.classList.remove("is-loading");
|
|
}
|
|
}
|
|
}
|
|
}
|