Files
Reservair/assets/js/forms/RsvAdminForm.js
T
Martas 1294a177ae (#1) - WebPack bundling of JS and CSS (#1)
This work was done with Claude.

Added bundling of CSS & JS with WebPack. This also means minimization.

---------

Co-authored-by: Martin Slachta <martin.slachta@outlook.com>
Reviewed-on: #1
2026-06-12 10:57:23 +00:00

61 lines
2.1 KiB
JavaScript

import { RsvFormEncoder } from './RsvFormEncoder.js';
import { show_notice } from '../../../src/components/admin.js';
/*
* 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(),
* });
*/
export const RsvAdminForm = {
// 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));
},
};