Draft state belongs to the editor
The following snapshot function illustrates the inputs and extra state the close guard must consider. It is not a complete modal controller. The application owns loading, submit state, focus management, topmost-modal selection and the in-page discard confirmation.
function draftSnapshot(form, pendingDeletes, pendingToggles) {
const fields = [...form.querySelectorAll('input, select, textarea')].map(field => {
if (field.type === 'checkbox' || field.type === 'radio') {
return [field.name || field.id, field.value, field.checked];
}
if (field instanceof HTMLSelectElement && field.multiple) {
return [field.name || field.id, [...field.selectedOptions].map(option => option.value)];
}
return [field.name || field.id, field.value];
});
return JSON.stringify([fields, [...pendingDeletes].sort(),
[...pendingToggles].sort(([a], [b]) => a.localeCompare(b))]);
}
Take the clean snapshot after async initialization. Include new/deleted child rows and every draft field, even if it has no form input. File editors additionally track selected files. Do not silently write on input change or reset the clean snapshot after each render. Before a user close request, reject it while submitting; otherwise compare the current snapshot and ask to discard only if dirty. Programmatic close after a successful save is a separate path.
Use modal-workflows for the full behavior contract. The example covers snapshot comparison only; it is not a complete close guard.