107 lines
5.9 KiB
JavaScript
107 lines
5.9 KiB
JavaScript
(() => {
|
|
const forms = [...document.querySelectorAll('form[data-unsaved-form]')];
|
|
if (!forms.length) return;
|
|
const serialise = data => JSON.stringify([...data.entries()].filter(([name]) => name !== '__RequestVerificationToken').map(([name, value]) => [name, typeof value === 'string' ? value : value.name]));
|
|
const snapshot = form => serialise(new FormData(form));
|
|
const states = forms.map(form => {
|
|
const status = document.createElement('p');
|
|
status.className = 'form-text mb-0'; status.hidden = true; status.setAttribute('role', 'status');
|
|
form.append(status);
|
|
return { form, status, baseline: snapshot(form), pending: null };
|
|
});
|
|
let leaving = false, choosing = false;
|
|
const dirty = state => snapshot(state.form) !== state.baseline;
|
|
const hasChanges = () => states.some(state => dirty(state) || state.pending);
|
|
const showStatus = (state, message, failed = false) => {
|
|
state.status.hidden = !message;
|
|
state.status.textContent = message;
|
|
state.status.classList.toggle('text-danger', failed);
|
|
state.status.setAttribute('role', failed ? 'alert' : 'status');
|
|
};
|
|
const save = state => {
|
|
if (state.pending) return state.pending;
|
|
const data = new FormData(state.form), sent = serialise(data);
|
|
const buttons = [...state.form.querySelectorAll('button[type=submit], input[type=submit]')].map(button => [button, button.disabled]);
|
|
buttons.forEach(([button]) => button.disabled = true);
|
|
showStatus(state, 'Saving…');
|
|
state.pending = (async () => {
|
|
try {
|
|
const response = await fetch(state.form.action, {
|
|
method: 'POST', body: data, credentials: 'same-origin',
|
|
headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
|
|
});
|
|
if (response.redirected) throw new Error('Your session or subscription needs attention. Open your account in another tab; your changes remain here.');
|
|
const result = await response.json().catch(() => null);
|
|
if (!response.ok || result?.ok !== true) throw new Error(result?.message || 'Unable to save. Your changes remain here; please try again.');
|
|
state.baseline = sent;
|
|
showStatus(state, dirty(state) ? 'Earlier changes saved; newer edits remain unsaved.' : 'Saved');
|
|
} catch (error) {
|
|
showStatus(state, error.message || 'Unable to save. Your changes remain here.', true);
|
|
throw error;
|
|
} finally {
|
|
buttons.forEach(([button, disabled]) => button.disabled = disabled);
|
|
state.pending = null;
|
|
}
|
|
})();
|
|
return state.pending;
|
|
};
|
|
const discard = state => {
|
|
const values = new Map();
|
|
for (const [name, value] of JSON.parse(state.baseline)) {
|
|
if (!values.has(name)) values.set(name, []);
|
|
values.get(name).push(value);
|
|
}
|
|
for (const field of state.form.elements) {
|
|
if (!field.name || field.name === '__RequestVerificationToken' || field.matches('button, input[type=submit]')) continue;
|
|
const original = values.get(field.name) || [];
|
|
if (field.matches('input[type=checkbox], input[type=radio]')) field.checked = original.includes(field.value);
|
|
else if (field.matches('select[multiple]')) [...field.options].forEach(option => option.selected = original.includes(option.value));
|
|
else if (field.type === 'file') field.value = '';
|
|
else field.value = original[0] ?? '';
|
|
}
|
|
showStatus(state, 'Changes discarded');
|
|
};
|
|
for (const state of states) {
|
|
state.form.addEventListener('input', () => { if (!state.pending) showStatus(state, dirty(state) ? 'Unsaved changes' : ''); });
|
|
state.form.addEventListener('change', () => { if (!state.pending) showStatus(state, dirty(state) ? 'Unsaved changes' : ''); });
|
|
state.form.addEventListener('submit', event => { event.preventDefault(); void save(state).catch(() => {}); });
|
|
}
|
|
window.addEventListener('beforeunload', event => {
|
|
if (leaving || !hasChanges()) return;
|
|
event.preventDefault(); event.returnValue = '';
|
|
});
|
|
window.addEventListener('pageshow', () => leaving = false);
|
|
document.addEventListener('click', async event => {
|
|
if (event.defaultPrevented || event.button !== 0 || event.ctrlKey || event.metaKey || event.altKey || event.shiftKey || !hasChanges()) return;
|
|
const link = event.target.closest('a[href]');
|
|
if (!link || link.matches('[data-help-open], [data-bs-toggle]') || link.hasAttribute('download') || (link.target && link.target !== '_self')) return;
|
|
const url = new URL(link.href, location.href);
|
|
if (!['http:', 'https:'].includes(url.protocol) || link.getAttribute('href').startsWith('#')
|
|
|| (url.origin === location.origin && url.pathname === location.pathname && url.search === location.search && url.hash)) return;
|
|
if (!window.PlotDirectorDialogs || !window.bootstrap?.Modal || !document.getElementById('pdApplicationDialogTemplate')) {
|
|
// The browser's beforeunload protection remains available if dialog assets fail.
|
|
states.filter(dirty).forEach(state => showStatus(state, 'Save your changes before leaving this page.', true));
|
|
return;
|
|
}
|
|
event.preventDefault();
|
|
if (choosing) return;
|
|
choosing = true;
|
|
try {
|
|
const result = await window.PlotDirectorDialogs.choose({
|
|
title: 'Unsaved changes', message: 'Save your changes before leaving this page?',
|
|
failureMessage: 'Changes remain unsaved. Save again or keep editing.',
|
|
actions: [
|
|
{ label: 'Save and leave', value: 'save', className: 'btn-primary', run: async () => {
|
|
for (const state of states.filter(state => dirty(state) || state.pending)) await save(state);
|
|
return !hasChanges();
|
|
} },
|
|
{ label: 'Discard and leave', value: 'discard', className: 'btn-outline-danger' },
|
|
{ label: 'Keep editing', value: 'cancel' }
|
|
]
|
|
});
|
|
if (result?.value === 'discard') states.forEach(discard);
|
|
if (result?.value === 'save' || result?.value === 'discard') { leaving = true; location.assign(url.href); }
|
|
} finally { choosing = false; }
|
|
}, true);
|
|
})();
|