2026-06-12 11:25:57 +02:00
|
|
|
import { RsvFormEncoder } from './RsvFormEncoder.js';
|
|
|
|
|
import { show_notice } from '../../../src/components/admin.js';
|
|
|
|
|
|
2026-06-11 19:03:29 +02:00
|
|
|
/*
|
|
|
|
|
* RsvAdminForm — shared submit handler for wp-admin forms.
|
|
|
|
|
*
|
|
|
|
|
* Serializes a <form> to JSON (via RsvFormEncoder), sends it to the form's
|
|
|
|
|
* `action` using the HTTP verb in `data-method`, always attaches the REST
|
|
|
|
|
* nonce, and reports the outcome through show_notice(). The only part that
|
|
|
|
|
* legitimately differs between forms — shaping the request body — is handled
|
|
|
|
|
* by the optional `transform(body, form)` hook.
|
|
|
|
|
*
|
|
|
|
|
* Usage:
|
|
|
|
|
* RsvAdminForm.bind(my_form, {
|
|
|
|
|
* transform: (body, form) => ({ ...body, block_size: parseInt(body.block_size) }),
|
|
|
|
|
* refresh: () => my_datagrid.refresh(),
|
|
|
|
|
* });
|
|
|
|
|
*/
|
2026-06-12 11:25:57 +02:00
|
|
|
export const RsvAdminForm = {
|
2026-06-11 19:03:29 +02:00
|
|
|
// Attach a submit listener that sends the form as JSON.
|
|
|
|
|
bind(form, options = {}) {
|
|
|
|
|
if (!form) return;
|
|
|
|
|
form.addEventListener('submit', (event) => {
|
|
|
|
|
event.preventDefault();
|
|
|
|
|
RsvAdminForm.submit(form, options);
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
// Send the form now. Returns the fetch promise.
|
|
|
|
|
submit(form, { transform, refresh, onSuccess } = {}) {
|
|
|
|
|
let body = RsvFormEncoder.encode_form(form);
|
|
|
|
|
if (transform) body = transform(body, form);
|
|
|
|
|
|
|
|
|
|
// `form.method` always returns a string (default 'get'), so default to POST
|
|
|
|
|
// explicitly unless the view opted into a verb via data-method.
|
|
|
|
|
const method = (form.dataset.method || 'POST').toUpperCase();
|
|
|
|
|
|
|
|
|
|
return fetch(form.action, {
|
|
|
|
|
method,
|
|
|
|
|
credentials: 'same-origin',
|
|
|
|
|
headers: {
|
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
'Accept': 'application/json',
|
|
|
|
|
'X-WP-Nonce': ReservairServiceAPI.nonce,
|
|
|
|
|
},
|
|
|
|
|
body: JSON.stringify(body),
|
|
|
|
|
})
|
|
|
|
|
.then(async (response) => {
|
|
|
|
|
const data = await response.json().catch(() => null);
|
|
|
|
|
if (!response.ok) throw new Error(data?.error || data?.message || 'Request failed');
|
|
|
|
|
return data;
|
|
|
|
|
})
|
|
|
|
|
.then((data) => {
|
|
|
|
|
show_notice(form, 'success', form.dataset.successMsg ?? 'Saved.');
|
|
|
|
|
if (refresh) refresh();
|
|
|
|
|
if (onSuccess) onSuccess(data);
|
|
|
|
|
})
|
|
|
|
|
.catch((error) => show_notice(form, 'error', error.message));
|
|
|
|
|
},
|
|
|
|
|
};
|